v0.2.0: Complete README with SLM-native, multi-agent, HITL, eval, streaming, tools, observability
Browse files13 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817913 unmodified lines- react- orchestration- modularpipeline_tag: text-generation---# Purpose Agent β Self-Improving Agentic Framework via State-Value EvaluationA lightweight, modular framework where an LLM agent improves across tasks **without weight updates** β using an RL-inspired self-reflection loop with a "Purpose Function" that evaluates intermediate state improvements.## Core PhilosophyThe agent improves via a **Purpose Function Ξ¦(s)** that measures distance-to-goal at every step. It rewards the agent **only if Ξ¦(s_new) > Ξ¦(s_current)**. High-reward trajectories are distilled into reusable heuristics stored in a 3-tier memory system, so the agent gets smarter on each subsequent task.**No real-time backprop. No PPO/DPO. Minimal infrastructure costs.**## Architecture```ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ORCHESTRATOR LOOP ββ ββ ββββββββββββ action βββββββββββββββ s_new ββ β ACTOR β βββββββββΊ β ENVIRONMENT β βββββββββββ ββ β(+memory) β β (your code) β β ββ ββββββ²ββββββ βββββββββββββββ β ββ β βΌ ββ β heuristics ββββββββββββββββββ (s, a, s') ββ ββββββββββββββββββ OPTIMIZER ββββββββββββ ββ β β (distillation) β β ββ β ββββββββββββββββββ β ββ β ββββββββββββββββββ Ξ¦(s)βΞ¦(s') ββ β β PURPOSE FN ββββββββββββ€ ββ β β (state critic) β β ββ β ββββββββββββββββββ β ββ β ββββββββββββββββββ β ββ ββββββββββββββββββ EXPERIENCE ββββββββββββ ββ β REPLAY BUFFER β ββ ββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ```## Modules| Module | File | Role ||--------|------|------|| **Actor** | `actor.py` | ReAct-style agent with 3-tier memory-augmented prompts || **Purpose Function** | `purpose_function.py` | Strict, non-hackable LLM critic that scores Ξ¦(s) transitions || **Experience Replay** | `experience_replay.py` | Trajectory storage with two-phase retrieval (similarity + Q-value) || **Optimizer** | `optimizer.py` | Distills winning trajectories into reusable heuristics || **Orchestrator** | `orchestrator.py` | Main loop tying everything together || **LLM Backend** | `llm_backend.py` | Swappable inference layer (HF, OpenAI, Ollama, custom) || **Types** | `types.py` | Shared data structures (State, Action, Trajectory, Heuristic, etc.) |## Literature Foundation| Paper | Contribution to this framework ||-------|-------------------------------|| [MUSE](https://arxiv.org/abs/2510.08002) | 3-tier memory hierarchy (strategic/procedural/tool) || [LATS](https://arxiv.org/abs/2310.04406) | LLM-as-value-function V(s) pattern || [REMEMBERER](https://arxiv.org/abs/2306.07929) | Q-value experience replay with Bellman updates || [Reflexion](https://arxiv.org/abs/2303.11366) | Verbal reinforcement via episodic self-reflection || [SPC](https://arxiv.org/abs/2504.19162) | Anti-reward-hacking via adversarial critic patterns || [CER](https://arxiv.org/abs/2506.06698) | Contextual experience distillation (Dynamics + Skills) || [MemRL](https://arxiv.org/abs/2601.03192) | Two-phase retrieval (semantic recall β Q-value re-rank) || [Voyager](https://arxiv.org/abs/2305.16291) | Skill library as long-term memory |## Quick Start```pythonfrom purpose_agent import Orchestrator, Statefrom purpose_agent.llm_backend import HFInferenceBackendfrom purpose_agent.orchestrator import Environment, Action# 1. Define your environmentclass MyEnv(Environment):def execute(self, action, current_state):# Your environment logicreturn State(data={...})# 2. Create orchestrator with any LLM backendorch = Orchestrator(llm=HFInferenceBackend(model_id="Qwen/Qwen3-32B", provider="cerebras"),environment=MyEnv(),available_actions={"search": "Search for items", "navigate": "Go somewhere"},persistence_dir="./agent_memory",)# 3. Run tasks β the agent self-improves across runsresult = orch.run_task(purpose="Find the answer to X", max_steps=20)print(result.summary())print(orch.get_heuristic_report()) # See what it learned```## Swapping LLM Backends```python# HuggingFace Inference Providers (cheapest)from purpose_agent.llm_backend import HFInferenceBackendllm = HFInferenceBackend(model_id="Qwen/Qwen3-32B", provider="cerebras")# OpenAIfrom purpose_agent.llm_backend import OpenAICompatibleBackendllm = OpenAICompatibleBackend(model="gpt-4o")# Local Ollamallm = OpenAICompatibleBackend(model="llama3.2",base_url="http://localhost:11434/v1",api_key="ollama",)# Use DIFFERENT models for Actor vs Critic (recommended for production)orch = Orchestrator(llm=cheap_fast_model, # Actor β needs throughputcritic_llm=strong_model, # Purpose Function β needs accuracyoptimizer_llm=cheap_fast_model, # Runs infrequentlyenvironment=my_env,)```## Purpose Function β Anti-Reward-Hacking DesignThe Purpose Function system prompt enforces 7 strict rules:1. **EVIDENCE REQUIRED** β Every score must cite specific observable state changes2. **NO CREDIT FOR INTENTIONS** β Scores based on actual state, not agent's predictions3. **NO SYCOPHANCY** β Lateral moves get Ξ=0.0, regressions get negative Ξ4. **MONOTONIC SCALE** β Ξ¦ 0.0β10.0 proportional to progress5. **ANTI-GAMING** β Superficial state manipulation flagged and penalized6. **CONSISTENCY** β Identical states must receive identical Ξ¦ scores (cache-enforced)7. **CONFIDENCE** β Ambiguous evaluations get reduced delta magnitudeAdditional programmatic safeguards:- Score caching prevents inconsistent evaluations- Anomaly detection flags suspiciously large single-step jumps- Confidence threshold filters uncertain scores- Z-score normalization prevents score inflation over long trajectories## 3-Tier Memory SystemBased on MUSE (arxiv:2510.08002):| Tier | Content | Loading | Update Trigger ||------|---------|---------|----------------|| **Strategic** | `<Dilemma, Strategy>` pairs | Always in system prompt | After each task || **Procedural** | Step-by-step SOPs | Index in prompt, details on demand | After high-reward trajectory || **Tool** | Per-action tips | Returned per step | When new patterns prove effective |## Running the Demo```bashpython demo.py```Runs 17 unit tests + full end-to-end demo with a simulated TreasureMaze environment. No API keys needed β uses MockLLMBackend.## Dependencies- **Core framework**: Python 3.10+ (stdlib only)- **HF backend**: `huggingface_hub`- **OpenAI backend**: `openai`- **Production embeddings**: `sentence-transformers` (optional, for better retrieval)## License13 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727813 unmodified lines- react- orchestration- modular- slm- small-language-models- multi-agent- human-in-the-loop- streaming- tools- evaluation- ollama- local-modelspipeline_tag: text-generation---# Purpose Agent v0.2.0**The world's first SLM-native self-improving agentic framework.**Works with both **Small Language Models** (0.6Bβ3B params, local, $0 cost) and **Large Language Models** (cloud APIs) with equal efficiency. Agents learn from experience via a Purpose Function Ξ¦(s) β no fine-tuning needed.## What Makes This Different| Feature | Purpose Agent | LangChain | LangGraph | CrewAI | AutoGen | smolagents ||---|:---:|:---:|:---:|:---:|:---:|:---:|| **Self-Improvement** | β Ξ¦(s) + experience replay + heuristic distillation | β | β | β | β | β || **SLM-Native** | β Grammar-constrained JSON, prompt compression, Tool RAG | β | β | β | β | β οΈ || **Anti-Reward-Hacking** | β 7 strict rules + cache consistency + anomaly detection | β | β | β | β | β || **3-Tier Memory** | β Strategic/Procedural/Tool with Q-value retrieval | β | β οΈ | β οΈ | β | β || **Multi-Agent with Shared Learning** | β Agents learn from each other | β | β οΈ | β | β | β οΈ || **Human Ξ¦ Override** | β Humans teach the critic β permanent learning | β | β οΈ | β | β | β || **Streaming** | β Event + token streaming | β | β | β οΈ | β οΈ | β || **Tool Framework** | β Schema, validation, retry, Tool RAG | β | β | β | β | β || **Cost Tracking** | β Per-call token + USD tracking | β οΈ | β οΈ | β | β | β || **Benchmark Harness** | β Improvement curve tracking | β | β | β | β | β || **Lightweight** | β ~150KB, stdlib only | β | β | β οΈ | β οΈ | β || **Literature-Grounded** | β 8 papers implemented | β | β | β | β | β |## Architecture```purpose_agent/βββ types.py # Core data typesβββ llm_backend.py # Cloud LLM backends (HF, OpenAI, Mock)βββ slm_backends.py # π SLM backends (Ollama, llama-cpp, prompt compression)βββ actor.py # ReAct agent with 3-tier memoryβββ purpose_function.py # Non-hackable Ξ¦(s) criticβββ experience_replay.py # Two-phase retrieval (similarity + Q-value)βββ optimizer.py # Trajectory β heuristic distillationβββ orchestrator.py # Main loopβββ streaming.py # π Async engine + event streamingβββ tools.py # π Tool framework + built-in tools + Tool RAGβββ observability.py # π Cost tracking, callbacks, metricsβββ multi_agent.py # π Agent teams with shared learningβββ hitl.py # π Human-in-the-loop + checkpointingβββ evaluation.py # π Benchmark runner + improvement curves```## Quick Start β Local SLM (Zero Cost)```bash# 1. Install Ollamacurl -fsSL https://ollama.ai/install.sh | sh# 2. Pull a small model (1.7B params, runs on any laptop)ollama pull qwen3:1.7b# 3. Run your agentpython my_agent.py``````pythonfrom purpose_agent import (Orchestrator, OllamaBackend, State, Environment, Action,CalculatorTool, ToolRegistry,)# SLM backend β runs locally, zero costllm = OllamaBackend(model="qwen3:1.7b") # 1.7B params# Or use a cloud LLM# from purpose_agent import HFInferenceBackend# llm = HFInferenceBackend(model_id="Qwen/Qwen3-32B", provider="cerebras")class MyEnv(Environment):def execute(self, action, state):return State(data={"result": "done"})orch = Orchestrator(llm=llm, environment=MyEnv())result = orch.run_task(purpose="Solve the problem", max_steps=10)print(result.summary())```## SLM Model RegistryPre-configured models optimized for agent tasks:```pythonfrom purpose_agent import create_slm_backendbackend = create_slm_backend("phi-4-mini") # 3.8B β best tool-use accuracybackend = create_slm_backend("qwen3-1.7b") # 1.7B β best balancebackend = create_slm_backend("qwen3-0.6b") # 0.6B β ultra-lightbackend = create_slm_backend("llama-3.2-1b") # 1B β 128K contextbackend = create_slm_backend("smollm2-1.7b") # 1.7B β HF native```## Multi-Agent with Shared LearningAgents learn from each other β when one agent solves a problem, all benefit:```pythonfrom purpose_agent import AgentSpec, AgentTeam, OllamaBackendresearcher = AgentSpec(name="researcher", role="Find information",model=OllamaBackend(model="qwen3:1.7b"), # Cheap SLMexpertise_keywords=["search", "find", "research"],)coder = AgentSpec(name="coder", role="Write and debug code",model=OllamaBackend(model="phi4-mini"), # Better SLM for codeexpertise_keywords=["code", "program", "debug"],)team = AgentTeam(agents=[researcher, coder],default_model=OllamaBackend(model="qwen3:1.7b"),environment=my_env,)# Auto-delegates to the best agentresult = team.run_task(purpose="Search for Python sorting algorithms")print(team.get_learning_report()) # See shared knowledge```## Human-in-the-LoopHumans can override Ξ¦ scores β the agent permanently learns preferences:```pythonfrom purpose_agent import HITLOrchestrator, CLIInputHandlerhitl = HITLOrchestrator(orchestrator=orch,input_handler=CLIInputHandler(),approve_actions=True, # Approve each actionreview_scores=True, # Override Ξ¦ scorescheckpoint_dir="./checkpoints",)result = hitl.run_task(purpose="Important task")# Inject knowledge directlyhitl.inject_heuristic(pattern="When facing {problem_type}",strategy="Always try the simplest approach first",)```## StreamingReal-time event streaming for UIs:```pythonimport asynciofrom purpose_agent import AsyncOrchestratorasync def main():async_orch = AsyncOrchestrator(orch)async for event in async_orch.run_task_stream(purpose="..."):if event.event_type == "action":print(f"π€ {event.data['name']}: {event.data['thought'][:100]}")elif event.event_type == "score":print(f"π Ξ¦: {event.data['phi_before']:.1f} β {event.data['phi_after']:.1f}")asyncio.run(main())```## Tool Framework```pythonfrom purpose_agent import FunctionTool, ToolRegistry, CalculatorTool, PythonExecTool# Create tool from any function@FunctionTool.from_functiondef search(query: str) -> str:"""Search the web for information."""return requests.get(f"https://api.search.com?q={query}").text# Tool RAG for SLMs (only load relevant tools into prompt)registry = ToolRegistry()registry.register(CalculatorTool())registry.register(PythonExecTool())registry.register(search)relevant = registry.get_relevant_tools("compute 2+2", top_k=2)# β [CalculatorTool, PythonExecTool] (search excluded β saves tokens)```## Cost Tracking```pythonfrom purpose_agent import CostTrackertracker = CostTracker(model_name="qwen3:1.7b", cost_per_1m_input=0.005)tracker.record(prompt_tokens=500, completion_tokens=200)print(tracker.summary())# β {'model': 'qwen3:1.7b', 'total_tokens': 700, 'estimated_cost_usd': 0.000005}```## Benchmark & Prove Self-Improvement```pythonfrom purpose_agent import BenchmarkRunner, BenchmarkTaskrunner = BenchmarkRunner(orchestrator=orch)tasks = [BenchmarkTask(id="t1", purpose="Find treasure", initial_state=...),BenchmarkTask(id="t2", purpose="Solve puzzle", initial_state=...),]result = runner.run(tasks, iterations=10, name="MazeTest")print(result.summary())# Iteration Success Rate Avg Ξ¦ Avg Steps Avg Reward# -----------------------------------------------------------------# 1 40.0% 4.20 12.0 3.20# 5 70.0% 6.80 8.0 6.50# 10 90.0% 8.50 6.0 8.90# Improvement: 40.0% β 90.0% (+50.0%)result.save("results/benchmark.json")```## Literature Foundation| Paper | What it contributes ||-------|-------------------|| [MUSE](https://arxiv.org/abs/2510.08002) | 3-tier memory (strategic/procedural/tool) || [LATS](https://arxiv.org/abs/2310.04406) | LLM-as-value-function V(s) || [REMEMBERER](https://arxiv.org/abs/2306.07929) | Q-value experience replay || [Reflexion](https://arxiv.org/abs/2303.11366) | Verbal reinforcement || [SPC](https://arxiv.org/abs/2504.19162) | Anti-reward-hacking || [CER](https://arxiv.org/abs/2506.06698) | Contextual experience distillation || [MemRL](https://arxiv.org/abs/2601.03192) | Two-phase retrieval || [TinyAgent](https://arxiv.org/abs/2409.00608) | SLM-native agent patterns |## Installation```bash# Core (no dependencies beyond stdlib)git clone https://huggingface.co/Rohan03/purpose-agentcd purpose-agent# For local SLMspip install ollama# For cloud LLMspip install huggingface_hub # or: pip install openai# Run demo (no API keys needed)python demo.py```## License
README.md+215-116