{"id":36645568,"url":"https://github.com/gtesei/agentic_design_patterns","last_synced_at":"2026-06-10T03:00:34.330Z","repository":{"id":331692579,"uuid":"1130872960","full_name":"gtesei/agentic_design_patterns","owner":"gtesei","description":"Agentic AI Design Patterns","archived":false,"fork":false,"pushed_at":"2026-05-31T20:41:42.000Z","size":1792,"stargazers_count":12,"open_issues_count":1,"forks_count":3,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-05-31T21:20:54.145Z","etag":null,"topics":["agentic","ai","ai-agents","chain-of-thought","design-patterns","generative-ai","lang","langchain","langg","langgraph","openai","python","reflection","tool-use-ai"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gtesei.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2026-01-09T06:17:14.000Z","updated_at":"2026-05-31T21:13:35.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/gtesei/agentic_design_patterns","commit_stats":null,"previous_names":["gtesei/agentic_design_patterns"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/gtesei/agentic_design_patterns","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gtesei%2Fagentic_design_patterns","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gtesei%2Fagentic_design_patterns/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gtesei%2Fagentic_design_patterns/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gtesei%2Fagentic_design_patterns/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gtesei","download_url":"https://codeload.github.com/gtesei/agentic_design_patterns/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gtesei%2Fagentic_design_patterns/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34134633,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-10T02:00:07.152Z","response_time":89,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agentic","ai","ai-agents","chain-of-thought","design-patterns","generative-ai","lang","langchain","langg","langgraph","openai","python","reflection","tool-use-ai"],"created_at":"2026-01-12T09:59:48.974Z","updated_at":"2026-06-10T03:00:34.319Z","avatar_url":"https://github.com/gtesei.png","language":"Python","funding_links":[],"categories":["📋 Templates \u0026 Starters"],"sub_categories":["🟩 Development Tools 🛠️"],"readme":"# 🤖 Agentic Design Patterns\n\n[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)\n[![LangChain](https://img.shields.io/badge/LangChain-latest-green.svg)](https://python.langchain.com/)\n[![LangGraph](https://img.shields.io/badge/LangGraph-latest-orange.svg)](https://langchain-ai.github.io/langgraph/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n[![GitHub stars](https://img.shields.io/github/stars/gtesei/agentic_design_patterns?style=social)](https://github.com/gtesei/agentic_design_patterns/stargazers)\n[![GitHub forks](https://img.shields.io/github/forks/gtesei/agentic_design_patterns?style=social)](https://github.com/gtesei/agentic_design_patterns/network)\n[![GitHub release](https://img.shields.io/github/v/release/gtesei/agentic_design_patterns?include_prereleases\u0026sort=semver)](https://github.com/gtesei/agentic_design_patterns/releases)\n[![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-000000.svg)](https://github.com/astral-sh/ruff)\n\n[中文版](README.zh-CN.md)\n\n\u003e **Transform your AI applications from simple prompts to sophisticated intelligent systems.**\n\n## 🧭 Principles\n\nThis repo is built around four commitments. They explain what stays in and what gets cut.\n\n1. **Lean, not exhaustive.** This is *not* a catalog of hundreds of patterns that no human will ever read, understand, or remember. It is a **lean catalog meant to be understood and memorized**. Long patterns lists are not features; they are noise.\n2. **Hard cap: at most 28 patterns.** If a pattern is not necessary, we remove it. If something new is added, something else gets dropped. The ceiling is a forcing function, not an aspiration.\n3. **Demos must actually work.** Every demo runs in an **automated weekly smoke test, for both Python *and* TypeScript** — and it must pass. (See [`.github/workflows/weekly-smoke.yml`](./.github/workflows/weekly-smoke.yml).) Educational code that doesn't run is educational code that lies.\n4. **Concrete relevance, not just papers.** For each pattern we measure how it shows up in **real coding agents** — currently [Pi](https://github.com/earendil-works/pi) — and write it down in a `pi.md` inside each pattern folder, plus a [repo-wide roll-up with a coverage heat map](./pi.md). We also maintain [`diff.md`](./diff.md) to disambiguate commonly-confused pattern pairs: **if two patterns can't be cleanly told apart, one of them probably doesn't belong here**. A pattern that only exists in a paper somewhere is a signal it may not belong either.\n\n---\n\nAI evolves too quickly for traditional books to stay current, especially in fast-moving areas like agentic systems. That’s why this is one of the best “living books” on agentic AI: a comprehensive, hands-on collection of design patterns for building robust AI agents, continuously updated with real-world implementations, practical examples, and detailed architectural guidance for scalable, maintainable AI applications.\n\n## Table of Contents\n\n- [📚 Academic Foundations](#-academic-foundations)\n- [🏗️ Repository Structure](#-repository-structure)\n- [🗂️ Patterns at a Glance](#-patterns-at-a-glance)\n- [📚 Foundational Patterns](#-foundational-patterns)\n- [🧠 Advanced Reasoning Patterns](#-advanced-reasoning-patterns)\n- [🛡️ Reliability Patterns](#-reliability-patterns)\n- [🎯 Orchestration Patterns](#-orchestration-patterns)\n- [📊 Observability Patterns](#-observability-patterns)\n- [🧩 Memory Patterns](#-memory-patterns)\n- [🎓 Learning Patterns](#-learning-patterns)\n- [🚀 Quick Start](#-quick-start)\n- [🗺️ Pattern Selection Guide](#-pattern-selection-guide)\n- [🎓 Learning Path](#-learning-path)\n- [🛠️ Tech Stack](#-tech-stack)\n- [📖 Resources](#-resources)\n- [🏛️ Standards \u0026 Compliance](#-standards--compliance)\n- [📌 How to Cite](#-how-to-cite)\n- [🙏 Acknowledgments](#-acknowledgments)\n\n\u003e **New: Pi implementation analyses**\n\u003e\n\u003e This repository now includes implementation-focused analyses of how they map to [Pi](https://github.com/earendil-works/pi), grounded in the actual Pi codebase with package/module references, line-numbered excerpts, and notes on architectural tradeoffs or limitations.\n\u003e\n\u003e Look for `pi.md` inside pattern folders. These writeups stay conservative: if Pi does not meaningfully implement a pattern, the analysis says so explicitly rather than forcing a match.\n\u003e\n\u003e See the [**Pi roll-up summary** (`pi.md`)](./pi.md) for a coverage heat map and one-line verdicts across all 28 patterns.\n\n**Currently available Pi analyses:**\n- Foundational: [Prompt Chaining](./foundational_design_patterns/1_prompt_chain/pi.md), [Routing](./foundational_design_patterns/2_routing/pi.md), [Parallelization](./foundational_design_patterns/3_parallelization/pi.md), [Reflection](./foundational_design_patterns/4_reflection/pi.md), [Tool Use](./foundational_design_patterns/5_tool_use/pi.md), [Planning](./foundational_design_patterns/6_planning/pi.md), [Multi-Agent Collaboration](./foundational_design_patterns/7_multi_agent_collaboration/pi.md), [ReAct](./foundational_design_patterns/8_react/pi.md), [HITL](./foundational_design_patterns/10_hitl/pi.md), [Structured Outputs](./foundational_design_patterns/11_structured_outputs/pi.md), [Computer Use](./foundational_design_patterns/12_computer_use/pi.md)\n- Reasoning: [Tree of Thoughts](./reasoning/tree_of_thoughts/pi.md), [Graph of Thoughts](./reasoning/graph_of_thoughts/pi.md), [Deep Research](./reasoning/deep_research/pi.md)\n- Reliability: [Error Recovery](./reliability/error_recovery/pi.md), [Guardrails](./reliability/guardrails/pi.md)\n- Orchestration: [Goal Management](./orchestration/goal_management/pi.md), [Subagents](./orchestration/subagents/pi.md), [Skills](./orchestration/skills/pi.md), [Agent Communication](./orchestration/agent_communication/pi.md), [MCP](./orchestration/mcp/pi.md), [Prioritization](./orchestration/prioritization/pi.md)\n- Observability: [Evaluation \u0026 Monitoring](./observability/evaluation_monitoring/pi.md), [Resource Optimization](./observability/resource_optimization/pi.md)\n- Memory: [Memory Management](./memory/memory_management/pi.md), [Context Management](./memory/context_management/pi.md)\n- Learning: [Adaptive Learning](./learning/adaptive_learning/pi.md)\n\n---\n\n## 📚 Academic Foundations\n\nThis repository implements design patterns grounded in peer-reviewed research and industry best practices. Key academic contributions include:\n\n### Core Research Papers\n\n#### **Reasoning and Acting**\n- **[ReAct: Synergizing Reasoning and Acting in Language Models](https://arxiv.org/abs/2210.03629)** (Yao et al., 2022, ICLR 2023)\n  Foundational paper demonstrating that interleaving reasoning traces with actions creates synergy superior to separate reasoning or acting approaches. Directly implemented in our [ReAct pattern](./foundational_design_patterns/8_react/).\n\n#### **Advanced Reasoning Frameworks**\n- **[Tree of Thoughts: Deliberate Problem Solving with Large Language Models](https://arxiv.org/abs/2305.10601)** (Yao et al., 2023, NeurIPS 2023)\n  Generalizes Chain-of-Thought by enabling exploration over coherent reasoning paths with self-evaluation and backtracking. Implemented in our [Tree of Thoughts pattern](./reasoning/tree_of_thoughts/).\n\n- **[Graph of Thoughts: Solving Elaborate Problems with Large Language Models](https://arxiv.org/abs/2308.09687)** (Besta et al., 2023)\n  Extends reasoning to arbitrary graph structures, enabling thought merging and non-hierarchical connections. Achieves 62% quality improvement with 31% cost reduction. Implemented in our [Graph of Thoughts pattern](./reasoning/graph_of_thoughts/).\n\n#### **Agentic RAG**\n- **[Agentic Retrieval-Augmented Generation: A Survey on Agentic RAG](https://arxiv.org/abs/2501.09136)** (Singh et al., 2025)\n  Comprehensive survey of autonomous AI agents managing retrieval strategies through reflection, planning, tool use, and multi-agent collaboration—transcending static RAG limitations. Informs our [RAG](./foundational_design_patterns/9_rag/) and [Multi-Agent](./foundational_design_patterns/7_multi_agent_collaboration/) patterns.\n\n### Research Impact\n\nThese patterns represent the evolution from:\n- **Chain-of-Thought** (linear reasoning) → **Tree of Thoughts** (branching exploration) → **Graph of Thoughts** (networked reasoning)\n- **Static RAG** (fixed retrieval) → **Agentic RAG** (autonomous, adaptive retrieval)\n- **Single-agent systems** → **Multi-agent collaboration** with specialized roles and communication protocols\n\n---\n\n## 🏗️ Repository Structure\n```\nagentic_design_patterns/\n├── foundational_design_patterns/\n│   ├── 1_prompt_chain/         # Sequential task decomposition\n│   ├── 2_routing/              # Intelligent query routing\n│   ├── 3_parallelization/      # Concurrent execution\n│   ├── 4_reflection/           # Iterative refinement\n│   ├── 5_tool_use/             # External system integration\n│   ├── 6_planning/             # Strategic task planning\n│   ├── 7_multi_agent_collaboration/  # Coordinated agents\n│   ├── 8_react/                # Reasoning and acting\n│   ├── 9_rag/                  # Retrieval-augmented generation\n│   ├── 10_hitl/                # Human-in-the-loop\n│   ├── 11_structured_outputs/  # Schema-constrained outputs\n│   └── 12_computer_use/        # Browser/UI automation\n│\n├── reasoning/                  # Advanced reasoning patterns\n│   ├── tree_of_thoughts/       # Systematic exploration\n│   ├── graph_of_thoughts/      # Non-hierarchical reasoning\n│   └── deep_research/          # Iterative research loops\n│\n├── reliability/                # Safety and resilience\n│   ├── error_recovery/         # Failure handling\n│   └── guardrails/             # Safety constraints\n│\n├── orchestration/              # Multi-agent coordination\n│   ├── goal_management/        # Objective decomposition\n│   ├── subagents/              # Orchestrator-worker topology\n│   ├── skills/                 # Agent-loadable capability packages\n│   ├── agent_communication/    # Inter-agent messaging\n│   ├── mcp/                    # Model Context Protocol\n│   └── prioritization/         # Task ranking\n│\n├── observability/              # Monitoring and optimization\n│   ├── evaluation_monitoring/  # Metrics and quality\n│   └── resource_optimization/  # Cost and performance\n│\n├── memory/                     # Context and history\n│   ├── memory_management/      # Long-term memory\n│   └── context_management/     # Context optimization\n│\n├── learning/                   # Continuous improvement\n│   └── adaptive_learning/      # Learning from feedback\n│\n├── tests/                      # Repo-level reliability smoke tests\n├── .github/workflows/          # CI workflows\n├── repo_support.py             # Shared runtime/bootstrap helper\n├── .env                        # Environment variables\n├── LICENSE                     # MIT License\n└── README.md                   # This file\n```\n\n---\n\n## 🗂️ Patterns at a Glance\n\nOne-row-per-pattern index for fast navigation. Each row links to the pattern's deep-dive directory; the Pi column links to its `pi.md` implementation analysis where available; the TS column marks patterns with a Bun/TypeScript port under `\u003cpattern\u003e/typescript/`.\n\n| # | Pattern | Category | Pi Analysis | TypeScript |\n|---|---|---|---|---|\n| 1 | [Prompt Chaining](./foundational_design_patterns/1_prompt_chain/) | Foundational | [pi](./foundational_design_patterns/1_prompt_chain/pi.md) | ✓ |\n| 2 | [Routing](./foundational_design_patterns/2_routing/) | Foundational | [pi](./foundational_design_patterns/2_routing/pi.md) | ✓ |\n| 3 | [Parallelization](./foundational_design_patterns/3_parallelization/) | Foundational | [pi](./foundational_design_patterns/3_parallelization/pi.md) | ✓ |\n| 4 | [Reflection](./foundational_design_patterns/4_reflection/) | Foundational | [pi](./foundational_design_patterns/4_reflection/pi.md) | ✓ |\n| 5 | [Tool Use](./foundational_design_patterns/5_tool_use/) | Foundational | [pi](./foundational_design_patterns/5_tool_use/pi.md) | ✓ |\n| 6 | [Planning](./foundational_design_patterns/6_planning/) | Foundational | [pi](./foundational_design_patterns/6_planning/pi.md) | ✓ |\n| 7 | [Multi-Agent Collaboration](./foundational_design_patterns/7_multi_agent_collaboration/) | Foundational | [pi](./foundational_design_patterns/7_multi_agent_collaboration/pi.md) | ✓ |\n| 8 | [ReAct](./foundational_design_patterns/8_react/) | Foundational | [pi](./foundational_design_patterns/8_react/pi.md) | ✓ |\n| 9 | [RAG](./foundational_design_patterns/9_rag/) | Foundational | — | ✓ |\n| 10 | [Human-in-the-Loop (HITL)](./foundational_design_patterns/10_hitl/) | Foundational | [pi](./foundational_design_patterns/10_hitl/pi.md) | ✓ |\n| 11 | [Structured Outputs](./foundational_design_patterns/11_structured_outputs/) | Foundational | [pi](./foundational_design_patterns/11_structured_outputs/pi.md) | ✓ |\n| 12 | [Computer Use](./foundational_design_patterns/12_computer_use/) | Foundational | [pi](./foundational_design_patterns/12_computer_use/pi.md) | ✓ |\n| 13 | [Tree of Thoughts](./reasoning/tree_of_thoughts/) | Reasoning | [pi](./reasoning/tree_of_thoughts/pi.md) | — |\n| 14 | [Graph of Thoughts](./reasoning/graph_of_thoughts/) | Reasoning | [pi](./reasoning/graph_of_thoughts/pi.md) | — |\n| 15 | [Deep Research](./reasoning/deep_research/) | Reasoning | [pi](./reasoning/deep_research/pi.md) | — |\n| 16 | [Error Recovery](./reliability/error_recovery/) | Reliability | [pi](./reliability/error_recovery/pi.md) | — |\n| 17 | [Guardrails](./reliability/guardrails/) | Reliability | [pi](./reliability/guardrails/pi.md) | — |\n| 18 | [Goal Management](./orchestration/goal_management/) | Orchestration | [pi](./orchestration/goal_management/pi.md) | — |\n| 19 | [Subagents](./orchestration/subagents/) | Orchestration | [pi](./orchestration/subagents/pi.md) | — |\n| 20 | [Skills](./orchestration/skills/) | Orchestration | [pi](./orchestration/skills/pi.md) | — |\n| 21 | [Agent Communication](./orchestration/agent_communication/) | Orchestration | [pi](./orchestration/agent_communication/pi.md) | — |\n| 22 | [MCP](./orchestration/mcp/) | Orchestration | [pi](./orchestration/mcp/pi.md) | — |\n| 23 | [Prioritization](./orchestration/prioritization/) | Orchestration | [pi](./orchestration/prioritization/pi.md) | — |\n| 24 | [Evaluation \u0026 Monitoring](./observability/evaluation_monitoring/) | Observability | [pi](./observability/evaluation_monitoring/pi.md) | — |\n| 25 | [Resource Optimization](./observability/resource_optimization/) | Observability | [pi](./observability/resource_optimization/pi.md) | — |\n| 26 | [Memory Management](./memory/memory_management/) | Memory | [pi](./memory/memory_management/pi.md) | — |\n| 27 | [Context Management](./memory/context_management/) | Memory | [pi](./memory/context_management/pi.md) | — |\n| 28 | [Adaptive Learning](./learning/adaptive_learning/) | Learning | [pi](./learning/adaptive_learning/pi.md) | — |\n\n---\n\n## 📚 Foundational Patterns\n\n### 1️⃣ [Prompt Chaining](./foundational_design_patterns/1_prompt_chain/)\n**Break complex tasks into sequential, manageable steps**\n```python\n# Transform a monolithic prompt into a chain of specialized prompts\ninput → extract_data → transform → validate → final_output\n```\n\n```mermaid\n---\ntitle: Prompt Chain — Laptop Spec to JSON\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    In([raw text:\u003cbr/\u003e'3.5 GHz octa-core,\u003cbr/\u003e16GB RAM, 1TB NVMe'])\n    Out([JSON:\u003cbr/\u003ecpu · memory · storage])\n\n    subgraph extract [\"step 1 — extraction\"]\n        P1[[prompt: spec extractor]]\n        L1{{ChatOpenAI}}\n        P1 --\u003e L1\n    end\n\n    Mid[/plain-text specs/]\n\n    subgraph transform [\"step 2 — transformation\"]\n        P2[[prompt: JSON formatter]]\n        L2{{ChatOpenAI}}\n        P2 --\u003e L2\n    end\n\n    In --\u003e P1\n    L1 --\u003e Mid --\u003e P2\n    L2 --\u003e Out\n```\n\n**When to use:**\n- Multi-step transformations (data extraction → analysis → formatting)\n- Tasks requiring intermediate validation\n- Complex workflows that benefit from decomposition\n\n**Key benefits:**\n- 🎯 Better accuracy through focused prompts\n- 🔍 Easier debugging with visible intermediate steps\n- 🔄 Reusable components across workflows\n\n[**📖 Learn More →**](./foundational_design_patterns/1_prompt_chain/README.md) · [**🔎 Pi Analysis →**](./foundational_design_patterns/1_prompt_chain/pi.md)\n\n---\n\n### 2️⃣ [Routing](./foundational_design_patterns/2_routing/)\n**Intelligently direct queries to specialized handlers**\n```python\n# Dynamic routing based on query classification\nuser_query → classifier → [technical_expert | sales_agent | support_bot]\n```\n\n```mermaid\n---\ntitle: Routing — Domain-Specific Handlers\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Q([user request])\n    R([response])\n\n    Cls{classifier\u003cbr/\u003eLLM}\n\n    subgraph handlers [\"specialist handlers\"]\n        B[booking_handler]\n        I[info_handler]\n        U[unclear_handler]\n    end\n\n    Q --\u003e Cls\n    Cls -- \"booking\" --\u003e B\n    Cls -- \"info\" --\u003e I\n    Cls -- \"unclear\" --\u003e U\n    B \u0026 I \u0026 U --\u003e R\n```\n\n**When to use:**\n- Multi-domain applications (support, sales, technical)\n- Specialized model selection (fast/cheap vs. slow/accurate)\n- Intent-based workflows requiring different processing paths\n\n**Key benefits:**\n- 💰 Cost optimization (use expensive models only when needed)\n- ⚡ Performance gains (route simple queries to fast handlers)\n- 🎨 Specialized handling (domain experts for domain queries)\n\n[**📖 Learn More →**](./foundational_design_patterns/2_routing/README.md) · [**🔎 Pi Analysis →**](./foundational_design_patterns/2_routing/pi.md)\n\n---\n\n### 3️⃣ [Parallelization](./foundational_design_patterns/3_parallelization/)\n**Execute independent operations simultaneously for dramatic speedups**\n```python\n# Sequential: 15 seconds          # Parallel: 5 seconds\ntask_a(5s) →                      task_a(5s) ↘\ntask_b(5s) →          vs.         task_b(5s) → combine → output\ntask_c(5s) → output               task_c(5s) ↗\n```\n\n```mermaid\n---\ntitle: Parallelization — Concurrent LLM Chains\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Doc([document])\n    Out([unified output])\n\n    subgraph parallel [\"RunnableParallel\"]\n        S[summarize chain]\n        Q[question-gen chain]\n        K[key-terms chain]\n    end\n\n    Syn[[synthesize]]\n\n    Doc --\u003e S \u0026 Q \u0026 K\n    S \u0026 Q \u0026 K --\u003e Syn --\u003e Out\n```\n\n**When to use:**\n- Multiple API calls (search engines, databases, external services)\n- Parallel data processing (analyze multiple documents)\n- Multi-source research or content generation\n\n**Key benefits:**\n- ⚡ 2-10x faster execution for I/O-bound tasks\n- 📈 Better resource utilization\n- 🚀 Improved user experience through reduced latency\n\n[**📖 Learn More →**](./foundational_design_patterns/3_parallelization/README.md) · [**🔎 Pi Analysis →**](./foundational_design_patterns/3_parallelization/pi.md)\n\n---\n\n### 4️⃣ [Reflection](./foundational_design_patterns/4_reflection/)\n**Iteratively improve outputs through systematic critique and refinement**\n\nOne of the four core agentic design patterns (Ng, 2024), reflection enables AI to systematically critique and improve its own outputs.\n```python\n# Single-shot: 5/10 quality        # With reflection: 8.5/10 quality\ninput → generate → done            input → generate → critique → \n                                          refine → critique → final\n```\n\n```mermaid\n---\ntitle: Reflection — Producer · Critic · Reviser Loop\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Task([write factorial n])\n    Final([final code])\n\n    subgraph loop [\"reflection loop\"]\n        P[producer LLM]\n        Draft[/draft code/]\n        Cr[critic LLM]\n        Fb[/feedback/]\n        Rv[reviser LLM]\n        P --\u003e Draft --\u003e Cr --\u003e Fb --\u003e Rv\n        Rv -. \"iterate\" .-\u003e Cr\n    end\n\n    Task --\u003e P\n    Rv --\u003e Final\n```\n\n**When to use:**\n- High-stakes content (code, legal docs, published articles)\n- Complex reasoning tasks (logic puzzles, strategic planning)\n- Quality-critical applications where \"good enough\" isn't enough\n\n**Key benefits:**\n- 🎯 50-70% higher quality scores\n- 🔍 Systematic error detection and correction\n- 🧠 Self-improving outputs without human intervention\n\n**Trade-offs:**\n- ⚠️ 3-5x higher token costs\n- ⏱️ 4-8x longer execution time\n\n[**📖 Learn More →**](./foundational_design_patterns/4_reflection/README.md) · [**🔎 Pi Analysis →**](./foundational_design_patterns/4_reflection/pi.md)\n\n---\n\n### 5️⃣ [Tool Use](./foundational_design_patterns/5_tool_use/)\n**Enable LLMs to interact with external systems and APIs**\n\nEssential for grounding LLM outputs in real-world data and actions, tool use is a foundational capability of modern agentic systems (Ng, 2024; Yao et al., 2022).\n```python\n# Without tools: Limited to training data\n# With tools: Access real-time data and take actions\nuser_query → LLM decides → call_weather_api(location) → integrate_result → response\n```\n\n```mermaid\n---\ntitle: Tool Use — Support Triage with CRM and Weather\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Case([support case:\u003cbr/\u003eCUST-1001 · Miami])\n    Resp([triage decision])\n\n    Agent{{create_agent}}\n\n    subgraph tools [\"parallel tool calls\"]\n        CRM[(CRM:\u003cbr/\u003etier · SLA)]\n        Wx[(Open-Meteo:\u003cbr/\u003eweather)]\n    end\n\n    Case --\u003e Agent\n    Agent --\u003e CRM \u0026 Wx\n    CRM \u0026 Wx --\u003e Agent\n    Agent --\u003e Resp\n```\n\n**When to use:**\n- Real-time data retrieval (weather, stock prices, news)\n- Private/proprietary data access (databases, CRM systems)\n- Precise calculations or code execution\n- External actions (send emails, update records, control devices)\n\n**Key benefits:**\n- 🌐 Access to live, dynamic information\n- 🎯 Precise calculations and data validation\n- 🔧 Integration with existing enterprise systems\n- 💰 Reduced token costs (fetch vs. embed in prompts)\n\n**Trade-offs:**\n- ⚠️ Added latency per tool call\n- 🔒 Security considerations (authentication, validation)\n\n[**📖 Learn More →**](./foundational_design_patterns/5_tool_use/README.md) · [**🔎 Pi Analysis →**](./foundational_design_patterns/5_tool_use/pi.md)\n\n---\n\n### 6️⃣ [Planning](./foundational_design_patterns/6_planning/)\n**Decompose complex goals into structured, executable action plans**\n\nA fundamental capability for agentic systems (Ng, 2024), enabling AI to decompose complex objectives strategically rather than responding reactively.\n```python\n# Without planning: Reactive, incomplete execution\n# With planning: Strategic breakdown and systematic execution\ncomplex_goal → analyze → decompose → plan_steps → execute_sequentially → final_result\n```\n\n```mermaid\n---\ntitle: Planning — Incident Response (Plan-and-Act)\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Inc([incident + context])\n    Done([resolved])\n\n    subgraph graph [\"LangGraph StateGraph\"]\n        Pl[planner_node]\n        Plan[/ordered actions/]\n        Ex[executor_node]\n        Rv{reviewer_node}\n        Pl --\u003e Plan --\u003e Ex --\u003e Rv\n        Rv -- \"next action\" --\u003e Ex\n        Rv -- \"replan\" --\u003e Pl\n    end\n\n    Inc --\u003e Pl\n    Rv -- \"complete\" --\u003e Done\n```\n\n**When to use:**\n- Multi-step workflows requiring orchestration (research reports, data pipelines)\n- Tasks with interdependent operations\n- Complex problem-solving requiring strategic thinking\n- Workflow automation (onboarding, procurement, project setup)\n\n**Key benefits:**\n- 🎯 Structured approach to complex objectives\n- 🧠 Strategic thinking vs. reactive responses\n- 🔄 Adaptability through dynamic replanning\n- 📊 Transparency into execution strategy\n\n**Trade-offs:**\n- ⚠️ Planning overhead (+20-40% tokens, 5-15s latency)\n- 🛠️ Requires sophisticated state management\n\n[**📖 Learn More →**](./foundational_design_patterns/6_planning/README.md) · [**🔎 Pi Analysis →**](./foundational_design_patterns/6_planning/pi.md)\n\n---\n\n### 7️⃣ [Multi-Agent Collaboration](./foundational_design_patterns/7_multi_agent_collaboration/)\n**Coordinate multiple specialized agents to solve complex tasks**\n\nMulti-agent systems, highlighted in both the Agentic RAG survey (Singh et al., 2025) and production deployments (LangChain, 2024), enable sophisticated task distribution and specialized expertise.\n```python\n# Agents as a team: specialize roles + coordinate communication\nuser_goal → manager/planner → [researcher | coder | designer | writer | reviewer] → synthesize → final_output\n```\n\n```mermaid\n---\ntitle: Multi-Agent Collaboration — Research Report Pipeline\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Goal([research goal])\n    Out([final report])\n\n    subgraph orchestration [\"orchestration\"]\n        Pl[planner_agent]\n        Plan[/plan steps/]\n        Ex{executor_agent}\n        Pl --\u003e Plan --\u003e Ex\n    end\n\n    subgraph specialists [\"specialist agents\"]\n        R[\"research_agent\u003cbr/\u003earXiv · Tavily · Wiki\"]\n        W[writer_agent]\n        Ed[editor_agent]\n    end\n\n    Goal --\u003e Pl\n    Ex --\u003e R \u0026 W \u0026 Ed\n    R \u0026 W \u0026 Ed -- \"result\" --\u003e Ex\n    Ex --\u003e Out\n```\n\n**When to use:**\n- Complex tasks requiring diverse expertise (research + writing + QA)\n- Workflows with distinct stages (research → draft → edit → package)\n- Tool-specialized roles (web search, code execution, image generation)\n- Quality-critical pipelines (critic/reviewer loops)\n\n**Key benefits:**\n- 🧩 Modularity: build and improve one role at a time\n- 🛡️ Robustness: reviewers catch errors / reduce hallucinations\n- ⚡ Parallelism: split independent workstreams for speed\n- ♻️ Reuse: agents can be reused across multiple products\n\n**Common collaboration models:**\n- Sequential handoffs (linear pipeline)\n- Supervisor/manager orchestration (hierarchical)\n- Parallel workstreams (merge results)\n- Debate/consensus (evaluate options)\n- Critic–reviewer (quality enforcement)\n- Network/all-to-all (exploratory, less predictable)\n- Custom hybrids (fit domain constraints)\n\n[**📖 Learn More →**](./foundational_design_patterns/7_multi_agent_collaboration/README.md) · [**🔎 Pi Analysis →**](./foundational_design_patterns/7_multi_agent_collaboration/pi.md)\n\n---\n\n### 8️⃣ [ReAct (Reasoning and Acting)](./foundational_design_patterns/8_react/) (Yao et al., 2022)\n**Interleave reasoning traces with tool execution for adaptive problem-solving**\n\nOriginally introduced by Yao et al. (2022) in the paper \"ReAct: Synergizing Reasoning and Acting in Language Models,\" this pattern demonstrates that interleaving reasoning traces with task-specific actions creates superior synergy compared to treating reasoning and acting as separate capabilities.\n\n```python\n# Traditional: Direct action without explicit reasoning\nuser_query → tool_call → response\n\n# ReAct: Explicit reasoning + grounded actions\nuser_query → Thought (reason) → Action (tool) → Observation (result) →\n             Thought (adapt) → Action → Observation → Final Answer\n```\n\n```mermaid\n---\ntitle: ReAct — Reason · Act · Observe Loop\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Q([query])\n    F([final answer])\n\n    subgraph loop [\"ReAct cycle\"]\n        T[Thought\u003cbr/\u003ereasoning trace]\n        A[Action\u003cbr/\u003etool call]\n        O[/Observation/]\n        T --\u003e A --\u003e O --\u003e T\n    end\n\n    Q --\u003e T\n    T -. \"enough info\" .-\u003e F\n```\n\n**When to use:**\n- Multi-step research requiring information lookup and verification\n- Complex problem-solving where the solution path isn't predetermined\n- Tasks requiring adaptation based on intermediate results\n- Debugging and exploratory analysis\n- Need transparent reasoning for interpretability\n\n**Key benefits:**\n- 🧠 Explicit reasoning traces improve decision quality\n- 🎯 Grounded actions reduce hallucinations\n- 🔄 Dynamic adaptation based on observations\n- 🔍 Transparent and debuggable decision-making\n- ✓ Self-correction and error recovery\n\n**Trade-offs:**\n- ⚠️ Higher latency (multiple reasoning + action cycles)\n- 💰 Increased token costs (reasoning traces + tool calls)\n- 🔁 Risk of unproductive loops without iteration limits\n\n[**📖 Learn More →**](./foundational_design_patterns/8_react/README.md) · [**🔎 Pi Analysis →**](./foundational_design_patterns/8_react/pi.md)\n\n---\n\n### 9️⃣ [RAG (Retrieval-Augmented Generation)](./foundational_design_patterns/9_rag/)\n**Ground LLM responses with relevant external knowledge**\n\nThis approach, enhanced by agentic capabilities as described in the recent survey by Singh et al. (2025), enables autonomous AI agents to dynamically manage retrieval strategies through reflection, planning, and tool use—transcending the limitations of static RAG workflows.\n\n```python\n# Without RAG: Limited to training data\nuser_query → LLM → response (may hallucinate)\n\n# With RAG: Knowledge-grounded responses\nuser_query → retrieve_relevant_docs → augment_context → LLM → grounded_response\n```\n\n```mermaid\n---\ntitle: RAG — Hybrid Retrieval + Grounded Generation\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Q([password reset question])\n    Ans([grounded answer + sources])\n\n    subgraph retrieval [\"retrieval\"]\n        Idx[(support docs\u003cbr/\u003evector store)]\n        Ret[hybrid retriever\u003cbr/\u003eBM25 + dense]\n        Ctx[/top-k chunks + citations/]\n        Idx -.-\u003e Ret --\u003e Ctx\n    end\n\n    subgraph generation [\"generation\"]\n        LLM{{ChatOpenAI}}\n    end\n\n    Q --\u003e Ret\n    Ctx --\u003e LLM\n    Q -. \"+ question\" .-\u003e LLM\n    LLM --\u003e Ans\n```\n\n**When to use:**\n- Dynamic or frequently updated information (documentation, product catalogs)\n- Private/proprietary knowledge bases\n- Domain-specific expertise beyond LLM training\n- Reducing hallucinations with factual grounding\n\n**Key benefits:**\n- 📚 Access to current and proprietary information\n- 🎯 Reduced hallucinations through grounding\n- 💰 No retraining needed for knowledge updates\n- 🔍 Source attribution and transparency\n\n[**📖 Learn More →**](./foundational_design_patterns/9_rag/README.md)\n\n---\n\n### 🔟 [Human-in-the-Loop (HITL)](./foundational_design_patterns/10_hitl/)\n**Integrate human oversight and approval into AI workflows**\n\nThe Human-in-the-Loop (HITL) pattern represents a pivotal strategy in agentic AI systems, deliberately interweaving the unique strengths of human cognition—such as judgment, creativity, and nuanced understanding—with the computational power and efficiency of AI. This strategic integration ensures that AI operates within ethical boundaries, adheres to safety protocols, and achieves its objectives with optimal effectiveness.\n\n```python\n# Without HITL: Fully automated\nagent_action → execute → result\n\n# With HITL: Human checkpoint\nagent_proposal → human_review → [approve|reject|modify] → execute → result\n```\n\n```mermaid\n---\ntitle: Human-in-the-Loop — Content Approval\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Brief([content brief])\n    Pub([published])\n    Audit[(audit_log.json)]\n\n    Gen[LLM draft]\n    Draft[/draft/]\n    H{human review}\n\n    Brief --\u003e Gen --\u003e Draft --\u003e H\n    H -- \"approve\" --\u003e Pub\n    H -- \"edit\" --\u003e Pub\n    H -- \"reject\" --\u003e Gen\n    H -. \"log decision\" .-\u003e Audit\n```\n\n**When to use:**\n- High-stakes decisions (financial transactions, legal actions, sentencing)\n- Quality-critical content (publications, customer communications)\n- Compliance and regulatory requirements\n- Complex scenarios requiring nuanced judgment\n- Learning from human expertise for continuous improvement\n- Tasks involving ambiguity beyond reliable LLM capabilities\n\n**Key aspects:**\n- **Human Oversight**: Monitoring AI performance via dashboards/logs to ensure guideline adherence\n- **Intervention \u0026 Correction**: Human operators rectify errors or guide agents in ambiguous scenarios\n- **Feedback for Learning**: Human preferences inform agent learning (e.g., RLHF)\n- **Decision Augmentation**: AI provides analysis/recommendations; humans make final decisions\n- **Human-Agent Collaboration**: Cooperative interaction leveraging respective strengths\n- **Escalation Policies**: Protocols dictating when agents escalate tasks to humans\n\n**Key benefits:**\n- 🛡️ Safety and risk mitigation in critical domains\n- ✅ Quality assurance and compliance\n- 🎓 Continuous learning from human feedback\n- 🤝 Building user trust through transparency\n- 🎯 Nuanced judgment in complex scenarios\n- 🔄 Feedback loops for ongoing improvement\n\n**Practical applications:**\n- **Content Moderation**: AI filters at scale; humans review ambiguous cases\n- **Autonomous Driving**: AI handles most tasks; humans take control in complex situations\n- **Financial Fraud Detection**: AI flags patterns; human analysts investigate high-risk alerts\n- **Legal Document Review**: AI scans/categorizes; lawyers review for accuracy and implications\n- **Customer Support**: Chatbots handle routine queries; complex/emotional cases escalate to humans\n- **Data Labeling**: Humans provide ground truth labels for training datasets\n- **Generative AI Refinement**: Human editors review/refine LLM outputs for quality and brand alignment\n- **Autonomous Networks**: AI analyzes KPIs; humans approve critical network changes\n\n**Trade-offs \u0026 caveats:**\n- ⚠️ **Scalability limitations**: Human oversight cannot handle millions of tasks\n- 👥 **Expertise dependency**: Effectiveness relies on skilled domain experts\n- 🔒 **Privacy concerns**: Sensitive information requires anonymization\n- 💰 **Cost considerations**: Human review adds operational overhead\n\n**\"Human-on-the-loop\" variation:**\nIn this approach, human experts define overarching policies, while AI handles immediate actions to ensure compliance (e.g., automated trading within human-defined rules, call center routing based on manager-set policies).\n\n[**📖 Learn More →**](./foundational_design_patterns/10_hitl/README.md) · [**🔎 Pi Analysis →**](./foundational_design_patterns/10_hitl/pi.md)\n\n---\n\n### 1️⃣1️⃣ [Structured Outputs](./foundational_design_patterns/11_structured_outputs/)\n**Enforce schema-valid LLM outputs for reliable downstream automation**\n```python\n# Naive parsing (brittle)\ntext → prompt_json_request → parse_string_json → runtime_fail\n\n# Structured outputs (reliable)\ntext → response_schema(Pydantic/JSON Schema) → validated_object → safe_automation\n```\n\n```mermaid\n---\ntitle: Structured Outputs — Schema-Enforced Extraction\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Inv([raw invoice text:\u003cbr/\u003e'Vendor: Northwind…'])\n\n    subgraph naive [\"naive path (anti-pattern)\"]\n        N[prompt + regex parse]\n        Fail([runtime error:\u003cbr/\u003emissing / wrong fields])\n        N --\u003e Fail\n    end\n\n    subgraph typed [\"schema-enforced path\"]\n        S[[ExtractedInvoice\u003cbr/\u003ePydantic schema]]\n        LLM{{ChatOpenAI\u003cbr/\u003e.with_structured_output}}\n        Valid([typed object:\u003cbr/\u003evendor · total · due_date])\n        S --\u003e LLM --\u003e Valid\n    end\n\n    Inv --\u003e N\n    Inv --\u003e S\n```\n\n**Key benefits:** Schema guarantees, lower parsing failures, safer agent loops\n\n[**📖 Learn More →**](./foundational_design_patterns/11_structured_outputs/README.md) · [**🔎 Pi Analysis →**](./foundational_design_patterns/11_structured_outputs/pi.md)\n\n---\n\n### 1️⃣2️⃣ [Computer Use](./foundational_design_patterns/12_computer_use/)\n**Automate browser/UI workflows with explicit safety controls**\n```python\n# Observe → Think → Act loop for UI tasks\nscreenshot/state → reasoning → ui_action(click/type/navigate) → observation → iterate\n```\n\n```mermaid\n---\ntitle: Computer Use — Screenshot · Think · Act · Observe\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Goal([find LLM info\u003cbr/\u003eon Wikipedia])\n    Done([result])\n\n    subgraph loop [\"control loop\"]\n        Snap[/screenshot/]\n        Think[LLM reasoning]\n        Act[click · type · fetch]\n        Obs[/new page state/]\n        Snap --\u003e Think --\u003e Act --\u003e Obs --\u003e Snap\n    end\n\n    Goal --\u003e Snap\n    Think -. \"task complete\" .-\u003e Done\n```\n\n**Key benefits:** Legacy-system automation, UI QA workflows, non-API task coverage\n\n[**📖 Learn More →**](./foundational_design_patterns/12_computer_use/README.md) · [**🔎 Pi Analysis →**](./foundational_design_patterns/12_computer_use/pi.md)\n\n---\n\n## 🧠 Advanced Reasoning Patterns\n\n### [Tree of Thoughts](./reasoning/tree_of_thoughts/) (Yao et al., 2023)\n**Explore multiple reasoning paths systematically**\n\nIntroduced at NeurIPS 2023, Tree of Thoughts (ToT) generalizes Chain-of-Thought prompting by enabling LLMs to explore multiple reasoning paths, self-evaluate choices, and backtrack when necessary—enabling deliberate problem solving for complex tasks.\n\n```python\n# Chain of Thought: Linear reasoning\ninput → step1 → step2 → step3 → answer\n\n# Tree of Thoughts: Branching exploration\ninput → [thought1, thought2, thought3] → evaluate → expand_best →\n        [refined_thoughts] → evaluate → solution\n```\n\n```mermaid\n---\ntitle: Tree of Thoughts — Branching Reasoning with Backtrack\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart TB\n    Q([problem])\n    Sol([solution])\n\n    Q --\u003e Ta[thought a] \u0026 Tb[thought b] \u0026 Tc[thought c]\n    Ta \u0026 Tb \u0026 Tc --\u003e E1{evaluate}\n    E1 -- \"best\" --\u003e Ta1[a · 1] \u0026 Ta2[a · 2]\n    Ta1 \u0026 Ta2 --\u003e E2{evaluate}\n    E2 --\u003e Sol\n    E1 -. \"backtrack\" .-\u003e Tb\n```\n\n**Key benefits:** Better solutions through systematic exploration, backtracking capability, transparent decision trees\n\n[**📖 Learn More →**](./reasoning/tree_of_thoughts/README.md) · [**🔎 Pi Analysis →**](./reasoning/tree_of_thoughts/pi.md)\n\n---\n\n### [Graph of Thoughts](./reasoning/graph_of_thoughts/) (Besta et al., 2023)\n**Enable non-hierarchical thought connections and merging**\n\nBuilding on ToT, Graph of Thoughts extends the reasoning paradigm from hierarchical trees to arbitrary graphs, enabling non-linear thought connections and aggregation—achieving 62% better quality on sorting tasks while reducing costs by 31% (Besta et al., 2023).\n\n```python\n# Thoughts can reference and build on ANY other thought (not just parent-child)\ninput → generate_perspectives → connect_thoughts → aggregate → synthesis\n```\n\n```mermaid\n---\ntitle: Graph of Thoughts — Non-Hierarchical Aggregation\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Q([input])\n    S([synthesis])\n\n    Q --\u003e Pa[perspective a] \u0026 Pb[perspective b] \u0026 Pc[perspective c]\n    Pa \u0026 Pb --\u003e R[refine: a × b]\n    Pa \u0026 Pb \u0026 Pc \u0026 R --\u003e Agg((aggregate))\n    Agg --\u003e S\n```\n\n**Key benefits:** Multi-perspective analysis, thought merging, flexible reasoning paths\n\n[**📖 Learn More →**](./reasoning/graph_of_thoughts/README.md) · [**🔎 Pi Analysis →**](./reasoning/graph_of_thoughts/pi.md)\n\n---\n\n### [Deep Research](./reasoning/deep_research/)\n**Run iterative research loops with gap-driven follow-up queries**\n```python\n# Plan → Search → Read → Reflect → Follow-up → Synthesize\nquestion → sub_queries → retrieve_sources → identify_gaps → refine_queries → cited_output\n```\n\n```mermaid\n---\ntitle: Deep Research — Iterative Gap-Driven Loop\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Q([research question])\n    Sy([cited synthesis])\n\n    subgraph loop [\"research loop\"]\n        Pl[plan sub-queries]\n        Se[(search sources)]\n        Rd[read \u0026 extract]\n        Rf{gaps?}\n        Pl --\u003e Se --\u003e Rd --\u003e Rf\n        Rf -- \"yes — refine\" --\u003e Pl\n    end\n\n    Q --\u003e Pl\n    Rf -- \"no\" --\u003e Sy\n```\n\n**Key benefits:** Better coverage, fewer blind spots, stronger citation quality\n\n[**📖 Learn More →**](./reasoning/deep_research/README.md) · [**🔎 Pi Analysis →**](./reasoning/deep_research/pi.md)\n\n---\n\n## 🛡️ Reliability Patterns\n\n### [Error Recovery](./reliability/error_recovery/)\n**Gracefully handle failures and self-correct**\n```python\n# Detect → Diagnose → Recover → Verify\noperation → [success | failure] → classify_error → [retry | fallback | self_correct] → verify\n```\n\n```mermaid\n---\ntitle: Error Recovery — Classify · Recover · Verify\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Op[operation]\n    OK([success])\n\n    R{result}\n    Cls[classify error]\n\n    subgraph recover [\"recovery strategies\"]\n        Rt[retry]\n        Fb[fallback]\n        Sc[self-correct LLM]\n    end\n\n    V{verify}\n\n    Op --\u003e R\n    R -- \"ok\" --\u003e OK\n    R -- \"fail\" --\u003e Cls\n    Cls -- \"transient\" --\u003e Rt\n    Cls -- \"known\" --\u003e Fb\n    Cls -- \"llm\" --\u003e Sc\n    Rt \u0026 Fb \u0026 Sc --\u003e V\n    V -- \"still bad\" --\u003e Cls\n    V -- \"good\" --\u003e OK\n```\n\n**Key benefits:** Resilience, graceful degradation, automatic self-healing, reduced downtime\n\n[**📖 Learn More →**](./reliability/error_recovery/README.md) · [**🔎 Pi Analysis →**](./reliability/error_recovery/pi.md)\n\n---\n\n### [Guardrails](./reliability/guardrails/)\n**Enforce safety constraints and compliance**\n```python\n# Multi-layer validation\ninput → validate → process → validate_output → [pass | block] → log\n```\n\n```mermaid\n---\ntitle: Guardrails — Multi-Layer Validation\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    In([user input])\n    Ok([response])\n    Log[(audit log)]\n\n    Vi{input validate}\n    Pr[process LLM]\n    Vo{output validate}\n    Bi([blocked: input])\n    Bo([blocked: output])\n\n    In --\u003e Vi\n    Vi -- \"fail\" --\u003e Bi\n    Vi -- \"pass\" --\u003e Pr --\u003e Vo\n    Vo -- \"fail\" --\u003e Bo\n    Vo -- \"pass\" --\u003e Ok\n    Bi \u0026 Bo \u0026 Ok -.-\u003e Log\n```\n\n**Key benefits:** Safety assurance, compliance, brand protection, risk reduction\n\n[**📖 Learn More →**](./reliability/guardrails/README.md) · [**🔎 Pi Analysis →**](./reliability/guardrails/pi.md)\n\n---\n\n## 🎯 Orchestration Patterns\n\n### [Goal Management](./orchestration/goal_management/)\n**Decompose and track complex objectives**\n```python\n# Hierarchical decomposition with progress tracking\ncomplex_goal → decompose → [subgoal1, subgoal2, subgoal3] →\n              track_dependencies → execute → monitor → replan\n```\n\n```mermaid\n---\ntitle: Goal Management — Hierarchical Decomposition\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    G([goal])\n    Done([complete])\n\n    De[decompose]\n\n    subgraph subs [\"subgoals\"]\n        S1[subgoal 1]\n        S2[subgoal 2]\n        S3[subgoal 3]\n    end\n\n    Tr[/dependency graph/]\n    Ex[execute]\n    M{monitor}\n    Rp[replan]\n\n    G --\u003e De\n    De --\u003e S1 \u0026 S2 \u0026 S3\n    S1 \u0026 S2 \u0026 S3 --\u003e Tr --\u003e Ex --\u003e M\n    M -- \"drift\" --\u003e Rp --\u003e De\n    M -- \"on track\" --\u003e Done\n```\n\n**Key benefits:** Structured execution, progress visibility, adaptive planning, resource optimization\n\n[**📖 Learn More →**](./orchestration/goal_management/README.md) · [**🔎 Pi Analysis →**](./orchestration/goal_management/pi.md)\n\n---\n\n### [Subagents (Orchestrator-Worker)](./orchestration/subagents/)\n**Spawn focused subagents with isolated context and structured summaries**\n```python\nlead_agent → decompose_task → spawn_workers_parallel → structured_summaries → synthesize\n```\n\n```mermaid\n---\ntitle: Subagents — Orchestrator · Worker\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    T([task])\n    Syn([synthesis])\n\n    Ld[lead agent]\n    D[decompose]\n\n    subgraph workers [\"isolated workers\"]\n        W1[\"worker 1\u003cbr/\u003eown context\"]\n        W2[\"worker 2\u003cbr/\u003eown context\"]\n        W3[\"worker 3\u003cbr/\u003eown context\"]\n    end\n\n    Sum[/structured summaries/]\n\n    T --\u003e Ld --\u003e D\n    D --\u003e W1 \u0026 W2 \u0026 W3\n    W1 \u0026 W2 \u0026 W3 --\u003e Sum --\u003e Ld\n    Ld --\u003e Syn\n```\n\n**Key benefits:** Context isolation, parallel throughput, cleaner synthesis\n\n[**📖 Learn More →**](./orchestration/subagents/README.md) · [**🔎 Pi Analysis →**](./orchestration/subagents/pi.md)\n\n---\n\n### [Skills](./orchestration/skills/)\n**Load capability packages on demand via metadata-first discovery**\n```python\nskill_catalog(metadata) → select_relevant_skill → load_SKILL_body → execute\n```\n\n```mermaid\n---\ntitle: Skills — Metadata-First Discovery\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Q([task])\n    Out([result])\n\n    Cat[(skill catalog\u003cbr/\u003emetadata only)]\n    Sel{select skill?}\n    Load[/load SKILL body/]\n    Ex[execute]\n\n    Q --\u003e Sel\n    Cat -.-\u003e Sel\n    Sel -- \"match\" --\u003e Load --\u003e Ex --\u003e Out\n    Sel -- \"no match\" --\u003e Out\n```\n\n**Key benefits:** Tool-scaling beyond flat lists, lower prompt load, modular capabilities\n\n[**📖 Learn More →**](./orchestration/skills/README.md) · [**🔎 Pi Analysis →**](./orchestration/skills/pi.md)\n\n---\n\n### [Agent Communication (A2A)](./orchestration/agent_communication/)\n**Enable agents to coordinate through message passing**\n```python\n# Direct messaging, pub-sub, negotiation protocols\nagent1 → message → agent2 → response → agent1\n```\n\n```mermaid\n---\ntitle: Agent Communication — Message Bus\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    A1[agent A]\n    A2[agent B]\n    A3[agent C]\n    Bus(((message bus\u003cbr/\u003edirect · pub-sub)))\n\n    A1 -- \"request\" --\u003e Bus\n    Bus -- \"deliver\" --\u003e A2\n    Bus -- \"broadcast\" --\u003e A3\n    A2 \u0026 A3 -- \"response\" --\u003e Bus\n    Bus -- \"deliver\" --\u003e A1\n```\n\n**Key benefits:** Loose coupling, dynamic discovery, scalability, fault tolerance\n\n[**📖 Learn More →**](./orchestration/agent_communication/README.md) · [**🔎 Pi Analysis →**](./orchestration/agent_communication/pi.md)\n\n---\n\n### [Model Context Protocol (MCP)](./orchestration/mcp/)\n**Standardized tool and resource integration**\n```python\n# USB for AI: Standard interface for tools/data\nLLM → discover_tools → invoke_tool(params) → receive_result → integrate\n```\n\n```mermaid\n---\ntitle: MCP — Model Context Protocol\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    LLM{{LLM client}}\n\n    subgraph servers [\"MCP servers\"]\n        Fs[(filesystem)]\n        Db[(database)]\n        Ws[(web search)]\n    end\n\n    LLM -- \"discover\" --\u003e Fs \u0026 Db \u0026 Ws\n    LLM -- \"invoke(tool, args)\" --\u003e Fs\n    Fs -- \"result\" --\u003e LLM\n```\n\n**Key benefits:** Standardization, reusability, interoperability, composability\n\n[**📖 Learn More →**](./orchestration/mcp/README.md) · [**🔎 Pi Analysis →**](./orchestration/mcp/pi.md)\n\n---\n\n### [Prioritization](./orchestration/prioritization/)\n**Optimize task ordering and resource allocation**\n```python\n# Multi-criteria scoring with dynamic rebalancing\ntasks → score(urgency, impact, effort) → rank → schedule → execute\n```\n\n```mermaid\n---\ntitle: Prioritization — Multi-Criteria Scoring\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    T([tasks])\n    Sc[score:\u003cbr/\u003eurgency · impact · effort]\n    Rk[rank]\n    Sch[schedule]\n    Ex[execute]\n    Rb{rebalance?}\n\n    T --\u003e Sc --\u003e Rk --\u003e Sch --\u003e Ex --\u003e Rb\n    Rb -- \"drift\" --\u003e Sc\n    Rb -- \"ok\" --\u003e Ex\n```\n\n**Key benefits:** Resource optimization, deadline adherence, fairness, efficiency\n\n[**📖 Learn More →**](./orchestration/prioritization/README.md) · [**🔎 Pi Analysis →**](./orchestration/prioritization/pi.md)\n\n---\n\n## 📊 Observability Patterns\n\n### [Evaluation \u0026 Monitoring](./observability/evaluation_monitoring/)\n**Track performance and quality metrics**\n```python\n# Quantitative + qualitative metrics\noperation → collect_metrics → evaluate_quality → aggregate → alert → visualize\n```\n\n```mermaid\n---\ntitle: Evaluation \u0026 Monitoring — Metrics + Quality\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Op[operation]\n\n    subgraph collect [\"data collection\"]\n        Met[(metrics)]\n        Q[LLM-as-judge]\n    end\n\n    Agg[aggregate]\n    Al{alert?}\n    Dash([dashboard])\n    Pg([page oncall])\n\n    Op --\u003e Met\n    Op --\u003e Q\n    Met \u0026 Q --\u003e Agg --\u003e Al\n    Al -- \"ok\" --\u003e Dash\n    Al -- \"regression\" --\u003e Pg\n```\n\n**Key benefits:** Visibility, early detection, data-driven decisions, continuous improvement\n\n[**📖 Learn More →**](./observability/evaluation_monitoring/README.md) · [**🔎 Pi Analysis →**](./observability/evaluation_monitoring/pi.md)\n\n---\n\n### [Resource Optimization](./observability/resource_optimization/)\n**Reduce costs and improve performance**\n```python\n# Caching, batching, model routing\nrequest → [cache_hit | cache_miss] → [cheap_model | expensive_model] → optimize\n```\n\n```mermaid\n---\ntitle: Resource Optimization — Cache + Model Routing\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Req([request])\n    Out([response])\n\n    Ca{cache?}\n    Hit([cached])\n    Cls{classify\u003cbr/\u003ecomplexity}\n\n    subgraph models [\"model tier\"]\n        Ch[cheap: haiku]\n        Ex[expensive: opus]\n    end\n\n    Req --\u003e Ca\n    Ca -- \"hit\" --\u003e Hit --\u003e Out\n    Ca -- \"miss\" --\u003e Cls\n    Cls -- \"simple\" --\u003e Ch\n    Cls -- \"hard\" --\u003e Ex\n    Ch \u0026 Ex --\u003e Out\n```\n\n**Key benefits:** 65-80% cost reduction, faster responses, better UX\n\n[**📖 Learn More →**](./observability/resource_optimization/README.md) · [**🔎 Pi Analysis →**](./observability/resource_optimization/pi.md)\n\n---\n\n## 🧩 Memory Patterns\n\n### [Memory Management](./memory/memory_management/)\n**Maintain conversation history and long-term memory**\n```python\n# Buffer + semantic memory\ninteraction → store → [buffer_memory | vector_memory] → retrieve_relevant → use\n```\n\n```mermaid\n---\ntitle: Memory Management — Buffer + Semantic\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Int([interaction])\n    Use([context-aware response])\n\n    St[store]\n\n    subgraph stores [\"memory stores\"]\n        Bf[(buffer:\u003cbr/\u003erecent turns)]\n        Vm[(vector:\u003cbr/\u003esemantic)]\n    end\n\n    Rt[retrieve relevant]\n\n    Int --\u003e St\n    St --\u003e Bf \u0026 Vm\n    Bf \u0026 Vm --\u003e Rt --\u003e Use\n```\n\n**Key benefits:** Context retention, personalization, learning from history\n\n[**📖 Learn More →**](./memory/memory_management/README.md) · [**🔎 Pi Analysis →**](./memory/memory_management/pi.md)\n\n---\n\n### [Context Management](./memory/context_management/)\n**Optimize context window usage**\n```python\n# Dynamic selection and compression\ncontent → score_relevance → compress → fit_window → optimize\n```\n\n```mermaid\n---\ntitle: Context Management — Score · Compress · Fit\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    C([many docs])\n    LLM{{LLM}}\n\n    Sc[score relevance]\n    Top[/top-k/]\n    Cp[compress / summarize]\n    Fit[/fit window/]\n\n    C --\u003e Sc --\u003e Top --\u003e Cp --\u003e Fit --\u003e LLM\n```\n\n**Key benefits:** 70-90% cost reduction, focused responses, better performance\n\n[**📖 Learn More →**](./memory/context_management/README.md) · [**🔎 Pi Analysis →**](./memory/context_management/pi.md)\n\n---\n\n## 🎓 Learning Patterns\n\n### [Adaptive Learning](./learning/adaptive_learning/)\n**Improve through feedback and continuous learning**\n```python\n# Learn from outcomes\naction → feedback → analyze_patterns → adapt_strategy → improve\n```\n\n```mermaid\n---\ntitle: Adaptive Learning — Feedback Loop\n---\n%%{init: {'look':'handDrawn','theme':'base','themeVariables':{'background':'#f5ecd9','primaryColor':'#ede0bd','primaryBorderColor':'#6b4423','primaryTextColor':'#3e2723','lineColor':'#6b4423','clusterBkg':'#efe5cd','clusterBorder':'#c5b393','fontFamily':'Caveat, Patrick Hand, cursive'}}}%%\nflowchart LR\n    Ac([action])\n    Im([improved policy])\n\n    Fb[/feedback:\u003cbr/\u003ereward · critique/]\n    An[analyze patterns]\n    St[update strategy]\n\n    Ac --\u003e Fb --\u003e An --\u003e St --\u003e Im\n    Im -. \"next action\" .-\u003e Ac\n```\n\n**Key benefits:** Continuous improvement, personalization, domain adaptation\n\n[**📖 Learn More →**](./learning/adaptive_learning/README.md) · [**🔎 Pi Analysis →**](./learning/adaptive_learning/pi.md)\n\n---\n\n## 🚀 Quick Start\n\n### Prerequisites\n```bash\n# Python 3.11 or higher\npython --version\n\n# Install uv \ncurl -LsSf https://astral.sh/uv/install.sh | sh\n```\n\n### Installation\n```bash\n# Clone the repository\ngit clone https://github.com/gtesei/agentic_design_patterns.git\ncd agentic_design_patterns\n\n# Set up shared environment\necho \"OPENAI_API_KEY=your_api_key_here\" \u003e .env\n```\n\n### Repository Runtime Notes\n\n- The repository requires **Python 3.11+**.\n- Each pattern folder has its own `pyproject.toml`, so run `uv sync` inside the pattern you want to execute.\n- Example scripts now use a shared bootstrap helper in `repo_support.py` to:\n  - locate the repo root\n  - load the root `.env`\n  - make the repo importable from any pattern folder\n- Set `OPENAI_MODEL` in your environment if you want to override the default example model:\n\n```bash\nexport OPENAI_MODEL=gpt-4o-mini\n```\n\n- If you are behind a corporate SSL interception proxy, SSL bypass is now **opt-in**:\n\n```bash\nexport AGENTIC_DISABLE_SSL=1\n```\n\n### Run Your First Pattern\n\nPython remains the canonical track. All current foundational patterns also include a Bun/TypeScript port under `\u003cpattern\u003e/typescript/`.\n\n```bash\n# Python\ncd foundational_design_patterns/3_parallelization\n[uv sync]\nuv run python src/parallelization.py\n\n# TypeScript\ncd foundational_design_patterns/3_parallelization/typescript\n[bun install]\nbash run.sh\n```\n\nFoundational patterns with both Python and TypeScript implementations currently live under:\n\n- `foundational_design_patterns/1_prompt_chain`\n- `foundational_design_patterns/2_routing`\n- `foundational_design_patterns/3_parallelization`\n- `foundational_design_patterns/4_reflection`\n- `foundational_design_patterns/5_tool_use`\n- `foundational_design_patterns/6_planning`\n- `foundational_design_patterns/7_multi_agent_collaboration`\n- `foundational_design_patterns/8_react`\n- `foundational_design_patterns/9_rag`\n- `foundational_design_patterns/10_hitl`\n- `foundational_design_patterns/11_structured_outputs`\n- `foundational_design_patterns/12_computer_use`\n\nFor TypeScript workspace conventions, coverage, and runtime details, see [typescript_base/TYPESCRIPT.md](./typescript_base/TYPESCRIPT.md).\n\n### Reliability And Smoke Tests\n\nUse these from the repo root:\n\n```bash\n# Python foundational offline smoke\nbash scripts/run_demos_smoke.sh --mode basic\n\n# TypeScript foundational offline smoke\nbash scripts/run_demos_smoke_typescript.sh --mode basic\n```\n\n### CI\n\nGitHub Actions runs the reliability gate on pushes and pull requests:\n\n- `.github/workflows/reliability-gate.yml`\n- Python shared-runtime smoke via `unittest`\n- foundational TypeScript type-checks via `bun --bun tsc --noEmit`\n- foundational TypeScript offline smoke via `scripts/run_demos_smoke_typescript.sh --mode basic`\n\n---\n\n## 🗺️ Pattern Selection Guide\n\n### Choose Your Pattern Based on Your Needs:\n\n**Need speed?** → **Routing** + **Parallelization** + **Resource Optimization** (caching, batching)\n\n**Need quality?** → **Reflection** + **RAG** (grounded knowledge) + **Evaluation \u0026 Monitoring**\n\n**Need cost optimization?** → **Routing** + **Resource Optimization** (65-80% savings) + **Context Management**\n\n**Need both speed AND quality?** → **Parallelization** + **Prompt Chaining** + **RAG**\n\n**Complex multi-step workflow?** → **Prompt Chaining** + **Planning** + **Goal Management**\n\n**Independent concurrent tasks?** → **Parallelization** will give you massive speedups\n\n**High-stakes output?** → **Reflection** + **HITL** (human approval) + **Guardrails** (safety)\n\n**External system integration?** → **Tool Use** + **MCP** (standardized protocols)\n\n**Multi-step automation?** → **Planning** + **Goal Management** + **Agent Communication**\n\n**Multiple roles working together?** → **Multi-Agent Collaboration** + **Agent Communication** (A2A)\n\n**Exploratory multi-step tasks?** → **ReAct** (reasoning + actions) or **Tree of Thoughts** (exploration)\n\n**Need transparent decision-making?** → **ReAct** (explicit reasoning) + **Evaluation \u0026 Monitoring**\n\n**Need strict machine-readable outputs?** → **Structured Outputs** + **Guardrails**\n\n**Need UI/browser automation?** → **Computer Use** + **HITL**\n\n**Need iterative cited synthesis?** → **Deep Research** + **RAG**\n\n**Need scalable multi-capability agents?** → **Subagents** + **Skills**\n\n**Knowledge-grounded responses?** → **RAG** retrieves relevant documents before generation\n\n**Complex reasoning tasks?** → **Tree of Thoughts** (systematic) or **Graph of Thoughts** (multi-perspective)\n\n**Production reliability?** → **Error Recovery** + **Guardrails** + **Evaluation \u0026 Monitoring**\n\n**Long conversations?** → **Memory Management** + **Context Management** (optimize windows)\n\n**Continuous improvement?** → **Adaptive Learning** + **Evaluation \u0026 Monitoring** (feedback loops)\n\n**Resource constraints?** → **Prioritization** + **Resource Optimization** + **Context Management**\n\n\n---\n\n## 🎓 Learning Path\n\n### Beginner → Intermediate → Advanced → Expert\n\n**Phase 1: Foundations (Start Here)**\n1. [Prompt Chaining](./foundational_design_patterns/1_prompt_chain/) - Foundation for everything\n2. [Routing](./foundational_design_patterns/2_routing/) - Learn to optimize model selection\n3. [Parallelization](./foundational_design_patterns/3_parallelization/) - Scale your applications\n4. [Reflection](./foundational_design_patterns/4_reflection/) - Master quality optimization\n5. [Tool Use](./foundational_design_patterns/5_tool_use/) - Connect to external systems\n\n**Phase 2: Core Patterns**\n6. [RAG](./foundational_design_patterns/9_rag/) - Knowledge-grounded responses\n7. [ReAct](./foundational_design_patterns/8_react/) - Reasoning + acting\n8. [Planning](./foundational_design_patterns/6_planning/) - Strategic decomposition\n9. [HITL](./foundational_design_patterns/10_hitl/) - Human oversight\n10. [Multi-Agent](./foundational_design_patterns/7_multi_agent_collaboration/) - Agent coordination\n\n**Phase 3: Advanced Reasoning**\n11. [Tree of Thoughts](./reasoning/tree_of_thoughts/) - Systematic exploration\n12. [Graph of Thoughts](./reasoning/graph_of_thoughts/) - Multi-perspective reasoning\n\n**Phase 4: Production Patterns**\n13. [Error Recovery](./reliability/error_recovery/) - Resilience\n14. [Guardrails](./reliability/guardrails/) - Safety\n15. [Evaluation \u0026 Monitoring](./observability/evaluation_monitoring/) - Metrics\n16. [Resource Optimization](./observability/resource_optimization/) - Cost/performance\n\n**Phase 5: Orchestration \u0026 Memory**\n17. [Goal Management](./orchestration/goal_management/) - Objective tracking\n18. [Agent Communication](./orchestration/agent_communication/) - Messaging\n19. [MCP](./orchestration/mcp/) - Standardized integration\n20. [Prioritization](./orchestration/prioritization/) - Task ranking\n21. [Memory Management](./memory/memory_management/) - Context retention\n22. [Context Management](./memory/context_management/) - Optimization\n\n**Phase 6: Continuous Improvement**\n23. [Adaptive Learning](./learning/adaptive_learning/) - Learning from feedback\n24. [Structured Outputs](./foundational_design_patterns/11_structured_outputs/) - Schema reliability\n25. [Computer Use](./foundational_design_patterns/12_computer_use/) - Browser/UI automation\n26. [Subagents](./orchestration/subagents/) - Orchestrator-worker topology\n27. [Skills](./orchestration/skills/) - Capability packages\n28. [Deep Research](./reasoning/deep_research/) - Iterative research loops\n\nEach pattern builds on concepts from previous ones. Start with Phase 1, then explore other phases based on your needs.\n\n---\n\n## 🛠️ Tech Stack\n\n### Core Frameworks\n- **[LangChain](https://python.langchain.com/)** - Comprehensive framework for LLM applications\n- **[LangGraph](https://langchain-ai.github.io/langgraph/)** - Stateful workflows and multi-agent orchestration\n- **[LangSmith](https://smith.langchain.com/)** - LLM application monitoring and evaluation\n\n### Models \u0026 APIs\n- **[OpenAI Models](https://openai.com/)** - Primary provider used throughout the examples, configured via environment variables\n- **[Anthropic Claude](https://anthropic.com/)** - Alternative frontier-model family with strong long-context support\n- **[Other LLM Providers](https://python.langchain.com/docs/integrations/llms/)** - Fully compatible through LangChain abstractions\n\n### Development Tools\n- **[Pydantic](https://docs.pydantic.dev/)** - Data validation and structured outputs\n- **[Python 3.11+](https://www.python.org/)** - Modern Python features (match/case, typing)\n- **[uv](https://github.com/astral-sh/uv)** - Fast Python package manager\n\n### Observability \u0026 Evaluation\n- **[W\u0026B Weave](https://wandb.ai/site/weave/)** - Agent evaluation and monitoring\n- **[LangSmith](https://smith.langchain.com/)** - Tracing and debugging\n\n---\n\n\n## 📖 Resources\n\n### 🎓 Academic Papers \u0026 Surveys\n\n**Reasoning \u0026 Planning:**\n- [ReAct: Synergizing Reasoning and Acting in Language Models](https://arxiv.org/abs/2210.03629) (Yao et al., 2022) - ICLR 2023\n- [Tree of Thoughts: Deliberate Problem Solving with Large Language Models](https://arxiv.org/abs/2305.10601) (Yao et al., 2023) - NeurIPS 2023\n- [Graph of Thoughts: Solving Elaborate Problems with Large Language Models](https://arxiv.org/abs/2308.09687) (Besta et al., 2023)\n\n**Retrieval-Augmented Generation:**\n- [Agentic Retrieval-Augmented Generation: A Survey on Agentic RAG](https://arxiv.org/abs/2501.09136) (Singh et al., 2025)\n- [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://arxiv.org/abs/2005.11401) (Lewis et al., 2020)\n\n### 📚 Books\n\n- **[Agentic Design Patterns: A Hands-On Guide to Building Intelligent Systems](https://link.springer.com/book/10.1007/978-3-031-87617-1)** - Antonio Gullí (Springer Nature, 2024) - Primary inspiration for this repository\n- **[Building LLM Powered Applications](https://www.oreilly.com/library/view/building-llm-powered/9781835462317/)** - Valentina Alto (Packt/O'Reilly, 2024)\n- **[Hands-On Large Language Models](https://www.oreilly.com/library/view/hands-on-large/9781098150952/)** - Jay Alammar \u0026 Maarten Grootendorst (O'Reilly, 2024)\n\n### 🎓 Courses \u0026 Educational Content\n\n**Foundational Courses:**\n- **[Agentic AI with Andrew Ng](https://www.deeplearning.ai/courses/agentic-ai/)** (DeepLearning.AI, 2024) - Covers reflection, tool use, planning, and multi-agent collaboration\n\n**Framework-Specific:**\n- [LangChain Academy](https://academy.langchain.com/) - Official LangChain courses\n- [LangGraph Tutorials](https://langchain-ai.github.io/langgraph/tutorials/) - Stateful agent workflows\n- [OpenAI Cookbook](https://cookbook.openai.com/) - Function calling and agent patterns\n- [Anthropic Prompt Engineering Interactive Tutorial](https://github.com/anthropics/prompt-eng-interactive-tutorial)\n\n### 🏭 Industry Documentation \u0026 Guides\n\n**Official Framework Documentation:**\n- [LangChain Documentation](https://python.langchain.com/docs/get_started/introduction)\n- [LangGraph Documentation](https://langchain-ai.github.io/langgraph/)\n- [Microsoft AutoGen](https://microsoft.github.io/autogen/stable/)\n- [OpenAI Function Calling Guide](https://platform.openai.com/docs/guides/function-calling)\n- [OpenAI Agents Platform](https://platform.openai.com/docs/guides/agents)\n- [Anthropic Prompt Engineering Guide](https://docs.anthropic.com/en/docs/build-with-claude/prompt-engineering/overview)\n\n**Production Best Practices:**\n- [LangChain: Top 5 LangGraph Agents in Production 2024](https://www.blog.langchain.com/top-5-langgraph-agents-in-production-2024/) - Real-world deployments\n- [Weights \u0026 Biases: Agentic RAG Guide](https://wandb.ai/byyoung3/Generative-AI/reports/Agentic-RAG-Enhancing-retrieval-augmented-generation-with-AI-agents--VmlldzoxMTcyNjQ5Ng)\n\n### 🌐 Community Resources\n\n**Curated Collections:**\n- [Awesome-LangGraph](https://github.com/von-development/awesome-LangGraph) - Comprehensive LangGraph ecosystem index\n- [Prompt Engineering Guide](https://www.promptingguide.ai/) - Comprehensive guide covering latest papers and techniques\n- [Learn Prompting](https://learnprompting.org/) - Free generative AI guide\n\n**Related Projects:**\n- [LangChain Templates](https://github.com/langchain-ai/langchain/tree/master/templates)\n- [Microsoft AutoGen](https://github.com/microsoft/autogen)\n- [CrewAI](https://github.com/joaomdmoura/crewAI)\n- [AG2 (formerly AutoGen)](https://github.com/ag2ai/ag2)\n\n### 🔬 Research Collections\n\n- [Papers with Code: Agents](https://paperswithcode.com/task/agents) - Latest research with implementations\n- [arXiv: Artificial Intelligence](https://arxiv.org/list/cs.AI/recent) - Recent AI papers\n- [Hugging Face Papers](https://huggingface.co/papers) - Trending ML research\n\n---\n\n## 🏛️ Standards \u0026 Compliance\n\n### NIST AI Risk Management Framework\n\nOrganizations deploying agentic AI systems should consider the NIST AI Risk Management Framework and associated guidance:\n\n#### **Core Framework**\n- **[NIST AI Risk Management Framework (AI RMF 1.0)](https://www.nist.gov/itl/ai-risk-management-framework)** (January 2023)\n  Voluntary framework to manage AI risks based on four core functions: Govern, Map, Measure, and Manage.\n\n#### **Generative AI Profile**\n- **[NIST AI RMF: Generative AI Profile (NIST.AI.600-1)](https://www.nist.gov/publications/artificial-intelligence-risk-management-framework-generative-artificial-intelligence)** (July 2024)\n  Addresses risks unique to Generative AI, including governance, content provenance, pre-deployment testing, and incident disclosure. Includes catalog of 400+ mitigation actions.\n\n### Compliance Mapping\n\n| NIST AI RMF Function | Relevant Patterns |\n|---------------------|-------------------|\n| **Govern** | [Human-in-the-Loop](./foundational_design_patterns/10_hitl/), [Guardrails](./reliability/guardrails/) |\n| **Map** | [Planning](./foundational_design_patterns/6_planning/), [Goal Management](./orchestration/goal_management/) |\n| **Measure** | [Evaluation \u0026 Monitoring](./observability/evaluation_monitoring/), [Adaptive Learning](./learning/adaptive_learning/) |\n| **Manage** | [Error Recovery](./reliability/error_recovery/), [Guardrails](./reliability/guardrails/) |\n\n### Key Focus Areas for Agentic Systems\n\n- **Transparency:** ReAct pattern provides explicit reasoning traces for auditability\n- **Human Oversight:** HITL pattern enables approval workflows\n- **Safety Constraints:** Guardrails pattern enforces compliance boundaries\n- **Evaluation:** Monitoring pattern tracks quality and bias metrics\n- **Error Recovery:** Graceful degradation and incident response\n\n### Additional Resources\n\n- [AI Executive Order 14110](https://www.whitehouse.gov/briefing-room/presidential-actions/2023/10/30/executive-order-on-the-safe-secure-and-trustworthy-development-and-use-of-artificial-intelligence/)\n- [EU AI Act](https://artificialintelligenceact.eu/)\n- [ISO/IEC 42001:2023](https://www.iso.org/standard/81230.html) - AI Management System standard\n\n---\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.\n\n---\n\n## 📌 How to Cite\n\nIf you reference this catalog in academic or professional work, please cite:\n\n```bibtex\n@misc{tesei_agentic_design_patterns,\n  author       = {Tesei, Gino},\n  title        = {Agentic Design Patterns: A Hands-On Catalog for Building Intelligent Systems},\n  year         = {2024},\n  publisher    = {GitHub},\n  howpublished = {\\url{https://github.com/gtesei/agentic_design_patterns}},\n  note         = {MIT License}\n}\n```\n\n---\n\n## 🙏 Acknowledgments\n\nThis repository's structure and approach were inspired by:\n\n### Primary References\n\n\u003e **Gullí, Antonio**, *Agentic Design Patterns: A Hands-On Guide to Building Intelligent Systems*, Springer Nature Switzerland, 2024.\n\n\u003e **Ng, Andrew**, *Agentic AI*, DeepLearning.AI, 2024.\n\n### Academic Foundations\n\nWe gratefully acknowledge the research contributions that ground these patterns:\n\n- **Yao, Shunyu et al.** - ReAct and Tree of Thoughts frameworks\n- **Singh, Aditi et al.** - Agentic RAG survey and taxonomy\n- **Besta, Maciej et al.** - Graph of Thoughts methodology\n- **Lewis, Patrick et al.** - Foundational RAG research\n\n### Community \u0026 Tools\n\nSpecial thanks to:\n- The **LangChain and LangGraph teams** for building production-grade agentic frameworks\n- The **open-source AI community** for advancing the state of the art\n- **NIST** for providing guidance on trustworthy AI development\n- **[Claude Code](https://claude.ai/)** for assistance in developing and refining the implementations in this repository\n- All **contributors** who help improve these patterns\n\n---\n\n## ⭐ Star History\n\nIf you find this repository helpful, please consider giving it a star! It helps others discover these patterns.\n\n[![Star History Chart](https://api.star-history.com/svg?repos=gtesei/agentic_design_patterns\u0026type=Date)](https://star-history.com/#gtesei/agentic_design_patterns\u0026Date)\n---\n\n\u003cdiv align=\"center\"\u003e\n\n**Built with ❤️ for the AI developer community**\n\n[⬆ Back to Top](#-agentic-design-patterns)\n\n\u003c/div\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgtesei%2Fagentic_design_patterns","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgtesei%2Fagentic_design_patterns","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgtesei%2Fagentic_design_patterns/lists"}