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.
examples/ folder next to this file.1 · The Agentic Loop
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;
response.content (with its tool_use block), not just .text.2 · stop_reason — the exam's favourite topic
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_reason | Meaning | What you do |
|---|---|---|
end_turn | Finished naturally | Return response; loop done |
tool_use | Wants a tool | Execute → append tool_result → loop |
max_tokens | Hit the output cap — truncated | Raise max_tokens, stream, or continue |
stop_sequence | Hit a custom stop sequence | Handle per protocol (rare) |
pause_turn | Server-side tool loop paused (~10 iters) | Re-send assistant turn as-is; server resumes |
refusal | Safety classifier / model declined | Check stop_details.category; surface it |
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
Break any → HTTP 400. Tool errored? add is_error = true
messages[]alternates user / assistant; first message must beuser.- A
tool_resultis user-role content; itstool_use_idmust match thetool_useblock it answers. - Return all results from one assistant turn in a single following user message.
- Failed tool → set
"is_error": trueso Claude adapts.
4 · Single agent vs. multi-agent
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;
5 · Orchestration patterns
6 · Failure modes & recovery
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;
max_retries, default 2).7 · Model · thinking · effort
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
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
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 / keyword | Answer |
|---|---|
| "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. |