What are AI agent design patterns?
AI agent design patterns are reusable ways to arrange model calls, tools and plain code so an AI system can finish a task reliably. Google's architecture guide puts it in one line: "Agent design patterns are common architectural approaches to build agentic applications."
The most useful split comes from Anthropic's post Building effective agents (19 December 2024). It sorts every pattern into one of two families:
- Workflows: "systems where LLMs and tools are orchestrated through predefined code paths." You decide the steps. The model fills in each step.
- Agents: "systems where LLMs dynamically direct their own processes and tool usage". The model decides the steps, usually by calling tools in a loop until it is done.
Think of a workflow as a recipe card: chop, then fry, then plate, every time. An agent is a cook who is handed a goal and a kitchen and decides what to do next after tasting the dish. The recipe card is cheaper and more predictable. The cook handles dishes nobody wrote a card for.
Both families are built from the same brick, which Anthropic calls the augmented LLM: "an LLM enhanced with augmentations such as retrieval, tools, and memory." Every pattern below is a different way of wiring those bricks together.
The advice every major guide gives first is to not reach for an agent by default. Anthropic: "we recommend finding the simplest solution possible, and only increasing complexity when needed. This might mean not building agentic systems at all." Microsoft: "Use the lowest level of complexity that reliably meets your requirements." OpenAI: "Our general recommendation is to maximize a single agent's capabilities first." We tested that advice below.
The patterns at a glance
"Model calls" is the minimum number of language model calls one request needs; N is the number of subtasks or rounds.
| Pattern | What it does | Use it when | Model calls |
|---|---|---|---|
| Single call | One well-built prompt with the right context | The task fits in one prompt. Try this first | 1 |
| Prompt chaining | A fixed sequence of calls, each using the last one's output, with code checks ("gates") in between | The task splits cleanly into fixed steps | 2+ |
| Routing | Classify the input, then send it to a specialised prompt, model or code path | Inputs fall into distinct categories that are easy to classify | 2 |
| Parallelization | Run independent parts at once (sectioning) or the same task several times and vote (voting) | Parts are independent, or you want several attempts for confidence | N, side by side |
| Orchestrator-workers | One model splits the task at run time, workers do the parts, the orchestrator combines them | You cannot know the subtasks in advance | N + 2 |
| Evaluator-optimizer | One call answers, another checks it and sends feedback, in a loop | You have clear criteria to check against | 2 per round |
| Agent (ReAct loop) | The model thinks, calls a tool, reads the result, and repeats until it can answer | Open-ended tasks where you cannot predict the steps | Unknown; cap it |
| Plan-and-execute | One call writes a plan, then the steps are carried out, often by cheaper models | Long tasks where a plan up front avoids wandering | Plan + N |
| Multi-agent | Several agents with their own roles hand work to each other or talk in a shared thread | One agent's prompt and tool list have grown too big to manage | Many |
The first six rows are workflows. The last three are agents. A human-in-the-loop step, where a person approves an action before it runs, can be added to any of them.
The five workflow patterns, explained
These are the five workflows in Anthropic's post. LangGraph's "Workflows and agents" guide implements the same five plus agents, and Microsoft and Google describe the same shapes under other names (see the name map).
1. Prompt chaining
"Prompt chaining decomposes a task into a sequence of steps, where each LLM call processes the output of the previous one." Between steps you can add "programmatic checks", which Anthropic calls a gate: plain code that stops the chain if a step's output is malformed. Example: step 1 pulls the order number out of a support email, the gate checks the order exists, step 2 writes the reply. The trade, in Anthropic's words, is "latency for higher accuracy, by making each LLM call an easier task."
2. Routing
"Routing classifies an input and directs it to a specialized followup task." A refund request goes to the refund prompt, a technical question to the tech prompt, an easy question to a small cheap model. It works when "classification can be handled accurately". If the classifier is wrong, everything after it is wrong, so routing is only as good as its first step.
3. Parallelization
Two versions. Sectioning: "Breaking a task into independent subtasks run in parallel", for example one call screens a message for abuse while another answers it. Voting: "Running the same task multiple times to get diverse outputs", then taking the majority. It costs more calls but not more waiting time, because the calls run at the same time.
4. Orchestrator-workers
"A central LLM dynamically breaks down tasks, delegates them to worker LLMs, and synthesizes their results." The difference from parallelization is that the subtasks are decided at run time, not written by you. A coding assistant that decides which files need changing, then changes each one, is the classic example. Our multi-agent systems test found the weak point: the orchestrator's summary of the task to each worker can drop the detail that matters.
5. Evaluator-optimizer
"One LLM call generates a response while another provides evaluation and feedback in a loop." It pays off "when we have clear evaluation criteria". This is the workflow version of what papers call reflection. Self-Refine (Madaan et al., 2023) had a model critique and rewrite its own output and reported "improving by ~20% absolute on average in task performance" across 7 tasks with GPT-3.5 and GPT-4. The catch, which our test shows, is that a checker no stronger than the writer can approve a wrong answer or "fix" a right one.
Agent patterns: ReAct, reflection, planning, multi-agent
Anthropic describes agents as "typically just LLMs using tools based on environmental feedback in a loop." Andrew Ng's widely shared list of four agentic design patterns (The Batch, 20 March 2024) names the moves inside that loop: reflection ("The LLM examines its own work to come up with ways to improve it"), tool use, planning and multi-agent collaboration.
ReAct: reason and act
ReAct comes from the paper ReAct: Synergizing Reasoning and Acting in Language Models (Yao et al., first posted 6 October 2022, published at ICLR). The full form is Reason + Act. The model writes a thought, takes an action (a tool call), reads the observation (the tool's result), and repeats. Google's guide describes it as "an iterative loop of thought, action, and observation until an exit condition is met." The paper reported that ReAct "outperforms imitation and reinforcement learning methods by an absolute success rate of 34% and 10%" on the ALFWorld and WebShop benchmarks, with only one or two examples in the prompt.
Most "AI agents" you meet in 2026 are a ReAct loop with native tool calling: the model returns a structured tool call instead of a written "Action:" line, and your code runs the tool and sends back the result. The one rule every guide repeats is to cap the loop. Microsoft: "To guard against infinite tool-call loops, set iteration limits."
Reflection and Reflexion
Reflection inside an agent means the agent reviews its own result before answering, or after a failed attempt. Reflexion (Shinn et al., 2023) keeps those reviews as notes: agents "verbally reflect on task feedback signals, then maintain their own reflective text in an episodic memory buffer". It reported "91% pass@1 accuracy on the HumanEval coding benchmark", against 80% for GPT-4 at the time. Note what made that work: running the code against tests is an outside signal, not the model's opinion of itself.
Planning: plan-and-execute and ReWOO
A ReAct agent decides one step at a time. A planning agent writes the whole plan first. Plan-and-Solve prompting (Wang et al., ACL 2023) has two parts: "first, devising a plan to divide the entire task into smaller subtasks, and then carrying out the subtasks according to the plan." LangChain's Plan-and-Execute post (10 May 2023) is honest about the cost: it "takes a lot more calls", with the hope that those calls can go to "smaller (and therefore faster and cheaper) models". ReWOO plans all tool calls before seeing any result and reported "5x token efficiency and 4% accuracy improvement on HotpotQA".
Multi-agent
When one agent's prompt and tool list grow too large, you split it into several agents. OpenAI's guide names two shapes: the manager pattern, where a central model calls other agents like tools, and the decentralized pattern, where "agents can 'handoff' workflow execution to one another". Microsoft adds group chat and "magentic" orchestration for open-ended problems. Microsoft's own warning is that multi-agent "Adds coordination overhead, latency, and failure modes." We tested four multi-agent designs on their own page.
Same patterns, different names
Searching for "agentic design patterns" turns up lists of 4, 5, 11 or 21 patterns. Most of the difference is naming. Here is how the main guides line up, as of 24 November 2026.
| Idea | Anthropic (Dec 2024) | Google Cloud | Microsoft Azure | Others |
|---|---|---|---|---|
| Fixed steps in order | Prompt chaining | Sequential pattern | Sequential orchestration ("pipeline, prompt chaining") | CrewAI: sequential process |
| Classify, then hand off | Routing | Coordinator pattern (closest: it dispatches to specialists) | Handoff orchestration ("routing, triage") | OpenAI: decentralized handoffs |
| Side by side | Parallelization | Parallel pattern | Concurrent orchestration ("fan-out/fan-in") | |
| Split at run time | Orchestrator-workers | Coordinator; hierarchical task decomposition | Magentic orchestration | OpenAI: manager pattern; CrewAI: hierarchical process |
| Write, check, fix | Evaluator-optimizer | Review and critique; iterative refinement; loop | Group chat ("maker-checker") | Ng: reflection |
| Tool loop | Agents | Reason and act (ReAct) | Single agent with tools | Ng: tool use, planning |
| Peers talk freely | Swarm pattern | Group chat | Ng: multi-agent collaboration | |
| Person approves | (checkpoints for human feedback) | Human-in-the-loop pattern | (human in the loop, any pattern) |
Antonio Gullí's book Agentic Design Patterns: A Hands-On Guide to Building Intelligent Systems (Springer, October 2025) goes the furthest, with "21 proven agentic patterns" across 29 chapters, from prompt chaining and tool use to guardrails. Springer's page shows eBook ISBN 978-3-032-01402-3. If you see a free "agentic design patterns PDF" link, check that it comes from the author or Springer before you download it.
We tested six patterns on one task
Pattern lists are easy to agree with and hard to choose from, so we built one small job and solved it six ways with the same model. The job: a refund desk for ShopKart, an invented online shop. A customer writes in, and the system must say how many rupees to refund under a four-rule policy:
ShopKart refund policy
1. Damaged item: if the customer reports it within 7 days of delivery, refund the item price. Shipping is not refunded. After 7 days, no refund.
2. Wrong item delivered: within 30 days of delivery, refund the item price plus the shipping fee.
3. Change of mind: within 10 days of delivery, refund the item price minus a 10% restocking fee. Final-sale items get no refund for change of mind.
4. Late delivery: if the order was delivered more than 3 days after the promised date, refund the shipping fee only. Otherwise no refund.
Anything else: no refund.
"Within N days" means the number of days from the delivery date to today is N or less. All amounts are in rupees.
There are 8 orders and 8 customer messages. Each message has a right answer we worked out by hand, and each one hides a trap that real refund desks see: a damage report that comes after the 7-day window, a "total paid" that includes shipping, a final-sale item (which blocks change-of-mind refunds but not damage refunds), a "late" order that was only 2 days late, and a 10% restocking fee to work out.
| Case | Order | What the customer says | Right refund | Why |
|---|---|---|---|---|
| 1 | SK1001 (wireless earbuds) | Order SK1001: the left earbud arrived cracked. I paid Rs 2,548 in total, please refund it. | 2,499 | damaged, 5 days after delivery: item price 2,499 (the 2,548 total includes 49 shipping, which is not refunded) |
| 2 | SK1004 (mechanical keyboard) | Hi, my keyboard from order SK1004 has two broken keys. It must have been damaged in transit. I only opened the box today. | 0 | damaged, but 11 days after delivery (limit 7): 0 |
| 3 | SK1003 (steel water bottle) | SK1003 was promised for 1 November and only came on 8 November. A whole week late. I want a refund. | 49 | late by 7 days (more than 3): shipping fee 49 only |
| 4 | SK1005 (running shoes) | I ordered running shoes (SK1005) but I changed my mind, I don't need them any more. Can I return them for a refund? | 0 | change of mind on a final-sale item: 0 |
| 5 | SK1006 (desk lamp) | The desk lamp (order SK1006) works fine, but it doesn't suit my room. I'd like to send it back. | 1,035 | change of mind, 6 days, not final sale: 1,150 - 10% = 1,035 |
| 6 | SK1007 (backpack) | Order SK1007: I ordered a backpack and you sent me a blue wallet instead. | 1,948 | wrong item, 20 days (limit 30): 1,899 + 49 shipping = 1,948 |
| 7 | SK1008 (phone case) | My phone case (SK1008) came late. That's not acceptable, I want my money back. | 0 | delivered 2 days after the promised date (needs more than 3): 0 |
| 8 | SK1002 (cotton kurta) | The kurta from order SK1002 has torn stitching on the sleeve. I know it was a sale item, but it arrived like this. | 1,299 | damaged, 4 days; final sale only blocks change-of-mind refunds: 1,299 |
The six designs, all with qwen2.5:3b (a free 3-billion-parameter model) running locally in Ollama 0.24.0 at temperature 0 with a fixed seed, on a busy laptop CPU:
- single: one call. The policy, all 8 orders, today's date and the message go in;
{"refund": n}comes out. - chain (prompt chaining with a gate): call 1 reads the message and returns the order id and the issue type as JSON. A code gate checks that the order exists and the issue is one of five labels, and asks once more if not. Call 2 gets the policy, only that order's row and the issue, and decides.
- routing: the same call 1 picks the issue type. Code routes to a handler prompt that holds only that issue's rule and the order's row.
- evaluator (evaluator-optimizer): the single call's answer goes to a checker call with the full policy and orders, which replies "correct" or gives a corrected amount. Up to 2 checker rounds.
- agent (a ReAct-style loop with native tool calls): the model has the policy and three tools,
get_order,days_betweenandcalculate, and calls them until it answers. Capped at 8 model calls. - extract+code: the same call 1, then plain Python applies the four rules. No model in the decision at all.
Chain, routing and extract+code share call 1: it ran once per case and its result was fed to all three, so they differ only in what happens after it. Every model call, with the exact messages sent and the reply, is in calls.jsonl.
desk.py (the policy, orders, cases and the answer key)
"""ShopKart refund desk (invented): the policy, the orders and the 8 test cases.
Every case has a right answer worked out by hand (see `why`), and `rules_refund` (plain Python)
must agree with all of them: `python3 desk.py` checks that and prints the table.
"""
from datetime import date
POLICY = """ShopKart refund policy
1. Damaged item: if the customer reports it within 7 days of delivery, refund the item price. Shipping is not refunded. After 7 days, no refund.
2. Wrong item delivered: within 30 days of delivery, refund the item price plus the shipping fee.
3. Change of mind: within 10 days of delivery, refund the item price minus a 10% restocking fee. Final-sale items get no refund for change of mind.
4. Late delivery: if the order was delivered more than 3 days after the promised date, refund the shipping fee only. Otherwise no refund.
Anything else: no refund.
"Within N days" means the number of days from the delivery date to today is N or less. All amounts are in rupees."""
ORDERS = {
"SK1001": {"item": "Wireless earbuds", "price": 2499, "shipping": 49, "promised": "2026-11-10", "delivered": "2026-11-12", "final_sale": False},
"SK1002": {"item": "Cotton kurta", "price": 1299, "shipping": 0, "promised": "2026-11-05", "delivered": "2026-11-05", "final_sale": True},
"SK1003": {"item": "Steel water bottle", "price": 699, "shipping": 49, "promised": "2026-11-01", "delivered": "2026-11-08", "final_sale": False},
"SK1004": {"item": "Mechanical keyboard", "price": 4850, "shipping": 99, "promised": "2026-11-12", "delivered": "2026-11-13", "final_sale": False},
"SK1005": {"item": "Running shoes", "price": 3199, "shipping": 0, "promised": "2026-11-14", "delivered": "2026-11-14", "final_sale": True},
"SK1006": {"item": "Desk lamp", "price": 1150, "shipping": 49, "promised": "2026-11-15", "delivered": "2026-11-15", "final_sale": False},
"SK1007": {"item": "Backpack", "price": 1899, "shipping": 49, "promised": "2026-11-02", "delivered": "2026-11-02", "final_sale": False},
"SK1008": {"item": "Phone case", "price": 399, "shipping": 49, "promised": "2026-11-18", "delivered": "2026-11-20", "final_sale": False},
}
ISSUES = ["damaged", "wrong_item", "change_of_mind", "late", "other"]
CASES = [
{"id": 1, "today": "2026-11-17", "order": "SK1001", "issue": "damaged", "expected": 2499,
"message": "Order SK1001: the left earbud arrived cracked. I paid Rs 2,548 in total, please refund it.",
"why": "damaged, 5 days after delivery: item price 2,499 (the 2,548 total includes 49 shipping, which is not refunded)"},
{"id": 2, "today": "2026-11-24", "order": "SK1004", "issue": "damaged", "expected": 0,
"message": "Hi, my keyboard from order SK1004 has two broken keys. It must have been damaged in transit. I only opened the box today.",
"why": "damaged, but 11 days after delivery (limit 7): 0"},
{"id": 3, "today": "2026-11-20", "order": "SK1003", "issue": "late", "expected": 49,
"message": "SK1003 was promised for 1 November and only came on 8 November. A whole week late. I want a refund.",
"why": "late by 7 days (more than 3): shipping fee 49 only"},
{"id": 4, "today": "2026-11-18", "order": "SK1005", "issue": "change_of_mind", "expected": 0,
"message": "I ordered running shoes (SK1005) but I changed my mind, I don't need them any more. Can I return them for a refund?",
"why": "change of mind on a final-sale item: 0"},
{"id": 5, "today": "2026-11-21", "order": "SK1006", "issue": "change_of_mind", "expected": 1035,
"message": "The desk lamp (order SK1006) works fine, but it doesn't suit my room. I'd like to send it back.",
"why": "change of mind, 6 days, not final sale: 1,150 - 10% = 1,035"},
{"id": 6, "today": "2026-11-22", "order": "SK1007", "issue": "wrong_item", "expected": 1948,
"message": "Order SK1007: I ordered a backpack and you sent me a blue wallet instead.",
"why": "wrong item, 20 days (limit 30): 1,899 + 49 shipping = 1,948"},
{"id": 7, "today": "2026-11-22", "order": "SK1008", "issue": "late", "expected": 0,
"message": "My phone case (SK1008) came late. That's not acceptable, I want my money back.",
"why": "delivered 2 days after the promised date (needs more than 3): 0"},
{"id": 8, "today": "2026-11-09", "order": "SK1002", "issue": "damaged", "expected": 1299,
"message": "The kurta from order SK1002 has torn stitching on the sleeve. I know it was a sale item, but it arrived like this.",
"why": "damaged, 4 days; final sale only blocks change-of-mind refunds: 1,299"},
]
def days_between(a, b):
return (date.fromisoformat(b) - date.fromisoformat(a)).days
def rules_refund(order_id, issue, today):
"""The policy as plain code. Used by the 'extract + code' design and to check the answer key."""
o = ORDERS.get(order_id)
if o is None:
return 0
days = days_between(o["delivered"], today)
if issue == "damaged":
return o["price"] if days <= 7 else 0
if issue == "wrong_item":
return o["price"] + o["shipping"] if days <= 30 else 0
if issue == "change_of_mind":
return 0 if o["final_sale"] or days > 10 else round(o["price"] * 0.9)
if issue == "late":
return o["shipping"] if days_between(o["promised"], o["delivered"]) > 3 else 0
return 0
def orders_table(ids=None):
rows = ["order_id | item | price | shipping fee | promised | delivered | final sale"]
for k, o in ORDERS.items():
if ids is None or k in ids:
rows.append(f"{k} | {o['item']} | {o['price']} | {o['shipping']} | {o['promised']} | {o['delivered']} | {'yes' if o['final_sale'] else 'no'}")
return "\n".join(rows)
if __name__ == "__main__":
ok = True
for c in CASES:
got = rules_refund(c["order"], c["issue"], c["today"])
flag = "OK" if got == c["expected"] else "MISMATCH"
ok &= got == c["expected"]
print(f"case {c['id']}: {c['order']} {c['issue']:<15} expected {c['expected']:>5} rules {got:>5} {flag} ({c['why']})")
print("answer key", "OK" if ok else "BROKEN")
Output of python3 desk.py
case 1: SK1001 damaged expected 2499 rules 2499 OK (damaged, 5 days after delivery: item price 2,499 (the 2,548 total includes 49 shipping, which is not refunded))
case 2: SK1004 damaged expected 0 rules 0 OK (damaged, but 11 days after delivery (limit 7): 0)
case 3: SK1003 late expected 49 rules 49 OK (late by 7 days (more than 3): shipping fee 49 only)
case 4: SK1005 change_of_mind expected 0 rules 0 OK (change of mind on a final-sale item: 0)
case 5: SK1006 change_of_mind expected 1035 rules 1035 OK (change of mind, 6 days, not final sale: 1,150 - 10% = 1,035)
case 6: SK1007 wrong_item expected 1948 rules 1948 OK (wrong item, 20 days (limit 30): 1,899 + 49 shipping = 1,948)
case 7: SK1008 late expected 0 rules 0 OK (delivered 2 days after the promised date (needs more than 3): 0)
case 8: SK1002 damaged expected 1299 rules 1299 OK (damaged, 4 days; final sale only blocks change-of-mind refunds: 1,299)
answer key OK
patterns.py (the six designs; standard library only, talks to Ollama's /api/chat)
"""Six designs, one refund desk, one small local model (qwen2.5:3b via Ollama, temperature 0, seed 42).
single one call: policy + all orders + message -> refund
chain prompt chaining: call 1 extracts order id + issue, a code gate checks it,
call 2 decides with the policy and only that order's row
routing the same call 1 picks the issue type; code routes to a handler prompt that
holds only that issue's rule + the order's row
evaluator evaluator-optimizer: the single call's answer, then a checker call that
accepts it or gives a corrected amount (max 2 checker rounds)
agent a ReAct-style tool loop: the model calls get_order / days_between / calculate
until it answers (max 8 model calls)
extract+code the same call 1, then plain Python applies the policy (no model in the decision)
Every model call is logged to calls.jsonl (messages, reply, token counts, seconds).
Results go to results.jsonl, one line per (case, design); finished pairs are skipped on re-run.
Usage: python3 patterns.py [case ids...]
"""
import ast
import json
import operator
import os
import re
import sys
import time
import urllib.request
from desk import CASES, ISSUES, ORDERS, POLICY, days_between, orders_table, rules_refund
HERE = os.path.dirname(os.path.abspath(__file__))
OLLAMA = "http://localhost:11434/api/chat"
MODEL = "qwen2.5:3b"
OPTIONS = {"temperature": 0, "seed": 42, "num_ctx": 4096, "num_thread": int(os.environ.get("NUM_THREAD", "0")) or None}
OPTIONS = {k: v for k, v in OPTIONS.items() if v is not None}
CALLS = os.path.join(HERE, "calls.jsonl")
RESULTS = os.path.join(HERE, "results.jsonl")
EXTRACT = os.path.join(HERE, "extract.json")
REFUND_SCHEMA = {"type": "object", "properties": {"refund": {"type": "integer"}}, "required": ["refund"]}
EXTRACT_SCHEMA = {"type": "object", "properties": {"order_id": {"type": "string"}, "issue": {"type": "string", "enum": ISSUES}},
"required": ["order_id", "issue"]}
CHECK_SCHEMA = {"type": "object", "properties": {"correct": {"type": "boolean"}, "refund": {"type": "integer"}},
"required": ["correct", "refund"]}
def chat(case_id, design, step, messages, fmt=None, tools=None):
body = {"model": MODEL, "messages": messages, "stream": False, "options": OPTIONS, "keep_alive": "30m"}
if fmt:
body["format"] = fmt
if tools:
body["tools"] = tools
t0 = time.time()
req = urllib.request.Request(OLLAMA, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=900) as r:
d = json.load(r)
secs = round(time.time() - t0, 1)
msg = d["message"]
rec = {"case": case_id, "design": design, "step": step, "messages": messages, "reply": msg.get("content", ""),
"tool_calls": msg.get("tool_calls"), "prompt_tokens": d.get("prompt_eval_count", 0),
"output_tokens": d.get("eval_count", 0), "seconds": secs,
"prompt_chars": sum(len(m.get("content") or "") for m in messages), "num_thread": OPTIONS.get("num_thread", "default")}
with open(CALLS, "a") as f:
f.write(json.dumps(rec) + "\n")
return msg, rec
def parse_refund(text):
try:
return int(round(float(json.loads(text)["refund"])))
except Exception:
m = re.findall(r"-?\d[\d,]*(?:\.\d+)?", text or "")
return int(round(float(m[-1].replace(",", "")))) if m else None
SYSTEM = "You are ShopKart's refund desk. Apply the refund policy exactly."
def ask_refund(case, design, context):
msgs = [{"role": "system", "content": SYSTEM},
{"role": "user", "content": f"{context}\n\nToday is {case['today']}.\nCustomer message: {case['message']}\n\n"
"How many rupees should we refund? Reply as JSON: {\"refund\": <integer>}"}]
msg, rec = chat(case["id"], design, "decide", msgs, fmt=REFUND_SCHEMA)
return parse_refund(msg["content"]), [rec]
def d_single(case):
return ask_refund(case, "single", f"{POLICY}\n\nOrders:\n{orders_table()}")
def extract(case):
"""Shared first step of chain, routing and extract+code. Code gate: known order id + known issue; one retry."""
cache = json.load(open(EXTRACT)) if os.path.exists(EXTRACT) else {}
if str(case["id"]) in cache:
return cache[str(case["id"])]
msgs = [{"role": "system", "content": "You read customer messages for ShopKart's refund desk."},
{"role": "user", "content": f"Customer message: {case['message']}\n\nWhich order is it about, and what is the issue? "
"issue must be one of: damaged, wrong_item, change_of_mind, late, other. "
"Reply as JSON: {\"order_id\": \"...\", \"issue\": \"...\"}"}]
recs, out, gate = [], None, []
for attempt in (1, 2):
msg, rec = chat(case["id"], "extract", f"extract-{attempt}", msgs, fmt=EXTRACT_SCHEMA)
recs.append(rec)
try:
out = json.loads(msg["content"])
except Exception:
out = {}
problems = []
if out.get("order_id") not in ORDERS:
problems.append(f"order_id {out.get('order_id')!r} is not a ShopKart order id (format SK followed by 4 digits)")
if out.get("issue") not in ISSUES:
problems.append(f"issue {out.get('issue')!r} is not one of {ISSUES}")
gate.append({"attempt": attempt, "output": out, "problems": problems})
if not problems:
break
msgs = msgs + [{"role": "assistant", "content": msg["content"]},
{"role": "user", "content": "That failed a check: " + "; ".join(problems) + ". Try again, same JSON format."}]
res = {"order_id": out.get("order_id"), "issue": out.get("issue"), "gate": gate, "calls": recs}
cache[str(case["id"])] = res
json.dump(cache, open(EXTRACT, "w"), indent=1)
return res
def d_chain(case):
ex = extract(case)
if not ex["gate"][-1]["problems"] == []:
return None, ex["calls"]
ctx = f"{POLICY}\n\nThe order:\n{orders_table([ex['order_id']])}\n\nIssue type: {ex['issue']}"
v, recs = ask_refund(case, "chain", ctx)
return v, ex["calls"] + recs
RULES = {i: line for i, line in zip(["damaged", "wrong_item", "change_of_mind", "late"], POLICY.splitlines()[1:5])}
def d_routing(case):
ex = extract(case)
if not ex["gate"][-1]["problems"] == []:
return None, ex["calls"]
if ex["issue"] == "other":
return 0, ex["calls"] # the 'other' route is fixed code: no refund
rule = RULES[ex["issue"]] + "\n" + POLICY.splitlines()[-1]
ctx = f"Refund rule for this request:\n{rule}\n\nThe order:\n{orders_table([ex['order_id']])}"
v, recs = ask_refund(case, "routing", ctx)
return v, ex["calls"] + recs
def d_extract_code(case):
ex = extract(case)
if not ex["gate"][-1]["problems"] == []:
return None, ex["calls"]
return rules_refund(ex["order_id"], ex["issue"], case["today"]), ex["calls"]
def d_evaluator(case, single_answer, single_recs):
proposed, recs = single_answer, list(single_recs)
for rnd in (1, 2):
msgs = [{"role": "system", "content": "You check refund decisions for ShopKart against the policy. Be strict."},
{"role": "user", "content": f"{POLICY}\n\nOrders:\n{orders_table()}\n\nToday is {case['today']}.\n"
f"Customer message: {case['message']}\n\nProposed refund: {proposed} rupees.\n"
"Is the proposed refund correct under the policy? "
"Reply as JSON: {\"correct\": true or false, \"refund\": <the correct amount, integer>}"}]
msg, rec = chat(case["id"], "evaluator", f"check-{rnd}", msgs, fmt=CHECK_SCHEMA)
recs.append(rec)
try:
d = json.loads(msg["content"])
except Exception:
break
if d.get("correct") is True:
break
new = parse_refund(json.dumps({"refund": d.get("refund")}))
if new is None or new == proposed:
break
proposed = new
return proposed, recs
TOOLS = [
{"type": "function", "function": {"name": "get_order", "description": "Look up a ShopKart order by its id.",
"parameters": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]}}},
{"type": "function", "function": {"name": "days_between", "description": "Number of days from start_date to end_date (YYYY-MM-DD).",
"parameters": {"type": "object", "properties": {"start_date": {"type": "string"}, "end_date": {"type": "string"}},
"required": ["start_date", "end_date"]}}},
{"type": "function", "function": {"name": "calculate", "description": "Evaluate an arithmetic expression, e.g. 1150 * 0.9",
"parameters": {"type": "object", "properties": {"expression": {"type": "string"}}, "required": ["expression"]}}},
]
OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.USub: operator.neg}
def safe_eval(expr):
def ev(n):
if isinstance(n, ast.Expression):
return ev(n.body)
if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)):
return n.value
if isinstance(n, ast.BinOp) and type(n.op) in OPS:
return OPS[type(n.op)](ev(n.left), ev(n.right))
if isinstance(n, ast.UnaryOp) and type(n.op) in OPS:
return OPS[type(n.op)](ev(n.operand))
raise ValueError("only numbers and + - * / are allowed")
return ev(ast.parse(expr.replace(",", ""), mode="eval"))
def run_tool(name, args):
try:
if name == "get_order":
o = ORDERS.get(str(args.get("order_id", "")).strip().upper())
return json.dumps(o) if o else "error: no such order"
if name == "days_between":
return str(days_between(args["start_date"], args["end_date"]))
if name == "calculate":
v = safe_eval(str(args["expression"]))
return str(round(v, 2))
return f"error: unknown tool {name}"
except Exception as e:
return f"error: {e}"
def d_agent(case, max_calls=8):
msgs = [{"role": "system", "content": SYSTEM + "\n\n" + POLICY + "\n\nUse the tools to look up the order and to do any date or "
"number calculation. When you know the answer, reply with only: REFUND: <amount>"},
{"role": "user", "content": f"Today is {case['today']}.\nCustomer message: {case['message']}"}]
recs, trace = [], []
for i in range(1, max_calls + 1):
msg, rec = chat(case["id"], "agent", f"step-{i}", msgs, tools=TOOLS)
recs.append(rec)
calls = msg.get("tool_calls") or []
if not calls:
trace.append({"final": msg.get("content", "")})
return parse_refund(msg.get("content", "")), recs, trace
msgs.append({"role": "assistant", "content": msg.get("content", ""), "tool_calls": calls})
for c in calls:
fn = c["function"]
out = run_tool(fn["name"], fn.get("arguments") or {})
trace.append({"tool": fn["name"], "args": fn.get("arguments"), "result": out})
msgs.append({"role": "tool", "content": out, "tool_name": fn["name"]})
trace.append({"stopped": f"no answer after {max_calls} model calls"})
return None, recs, trace
def summarize(recs):
return {"model_calls": len(recs), "prompt_tokens": sum(r["prompt_tokens"] for r in recs),
"output_tokens": sum(r["output_tokens"] for r in recs), "seconds": round(sum(r["seconds"] for r in recs), 1),
"prompt_chars": sum(r["prompt_chars"] for r in recs)}
def main():
want = {int(a) for a in sys.argv[1:]} or {c["id"] for c in CASES}
done = set()
single_cache = {}
if os.path.exists(RESULTS):
for line in open(RESULTS):
r = json.loads(line)
done.add((r["case"], r["design"]))
if os.path.exists(CALLS):
for line in open(CALLS):
r = json.loads(line)
if r["design"] == "single":
single_cache[r["case"]] = r
def save(case, design, value, recs, extra=None):
row = {"case": case["id"], "design": design, "answer": value, "expected": case["expected"],
"correct": value == case["expected"], **summarize(recs), **(extra or {})}
with open(RESULTS, "a") as f:
f.write(json.dumps(row) + "\n")
print(f"case {case['id']} {design:<13} answer {value!s:>6} expected {case['expected']:>5} "
f"{'OK ' if row['correct'] else 'BAD'} calls {row['model_calls']} {row['seconds']} s", flush=True)
for case in CASES:
if case["id"] not in want:
continue
if (case["id"], "single") not in done:
v, recs = d_single(case)
single_cache[case["id"]] = recs[0]
save(case, "single", v, recs)
srec = single_cache[case["id"]]
s_val = parse_refund(srec["reply"])
for name, fn in (("chain", d_chain), ("routing", d_routing), ("extract+code", d_extract_code)):
if (case["id"], name) not in done:
v, recs = fn(case)
ex = extract(case)
save(case, name, v, recs, {"extracted": {"order_id": ex["order_id"], "issue": ex["issue"]},
"gate_retries": len(ex["gate"]) - 1})
if (case["id"], "evaluator") not in done:
v, recs = d_evaluator(case, s_val, [srec])
save(case, "evaluator", v, recs, {"started_from": s_val})
if (case["id"], "agent") not in done:
v, recs, trace = d_agent(case)
save(case, "agent", v, recs, {"trace": trace})
if __name__ == "__main__":
main()
What the run shows
All 48 results (8 cases × 6 designs), run on 24 November 2026. "Prompt tokens" and "output tokens" are Ollama's own counts, summed over every model call a design made for all 8 cases. Chain, routing and extract+code each include the shared call 1.
| Design | Right answers | Model calls | Calls per case | Prompt tokens | Output tokens | Median seconds per case |
|---|---|---|---|---|---|---|
| single | 1 of 8 | 8 | 1.0 | 5,100 | 77 | 134 |
| chain | 4 of 8 | 16 | 2.0 | 3,470 | 230 | 82 |
| routing | 4 of 8 | 16 | 2.0 | 2,628 | 242 | 68 |
| evaluator | 1 of 8 | 22 | 2.8 | 14,342 | 312 | 301 |
| agent | 1 of 8 | 19 | 2.4 | 10,942 | 703 | 362 |
| extract+code | 8 of 8 | 8 | 1.0 | 828 | 154 | 24 |
| Case | Right | single | chain | routing | evaluator | agent | extract+code |
|---|---|---|---|---|---|---|---|
| 1 | 2,499 | 2,499 ✓ | 2,499 ✓ | 2,499 ✓ | 0 ✗ | 2,499 ✓ | 2,499 ✓ |
| 2 | 0 | 5,261 ✗ | 4,859 ✗ | 4,859 ✗ | 2,850 ✗ | 4,752 ✗ | 0 ✓ |
| 3 | 49 | 749 ✗ | 49 ✓ | 49 ✓ | 749 ✗ | 500 ✗ | 49 ✓ |
| 4 | 0 | 3,199 ✗ | 3,298 ✗ | 3,167 ✗ | 3,199 ✗ | -3,199 ✗ | 0 ✓ |
| 5 | 1,035 | 1,159 ✗ | 1,159 ✗ | 1,035 ✓ | 0 ✗ | 1,199 ✗ | 1,035 ✓ |
| 6 | 1,948 | 1,899 ✗ | 1,948 ✓ | 2,398 ✗ | 0 ✗ | 1,753 ✗ | 1,948 ✓ |
| 7 | 0 | 49 ✗ | 49 ✗ | 49 ✗ | 0 ✓ | 500 ✗ | 0 ✓ |
| 8 | 1,299 | 1,349 ✗ | 1,299 ✓ | 1,299 ✓ | 0 ✗ | 1,169 ✗ | 1,299 ✓ |
1. Putting the rules in code won outright. extract+code got all 8 right with one small model call per case, the fewest prompt tokens (828 in total, against 5,100 for the single call) and the lowest median time (24 seconds). The model did only what it is good at, reading a message. Plain Python did what it is good at, counting days and applying a 10% fee. No other design came close.
2. The model read every message correctly. It was the rules it got wrong. Call 1 found the right order id and the right issue type in all 8 cases, first time, so the code gate never had to ask again. Yet the same model, given the same policy, got only 1 of 8 refunds right in a single call. It refunded ₹5,261 for a keyboard reported 11 days after delivery (limit 7), ₹749 on a late order that is owed only the ₹49 shipping fee, and ₹3,199 for a change of mind on a final-sale item. Understanding the request and applying a policy are different jobs, and a small model is only good at the first.
3. Smaller, focused prompts doubled the score, then hit a wall. Chain (one order's row instead of all 8) and routing (one rule instead of four) each got 4 of 8, against 1 of 8 for the single call, with a quarter to a third of the prompt tokens per call (164 and 217 against 638). But they failed on different cases: routing got the 10% restocking fee right (₹1,035) where chain did not, and chain got the wrong-item case right (₹1,948) where routing did not. Neither fixed the date windows: both refunded ₹4,859 on the 11-day damage report and ₹49 on the order that was only 2 days late.
4. The evaluator made things worse, not better. It started from the single call's answers (1 of 8 right) and ended at 1 of 8, while spending the most tokens of any design (14,342) and the most time (median 301 seconds). On case 1 it took the one right answer, ₹2,499, first "corrected" it to ₹2,548 (the trap: the customer's total including shipping) and then to ₹0. On case 3 it replied "correct": true for a wrong ₹749 while putting ₹529 in the same reply. It fixed exactly one case (the 2-days-late phone case, ₹49 to ₹0) and pushed 5 of 8 final answers to ₹0. A checker that is the same small model, with the same blind spots, is not a check.
5. The agent had the tools and the facts, and still applied the rules wrong. On case 2 it called get_order, then days_between and got 11 back, and answered "REFUND: 4751.89" anyway. On case 6 it used the calculate tool perfectly on the wrong formula, (1899 + 49) * (1 - 0.1), putting a restocking fee on a wrong-item refund. On cases 3 and 7 it never looked up the order at all and answered "REFUND: 500.0", a number that appears nowhere in the data. On case 4 it answered minus ₹3,199. Tools make the arithmetic exact. They do not make the model choose the right rule or the right arithmetic, and an agent loop gives a small model more places to go wrong, not fewer. It scored 1 of 8 with 2 to 3 model calls per case.
6. More model calls bought nothing here. Look at "Calls per case" against "Right answers": the two designs with the most calls (evaluator at 2.75, agent at 2.4) scored lowest, and the design with the fewest (extract+code at 1) scored highest. Agentic patterns trade latency and cost for quality only when the extra calls add something the first call lacked: a better model, an outside check, or information the model did not have.
summary.out (python3 results.py: right answers, calls, tokens and every answer per design)
single 1/8 calls 8 ptok 5100 otok 77 med 133.7 s total 1484.1 s wrong [2, 3, 4, 5, 6, 7, 8] answers {1: 2499, 2: 5261, 3: 749, 4: 3199, 5: 1159, 6: 1899, 7: 49, 8: 1349}
chain 4/8 calls 16 ptok 3470 otok 230 med 81.8 s total 1078.3 s wrong [2, 4, 5, 7] answers {1: 2499, 2: 4859, 3: 49, 4: 3298, 5: 1159, 6: 1948, 7: 49, 8: 1299}
routing 4/8 calls 16 ptok 2628 otok 242 med 67.7 s total 2100.9 s wrong [2, 4, 6, 7] answers {1: 2499, 2: 4859, 3: 49, 4: 3167, 5: 1035, 6: 2398, 7: 49, 8: 1299}
evaluator 1/8 calls 22 ptok 14342 otok 312 med 300.9 s total 3707.3 s wrong [1, 2, 3, 4, 5, 6, 8] answers {1: 0, 2: 2850, 3: 749, 4: 3199, 5: 0, 6: 0, 7: 0, 8: 0}
agent 1/8 calls 19 ptok 10942 otok 703 med 361.7 s total 2794.4 s wrong [2, 3, 4, 5, 6, 7, 8] answers {1: 2499, 2: 4752, 3: 500, 4: -3199, 5: 1199, 6: 1753, 7: 500, 8: 1169}
extract+code 8/8 calls 8 ptok 828 otok 154 med 23.9 s total 301.3 s wrong [] answers {1: 2499, 2: 0, 3: 49, 4: 0, 5: 1035, 6: 1948, 7: 0, 8: 1299}
The machine was shared with other jobs and swapping during the run, so per-call times ranged from 12 seconds (a checker call that reused the cached prompt) to over 10 minutes. Read the times as a comparison between designs. Seven calls in the middle of the run (case 2's agent and part of case 3) ran with Ollama's thread count set to 4 while we tried to ease the load. It slowed those calls down and did not change answers: one chain step that ran twice, at 4 threads and at the default, gave the same reply both times.
How to choose a design pattern
Walk down this list and stop at the first answer that works. Each step adds cost, delay and new ways to fail.
- Can one call do it? Give the model the right context (retrieval, examples, a schema for the output) and measure. Anthropic: "optimizing single LLM calls with retrieval and in-context examples is usually enough."
- Is any step a rule? Dates, sums, limits, eligibility, permissions: write them in code and let the model do only the language part. In our test this was the single biggest win.
- Are the steps fixed? Use prompt chaining, with a code gate after each step that can be checked.
- Are there distinct kinds of input? Use routing, but test the classifier on its own first; its mistakes flow into everything after it.
- Are the parts independent? Run them in parallel. Use voting only when a majority of tries is more likely right than one try.
- Can you check the answer? Add an evaluator only if the check is stronger than the writer: tests that run, a schema, a rule, a bigger model, or a person.
- Is the path truly unknown? Then use an agent loop with tools, an iteration cap, and logs of every step. Split into several agents only when one agent's tools and instructions no longer fit.
Interview questions on agent design patterns
1. What is the difference between an agentic workflow and an AI agent?
In a workflow, your code fixes the steps and the model fills each one in. In an agent, the model decides the next step itself, usually by calling tools in a loop. Anthropic calls both "agentic systems" and draws the line at who controls the path.
2. What does ReAct stand for, and how does the loop work?
Reason + Act (Yao et al., 2022). The model writes a thought, calls a tool, reads the result (the observation), and repeats until it can answer or hits a stop condition such as a maximum number of steps.
3. Prompt chaining vs routing?
Chaining runs the same fixed steps for every input, one after another. Routing classifies each input first and sends it down a different path, so different inputs get different prompts, models or code.
4. What is a "gate" in prompt chaining?
A programmatic check between two model calls, for example "is this a real order number?" or "does the JSON match the schema?". If it fails, you retry or stop instead of passing bad output to the next step.
5. Parallelization vs orchestrator-workers?
In parallelization you write the subtasks in advance. In orchestrator-workers a model decides the subtasks at run time, which handles new kinds of task but adds a planning call and a place for the task to be misread.
6. When does an evaluator-optimizer loop make results worse?
When the evaluator is no better than the generator. It can approve wrong answers and change right ones. Use a checker with an outside signal: tests, a schema, rules in code, a stronger model or a human.
7. How do you stop an agent from looping forever?
Set a maximum number of model calls or tool calls, a time or token budget, and a clear finish condition in the prompt. Log every step so you can see why it did not stop.
8. How would you build a refund assistant?
Let the model read the message and pull out the order number and the issue into a fixed schema, check those against the database, then apply the refund policy in code and let the model write the reply. That is a short chain with a gate and rules in code, not an open-ended agent.
Limits of this test
- One small model. qwen2.5:3b is a 3-billion-parameter model. A frontier model would likely get more of these cases right in every design, and the gaps between designs would likely shrink. The gap between "the model does the rule" and "code does the rule" does not go to zero, though: code is right every time, and costs nothing.
- 8 cases. This is a worked example, not a benchmark. One case more or less changes a score by 12.5 percentage points, so read the table for its pattern, not its decimals.
- Seconds are from a busy laptop. Ollama ran on the CPU (an x86 build under Rosetta, on a 10-core, 16 GB machine) while other jobs were running and the machine was swapping, with load averages from 9 to over 80, so absolute times are slow and noisy. Compare the designs with each other, not with a hosted API.
- Parallelization and orchestrator-workers were not run. A single laptop CPU runs calls one after another, so parallel calls would not show their real benefit (the same total cost, less waiting). Orchestrator-workers is tested on the multi-agent systems page.
- Our prompts, our policy. Better prompts, few-shot examples or a different output schema could change any single result. We wrote all six designs before the run and did not tune them afterwards.
- Plain prompts, no examples. None of the prompts had worked examples. Anthropic's advice to optimise single calls "with retrieval and in-context examples" would likely lift the single call, chain and routing scores. It would not make them as reliable as code for a rule that can be written as code.
- Temperature 0, one run. With a fixed seed the same inputs give the same outputs on this machine, so voting (several tries, majority wins) would add nothing here. With sampling turned on, results would vary from run to run.
Frequently asked questions
What are AI agent design patterns?
They are reusable ways to arrange language model calls, tools and ordinary code so an AI system finishes a task reliably. The common ones are prompt chaining, routing, parallelization, orchestrator-workers, evaluator-optimizer, the ReAct agent loop, planning and multi-agent setups. Each trades extra calls, cost and delay for a specific kind of help.
What is the difference between an agentic workflow and an AI agent?
In an agentic workflow your code fixes the steps and the model fills in each one, such as extract, check, then reply. In an AI agent the model decides the next step itself, usually by calling tools in a loop until it is done. Anthropic calls both agentic systems and separates them by who controls the path.
What is the ReAct pattern in AI agents?
ReAct stands for Reason + Act, from a 2022 paper by Yao et al. The model writes a thought, calls a tool, reads the result, and repeats until it can answer or hits a stop condition such as a maximum number of steps. Most tool-calling agents today are a ReAct loop with native tool calls.
What are the four agentic design patterns?
That list comes from Andrew Ng's letter in The Batch on 20 March 2024: reflection (the model reviews its own work), tool use, planning (the model writes and follows a multistep plan) and multi-agent collaboration. Anthropic's five workflows and Google's and Microsoft's pattern lists describe the same ideas in more detail.
Which AI agent design pattern should I use?
Start with the simplest that works: one well-built call, then a fixed chain with code checks, then routing, and only then an agent loop. Put anything that is a rule, such as dates, limits or fees, in code. In our test that one change took a small model from 1 of 8 to 8 of 8 right.
Does an evaluator or reflection loop always improve answers?
No. It helps when the checker has something the writer lacks, such as tests that run, a schema, rules in code, a stronger model or a person. In our test the same small model checking its own answers broke a right answer, approved wrong ones, and ended with the same 1 of 8 it started with.
Where can I read the Agentic Design Patterns book by Antonio Gulli?
It is published by Springer as Agentic Design Patterns: A Hands-On Guide to Building Intelligent Systems (October 2025, eBook ISBN 978-3-032-01402-3), with 21 patterns across 29 chapters. Buy or borrow it through Springer or a library, and be careful with free PDF links that do not come from the author or publisher.
Crio AI Engineering
Build agents that work outside a demo
Crio's AI Engineering program is project-first: you build LLM apps, RAG pipelines and tool-using agents, then learn to evaluate, secure and ship them. Talk to the team about whether it fits you.
Sources
- Building effective agents (19 December 2024) · Anthropic
- Choose a design pattern for your agentic AI system · Google Cloud
- AI agent orchestration patterns · Microsoft
- A practical guide to building agents (PDF) · OpenAI
- ReAct: Synergizing Reasoning and Acting in Language Models (Yao et al.) · arXiv
- Reflexion: Language Agents with Verbal Reinforcement Learning (Shinn et al.) · arXiv
- Self-Refine: Iterative Refinement with Self-Feedback (Madaan et al.) · arXiv
- Plan-and-Solve Prompting (Wang et al., ACL 2023) · arXiv
- ReWOO: Decoupling Reasoning from Observations (Xu et al.) · arXiv
- Plan-and-Execute Agents (10 May 2023) · LangChain
- Workflows and agents · LangChain (LangGraph docs)
- The Batch, issue 241: agentic design patterns (20 March 2024) · DeepLearning.AI
- Agentic Design Patterns (Antonio Gullí, Springer, 2025) · Springer Nature
- CrewAI Processes · CrewAI
- Ollama: tool calling · Ollama
- Ollama: structured outputs · Ollama
- qwen2.5 model page · Ollama
Facts are quoted from the pages above as fetched on 24 November 2026 (Springer's page via its Internet Archive copy). The test kit, every model call and every result are reproduced on this page.
Last updated: