Transform your AI applications from simple prompts to sophisticated intelligent systems.
A comprehensive, hands-on collection of design patterns for building robust agentic AI systems. Each pattern is implemented with real-world examples and detailed documentation to help you architect scalable, maintainable AI applications.
1๏ธโฃ Prompt Chaining
Break complex tasks into sequential, manageable steps
# Transform a monolithic prompt into a chain of specialized prompts
input โ extract_data โ transform โ validate โ final_outputWhen to use:
- Multi-step transformations (data extraction โ analysis โ formatting)
- Tasks requiring intermediate validation
- Complex workflows that benefit from decomposition
Key benefits:
- ๐ฏ Better accuracy through focused prompts
- ๐ Easier debugging with visible intermediate steps
- ๐ Reusable components across workflows
2๏ธโฃ Routing
Intelligently direct queries to specialized handlers
# Dynamic routing based on query classification
user_query โ classifier โ [technical_expert | sales_agent | support_bot]When to use:
- Multi-domain applications (support, sales, technical)
- Specialized model selection (fast/cheap vs. slow/accurate)
- Intent-based workflows requiring different processing paths
Key benefits:
- ๐ฐ Cost optimization (use expensive models only when needed)
- โก Performance gains (route simple queries to fast handlers)
- ๐จ Specialized handling (domain experts for domain queries)
3๏ธโฃ Parallelization
Execute independent operations simultaneously for dramatic speedups
# Sequential: 15 seconds # Parallel: 5 seconds
task_a(5s) โ task_a(5s) โ
task_b(5s) โ vs. task_b(5s) โ combine โ output
task_c(5s) โ output task_c(5s) โWhen to use:
- Multiple API calls (search engines, databases, external services)
- Parallel data processing (analyze multiple documents)
- Multi-source research or content generation
Key benefits:
- โก 2-10x faster execution for I/O-bound tasks
- ๐ Better resource utilization
- ๐ Improved user experience through reduced latency
4๏ธโฃ Reflection
Iteratively improve outputs through systematic critique and refinement
# Single-shot: 5/10 quality # With reflection: 8.5/10 quality
input โ generate โ done input โ generate โ critique โ
refine โ critique โ finalWhen to use:
- High-stakes content (code, legal docs, published articles)
- Complex reasoning tasks (logic puzzles, strategic planning)
- Quality-critical applications where "good enough" isn't enough
Key benefits:
- ๐ฏ 50-70% higher quality scores
- ๐ Systematic error detection and correction
- ๐ง Self-improving outputs without human intervention
Trade-offs:
โ ๏ธ 3-5x higher token costs- โฑ๏ธ 4-8x longer execution time
5๏ธโฃ Tool Use
Enable LLMs to interact with external systems and APIs
# Without tools: Limited to training data
# With tools: Access real-time data and take actions
user_query โ LLM decides โ call_weather_api(location) โ integrate_result โ responseWhen to use:
- Real-time data retrieval (weather, stock prices, news)
- Private/proprietary data access (databases, CRM systems)
- Precise calculations or code execution
- External actions (send emails, update records, control devices)
Key benefits:
- ๐ Access to live, dynamic information
- ๐ฏ Precise calculations and data validation
- ๐ง Integration with existing enterprise systems
- ๐ฐ Reduced token costs (fetch vs. embed in prompts)
Trade-offs:
โ ๏ธ Added latency per tool call- ๐ Security considerations (authentication, validation)
6๏ธโฃ Planning
Decompose complex goals into structured, executable action plans
# Without planning: Reactive, incomplete execution
# With planning: Strategic breakdown and systematic execution
complex_goal โ analyze โ decompose โ plan_steps โ execute_sequentially โ final_resultWhen to use:
- Multi-step workflows requiring orchestration (research reports, data pipelines)
- Tasks with interdependent operations
- Complex problem-solving requiring strategic thinking
- Workflow automation (onboarding, procurement, project setup)
Key benefits:
- ๐ฏ Structured approach to complex objectives
- ๐ง Strategic thinking vs. reactive responses
- ๐ Adaptability through dynamic replanning
- ๐ Transparency into execution strategy
Trade-offs:
โ ๏ธ Planning overhead (+20-40% tokens, 5-15s latency)- ๐ ๏ธ Requires sophisticated state management
7๏ธโฃ Multi-Agent Collaboration
Coordinate multiple specialized agents to solve complex tasks
# Agents as a team: specialize roles + coordinate communication
user_goal โ manager/planner โ [researcher | coder | designer | writer | reviewer] โ synthesize โ final_outputWhen to use:
- Complex tasks requiring diverse expertise (research + writing + QA)
- Workflows with distinct stages (research โ draft โ edit โ package)
- Tool-specialized roles (web search, code execution, image generation)
- Quality-critical pipelines (critic/reviewer loops)
Key benefits:
- ๐งฉ Modularity: build and improve one role at a time
- ๐ก๏ธ Robustness: reviewers catch errors / reduce hallucinations
- โก Parallelism: split independent workstreams for speed
- โป๏ธ Reuse: agents can be reused across multiple products
Common collaboration models:
- Sequential handoffs (linear pipeline)
- Supervisor/manager orchestration (hierarchical)
- Parallel workstreams (merge results)
- Debate/consensus (evaluate options)
- Criticโreviewer (quality enforcement)
- Network/all-to-all (exploratory, less predictable)
- Custom hybrids (fit domain constraints)
# Python 3.11 or higher
python --version
# Install uv
curl -LsSf https://astral.sh/uv/install.sh | sh# Clone the repository
git clone https://github.com/yourusername/agentic_design_patterns.git
cd agentic_design_patterns
# Set up environment
echo "OPENAI_API_KEY=your_api_key_here" > .env
# Install dependencies (using uv)
uv sync# Try prompt chaining
cd foundational_design_patterns/1_prompt_chain
bash run.sh
# Try routing
cd ../2_routing
uv run python src/routing_example.py
# Try parallelization
cd ../3_parallelization
bash run.sh
# Try reflection (stateful loops)
cd ../4_reflection
bash run.shNeed speed? โ Start with Routing and Parallelization
Need quality? โ Use Prompt Chaining + Reflection
Need cost optimization? โ Implement Routing to avoid expensive models
Need both speed AND quality? โ Combine Parallelization + Prompt Chaining
Complex multi-step workflow? โ Prompt Chaining is your foundation
Independent concurrent tasks? โ Parallelization will give you massive speedups
High-stakes output? โ Reflection is worth the cost
External system integration? โ Tool Use enables real-world interaction
Multi-step automation requiring orchestration? โ Planning provides strategic execution
Need multiple roles working together? โ Multi-Agent Collaboration (specialists + coordinator)
agentic_design_patterns/
โโโ foundational_design_patterns/
โ โโโ 1_prompt_chain/
โ โ โโโ src/
โ โ โ โโโ chain_prompt.py # Basic chaining
โ โ โ โโโ advanced_chain.py # Complex workflows
โ โ โโโ README.md # Pattern documentation
โ โ โโโ SKILL.md # Implementation guide
โ โ
โ โโโ 2_routing/
โ โ โโโ src/
โ โ โ โโโ routing.py # Intent-based routing
โ โ โ โโโ semantic_routing.py # Advanced routing
โ โ โโโ README.md
โ โ โโโ SKILL.md
โ โ
โ โโโ 3_parallelization/
โ โ โโโ src/
โ โ โ โโโ parallel_example.py # LCEL parallelization
โ โ โ โโโ async_parallel.py # Async operations
โ โ โโโ README.md
โ โ โโโ SKILL.md
โ โ
โ โโโ 4_reflection/
โ โโโ src/
โ โ โโโ reflection.py # Single-step reflection
โ โ โโโ reflection_stateful_loop.py # Iterative refinement
โ โโโ README.md
โ โโโ SKILL.md
...
...
โโโ .env # Environment variables
โโโ LICENSE # MIT License
โโโ README.md # This file
- Start here: Prompt Chaining - Foundation for everything
- Next: Routing - Learn to optimize model selection
- Then: Parallelization - Scale your applications
- Finally: Reflection - Master quality optimization
- Advanced: Multi-Agent Collaboration - Build coordinated agent teams
Each pattern builds on concepts from previous ones, so we recommend following this sequence.
- LangChain - Framework for LLM applications
- LangGraph - Stateful workflows and agents
- OpenAI GPT-4/GPT-4o/GPT-5.2 - Primary LLM (configurable)
- Pydantic - Data validation and structured outputs
- Python 3.11+ - Modern Python features
We're actively developing additional patterns:
- Retrieval-Augmented Generation (RAG) - Knowledge-grounded responses
- Human-in-the-Loop - Interactive approval and refinement
- Guardrails - Safety, compliance, and quality enforcement
Want a specific pattern? Open an issue and let us know!
This project is licensed under the MIT License - see the LICENSE file for details.
This repository's structure and approach were inspired by:
Gullรญ, Antonio, Agentic Design Patterns: A Hands-On Guide to Building Intelligent Systems, Springer Nature Switzerland.
Andrew Ng, Agentic AI, DeepLearning.AI.
Special thanks to:
- The LangChain team for building incredible tools
- The open-source AI community for pushing the boundaries
- All contributors who help improve these patterns
If you find this repository helpful, please consider giving it a star! It helps others discover these patterns.
Built with โค๏ธ for the AI developer community