Domain 1 — Agentic Architecture & Orchestration

Claude Certified Architect · Foundations (CCA-F)

27% of the exam · the biggest & hardest domain — master this first

Overview

An agent is a loop wrapped around one stateless endpoint (POST /v1/messages). You send the whole conversation; the model replies; if it asked for a tool, you run it, append the result, and call again — until it stops. Everything on this page is verified against the current Messages API, not just the summary study guide.

🖼️ Diagrams on this page are drawn live by Mermaid.js. They need internet the first time (loaded from a CDN). Runnable Python is in the examples/ folder next to this file.

1 · The Agentic Loop

flowchart TD U([User request]) --> B["Build messages array
system + FULL history
API is stateless — resend every call"] B --> C["client.messages.create(model, tools, messages)"] C --> D{"response.stop_reason ?"} D -->|"end_turn ✅"| E([Return text to user · DONE]) D -->|"tool_use 🛠"| F["Append WHOLE response.content
then run tool → tool_result"] F --> B D -->|"pause_turn ⏸"| G["Re-send assistant turn as-is
server resumes · no Continue msg"] G --> C D -->|"max_tokens ✂"| H["Output truncated
raise max_tokens / stream / continue"] H --> B D -->|"refusal 🚫"| I([Surface the decline
don't retry same prompt]) classDef done fill:#d4edda,stroke:#28a745,color:#155724; classDef warn fill:#fff3cd,stroke:#ffc107,color:#856404; classDef stop fill:#f8d7da,stroke:#dc3545,color:#721c24; class E done; class H,G warn; class I stop;
🧠 The two things people forget: the API is stateless (you resend the full history every call), and you must append the whole response.content (with its tool_use block), not just .text.

2 · stop_reason — the exam's favourite topic

flowchart LR S{{stop_reason}} --> ET["end_turn ✅
finished naturally"] S --> TU["tool_use 🛠
wants a tool"] S --> MT["max_tokens ✂
OUTPUT truncated"] S --> SS["stop_sequence 🛑
hit your stop seq"] S --> PT["pause_turn ⏸
server-tool paused"] S --> RF["refusal 🚫
safety decline"] ET --> X([■ exit loop]); SS --> X; RF --> X TU --> L([↻ keep looping]); MT --> L; PT --> L classDef exit fill:#f8d7da,stroke:#dc3545,color:#721c24; classDef loop fill:#d1ecf1,stroke:#17a2b8,color:#0c5460; class X exit; class L loop;
stop_reasonMeaningWhat you do
end_turnFinished naturallyReturn response; loop done
tool_useWants a toolExecute → append tool_result → loop
max_tokensHit the output cap — truncatedRaise max_tokens, stream, or continue
stop_sequenceHit a custom stop sequenceHandle per protocol (rare)
pause_turnServer-side tool loop paused (~10 iters)Re-send assistant turn as-is; server resumes
refusalSafety classifier / model declinedCheck stop_details.category; surface it
⚠️ Six values total — the "4-value" list in most guides is incomplete. max_tokens = the output was cut off, not "conversation too long." On a refusal, content can be empty — branch on stop_reason before reading content[0].

3 · Message structure & the tool-result contract

sequenceDiagram participant H as Your harness participant C as Claude (Messages API) H->>C: user turn — weather in Paris? C-->>H: assistant turn — tool_use (id = toolu_A) Note over H: run get_weather(Paris) → 18C sunny H->>C: user turn — tool_result (tool_use_id = toolu_A) ✅ ids match C-->>H: assistant turn — It's 18C and sunny. (end_turn) Note over H,C: results in a USER turn · ids MUST match · roles alternate
Break any → HTTP 400. Tool errored? add is_error = true
  • messages[] alternates user / assistant; first message must be user.
  • A tool_result is user-role content; its tool_use_id must match the tool_use block it answers.
  • Return all results from one assistant turn in a single following user message.
  • Failed tool → set "is_error": true so Claude adapts.

4 · Single agent vs. multi-agent

flowchart TD Q(["What is the task?"]) --> P{"Independent
parallel sub-tasks?"} P -->|Yes| M["🤖🤖 Multi-agent
parallelise to cut wall-clock"] P -->|No| CL{"Cost / latency
sensitive?"} CL -->|Yes| S1["🤖 Single agent + tools
simplest tier wins"] CL -->|No| ST{"5+ steps OR
distinct specialised roles?"} ST -->|Yes| M ST -->|No| S2["🤖 Single agent + tools
don't over-engineer"] classDef single fill:#d4edda,stroke:#28a745,color:#155724; classDef multi fill:#e2d4f0,stroke:#764ba2,color:#3d1a5b; class S1,S2 single; class M multi;
Golden rule: pick the simplest tier that works. "Should I build an agent at all?" — only if it's Complex, the Value justifies cost/latency, Claude is Viable at it, and errors are recoverable (Cost-of-error). Any "no" → simpler tier.

5 · Orchestration patterns

flowchart TD subgraph HS["Hub & Spoke — start here"] A1["🤖 agent"] --> T1["🛠 tool"]; A1 --> T2["🛠 tool"]; A1 --> T3["🛠 tool"] end subgraph CO["Coordinator / Sub-agent"] K["🧭 coordinator"] --> R1["🤖 refund"]; K --> R2["🤖 technical"]; K --> R3["🤖 billing"] R1 --> MG(["merge → response"]); R2 --> MG; R3 --> MG end subgraph SP["Sequential pipeline"] P1["research"] --> P2["outline"] --> P3["draft"] --> P4["edit"] end
🔑 Sub-agents are context-isolated — they don't see the coordinator's history. Pass what they need explicitly. Parallelise independent agents to cut latency; don't switch the main loop's model mid-conversation (it kills the prompt cache) — spawn a sub-agent instead.

6 · Failure modes & recovery

flowchart LR F1["💣 Cascade
a1 ✗ → a2 ✗ → a3 ✗"] --> S1["🔌 Circuit breaker"] F2["🕳 Lost state
sub-agent has no context"] --> S2["📨 Pass state explicitly"] F3["⏳ Timeout chain
A→B→C latency adds up"] --> S3["⚡ Parallelise independents"] F4["✂ Truncation
stop_reason = max_tokens"] --> S4["⬆ Raise cap / stream"] F5["🌩 Transient
429 / 500 / 529"] --> S5["↩ Retry w/ backoff (SDK auto)"] classDef fail fill:#f8d7da,stroke:#dc3545,color:#721c24; classDef fix fill:#d4edda,stroke:#28a745,color:#155724; class F1,F2,F3,F4,F5 fail; class S1,S2,S3,S4,S5 fix;
Recovery ladder: retry (transient) → fallback (alt / skip) → escalate (human). The SDK auto-retries 429 / 5xx / 529 with exponential backoff (max_retries, default 2).

7 · Model · thinking · effort

flowchart LR subgraph MODEL O["claude-opus-4-8
default · agentic"] SN["claude-sonnet-4-6
speed / volume"] HA["claude-haiku-4-5
cheap · fast · sub-tasks"] end subgraph THINKING TH["type: adaptive
Claude picks depth &
interleaves automatically
budget_tokens is GONE"] end subgraph EFFORT EF["low ─ medium ─ high ─ max
cheaper ◀──▶ more thorough"] end MODEL --> THINKING --> EFFORT
Enable thinking with thinking={"type":"adaptive"} (the fixed budget_tokens is removed on current models). Stream any request with a large max_tokens (≳16K) to dodge HTTP timeouts.

8 · Code snippets

The manual loop, in miniature

# stateless: resend the full messages[] every call
messages = [{"role": "user", "content": user_input}]
while True:
    resp = client.messages.create(
        model="claude-opus-4-8", max_tokens=16000,
        tools=TOOLS, messages=messages,
    )
    if resp.stop_reason == "end_turn": break
    if resp.stop_reason == "pause_turn":            # server-tool paused
        messages.append({"role": "assistant", "content": resp.content})
        continue                                    # re-send as-is; server resumes
    messages.append({"role": "assistant", "content": resp.content})  # WHOLE turn!
    results = []
    for b in resp.content:
        if b.type == "tool_use":
            results.append({"type": "tool_result",
                            "tool_use_id": b.id,          # MUST match, or 400
                            "content": run_tool(b.name, b.input)})
    messages.append({"role": "user", "content": results})  # results in a USER turn
Full runnable versions live next to this page: examples/01_agentic_loop.py (needs an API key) and three no-key concept demos — 02_stop_reasons.py, 03_tool_result_contract.py, 04_single_vs_multi.py.

9 · Flashcards (click a card to flip)

10 · Practice questions

Q1 · Your loop appends only response.content[0].text. The 2nd tool call errors. Why?

You must append the entire response.content. The assistant turn holds the tool_use block; dropping it means the next tool_result references a tool_use_id not in history → 400.

Q2 · stop_reason == "max_tokens". What happened, best fix?

The output hit its cap and is truncated — not "conversation too long." Raise max_tokens, stream, or continue the turn. Summarising history is the wrong lever.

Q3 · A web-search call returns pause_turn. What do you send next?

Re-send the assistant turn as-is; the server resumes its own loop. Adding a "Continue." user message is wrong — the API detects the trailing server_tool_use block. Cap continuations to avoid infinite loops.

Q4 · 10 tools, one escalation path, cost- & latency-sensitive. Single or multi-agent?

Single agent + tools. No distinct roles or parallel work; cost + latency both favour the simplest tier. Multi-agent adds tokens/latency for no benefit.

Q5 · A billing sub-agent keeps re-asking for the customer ID the coordinator had. Cause?

Lost state / prompt isolation. Sub-agents don't share the coordinator's context — pass the required state explicitly in the delegated message.

Q6 · Code reads content[0].text and sometimes throws an index error. Why?

The turn was a refusal (or first block isn't text) — content can be empty. Branch on stop_reason first; for refusals inspect stop_details.

Q7 · You want a cheaper model for just one sub-step of a long Opus chat. Best approach?

Spawn a sub-agent on the cheaper model. Switching the main loop's model invalidates the model-scoped prompt cache, forcing a full re-process of the prefix.

11 · Exam traps & quick answers

Trap / keywordAnswer
"How does the agent remember earlier turns?"You resend full messages[]; the API is stateless.
"Loop appended reply but next tool call failed"Appended only .text; append the whole response.content.
"Server tool returned pause_turn"Re-send assistant turn unchanged; don't add "Continue."
"max_tokens — conversation too long?"No — the output hit its cap.
"Which stop_reasons exist?"end_turn, tool_use, max_tokens, stop_sequence, pause_turn, refusal.
"cost-effective"Single agent + tools · Sonnet/Haiku · lower effort.
"least latency"Parallelise; don't add agents.
"best-practice / robust"Explicit state, retries, circuit breakers.