AI · Topic 3 · Exam domain D1

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.

D1 27% of the exam 3 animated diagrams 4 runnable code files ≈ 75 min read

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.

Working definitionAgent = model + tools + a loop + an environment, where the model decides the next step. If your code decides every step, you've built a workflow instead. That's often the better choice.

🧠 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

Single LLM call one prompt → one answer Workflow your code picks the steps Agent the model picks the steps Multi-agent agents delegate to agents more predictable · cheaper · easier to test more flexible · costlier · harder to test
Move right only when the task needs it. Each step to the right buys flexibility and costs predictability, latency, and tokens.

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.

Context window prompt + history + results Model decides the next step Harness runs tool permission check · execute Observation tool_result appended Final answer stop_reason: end_turn ① context in ② tool_use ③ result ④ append & repeat
The green dot is one iteration. Each lap costs a model call. When the model has nothing more to do it ends the turn (dashed arrow) instead of asking for a tool.

How your code knows what to do next: stop_reason

stop_reasonMeaningYour loop should…
tool_useThe model wants one or more tools runExecute every tool_use block and send all results back in one user message
end_turnThe model is doneReturn the answer, or verify it first (tests, checks)
max_tokensThe output hit your max_tokens capRaise the cap, or ask it to continue. Don't treat a truncated answer as done
pause_turnA long-running server tool paused the turnSend the conversation back unchanged so it can resume
refusalSafety classifiers declined the requestStop; read stop_details; don't retry blindly
stop_sequenceA custom stop string was producedHandle 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?"))
⚠️ The classic loop bugs
  • Appending only the text of the assistant reply. You must append the full response.content, because the tool_use blocks (and thinking blocks) have to be there for the tool_result ids 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: true with 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.

Game · The agent loop

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.

AskIf "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
🎯 Exam lensWhen a scenario has known, fixed steps (extract → validate → format), the right answer is almost always a workflow or prompt chain, not an autonomous agent. Pick an agent when the path depends on what is discovered along the way (debugging, research, open-ended coding).
Game · Workflows vs agents

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

LLM 1 gate LLM 2 LLM 3

Fixed sequence; each step's output feeds the next. Checks between steps catch problems early. Use for: outline → draft → edit; extract → translate.

2 · Routing

classifier billing prompt technical prompt general (cheap model)

Classify first, then handle with a specialised prompt or model. Use for: support triage; sending easy questions to a small model.

3 · Parallelization

security performance tests merge

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

orchestrator worker ? worker ? worker ? synthesize

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

generator draft evaluator feedback

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
💡 Design notes from the code
  • 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 use claude-opus-5-5.
  • Every loop is bounded (max_rounds), and every gate fails loudly.
Game · Workflow patterns

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.

Lead agent (orchestrator) plans · delegates · synthesizes ✓ synthesized answer task + clear brief condensed result only Subagent A own context window Subagent B own context window Subagent C own context window tool calls, file reads, and dead ends stay inside each subagent
Big orange dots = task briefs going out. Bars = each subagent's private context filling up as it works. Small green dots = short summaries coming back. The lead's context stays clean.

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

  1. ObjectiveOne concrete goal: "Find the three most-cited 2025 papers on X", not "research X".
  2. Output formatExactly what to return and how long. The lead must be able to merge it.
  3. Tools & sourcesWhich tools to use and which to avoid; where to look first.
  4. 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())
Two communication shapesHub-and-spoke (shown above): subagents only talk to the lead, which keeps control and context clean. Handoff / peer-to-peer: one agent passes the whole conversation to another, which suits phase changes (triage → specialist). Default to hub-and-spoke; it's easier to debug.

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.

Context window (fixed size) system+tools summary compaction threshold each turn appends messages and tool results… …compaction replaces old turns with a short summary, and work continues
Orange = conversation history. Without management it reaches the limit. With compaction, the oldest turns become a summary (green) and the agent keeps going.

Five techniques

TechniqueWhat it doesExample
Just-in-time retrievalKeep lightweight references (paths, URLs, IDs) and load content with tools only when neededClaude Code uses glob/grep to find files instead of pasting the whole repo
CompactionSummarise old turns when nearing the limitAPI server-side compaction (compact_20260112); Claude Code's auto-compact
Clearing stale tool resultsDrop old, already-used tool outputs from the windowContext editing (clear_tool_uses_20250919)
Structured note-takingThe agent writes progress, decisions, and to-dos to a file and re-reads it laterNOTES.md, a progress file, the memory tool
Subagent isolationPush exploration into a subagent; only its summary comes backThe multi-agent pattern above
💡 Rule of thumbFind the smallest set of high-signal tokens that lets the model do the next step well. More context isn't better context.
Game · Context engineering

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

KindLives inLifetimeExamples
Working memoryThe context windowOne session (until compacted)Conversation, tool results, current plan
Procedural (how to work)Instruction files loaded at startPersistent, versionedCLAUDE.md, skills, system prompts
Episodic (what happened)Files or stores the agent writesAcross sessionsProgress logs, git history, session summaries
Semantic (facts)External stores queried by toolsLong-termThe memory tool (memory_20250818, a /memories directory you host), a database, or a vector index for RAG
⚠️ TrapThe model itself is stateless. It remembers nothing between API calls. "Memory" always means the harness puts text back into the prompt, either up front (instruction files) or on demand (a tool reads it).

8. Planning and reasoning patterns

PatternHow it worksUse it when
ReAct (reason + act)Think → act (tool) → observe → think… This is the default agent loopAlmost always; it's the baseline
Plan-and-executeWrite an explicit plan first (often a to-do list), then work through it, re-planning when reality differsLong tasks; when a human should approve the plan (Claude Code's plan mode)
Reflection / self-critiqueAfter acting, the agent (or a separate grader) checks the result against criteria and revisesQuality-sensitive outputs (the evaluator–optimizer pattern)
Extended reasoningAdaptive thinking lets the model reason privately before and between tool calls; output_config.effort trades depth against costHard 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 modeSymptomArchitectural fix
Runaway loopsSame tool called again and again; cost spikesTurn/token/dollar budgets; detect repeated identical calls
Premature "done"Agent declares success without checkingVerification step (tests, checks) before accepting end_turn
Goal driftLong sessions wander from the taskWritten plan or to-do list re-read each step; progress notes
Tool misuseWrong tool, malformed argumentsBetter tool names/descriptions, strict: true schemas, fewer overlapping tools
Irreversible mistakesDeleted data, sent emails, pushed to mainHuman approval gates for destructive actions; sandboxes; dry-run modes
Prompt injectionA web page or file tells the agent to do something elseTreat tool output as data; least-privilege tools; approvals; never give one agent private data + untrusted input + a way to send data out
Context overflow / rotQuality drops late in long sessionsCompaction, clearing, notes, subagents (section 6)
🎯 Exam lensGuardrails that must always hold (never push to main, never delete outside the workspace) belong in deterministic code: hooks, permission rules, sandboxes. They don't belong only in the prompt. Prompts guide behaviour; code enforces it.

Design checklist for a new agent

  1. Prove it needs to be an agentTry a single call or a workflow first (section 3).
  2. Define doneA checkable success condition (tests pass, schema valid, human approves).
  3. Design a small tool setFew, well-described, non-overlapping tools (see Tool Design & MCP).
  4. Set limitsMax turns, tokens or dollars, and wall-clock time.
  5. Gate the dangerous actionsPermissions, approvals, sandbox.
  6. Plan for contextRetrieval strategy, compaction, notes, subagents.
  7. Observe and evaluateTrace every step; run a fixed task set on every change (see Harness Engineering).

Self-check quiz

Score: 0 / 0 answered

1 · An invoice pipeline always does: extract fields → validate totals → format JSON. Which architecture fits best?
B. The steps are fixed and known in advance, so code should own the flow. A gate between steps catches errors cheaply. An agent adds cost and unpredictability for no benefit.
2 · Claude returns three tool_use blocks in one response. How should the loop reply?
C. Every tool_use needs a matching tool_result (failures included, with is_error), all in a single message.
3 · What is the main reason to give a research task to subagents rather than one long-running agent?
A. Context isolation (plus parallelism) is the point. Total token use usually goes up, often by a lot.
4 · An agent must never run git push --force. Where should that rule be enforced?
D. Prompts are guidance and can be ignored or injected against. Hooks and permission rules are guarantees.
5 · Late in a long session the agent's answers degrade, and the transcript is full of old file dumps. Best first fix?
B. This is context rot. A bigger window delays the problem but doesn't remove the noise; max_tokens only limits output length.
6 · Which pattern fits "translate legal text until a reviewer finds no issues, max 3 rounds"?
C. Generate, grade against criteria, revise, with a bounded loop.
7 · Your loop receives stop_reason: "max_tokens". What does it mean?
A. Raise 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.
8 · An orchestrator–workers system differs from plain parallelization because…
D. In sectioning, your code defines the sub-tasks. An orchestrator plans them based on the input.