README: complete rewrite with visual architecture, animations, feature map, usage guide
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143<div align="center"><img src="assets/hero_animation.svg" alt="Purpose Agent Hero" width="100%"></div># Purpose Agent v3.0**A local-first self-improvement kernel for AI agents.**Agents that learn from experience β without fine-tuning, cloud infrastructure, or vendor lockβin.```bashpip install purpose-agent```## π What's New in v3.0?> [!TIP]> Purpose Agent v3.0 hardens the kernel for production use, focusing on security, token efficiency, and absolute execution reliability.- **Strict Tool Validation**: Hallucinationβproof tool calling schema. Any hallucinated arguments instantly trigger a corrective loop.- **O(1) Markovian Critic**: The new `delta` stateβevaluator saves tokens by evaluating *only what changed* instead of the full environment state.- **Popperian Falsification**: Mathematical, zeroβhallucination code scoring where assertions evaluate code correctness automatically.- **PEPβ―578 Sandboxing**: Secure, isolated execution for the Python environment.---## π€οΈ Three Tracks of UsagePurpose Agent scales with your needs, from a simple oneβliner to full multiβagent orchestration.### Track 1: AutoβPilot (Describe your goal)Provide a purpose, and the framework automatically delegates the necessary agents (Architect, Coder, Tester, etc.) and executes.```mermaidgraph LRA[pa.purpose] --> B(AutoβTeam Assembly)B --> C{Execution Loop}C -->|Success| D[Heuristics Extracted]C -->|Fail| E[Feedback Provided]D --> F[Smarter Next Run]``````pythonimport purpose_agent as pateam = pa.purpose("Write Python code and test it")result = team.run("Write a sorting algorithm")team.teach("Always handle edge cases") # Injects into procedural memoryprint(team.status())```### Track 2: Bring Your Own ModelSwap in local models for free, private execution, or connect to OpenRouter, Groq, or OpenAI for stateβofβtheβart reasoning.```mermaidgraph TDA[Your Application] --> B(purpose_agent)B --> C[Ollama local]B --> D[OpenRouter / Cloud]B --> E[HuggingFace Hub]``````python# Local (free, private)team = pa.purpose("Code helper", model="qwen3:1.7b")# Cloud providersteam = pa.purpose("Code helper", model="openrouter:meta-llama/llama-3.3-70b-instruct")team = pa.purpose("Code helper", model="groq:llama-3.3-70b-versatile")team = pa.purpose("Code helper", model="openai:gpt-4o")# Any OpenAIβcompatible APIfrom purpose_agent import resolve_backendbackend = resolve_backend("openrouter:google/gemma-4-26b-a4b-it", api_key="sk-or-...")```### Track 3: Full MultiβAgent ControlTake total control over the orchestration with `Spark` (Agent), `Flow` (Workflow DAG), `Council` (Deliberation), and `Vault` (RAG).```mermaidgraph LRA((BEGIN)) --> B[Research Spark]B --> C[Write Spark]C --> D{Review?}D -- Pass --> E((DONE))D -- Fail --> B``````pythonimport purpose_agent as pa# ββ Spark: a single intelligent agent ββspark = pa.Spark("coder", model="openrouter:meta-llama/llama-3.3-70b-instruct")result = spark.run("Write a fibonacci function")# ββ Flow: workflow engine with conditional routing ββflow = pa.Flow()flow.add_node("research", pa.Spark("researcher", model="qwen3:1.7b"))flow.add_node("write", pa.Spark("writer", model="qwen3:1.7b"))flow.add_edge(pa.BEGIN, "research")flow.add_edge("research", "write")flow.add_conditional_edge("write", review_fn, {"pass": pa.DONE_SIGNAL, "retry": "research"})result = flow.run(initial_state)# ββ Council: agents deliberate together ββcouncil = pa.Council([pa.Spark("researcher"), pa.Spark("coder"), pa.Spark("reviewer")])result = council.run("Design a web scraper", rounds=3)```---## π‘οΈ EvidenceβGated Memory & Immune SystemAgents don't just accumulate knowledge blindly. Every new memory goes through a secure pipeline:```mermaidflowchart LRA[Candidate Memory] --> B{Immune Scan}B -- Block --> C[Quarantine]B -- Pass --> D[Replay Test]D -- Helps --> E[Promoted to SOP]D -- Hurts --> F[Rejected]```- **Immune scan** blocks prompt injection, score manipulation, API key leaks, tool misuse.- **Quarantine** holds memories until they're tested.- **Promotion** happens only after empirical evidence shows the memory improves reward.## π¦ Install```bashpip install purpose-agent # Core (zero dependencies)pip install purpose-agent[openai] # + OpenAI / Groq / OpenRouterpip install purpose-agent[ollama] # + Local Ollamapip install purpose-agent[all] # Everything```## π LicenseMIT123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426---library_name: purpose-agentlicense: mitlanguage:- entags:- agents- self-improving- multi-agent- memory-system- local-first- slm- safety- event-driven- rag- toolspipeline_tag: text-generation---<div align="center"># π§ Purpose Agent### The framework where AI agents actually learn from experience.**Local-first Β· Self-improving Β· Domain-agnostic Β· Production-hardened**[](https://pypi.org/project/purpose-agent/)[](https://pypi.org/project/purpose-agent/)[](LICENSE)[]()[]()---```pip install purpose-agent```</div>---## π― What Problem Does This Solve?Every other agent framework (LangChain, CrewAI, AutoGen) runs **the same way every time**. Your agent fails at a task? Next time, it fails the exact same way. No learning. No memory. No improvement.**Purpose Agent is different.** After every task:```ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ Task β Execute β Score β Extract Lessons β Remember ββ β β ββ ββββββ Next task uses lessons βββββββββββββββ ββ ββ Run 1: Agent struggles ββββββββ Ξ¦ = 3.0 ββ Run 2: Uses learned heuristics β Ξ¦ = 7.0 ββ Run 3: Refined further ββββββββ Ξ¦ = 9.5 ββ ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ```**No fine-tuning. No GPU training. Just memory + experience.**---## β‘ 3-Line Quickstart```pythonimport purpose_agent as pateam = pa.purpose("Help me write Python code")result = team.run("Write a fibonacci function")```That's it. The framework auto-detects your model, builds the right team, executes the task, scores the result, and stores lessons for next time.---## ποΈ Architecture at a Glance```βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ PURPOSE AGENT v3.0 ββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ£β ββ ββββββββββββ βββββββββββββββ ββββββββββββββββββββ ββ β YOU βββββΆβ EASY API βββββΆβ ORCHESTRATOR β ββ β (purpose) β β (auto-team) β β (step loop) β ββ ββββββββββββ βββββββββββββββ ββββββββββ¬ββββββββββ ββ β ββ ββββββββββββββββββββββββββββββββββΌβββββββββββ ββ β βΌ β ββ β ββββββββββββ ββββββββββββββββββββ β ββ β β ACTOR βββββΆβ ENVIRONMENT β β ββ β β (decide) β β (execute) β β ββ β ββββββββββββ ββββββββββ¬ββββββββββ β ββ β β β ββ β βββββββββββββββββββββΌββββββ β ββ β β PURPOSE FUNCTION (Ξ¦) β β ββ β β Score: 0 ββββββββ 10 β β ββ β β O(1) state-delta mode β β ββ β βββββββββββββββββββββ¬ββββββ β ββ β β β ββ β ββββββββββββββββββββββββββΌββββββββββ β ββ β β MEMORY (immune-scanned) β β ββ β β 7 types Β· 5 statuses Β· scoped β β ββ β β quarantine β test β promote β β ββ β ββββββββββββββββββββββββββββββββββββ β ββ β β ββ βββββ SELF-IMPROVEMENT LOOP ββββββββββββββββ ββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ```---## π¨ Three Ways to Use It### π’ Level 1 β Just Describe What You Want```pythonimport purpose_agent as pa# Auto-detects the right team compositionteam = pa.purpose("Write Python code and test it") # β architect + coder + testerteam = pa.purpose("Research quantum computing") # β researcher + analystteam = pa.purpose("Analyze sales data") # β analyst + reporterteam = pa.purpose("Write a blog post") # β writer + editorresult = team.run("Create a sorting algorithm")team.teach("Always handle edge cases") # Inject knowledge directlyprint(team.status()) # See what it's learned```### π‘ Level 2 β Choose Your Model & Add Knowledge```pythonimport purpose_agent as pa# 10+ providers supportedteam = pa.purpose("Code helper", model="ollama:qwen3:1.7b") # Local, freeteam = pa.purpose("Code helper", model="openrouter:meta-llama/llama-3.3-70b-instruct")team = pa.purpose("Code helper", model="groq:llama-3.3-70b-versatile")team = pa.purpose("Code helper", model="openai:gpt-4o")# Add your own documents as knowledgeteam = pa.purpose("Answer questions about our product",knowledge="./docs/", # Load entire foldermodel="qwen3:1.7b",)answer = team.ask("What's our refund policy?")```### π΄ Level 3 β Full Control```pythonimport purpose_agent as pa# ββ Spark: single intelligent agent ββspark = pa.Spark("coder", model="ollama:qwen3:1.7b", tools=[pa.PythonExecTool()])result = spark.run("Write fibonacci")# ββ Flow: workflow with conditional routing ββflow = pa.Flow()flow.add_node("research", pa.Spark("researcher"))flow.add_node("write", pa.Spark("writer"))flow.add_edge(pa.BEGIN, "research")flow.add_conditional_edge("write", check_fn, {"pass": pa.DONE_SIGNAL, "revise": "research"})result = flow.run(state)# ββ swarm: parallel execution ββresults = pa.swarm(["task_a", "task_b", "task_c"], agents=[a1, a2, a3])# ββ Council: multi-agent deliberation ββcouncil = pa.Council([pa.Spark("alice"), pa.Spark("bob"), pa.Spark("carol")])result = council.run("Should we use microservices?", rounds=3)# ββ Vault: knowledge RAG ββvault = pa.Vault.from_directory("./research_papers/")agent = pa.Spark("analyst", tools=[vault.as_tool()])# ββ Generate entire systems ββfrom purpose_agent.mas_generator import generatesystem = generate("Monitor GitHub repos for CVEs and alert the team")# β 4 agents + workflow + tools + eval suite + routing policy```---## π‘οΈ Safety & Security```ββββββββββββββββββββββββββββββββββββββββββββββββ MEMORY IMMUNE SYSTEM ββ ββ candidate βββ immune scan βββ quarantine ββ β β ββ βββββββΌββββββ ββββββΌβββββ ββ β REJECTED β β TEST β ββ β (5 scans) β β (replay)β ββ ββββββββββββββ ββββββ¬βββββ ββ β ββ βββββββΌββββββ ββ β PROMOTED β ββ β (active) β ββ βββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ```**5 threat scanners:** prompt injection, score manipulation, tool misuse, privacy leaks, scope overreach**PEP 578 kernel sandbox:** Unbypassable audit hooks at the C-interpreter level. No Docker needed.**Falsification critic:** Code is scored by CPU-executed assertions, not LLM hallucinations.---## π¬ First-Principles Engineering| Problem | Old Approach | Purpose Agent ||---------|-------------|---------------|| Token cost grows O(NΒ²) | Pass full history to critic | **O(1) state-delta** β only pass what changed || SLMs hallucinate scores | "Rate this 0-10" β guess | **Falsification** β generate asserts, CPU executes, score = math || Sandbox bypassed via dynamic code | AST analysis (weak) | **PEP 578 audit hooks** β kernel-level, unbypassable || Heuristics overflow context | Inject all 200 heuristics | **MoH cap K=10** β only top heuristics by Q-value || UNKNOWN action crashes | Parse failure β crash | **Safe fallback to DONE** β never propagates garbage |---## π¦ What's Inside (45+ modules)<details><summary><b>π§ Core Engine</b></summary>| Module | What ||--------|------|| `orchestrator.py` | Main step loop with 3 critic modes (standard/delta/falsification) || `actor.py` | ReAct agent with 3-tier memory + heuristic cap || `purpose_function.py` | Ξ¦(s) scorer with 7 anti-gaming rules || `experience_replay.py` | Thread-safe trajectory storage with Q-value retrieval || `optimizer.py` | Trajectory οΏ½οΏ½οΏ½ heuristic distillation |</details><details><summary><b>𧬠Self-Improvement</b></summary>| Module | What ||--------|------|| `memory.py` | 7 memory kinds Γ 5 statuses, scoped, versioned || `memory_ci.py` | Quarantine β immune scan β test β promote/reject || `memory_homeostasis.py` | Budget enforcement, consolidation, archive || `immune.py` | 5 threat scanners for memory safety || `breakthroughs.py` | Self-improving critic, MoH, hindsight relabeling, evolution |</details><details><summary><b>β‘ First-Principles</b></summary>| Module | What ||--------|------|| `state_delta.py` | O(1) Markovian state-diff for critic || `falsification_critic.py` | Popperian scoring via adversarial assertions || `sandbox_hooks.py` | PEP 578 kernel-level audit hooks || `hardening.py` | Null safety, timeouts, validation, graceful degradation || `sre_patches.py` | 5 auto-applied critical vulnerability fixes |</details><details><summary><b>π Protocols & Interop</b></summary>| Module | What ||--------|------|| `protocols/mcp_bridge.py` | MCP tool server integration || `protocols/a2a.py` | Agent-to-Agent delegation with circuit breaker || `protocols/agui.py` | AG-UI frontend streaming || `protocols/agents_md.py` | AGENTS.md repo-local instructions || `quorum.py` | Consensus/disagreement topology switching |</details><details><summary><b>π§ Intelligence</b></summary>| Module | What ||--------|------|| `routing.py` | Smart model selection (local-first, cost-aware) || `mas_generator.py` | Use-case β complete multi-agent system || `skills/schema.py` | Versioned, evolvable, testable skill cards || `skills/ci.py` | Skill testing + rollback + Darwinian selection || `llm_compiler.py` | Parallel tool execution via DAG planning |</details><details><summary><b>π Optimization</b></summary>| Module | What ||--------|------|| `optimization/fingerprint.py` | Capability profiling from traces || `optimization/dataset.py` | Trace β filtered training dataset || `optimization/prompt_pack.py` | Epigenetic prompt optimization || `optimization/shadow_eval.py` | Candidate vs baseline comparison || `optimization/optimizer.py` | Improving/plateau/degrading policy || `optimization/lora_plan.py` | LoRA/distillation dry-run planning |</details><details><summary><b>ποΈ Runtime</b></summary>| Module | What ||--------|------|| `runtime/events.py` | 30 canonical event types || `runtime/event_bus.py` | Async pub/sub with backpressure || `runtime/state.py` | Typed execution state for checkpointing || `runtime/checkpoint.py` | InMemory/JSONL/SQLite durability || `streaming_v3.py` | AG-UI compatible stream adapters |</details>---## π Supported Providers```pythonfrom purpose_agent import resolve_backendresolve_backend("ollama:qwen3:1.7b") # Local (free)resolve_backend("openrouter:meta-llama/llama-3.3-70b-instruct")resolve_backend("groq:llama-3.3-70b-versatile")resolve_backend("openai:gpt-4o")resolve_backend("together:meta-llama/Llama-3.3-70B-Instruct-Turbo")resolve_backend("fireworks:accounts/fireworks/models/llama-v3p1-70b")resolve_backend("cerebras:llama-3.3-70b")resolve_backend("deepseek:deepseek-chat")resolve_backend("mistral:mistral-large-latest")resolve_backend("hf:Qwen/Qwen3-32B")```---## π Real-World Test ResultsTested with **Llama-3.3-70B** and **Gemma-4-26B** via OpenRouter:| Test | Llama-70B | Gemma-26B ||------|:---------:|:---------:|| fibonacci (4 unit tests) | β 100% | β 100% || fizzbuzz (4 unit tests) | β 100% | β 100% || factorial (3 unit tests) | β 100% | β 100% || Self-improvement (heuristic growth) | 0β18 | 0β11 || Immune system (adversarial) | 93% catch | β || Production test (19 checks) | 19/19 β | β |**250+ automated tests. Zero failures required for release.**---## π Research FoundationBuilt on **13 published papers**. Every module traces back to a specific result.| Paper | Module | Contribution ||-------|--------|-------------|| Ng et al. 1999 (PBRS) | purpose_function | Ξ¦ preserves optimal policy || MUSE (2510.08002) | actor, optimizer | 3-tier memory hierarchy || REMEMBERER (2306.07929) | experience_replay | Q-value retrieval || Reflexion (2303.11366) | orchestrator | Verbal reinforcement || SPC (2504.19162) | immune | Anti-reward-hacking || Meta-Rewarding (2407.19594) | meta_rewarding | Self-improving critic || DSPy (2310.03714) | prompt_optimizer | Automatic few-shot bootstrap || LLMCompiler (2312.04511) | llm_compiler | Parallel tool DAG || Retroformer (2308.02151) | retroformer | Structured reflection || TinyAgent (2409.00608) | slm_backends | SLM-native patterns || DeepSeek MoE (2401.06066) | breakthroughs | MoH sparse selection || HER (1707.01495) | breakthroughs | Hindsight relabeling || Self-Taught Eval (2408.02666) | self_taught | Synthetic critic training |Full proofs: [PURPOSE_LEARNING.md](PURPOSE_LEARNING.md) Β· Research trace: [COMPILED_RESEARCH.md](COMPILED_RESEARCH.md)---## π Install```bashpip install purpose-agent # Core (zero dependencies)pip install purpose-agent[openai] # + OpenAI/Groq/OpenRouterpip install purpose-agent[ollama] # + Local Ollamapip install purpose-agent[all] # Everything```**For local models (recommended β free, private):**```bashcurl -fsSL https://ollama.ai/install.sh | shollama pull qwen3:1.7b```---## π₯οΈ CLI```bashpython -m purpose_agent # Interactive wizardpurpose-agent # Same, via entry point```---## π LicenseMIT β use it for anything.---<div align="center">**Built on 13 papers. Zero fine-tuning. Agents that actually improve.**[PyPI](https://pypi.org/project/purpose-agent/) Β· [Architecture](ARCHITECTURE.md) Β· [Formal Proofs](PURPOSE_LEARNING.md) Β· [Changelog](CHANGELOG.md)</div>
README.md+368-85