Skip to main content

Agent Design Patterns

Study notes for ML engineers evaluating or building agentic workflows. Assumes Python/LLM experience. Knowledge cutoff: mid-2026.


What is an agent?​

agent = LLM + memory + tools + control flow
AbstractionControl flowUse when
LLM callNone β€” one shotSingle task, no external state needed
ChainFixed at design timeSteps are always the same
AgentDynamic β€” LLM decidesSteps depend on intermediate results

Default to a chain. Only add an agent loop when the number or sequence of steps genuinely can't be determined upfront. Agents are slower, harder to debug, and more expensive than chains.


Tier 1 β€” Foundational (single-agent)​

PatternCore ideaBest signal to use it
ReActThink β†’ Act β†’ Observe loopTask needs real-time external data
Plan and ExecutePlan once upfront, then executeLong-horizon task with many independent steps
ReflectionGenerator β†’ Critic β†’ Revise loopOutput quality matters more than latency
Tool UseStructured typed tool schemasAgent needs to read/write external state

1. ReAct (Reason + Act)​

The model alternates between Thought (explicit reasoning), Action (tool call), and Observation (tool result) until it has a final answer. Forcing verbalized reasoning before acting improves accuracy and debuggability.

Use when β€” the task requires real-time data (search, APIs); the number of tool calls is unknown upfront; you need an audit trail of reasoning steps.

Skip when β€” the sequence of steps is always the same (use a chain); latency is tight (each thought/action/observation adds a model round-trip).

Example: A research assistant asks "What are the top 3 cloud providers by market cap today?" It can't answer from training data β€” it reasons, calls a financial API, gets partial data, calls again, then synthesizes.


2. Plan and Execute​

A planner LLM produces a full step-by-step plan upfront. An executor (often a cheaper model) runs each step. Unlike ReAct, the plan is fixed before any execution begins β€” better for long-horizon tasks where global coherence matters.

Use when β€” tasks decompose cleanly into independent steps; you want to show users a plan before committing; you want to use Opus for planning and Sonnet/Haiku for execution.

Skip when β€” early steps reveal information that changes what later steps should be (ReAct handles this better); the task has 2–3 steps (overkill).

Example: Monthly investor update β€” planner emits (1) pull revenue, (2) pull expenses, (3) compare to prior quarter, (4) draft commentary, (5) format. These steps don't change based on what the numbers are, so a fixed plan works.


3. Reflection / Self-Critique​

A generator LLM produces a draft. A critic LLM evaluates it against a rubric and returns structured feedback. The generator revises. Loop until the critic passes or a max-iteration limit is hit. The critic can be a stronger (and more expensive) model than the generator.

Use when β€” output quality is hard to verify automatically (essays, plans, complex code); you have an expressible rubric; cost of a bad first draft is high.

Skip when β€” output has deterministic ground truth (just run the code and check); the generator and critic are the same model at the same temperature (it'll agree with itself); latency budget doesn't allow multiple passes.

Example: CI code review agent β€” generator writes a first-pass review, critic (prompted as a senior engineer) flags missed issues and false positives, generator revises. Two passes consistently outperform one.

Go deeper

4. Tool Use / Function Calling​

Tools are declared as JSON schemas. The LLM returns a structured tool call object; your code executes it and feeds the result back. Modern models emit multiple tool calls in one response for parallel execution β€” use this aggressively.

Use when β€” the agent needs to read or write external state; you need deterministic, typed actions instead of free-text descriptions of actions; parallel tool calling can reduce latency.

Skip when β€” a plain prompt with instructions is sufficient; tool schemas are too broad or overlapping (models struggle to pick).

⚠️ Don't give agents destructive tools (DELETE, send email, deploy) without a HITL gate β€” see Pattern 8.

Example: Calendar scheduling agent. User: "Find a 1-hour slot for Alice and Bob this week, no mornings." Agent calls get_availability() in parallel for both users, reasons about overlap, calls create_event().


Tier 2 β€” Orchestration (multi-agent)​

PatternCore ideaBest signal to use it
Orchestrator–SubagentCentral router delegates to specialist agentsProblem has clearly separable domains
ParallelizationFan-out independent tasks, aggregate resultsSubtasks are genuinely independent; latency matters
Pipeline / DAGTyped handoffs in a directed acyclic graphFixed structure, step-level retry/resume needed

5. Orchestrator–Subagent​

A central orchestrator routes tasks to specialist subagents with domain-specific prompts, tools, and optionally different models. Subagents are stateless from the orchestrator's view β€” they receive a task, return a result.

Use when β€” problem has clearly separable domains (billing vs. tech support vs. account management); different domains need different tools or prompts; teams want to own separate agents.

Skip when β€” domains bleed into each other (routing ambiguity causes thrash); overhead of serialization exceeds the benefit β€” try a single well-prompted agent first.

Example: SaaS customer support β€” orchestrator classifies tickets. Billing β†’ Stripe API agent. Tech issues β†’ runbook + log agent. Account changes β†’ user DB agent. Low-confidence routes β†’ HITL queue.

Go deeper

6. Parallelization / Fan-out​

Independent subtasks are dispatched concurrently and results aggregated. If 5 tasks each take 3s sequentially = 15s; in parallel β‰ˆ 3s. Also useful for N-way voting β€” run the same prompt N times and take majority to improve reliability on ambiguous tasks.

Use when β€” subtasks are genuinely independent; large documents can be chunked for parallel analysis; N-way voting improves reliability.

Skip when β€” tasks have hidden dependencies; API rate limits will serialize you anyway; the aggregation step is harder than the subtasks.

Example: 200-page M&A due diligence doc β€” 6 worker agents (financials, legal, IP, HR, infrastructure, regulatory) run in parallel. Total time β‰ˆ slowest section, not sum of all.


7. Pipeline / DAG​

Each node is an agent or function with defined input/output types. Edges encode dependencies. The engine runs nodes in topological order, with parallelism where the graph allows. State is persisted at each node boundary β€” a failed node can be retried without re-running upstream work.

Use when β€” the workflow has a fixed structure but complex dependencies; steps need individual retry/testability; different steps need different models or environments.

Skip when β€” the graph structure changes per input (use ReAct); 2–3 steps with no branching (a chain is simpler).

Example: PR review pipeline β€” ingest diff β†’ [lint check β€– test run β€– security scan] β†’ LLM review (reads all three results) β†’ post comment. If test_run fails, retry only that node.


Tier 3 β€” Reliability and Memory​

PatternCore ideaBest signal to use it
HITLPause before irreversible actions for human approvalAgent can send, delete, deploy, or charge
Memory ManagementPersist context across sessions and context windowsAgent needs history across runs
GuardrailsValidate input/output and gate tool callsCustomer-facing or regulated domain

8. Human in the Loop (HITL)​

The agent pauses at interrupt points before irreversible actions and persists full state. A human approves, rejects, or redirects. On approval, execution resumes from the exact point of interruption.

Use when β€” any irreversible or high-value action (send email, execute payment, deploy, delete); regulated domains with mandatory human sign-off; building a ground-truth dataset from early agent runs.

Skip when β€” high-volume, low-risk, easily reversible actions (HITL becomes a bottleneck); you have automated rollback and the agent is well-validated.

Example: Sales email agent β€” drafts under $50K ARR accounts auto-send; above $50K pauses, sends Slack message with approve/reject/edit buttons, resumes on approval. The manager's edit feeds back to the agent as revision notes.


9. Memory Management​

Four memory types serve different purposes:

TypeStorageScopeUse for
In-contextActive promptCurrent sessionRecent turns, current task state
External vectorVector DBPersistentUser history, past interactions
EpisodicStructured storePersistentPast agent run outcomes
SemanticKey-value / graphPersistentExtracted facts, user preferences

Use when β€” personal assistant needs user preferences across sessions; context window fills before the task completes; agent accumulates findings over multiple runs.

Skip when β€” stateless one-shot task (code review, single summarization); privacy/retention regulations prohibit storing user data.

Rule of thumb: If your agent regularly hits 80%+ of its context budget, you have a context management problem. Profile which turns produce the most tokens β€” tool outputs and long documents are the usual culprits.

Go deeper

10. Guardrails and Validation​

Three layers:

  • Input: sanitize and screen before the agent sees it (PII detection, injection, content policy)
  • Output: enforce schema, check policy, verify groundedness before returning to user
  • Action gating: validate tool call parameters before execution

Use when β€” any customer-facing agent; regulated domain (medical, legal, financial); structured-output agents where downstream systems depend on schema correctness.

Skip when β€” internal dev tooling where users are engineers who understand the risks; guardrails are so restrictive they trigger over-refusal (a real failure mode β€” ~5% bad output is better than 30% refused output).

Example: Medical info chatbot β€” input guard blocks diagnostic-advice requests; output guard checks factual groundedness against cited sources; schema guard enforces { disclaimer_included: bool, sources: List[str] } and retries with validation error as feedback.

Go deeper

Cross-Cutting Concerns​

Context window management​

Three strategies: (1) Summarize older turns into a compressed node injected at the top of context. (2) Sliding window β€” keep only the last N turns; works when recency matters more than full history. (3) Eviction β€” score message importance (tool calls, errors, stated facts score high; filler scores low) and drop the lowest. LangGraph's trim_messages and Letta's archival memory implement versions of these. For document-heavy pipelines, paginate or chunk large tool outputs before they enter context β€” they're almost always the primary offender.

Model routing​

Not every step deserves a frontier model. Default heuristic:

Task typeModel tierSignal
Planning, novel decompositionOpus-classMulti-step reasoning required
Execution with clear instructionsSonnet-classTask is well-specified
Classification, routing, triageHaiku-classTask fits in 2 sentences

Haiku is ~30Γ— cheaper per token than Opus. Routing even 50% of calls to Haiku materially changes unit economics at scale.

Observability and tracing​

Every agent turn should emit: request ID (propagated to all sub-calls), model used, input messages, tool calls (name + args), tool results, output, latency per step, token counts (input / output / cache hit). For multi-agent systems, trace IDs must be hierarchical β€” parent span for the orchestrator, child spans per subagent. LangSmith and Langfuse both offer first-class LangGraph integration. Minimum viable: log enough to replay a failed run and pinpoint exactly which node failed and why.

Error recovery​

Three error categories, three responses:

Error typeExampleResponse
TransientAPI timeout, rate limitRetry with exponential backoff, cap at 3 attempts
DeterministicSchema mismatch, malformed tool callFeed error back to model as observation β€” it often self-corrects
SemanticModel misunderstood the taskEscalate to human; retrying reproduces the same misunderstanding

All tool calls with external effects should be idempotent β€” use idempotency keys for API calls. Preserve partial results from failed multi-step runs for resume (LangGraph checkpointing does this).


Framework Comparison​

FrameworkBest forGraph/DAGHITLBuilt-in memoryObservabilityMulti-modelMaturity
LangGraphProduction stateful agents, HITLYesYes (interrupt + checkpoint)Yes (MemorySaver, Postgres, Store)LangSmith nativeYesHigh
CrewAIRole-based prototyping, fast MVPLimitedCLI onlyBasicCrewAI+ (paid)YesMedium
Google ADKGCP/Gemini-native, multimodal, A2AYes (hierarchical)Callback-basedSession state + memory serviceCloud TraceGemini-primaryMedium
OpenAI Agents SDKMinimal surface area, strong tracingHandoff graphManual loopNo (bring your own)Built-in traces dashboardYesMedium
Microsoft Agent FrameworkAzure/enterprise, Python + .NETYes (GroupChat, Swarm)Yes (human proxy)YesAzure MonitorYesMedium-High
Anthropic Claude SDKClaude-first, close-to-metal, MCPManualManualNo (bring your own)Pair with Langfuse/OTELClaude onlyHigh for tool use
LlamaIndex WorkflowsDocument/RAG pipelinesYes (event-driven)NoYes (vector + chat memory)LlamaTrace / ArizeYesMedium

How to choose​

  • LangGraph β€” need production stateful graphs with checkpointing and first-class HITL
  • CrewAI β€” want role-based prototyping speed with minimal setup
  • Google ADK β€” GCP-native, need multimodal or A2A cross-framework communication
  • OpenAI Agents SDK β€” want minimal surface area and strong built-in tracing
  • Microsoft Agent Framework β€” Azure / .NET enterprise stack, or migrating from AutoGen / Semantic Kernel
  • Anthropic Claude SDK β€” Claude-first, staying close to the metal with MCP integration
  • LlamaIndex β€” workload is primarily document ingestion, retrieval, and synthesis

Use Case Deep Dives​

The patterns above are building blocks. The pages below walk through end-to-end implementations for specific use cases, mapping each use case to the relevant patterns and showing concrete code.

Use CasePatterns usedStatus
Data Validation AgentTool Use, ReAct, HITL, ParallelizationDone