---
name: agentic-patterns
description: Choose and apply proven design patterns when designing or reviewing an AI agent, a multi-agent system or an agentic feature (agent loops, routing, memory, safety, runtime, evaluation, fast/slow models), or when setting up a repo and workflow for AI coding agents (specs, CLAUDE.md, plan mode, tests, PRs, worktrees).
---

# Agentic Pattern Library

48 patterns by Vikas Goyal, in two tracks: designing agentic systems, and building software with coding agents. Source: https://vikasgoyal.github.io/agentic/patterns/

## How to use this skill

1. **Match.** Read the task, then scan the index below. Pick the 1–3 patterns whose "use when" fits and whose "avoid when" doesn't. Patterns combine; most real designs use several.
2. **Read the full card** before designing or writing code. Fetch `https://vikasgoyal.github.io/agentic/patterns/<id>/` for the page, or find the `## <title>` section in `https://vikasgoyal.github.io/agentic/patterns/llms-full.txt`. Structured fields are in `https://vikasgoyal.github.io/agentic/patterns/patterns.json`.
3. **Apply.** Name the patterns you chose and why. Address each failure mode from the card in the design or the code (for example, a step cap, a confidence threshold with a fallback, a protected test file). Check the related patterns for anything that should be combined.
4. **Don't copy example numbers.** Values in worked examples (thresholds, caps, budgets, timings) are illustrative. Derive real values from the user's requirements, make them configurable, and say what you assumed.
5. **Say when no pattern fits.** Don't force one.

## Index

### Track: Agentic systems

#### Core loop
- **Tool Use** (`tool-use`): The model calls external functions or APIs through structured schemas, grounding it in real data and actions. Use when: The answer depends on live or private data (orders, tickets, inventory); The task needs an action in another system (create, update, send); Exact computation matters, such as math, dates or currency; Downstream code needs structured output it can trust. Avoid when: The model already has everything it needs in the prompt.
- **ReAct** (`react`): Reason, act, observe, repeat. The default loop in most agent frameworks. Use when: The path to the answer isn't known in advance; Each step is cheap and the task needs 2–10 of them; You need a readable trace of why the agent did what it did; Tools return information that changes what to try next. Avoid when: The steps are always the same; use Prompt Chaining instead.
- **Plan-and-Execute** (`plan-and-execute`): Write the plan first, then execute step by step and replan on failure. Use when: Tasks have several distinct parts, like research, compare, then draft; You want a human to approve the plan before anything runs; Execution steps are simple enough for a cheaper model; Progress needs to be tracked or resumed after an interruption. Avoid when: The task is one or two steps; planning is overhead.
- **Reflection** (`reflection`): The agent critiques and revises its own output before returning it. Use when: Errors are cheap to detect once you look (format, missing items, math); You can write a short, specific checklist; A bit of extra latency is acceptable for higher quality; An external signal is available, such as tests, a schema or source data. Avoid when: Quality needs an independent judge; use Evaluator–Optimizer.
- **Prompt Chaining** (`prompt-chaining`): A fixed sequence of LLM calls with checks between steps. Predictable and debuggable. Use when: The task always breaks into the same steps; Each step's output can be checked with code; You need predictable cost, latency and behavior; Different steps benefit from different prompts or models. Avoid when: The steps depend on what earlier results reveal; use ReAct.
- **Routing** (`routing`): Classify the request and send it to the right prompt, model or agent. Use when: Requests fall into distinct categories with different needs; Some categories are simple enough for a deterministic workflow or small model; Separate teams own different domains and want separate prompts; Cost matters and most traffic is routine. Avoid when: Categories overlap so much that the classifier can't separate them.
- **Parallelization** (`parallelization`): Run independent subtasks at once, or run one task several times and vote. Use when: The task splits into parts that don't depend on each other; Each part benefits from its own focused prompt; Wall-clock latency matters more than total tokens; A judgment call needs more confidence than one answer gives. Avoid when: Steps depend on each other's output; use Prompt Chaining.

#### Multi-agent
- **Orchestrator–Workers** (`orchestrator-workers`): A lead agent decomposes the task at runtime, delegates, and merges results. Use when: The number and shape of subtasks can't be known in advance; Subtasks are broad, like research across many sources or changes across many files; Parallel work would cut wall-clock time significantly; The full job won't fit in one agent's context. Avoid when: The split is always the same; use Parallelization or Prompt Chaining.
- **Evaluator–Optimizer** (`evaluator-optimizer`): One agent generates, another grades against a rubric, and they loop until it passes. Use when: Quality criteria can be written down as a rubric; A first draft is usually close but not quite right; Outputs go to customers or executives, where polish matters; You want an audit trail of why an output passed. Avoid when: There is no clear rubric; the judge will just add noise.
- **Hierarchical Supervisor** (`hierarchical-supervisor`): Managers over leads over specialists, mirroring an org chart. Use when: The task spans several distinct domains, each with its own tools and checks; One orchestrator would need to manage more than about 5–7 agents; Different teams own different domains and their agents; You need clear accountability for each part of the result. Avoid when: A flat Orchestrator–Workers setup handles the task fine.
- **Handoff** (`handoff`): Agents pass control and context peer-to-peer with no central boss. Use when: Customer conversations that move across domains (sales, billing, support); Each domain has a clear owner with its own prompts and tools; You want the active specialist talking to the user directly; Topic changes happen mid-conversation, not just at the start. Avoid when: Tasks need several agents working at once; use Orchestrator–Workers.
- **Debate / Multi-Critic** (`debate`): Agents argue from different viewpoints and a judge picks the answer. Use when: High-stakes judgment calls with real trade-offs; You want risks surfaced before a decision, not after; Criteria for a good decision can be written down for the judge; The output feeds a human decision-maker, not an automatic action. Avoid when: Questions with a checkable right answer; verify instead.
- **Blackboard** (`blackboard`): Agents read and write a shared workspace and contribute when they can. Use when: Investigations or diagnoses where findings unlock each other unpredictably; Many specialists may contribute, and the set changes over time; You want a full, attributed record of how the answer was reached; Agents run at different speeds or on different schedules. Avoid when: The steps are known in advance; use a pipeline or Plan-and-Execute.

#### Context & memory
- **Agentic RAG** (`agentic-rag`): The agent decides when and what to retrieve, rewrites queries and checks relevance. Use when: Questions vary widely in wording and complexity; Answers often need facts from more than one source; Users need citations they can check; Bad answers from irrelevant context are costly. Avoid when: Simple lookups where one search reliably works.
- **Tiered Memory** (`tiered-memory`): Working, episodic and semantic memory stored and recalled separately. Use when: Users return over days or weeks and expect continuity; Past outcomes can improve future runs; Personal preferences change how the agent should respond; Sessions are too long or too many to keep in raw form. Avoid when: Single-shot tasks with no returning users.
- **Context Compaction** (`context-compaction`): Summarize or prune history so long tasks fit the context window. Use when: Agents run for many steps or hours; Tool outputs are large (logs, documents, search results); Early instructions or decisions must stay in force throughout; Cost and latency rise noticeably as context grows. Avoid when: Short tasks that never approach the context limit.
- **Sub-agent Context Isolation** (`context-isolation`): A sub-agent explores in a clean context and returns only a summary. Use when: A step needs heavy reading or searching to produce a small answer; Exploration involves trial and error the main agent doesn't need to see; The main task is long and its context is precious; The step can be described clearly without the main agent's full history. Avoid when: The step needs the main agent's full context to be done right.

#### Safety & control
- **Human-in-the-Loop** (`human-in-the-loop`): Pause for human approval before risky or irreversible actions. Use when: The agent takes irreversible actions (payments, deletions, external messages); Regulations or contracts require a named person to approve; You're rolling out a new agent and building trust in it; Errors are rare but very costly. Avoid when: Every action is easily reversible; log and allow undo instead.
- **Guardrails** (`guardrails`): Input and output filters, policy checks and schema validation around the agent. Use when: The agent handles untrusted input, such as public users, emails or web pages; Outputs go to customers or into other systems; Personal data, secrets or regulated content are in play; You need evidence that policies are enforced, not just requested. Avoid when: Never; every production agent needs some guardrails.
- **Bounded Autonomy** (`bounded-autonomy`): Limits enforced by policy, not prompts: tool allowlists, spend caps, scope. Use when: Always, for any agent that can call tools with side effects; The agent processes untrusted content that might contain injections; Different agents or users need different levels of access; You need to show auditors exactly what an agent is able to do. Avoid when: Never skip it; scale how strict it is to the risk.
- **Sandboxed Execution** (`sandboxed-execution`): Code and actions run in isolation with checkpoints and rollback. Use when: The agent writes and runs code, or installs packages; The agent edits files, databases or infrastructure; It processes untrusted content that might contain attacks; Multi-step changes need a clean undo. Avoid when: The agent only reads data and calls narrow, safe APIs.

#### Runtime & interop
- **Agent Harness** (`agent-harness`): A reusable runtime for loop, tools, memory, permissions and progress, instead of one-off scripts. Use when: An organization plans more than a handful of agents; Governance, audit and security need one enforcement point; Employees should be able to build their own agents and workflows safely; Agents run long tasks that need progress tracking and recovery. Avoid when: A single, narrow agent with no plans to add more.
- **Code-as-Action** (`code-as-action`): The agent writes code that chains many tool calls, instead of one JSON call per step. Use when: Tasks loop over many items or combine results from several tools; Intermediate data is large but the needed answer is small; Latency and token cost from many round trips are a problem; A sandbox is already available. Avoid when: One or two tool calls do the job.
- **Skills / Progressive Disclosure** (`skills`): Packaged instructions load only when relevant, keeping base context small. Use when: The agent handles many distinct kinds of tasks; Each task type has detailed procedures, templates or scripts; Different teams own different capabilities; Base prompt size has become a cost or quality problem. Avoid when: The agent does one narrow job; put the instructions in the prompt.
- **Protocol Interop (MCP / A2A)** (`protocol-interop`): Standard servers for tools and agent-to-agent messaging across vendors. Use when: Several agents need the same systems; Agents from different vendors or teams must work together; You want to swap models or frameworks without rewriting integrations; Security wants a single choke point for agent access. Avoid when: One agent and one or two systems; a direct integration is simpler.
- **Budget-aware Planning** (`budget-aware-planning`): Each stage gets a token, time or dollar budget and degrades gracefully. Use when: Open-ended tasks like research, debugging or multi-agent runs; Cost or response time must be predictable; A partial answer is better than none; Different users or request types justify different spend. Avoid when: Tasks with a fixed, small number of steps.
- **Ambient Agents** (`ambient-agents`): Always-on agents watch event streams and act or alert without a prompt. Use when: Important signals are spread across many systems and arrive continuously; Missing a signal is costly (churn, outages, deadlines); Users would welcome a daily digest of what changed; You have strong permission and audit controls in place. Avoid when: Users can't easily control or silence the agent.
- **Generative UI** (`generative-ui`): The agent renders or changes interface elements, not just chat text. Use when: Answers are naturally tables, charts, forms or filtered views; Users work in an app and want the app itself to respond; The app has a component library that can be described with schemas; Actions should be reviewable in a form before they're submitted. Avoid when: Short factual answers where text is clearest.
- **Delegated Agent Identity** (`delegated-identity`): Agents get their own scoped, auditable credentials to act for a user. Use when: Agents act in systems on behalf of specific users; Audit must distinguish agent actions from human actions; Several agents need different, limited access; Users should control and revoke what agents can do. Avoid when: The agent never touches user-specific data or systems.

#### Evaluation & learning
- **Rubric LLM-as-Judge** (`llm-as-judge`): Automated graders with explicit rubrics for CI evals and runtime monitoring. Use when: Outputs are open-ended text, plans or actions; You change prompts, models or tools often and need regression checks; Quality criteria can be written down and illustrated with examples; You want ongoing monitoring of live quality. Avoid when: Outputs can be checked exactly (math, schemas, tests); check them directly.
- **Self-Improving Learning Loop** (`learning-loop`): Feedback and outcomes become updated memory, skills or prompts over time. Use when: The agent runs often enough to generate steady feedback; Users edit or correct outputs in ways you can capture; You have an evaluation set to test changes before rollout; Improvement over weeks matters more than perfection on day one. Avoid when: Low volume, so feedback is too sparse to learn from.

#### Fast & slow
- **Talker–Reasoner** (`talker-reasoner`): A System 1 model keeps the conversation live while a System 2 model works in the background. Use when: Voice agents or live chat where silence feels broken; Tasks need tools or reasoning that take many seconds; Users add details or change requests while work is in progress; You want the conversational tone tuned separately from task logic. Avoid when: Tasks finish in a second or two; one model is simpler.
- **Fast/Slow Escalation** (`fast-slow-escalation`): System 1 by default; escalate to System 2 when signals say the task is hard. Use when: Traffic is mostly routine with a long tail of hard cases; Latency matters, such as chat, voice or customer-facing flows; You can define stakes in business terms, such as refund amount or account tier; You have logs to calibrate thresholds. Avoid when: Every request is hard, so escalation would fire constantly.
- **Draft–Verify** (`draft-verify`): System 1 drafts quickly; System 2 checks or corrects the draft. Use when: High-volume outputs that are mostly correct already; Claims can be checked against provided sources or data; Verifying is clearly cheaper than generating, such as long drafts with a few facts; Errors are costly but latency can absorb one check. Avoid when: The fast model is wrong so often that most drafts get regenerated.
- **Respond-then-Refine** (`respond-then-refine`): An instant first answer from System 1, followed by a refined System 2 version. Use when: Interactive tools where waiting 20+ seconds loses the user; Analysis questions where a first take is useful and a deeper one is better; Users can see an answer update in place (dashboards, chat with streaming UI); You can tell which requests deserve the background pass. Avoid when: The first answer will trigger an irreversible action.
- **Adaptive Thinking Budget** (`adaptive-thinking`): One model switches between no thinking and deep thinking based on difficulty. Use when: Your model supports adjustable thinking or effort levels; Request difficulty varies a lot within the same product; You want fast/slow behavior without running two models; You can measure quality per effort level to tune the policy. Avoid when: Your model has no effort control.
- **Metacognitive Monitor** (`metacognitive-monitor`): A lightweight watcher spots surprises and switches the agent into System 2 mode. Use when: Long-running or multi-step agents where mid-run errors compound; Agents that take real actions in other systems; You can name concrete warning signs from past failures; Fast mode is right most of the time but fails in recognizable ways. Avoid when: Short, single-call tasks; check the output instead.
- **Habit Formation** (`habit-formation`): Repeated System 2 solutions get compiled into fast System 1 skills or rules. Use when: The same kinds of hard case keep reaching System 2; Outcomes can be judged, so you know which solutions worked; You already log traces from the slow path; Cost or latency of escalations is a real concern. Avoid when: Hard cases are genuinely unique each time.
- **Reflex Layer** (`reflex-layer`): Instant System 1 responses for routine or safety-critical checks: triage, guardrails, stop/continue. Use when: A check must run on every request or every step; The question is narrow and typed (yes/no, label, score); Speed or cost rules out a large model for the check; Safety or compliance needs a consistent first line of defense. Avoid when: The judgment is nuanced and depends on wide context.

### Track: Building with coding agents

#### Working agreements
- **Spec-Driven Development** (`spec-driven-development`): A short spec is the source of truth; the agent builds from it, not from chat history. Use when: Building anything bigger than a single small change; Work spans several sessions, agents or teammates; You need clear acceptance criteria to know when you're done; Stakeholders need to agree on scope before code is written. Avoid when: Quick fixes and experiments where the spec would be longer than the change.
- **Project Memory File** (`project-memory-file`): A CLAUDE.md or AGENTS.md file holds conventions, commands and decisions that build up over time. Use when: Any repo where coding agents work more than once; Several developers or agents work on the same codebase; The project has conventions or commands that aren't obvious; You keep correcting the agent on the same thing. Avoid when: One-off scripts that won't be touched again.
- **Agent-Ready Repo** (`agent-ready-repo`): One-command setup, scripted checks and clear docs, so an agent can run and verify its own work. Use when: Coding agents work in the repo regularly; Setup or tests currently need manual steps or tribal knowledge; Agents often claim work is done that later fails in CI; Several agents or new developers need to get started quickly. Avoid when: Throwaway prototypes that won't live long.
- **Artifact Ownership** (`artifact-ownership`): Each artifact is marked developer-owned, AI-drafted or joint, so everyone knows who decides what. Use when: Agents have broad write access to the repo; Some files encode business decisions, contracts or security choices; Several people and agents share the same codebase; Agents have changed tests or specs to make their work "pass". Avoid when: Solo throwaway projects where you review everything anyway.

#### Build loop
- **Plan-then-Code** (`plan-then-code`): The agent proposes a plan; a human approves it before any files change. Use when: Tasks touch several files or an unfamiliar part of the codebase; There's more than one reasonable approach; Mistakes would be expensive to unwind (schema, API, security changes); You want to stay in control of design without writing the code. Avoid when: One-line fixes and obvious changes.
- **Test-First Agent Loop** (`test-first-loop`): Tests define "done"; the agent iterates until they pass. Use when: Behavior can be expressed as automated tests; The agent can run the test suite quickly (see Agent-Ready Repo); Bug fixes, where a failing test reproduces the bug first; Refactors, where existing tests must keep passing. Avoid when: Visual or UX work that tests can't capture well; review manually.
- **Thin-Slice MVPs** (`thin-slice-mvps`): Each session ships one small, working vertical slice (MVP1 → MVP2 → MVP3). Use when: Building a new app or feature with a coding agent; Requirements are likely to change once people use the software; You want reviewable PRs instead of one giant change; Several sessions or developers will contribute over time. Avoid when: Tiny tasks that are already one slice.

#### Review & scale
- **PR as Review Gate** (`pr-review-gate`): Agents work on branches, and every change lands through a reviewed pull request. Use when: Any shared codebase where agents make changes; Teams need an audit trail of what agents changed and who approved it; Changes must pass CI before anyone depends on them; Several agents or developers work in parallel. Avoid when: Personal scratch repos where speed matters more than review.
- **Parallel Agents in Worktrees** (`parallel-worktrees`): Several agents work on isolated branches at once, then merge through review. Use when: The backlog has several independent tasks; The repo is agent-ready, so each workspace can set up and test itself; Review capacity can keep up with several PRs; Wall-clock time matters more than token cost. Avoid when: Tasks touch the same files or depend on each other.

