The model call is one box in a production system. Around it sit the stages that decide whether a request is allowed in, what the model sees, whether the answer is usable, where it goes, and how the next version gets better. Scenario questions about a "wrong" output usually hinge on one skill: identifying which stage should have caught the failure and putting the control there. This lesson gives you the reference architecture; lesson 2.3 covers the pattern inside the processing stage, lesson 1.4 and 3.6 cover observability and monitoring in depth, and lesson 4.1 covers guardrails.
The reference architecture
| Stage | Responsibility | Failure it prevents |
|---|---|---|
| 1. Intake and validation | Authenticate, check size and schema, apply rate limits and idempotency keys, decide the execution mode (interactive, queued, batch) | Malformed, abusive or duplicate requests; unbounded spend |
| 2. Context assembly | Build system prompt, retrieved documents, memory, tool definitions and history in a deliberate order | Missing or wrong context; cache misses; injection through untrusted content |
| 3. Model call(s) | Run the chosen pattern with the chosen model, effort, token limits and timeouts | Timeouts, overload, runaway loops |
| 4. Tools and actions | Execute tool calls, return results or errors, enforce permissions | Duplicate side effects; silent tool failure |
| 5. Output validation | Check stop reason, parse, validate schema, business rules and grounding | Truncated, malformed, wrong or ungrounded output reaching users |
| 6. Delivery | Stream, enqueue, write to the system of record, or hold for human review | Irreversible action without review; wrong destination |
| 7. Feedback and improvement | Log, capture signals, triage failures, grow the eval set, gate releases | Recurring failures; silent regressions |
Key concept: guarantees live in the code around the model
The model call is probabilistic. Every property you must be able to promise (schema, limits, permissions, idempotency, auditability) is enforced by a deterministic stage before or after it. When you are asked where to put a control, prefer the stage that can enforce it with code over an instruction inside the prompt.
Stages 1 and 2: intake and context assembly
Validate before you spend tokens. Anything that can be rejected with code should be. Also decide the execution mode here, because it shapes everything downstream: an interactive request streams a response to someone waiting; a queued job tolerates seconds to minutes; independent items with no latency need can go to the Message Batches API, which the documentation describes as roughly half the cost of standard calls, with most batches finishing within an hour and a 24-hour expiry. Batch results can return in any order, so the design must key on custom_id.
Context assembly is a design step, not string concatenation. Two rules matter architecturally. First, ordering: prompt caching reuses a matching prefix, and a change invalidates that level and everything after it in the order tools, system, messages. Put stable content (tool definitions, system prompt, reference material) first and per-request content last. Second, trust: web pages, inbound email, uploads and third-party API responses are untrusted. Anthropic's tool documentation recommends keeping such content inside tool_result blocks rather than in the system prompt or plain user text, and treating it as a potential indirect prompt injection vector. Retrieval, memory and context budgeting are covered in Domains 1 and 6.
Stages 3 and 4: the call and the tool loop
With client-executed tools your application owns the loop: send the request, and while stop_reason is tool_use, execute each tool and send back tool_result blocks; any other stop reason ends the loop. The tool results must immediately follow the assistant's tool_use message and come first in the user content. A failed tool returns its message with is_error: true, and the documentation advises instructive messages (what failed and what to try next) so the model can recover. Architecturally, add what the API does not: a maximum iteration count or budget, permission checks per tool, and idempotency for anything with side effects.
Separate transient from persistent failures. The official SDKs retry connection errors, rate limits and 5xx errors with exponential backoff (twice by default) and honor retry-after. A 429 caused by hitting a spend cap has no retry-after and keeps failing, so blind retry there is wrong; it needs an alert and a degraded mode. For long generations the docs recommend streaming or batches instead of one very long blocking request. Every response carries a request-id header; log it, because it is the handle support and your own traces need.
Stage 5: output validation in layers
Treat validation as four layers, cheapest first:
- Stop reason.
max_tokensmeans the response was truncated, so never parse it as complete.refusalmeans Claude declined; the docs point you tostop_detailsand to retrying on a fallback model.model_context_window_exceededalso means truncation, andpause_turnmeans a server-tool loop needs to be continued. - Schema. Structured outputs (
output_config.formatwith a JSON schema) and strict tool use (strict: true) use constrained decoding so the result conforms to your schema. That is a guarantee about shape, not truth. The documentation lists unsupported constraints such as numeric minimum and maximum and string length limits, and notes that refusals andmax_tokenscan still yield non-conforming output. - Business rules in code. Totals equal the sum of the lines, IDs exist in the system of record, dates fall in range, cited passages exist in the retrieved set. These cross-field checks cannot be expressed in the schema and must not be left to the prompt.
- Semantic or subjective quality. LLM-graded checks or sampled human review for tone, completeness and faithfulness (Domain 3 and lesson 4.3).
Decide the failure policy up front: a bounded repair attempt that feeds the specific error back, then escalation to a review queue or a safe fallback. Never emit a failed result silently, and never loop unbounded.
Common exam distractor
"Turn on structured outputs and the problem is solved" and "tell the model to always return consistent totals" are both attractive and both wrong when the defect is a value that is well-formed but incorrect. Schema conformance is not correctness, and a prompt instruction is not enforcement. The answer that adds a deterministic validation stage with a defined failure path is the one that holds up. Equally, cost levers (batching, caching) and token limits do not fix correctness defects.
Stages 6 and 7: delivery and the feedback loop
Delivery is where reversibility matters. Make writes idempotent so a retried job does not act twice, and put human review before actions that cannot be undone (lesson 4.3 covers where to place gates).
The feedback loop is closed only when a production failure becomes a test that gates the next release. Capture, per request: the request ID, the prompt and configuration version, model, token usage, latency, stop reason, validation outcome and final disposition, plus whatever human signal exists (an edit, a rejection, a rating). Then triage regularly and convert real failures into eval cases; Anthropic's guidance on agent evals is to start from what you already test manually and turn user-reported failures into test cases. Run regression evals before any prompt or model change, and combine them with production monitoring and human review, because no single layer catches every issue. Logging prompts means logging personal data, so retention and access decisions belong in this stage (lessons 1.4 and 4.4).
A dashboard of thumbs-up rates is not a feedback loop. It measures sentiment; it does not change what the system will do tomorrow.