Agentic architecture: from one LLM call to multi-agent systems
An agent is a model that uses tools in a loop to reach a goal, choosing its own next step. This page builds the idea up from a single API call: the agent loop, when not to build an agent, the five workflow patterns, multi-agent orchestration, context engineering, memory, and how to make agents reliable. Each idea comes with an animated diagram or tested code.
1. What is an agent?
A plain LLM call is a function: text in, text out. It can't look anything up, change anything, or check its own work. An agent wraps the model in a loop and gives it tools. It reads the situation, chooses an action, sees what happened, and repeats until the goal is met.
🧠 Model (brain)
Reasons about the goal, picks the next action, and judges when it's done. Claude emits tool_use blocks; it never executes anything itself.
🛠️ Tools (hands)
Functions the model may call: search, read a file, run tests, send an email. Their names, descriptions, and schemas are the model's whole picture of what it can do.
🔁 Loop & harness (body)
Your code: calls the model, runs the tools it asks for, feeds results back, enforces limits and permissions. See Harness Engineering.
🗂️ Context & memory
Everything the model can see on this turn (instructions, history, tool results), plus anything saved outside the window (files, memory stores).
The autonomy spectrum
2. The agent loop
Every agent, from a 30-line script to Claude Code, runs the same loop. The model sees the context, either answers or asks for a tool, your code runs the tool, the result is appended, and the model looks again.
How your code knows what to do next: stop_reason
stop_reason | Meaning | Your loop should… |
|---|---|---|
tool_use | The model wants one or more tools run | Execute every tool_use block and send all results back in one user message |
end_turn | The model is done | Return the answer, or verify it first (tests, checks) |
max_tokens | The output hit your max_tokens cap | Raise the cap, or ask it to continue. Don't treat a truncated answer as done |
pause_turn | A long-running server tool paused the turn | Send the conversation back unchanged so it can resume |
refusal | Safety classifiers declined the request | Stop; read stop_details; don't retry blindly |
stop_sequence | A custom stop string was produced | Handle per your protocol |
The loop, written by hand
A complete support agent with two tools. The numbered comments are the six rules every hand-written loop must follow.
"""The agent loop, written by hand: the model decides, your code executes."""
import json
import anthropic
client = anthropic.Anthropic()
MODEL = "claude-opus-5-5"
TOOLS = [
{
"name": "get_order",
"description": (
"Look up a customer order by ID. Returns status, items and ship date as JSON. "
"Use it whenever the customer mentions an order number such as 'A-1042'."
),
"input_schema": {
"type": "object",
"properties": {"order_id": {"type": "string", "description": "Order ID, e.g. A-1042"}},
"required": ["order_id"],
"additionalProperties": False,
},
"strict": True,
},
{
"name": "refund_order",
"description": "Refund a delivered order. Only call after get_order confirms it was delivered.",
"input_schema": {
"type": "object",
"properties": {
"order_id": {"type": "string"},
"reason": {"type": "string", "enum": ["damaged", "late", "not_as_described"]},
},
"required": ["order_id", "reason"],
"additionalProperties": False,
},
"strict": True,
},
]
ORDERS = {"A-1042": {"status": "delivered", "items": ["kettle"], "shipped": "2026-10-01"}}
def run_tool(name: str, args: dict) -> str:
if name == "get_order":
order = ORDERS.get(args["order_id"])
if order is None:
raise LookupError(f"No order {args['order_id']}. Ask the customer to re-check the ID.")
return json.dumps(order)
if name == "refund_order":
return json.dumps({"refunded": True, "order_id": args["order_id"], "reason": args["reason"]})
raise ValueError(f"Unknown tool: {name}")
def run_agent(task: str, max_turns: int = 10) -> str:
messages = [{"role": "user", "content": task}]
for _ in range(max_turns): # 1. hard stop: never loop forever
response = client.messages.create(
model=MODEL,
max_tokens=16000,
system="You are a support agent. Always verify an order before refunding it.",
tools=TOOLS,
messages=messages,
)
messages.append({"role": "assistant", "content": response.content}) # 2. keep ALL blocks
if response.stop_reason != "tool_use": # 3. end_turn, max_tokens, refusal ...
return "".join(b.text for b in response.content if b.type == "text")
results = []
for block in response.content: # 4. there may be several calls (parallel)
if block.type != "tool_use":
continue
try:
output, failed = run_tool(block.name, block.input), False
except Exception as exc: # 5. errors go back to the model, not up the stack
output, failed = f"Error: {exc}", True
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": output, "is_error": failed})
messages.append({"role": "user", "content": results}) # 6. all results in ONE message
return "Stopped: turn limit reached."
if __name__ == "__main__":
print(run_agent("My kettle from order A-1042 arrived cracked. Can I get a refund?"))
- Appending only the text of the assistant reply. You must append the full
response.content, because thetool_useblocks (and thinking blocks) have to be there for thetool_resultids to match. - One message per tool result. When the model makes parallel calls, return all results in one user message. Splitting them teaches the model to stop making parallel calls.
- Raising on tool errors. A failed tool should return
is_error: truewith a helpful message. The model can usually recover; a crashed loop can't. - No turn limit. Agents can loop. Always cap turns, tokens, or dollars.
The same agent with the SDK's tool runner
In most projects you don't hand-write the loop. The Python SDK's tool_runner (beta) builds each tool's schema from the function signature and docstring, then runs the call → execute → append cycle for you:
"""Same agent, but the SDK's tool runner owns the loop. You only write tools."""
import json
import anthropic
from anthropic import beta_tool
client = anthropic.Anthropic()
ORDERS = {"A-1042": {"status": "delivered", "items": ["kettle"]}}
@beta_tool
def get_order(order_id: str) -> str:
"""Look up a customer order by ID and return its status as JSON.
Args:
order_id: Order ID, e.g. A-1042.
"""
return json.dumps(ORDERS.get(order_id, {"error": f"no order {order_id}"}))
@beta_tool
def refund_order(order_id: str, reason: str) -> str:
"""Refund a delivered order. Only call after get_order confirms delivery.
Args:
order_id: Order ID, e.g. A-1042.
reason: One of damaged, late, not_as_described.
"""
return json.dumps({"refunded": True, "order_id": order_id})
if __name__ == "__main__":
runner = client.beta.messages.tool_runner(
model="claude-opus-5-5",
max_tokens=16000,
tools=[get_order, refund_order],
messages=[{"role": "user", "content": "Order A-1042 arrived damaged. Refund it please."}],
)
for message in runner: # one iteration per model turn; stops when Claude is done
for block in message.content:
if block.type == "text":
print(block.text)
Write the loop by hand when you need control the runner doesn't give you. Otherwise prefer the runner. Its per-turn hooks still let you add approvals and logging.
Be the harness
Everyday picture: a restaurant waiter. The chef (the model) writes order slips (tool_use). You, the waiter (the harness), take every slip to the right station, bring all the dishes back on one tray (tool_result), and only serve the table when the chef says the meal is done (end_turn).
A user asks: “Will it rain in Paris tomorrow, and should I move my picnic to Saturday?” You are the code running the loop. Make the right call at each step.
3. Workflows vs agents: choose the simplest thing that works
The most common architecture mistake is building an agent when a workflow would do. A workflow runs LLM calls along paths your code defines. An agent lets the model choose the path. Workflows are cheaper, faster, and much easier to test. Agents are for problems whose steps you can't predict in advance.
| Ask | If "no"… |
|---|---|
| Complexity: Is the task multi-step and hard to fully specify in advance? | Use a single call or a fixed workflow |
| Value: Does the outcome justify extra cost and latency (agents use many more tokens)? | Use a workflow with a cheaper model |
| Viability: Is the model actually good at this kind of task? | Narrow the task or keep a human in the loop |
| Cost of error: Can mistakes be caught and undone (tests, review, rollback)? | Add approval gates, or don't automate it |
Recipe or chef?
Everyday picture: a recipe versus a chef. When you know the steps, a recipe (a workflow) is cheaper, faster and predictable. You hire a chef (an agent) when the meal depends on what you find in the fridge. And sometimes you just need one sandwich (a single call).
Choose the simplest thing that works for each task.
4. The five workflow patterns
These building blocks cover most production LLM systems. They compose freely: a router can send work to an orchestrator, which can use evaluator loops inside its workers.
1 · Prompt chaining
Fixed sequence; each step's output feeds the next. Checks between steps catch problems early. Use for: outline → draft → edit; extract → translate.
2 · Routing
Classify first, then handle with a specialised prompt or model. Use for: support triage; sending easy questions to a small model.
3 · Parallelization
Sectioning: independent sub-tasks at once. Voting: the same task N times, then take the majority. Use for: multi-aspect reviews; high-stakes classification.
4 · Orchestrator–workers
Like parallelization, but the model decides the sub-tasks at runtime. Use for: research, multi-file changes where the files aren't known in advance.
5 · Evaluator–optimizer
One call generates, another grades against explicit criteria, and the loop repeats until it passes (bounded). Use for: translation quality, code that must meet a spec, writing with a rubric.
All five patterns in code
One file, one function per pattern. Note where your code owns the control flow (gates, routes, vote counting, round limits). That's what makes these workflows and not agents.
"""The five workflow patterns. Your code owns the control flow; the model fills in steps."""
import asyncio
import json
from collections import Counter
import anthropic
client = anthropic.Anthropic()
aclient = anthropic.AsyncAnthropic()
SMART, FAST = "claude-opus-5-5", "claude-haiku-5-5"
def text_of(response) -> str:
return "".join(b.text for b in response.content if b.type == "text")
def ask(system: str, prompt: str, model: str = SMART) -> str:
r = client.messages.create(model=model, max_tokens=16000, system=system,
messages=[{"role": "user", "content": prompt}])
return text_of(r)
def ask_json(system: str, prompt: str, schema: dict, model: str = SMART) -> dict:
"""Structured output: the reply is guaranteed to match `schema`."""
r = client.messages.create(
model=model, max_tokens=16000, system=system,
output_config={"format": {"type": "json_schema", "schema": schema}},
messages=[{"role": "user", "content": prompt}],
)
return json.loads(text_of(r))
# 1. Prompt chaining: fixed steps, with a programmatic gate between them ------------
def launch_post(product_notes: str) -> str:
outline = ask("You write product marketing.",
f"Write a 5-bullet outline (one '- ' bullet per line) for:\n{product_notes}")
if sum(line.startswith("- ") for line in outline.splitlines()) < 5: # gate
raise ValueError("Outline gate failed; not worth spending tokens on a draft.")
draft = ask("You write product marketing.", f"Expand into a 300-word post:\n{outline}")
return ask("You are a strict copy editor. Return only the edited post.", draft)
# 2. Routing: classify once, then send to a specialised prompt (or cheaper model) ---
ROUTES = {
"billing": "You are a billing specialist. Be precise about amounts and dates.",
"technical": "You are a senior support engineer. Ask for logs if needed.",
"general": "You are a friendly support agent.",
}
ROUTE_SCHEMA = {
"type": "object",
"properties": {"category": {"type": "string", "enum": list(ROUTES)}},
"required": ["category"],
"additionalProperties": False,
}
def handle_ticket(ticket: str) -> str:
category = ask_json("Classify the support ticket.", ticket, ROUTE_SCHEMA, model=FAST)["category"]
return ask(ROUTES[category], ticket)
# 3a. Parallelization, sectioning: independent sub-tasks at the same time -----------
async def review_diff(diff: str) -> dict[str, str]:
focuses = {
"security": "Review ONLY for security issues.",
"performance": "Review ONLY for performance issues.",
"tests": "Review ONLY for missing or weak tests.",
}
async def one(name: str, system: str) -> tuple[str, str]:
r = await aclient.messages.create(model=SMART, max_tokens=16000, system=system,
messages=[{"role": "user", "content": diff}])
return name, text_of(r)
return dict(await asyncio.gather(*(one(n, s) for n, s in focuses.items())))
# 3b. Parallelization, voting: same question N times, take the majority ------------
async def is_phishing(email: str, votes: int = 3) -> bool:
async def vote() -> str:
r = await aclient.messages.create(
model=FAST, max_tokens=256,
system="Answer with exactly one word: PHISHING or SAFE.",
messages=[{"role": "user", "content": email}])
return text_of(r).strip().upper()
tally = Counter(await asyncio.gather(*(vote() for _ in range(votes))))
return tally["PHISHING"] > votes // 2
# 4. Orchestrator-workers: the model decides the sub-tasks at runtime ---------------
PLAN_SCHEMA = {
"type": "object",
"properties": {"subtasks": {"type": "array", "items": {
"type": "object",
"properties": {"title": {"type": "string"}, "instructions": {"type": "string"}},
"required": ["title", "instructions"],
"additionalProperties": False,
}}},
"required": ["subtasks"],
"additionalProperties": False,
}
async def research(goal: str) -> str:
plan = ask_json("Split the goal into 2-5 independent research sub-tasks.", goal, PLAN_SCHEMA)
async def worker(task: dict) -> str: # fresh, isolated context per worker
r = await aclient.messages.create(
model=FAST, max_tokens=16000,
system="Complete the sub-task. Reply with a dense summary under 200 words.",
messages=[{"role": "user", "content": f"{task['title']}\n\n{task['instructions']}"}])
return f"## {task['title']}\n{text_of(r)}"
findings = await asyncio.gather(*(worker(t) for t in plan["subtasks"]))
return ask("Synthesize the findings into one answer. Cite sub-task titles.",
f"Goal: {goal}\n\n" + "\n\n".join(findings))
# 5. Evaluator-optimizer: generate, grade against criteria, revise -----------------
VERDICT_SCHEMA = {
"type": "object",
"properties": {"passed": {"type": "boolean"}, "feedback": {"type": "string"}},
"required": ["passed", "feedback"],
"additionalProperties": False,
}
def write_with_review(task: str, criteria: str, max_rounds: int = 3) -> str:
draft = ask("You are a technical writer.", task)
for _ in range(max_rounds): # bounded: the loop must end
verdict = ask_json(f"You are a demanding reviewer. Criteria:\n{criteria}",
draft, VERDICT_SCHEMA)
if verdict["passed"]:
break
draft = ask("You are a technical writer.",
f"{task}\n\nPrevious draft:\n{draft}\n\nReviewer feedback:\n{verdict['feedback']}"
"\n\nRewrite the draft to address every point.")
return draft
- Structured outputs (
output_config.format) make routing and grading reliable. You parse guaranteed JSON instead of hoping the model said "billing". - Cheap models for narrow jobs: the router, voters, and workers use
claude-haiku-5-5; planning and synthesis useclaude-opus-5-5. - Every loop is bounded (
max_rounds), and every gate fails loudly.
Name that pattern
Everyday picture: a restaurant kitchen. Dishes move down a line of stations (chaining); a host seats each guest in the right section (routing); several cooks prep at once or taste-test a sauce (parallelization); a head chef assigns tasks once they see the order (orchestrator–workers); and the chef sends plates back until they're right (evaluator–optimizer).
Match each system to one of the five workflow patterns.
5. Multi-agent systems
A multi-agent system is orchestrator–workers where the workers are themselves agents: each subagent runs its own loop with its own tools and its own context window. The lead agent plans, delegates, and combines condensed results.
Why it works, and what it costs
✅ Benefits
- Context isolation: each subagent explores in a fresh window and returns a condensed result (often around 1–2k tokens), so the lead's context stays focused.
- Parallelism: independent research threads run at the same time.
- Specialisation: different prompts, tools, and models per role (e.g. a read-only reviewer).
⚠️ Costs
- Tokens: Anthropic reported its multi-agent research system used roughly 15× the tokens of a chat. Use it only where the value justifies that.
- Coordination: subagents can duplicate work or misread vague briefs.
- Poor fit for tightly coupled work where every agent needs the same evolving state (e.g. many agents editing the same files).
Writing a good subagent brief
- ObjectiveOne concrete goal: "Find the three most-cited 2025 papers on X", not "research X".
- Output formatExactly what to return and how long. The lead must be able to merge it.
- Tools & sourcesWhich tools to use and which to avoid; where to look first.
- BoundariesWhat is out of scope, plus effort limits ("stop after ~10 tool calls"), so subagents don't overlap or sprawl.
Subagents with the Claude Agent SDK
The Agent SDK packages Claude Code's harness as a library. Subagents are declared with AgentDefinition and launched by the model through the built-in Agent tool. In Claude Code itself, the equivalent is a Markdown file in .claude/agents/.
"""A full agent with built-in tools and a subagent, using the Claude Agent SDK."""
import asyncio
from claude_agent_sdk import AgentDefinition, ClaudeAgentOptions, ResultMessage, query
options = ClaudeAgentOptions(
model="claude-opus-5-5",
system_prompt="You are a careful senior engineer. Read code before changing it.",
allowed_tools=["Read", "Grep", "Glob", "Edit", "Bash", "Agent"],
permission_mode="acceptEdits", # edits auto-approved; other risky tools still ask
max_turns=40, # hard stop for the loop
max_budget_usd=2.00, # hard stop for spend
agents={
"test-runner": AgentDefinition(
description="Runs the test suite and reports failures. Use after every code change.",
prompt="Run the tests. Report ONLY failing tests as file:line plus the error message.",
tools=["Bash", "Read"],
model="haiku", # cheaper model for a narrow job
),
},
)
async def main() -> None:
async for message in query(prompt="Fix the failing date-parsing test in src/", options=options):
if isinstance(message, ResultMessage):
print(message.result)
print(f"turns={message.num_turns} cost=${message.total_cost_usd}")
if __name__ == "__main__":
asyncio.run(main())
6. Context engineering
The context window is the agent's working memory, and it's a finite attention budget. As it fills with stale tool output and old turns, quality drops ("context rot") and cost rises. Context engineering means deciding what goes into the window on every turn.
Five techniques
| Technique | What it does | Example |
|---|---|---|
| Just-in-time retrieval | Keep lightweight references (paths, URLs, IDs) and load content with tools only when needed | Claude Code uses glob/grep to find files instead of pasting the whole repo |
| Compaction | Summarise old turns when nearing the limit | API server-side compaction (compact_20260112); Claude Code's auto-compact |
| Clearing stale tool results | Drop old, already-used tool outputs from the window | Context editing (clear_tool_uses_20250919) |
| Structured note-taking | The agent writes progress, decisions, and to-dos to a file and re-reads it later | NOTES.md, a progress file, the memory tool |
| Subagent isolation | Push exploration into a subagent; only its summary comes back | The multi-agent pattern above |
Pack the carry-on
Everyday picture: packing a carry-on bag. Space is limited, so you take what you need for this trip and leave the rest at home, knowing where to find it. The context window is the agent's carry-on: a finite attention budget, not a storage unit.
Your mission: the agent's next job is “Fix the failing login test in auth/session.ts”. Pack its context window (10,000 tokens in this game) with what helps most. Click items to pack or unpack them.
7. Memory: what survives the context window
| Kind | Lives in | Lifetime | Examples |
|---|---|---|---|
| Working memory | The context window | One session (until compacted) | Conversation, tool results, current plan |
| Procedural (how to work) | Instruction files loaded at start | Persistent, versioned | CLAUDE.md, skills, system prompts |
| Episodic (what happened) | Files or stores the agent writes | Across sessions | Progress logs, git history, session summaries |
| Semantic (facts) | External stores queried by tools | Long-term | The memory tool (memory_20250818, a /memories directory you host), a database, or a vector index for RAG |
8. Planning and reasoning patterns
| Pattern | How it works | Use it when |
|---|---|---|
| ReAct (reason + act) | Think → act (tool) → observe → think… This is the default agent loop | Almost always; it's the baseline |
| Plan-and-execute | Write an explicit plan first (often a to-do list), then work through it, re-planning when reality differs | Long tasks; when a human should approve the plan (Claude Code's plan mode) |
| Reflection / self-critique | After acting, the agent (or a separate grader) checks the result against criteria and revises | Quality-sensitive outputs (the evaluator–optimizer pattern) |
| Extended reasoning | Adaptive thinking lets the model reason privately before and between tool calls; output_config.effort trades depth against cost | Hard decisions inside the loop; turn effort up for coding and agentic work, down for simple routing |
9. Reliability: how agents fail and how to stop it
| Failure mode | Symptom | Architectural fix |
|---|---|---|
| Runaway loops | Same tool called again and again; cost spikes | Turn/token/dollar budgets; detect repeated identical calls |
| Premature "done" | Agent declares success without checking | Verification step (tests, checks) before accepting end_turn |
| Goal drift | Long sessions wander from the task | Written plan or to-do list re-read each step; progress notes |
| Tool misuse | Wrong tool, malformed arguments | Better tool names/descriptions, strict: true schemas, fewer overlapping tools |
| Irreversible mistakes | Deleted data, sent emails, pushed to main | Human approval gates for destructive actions; sandboxes; dry-run modes |
| Prompt injection | A web page or file tells the agent to do something else | Treat tool output as data; least-privilege tools; approvals; never give one agent private data + untrusted input + a way to send data out |
| Context overflow / rot | Quality drops late in long sessions | Compaction, clearing, notes, subagents (section 6) |
Design checklist for a new agent
- Prove it needs to be an agentTry a single call or a workflow first (section 3).
- Define doneA checkable success condition (tests pass, schema valid, human approves).
- Design a small tool setFew, well-described, non-overlapping tools (see Tool Design & MCP).
- Set limitsMax turns, tokens or dollars, and wall-clock time.
- Gate the dangerous actionsPermissions, approvals, sandbox.
- Plan for contextRetrieval strategy, compaction, notes, subagents.
- Observe and evaluateTrace every step; run a fixed task set on every change (see Harness Engineering).
Self-check quiz
Score: 0 / 0 answered
tool_use blocks in one response. How should the loop reply?tool_use needs a matching tool_result (failures included, with is_error), all in a single message.git push --force. Where should that rule be enforced?max_tokens only limits output length.stop_reason: "max_tokens". What does it mean?max_tokens or ask it to continue, and never treat it as a completed answer. Tool calls give tool_use; normal completion gives end_turn.