{"course":{"slug":"building-with-ai","title":"Building with AI","url":"https://addaly.com/learn/building-with-ai","level":"intermediate","track":"build"},"lesson":{"slug":"reading-the-response","title":"Every field in the response, and the two that catch bugs","url":"https://addaly.com/learn/building-with-ai/reading-the-response","position":6,"of":80,"minutes":8,"answer":"Check stop_reason before you parse and log the returned model string and usage on every call.","keyIdea":"Check stop_reason before you parse and log the returned model string and usage on every call, because a truncated answer and a silently swapped model version both look like a working response until they do not."},"body":{"format":"markdown","text":"## Most people read one field\n\nReading only the visible text loses information about how generation ended and what the request consumed. Inspect the schema for the chosen API. The examples below use Claude Messages responses.\n\nHere is what comes back, and what each part is for.\n\n**`id`** identifies the message. Log it with your own trace ID and the HTTP request ID. The Python SDK exposes the latter as `_request_id` on a response. These identifiers help correlate failures and support investigations. [SDK request IDs](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python).\n\n**`model`**: the model that actually served the request, which is not always the string you sent. Ask for an alias like `latest` and you get whatever the provider is currently pointing that alias at. Log the returned value, not the requested one. The morning your outputs shift for no reason you changed, this field is the evidence.\n\n**`role`** is `assistant` on this Messages response.\n\n**`content`**: a **list of blocks**, not a string. A response can contain a text block, then a tool-use block, then more text. Any code written as `content[0].text` is one tool call away from a crash or, worse, from silently dropping half the answer. Iterate over blocks and switch on the type.\n\n**`stop_reason`** (or `finish_reason`): why generation ended. This is the field that catches bugs.\n\n**`usage`**: token counts. This is the field that controls your bill.\n\n## Read the stopping condition\n\nFor Claude Messages, inspect `stop_reason` alongside the content and the task's validation rules.\n\n- **`end_turn`** means the model ended its turn naturally. The response can still be empty, incorrect or unsuitable for the task.\n- **`max_tokens`** means the output cap was reached. Treat the answer as potentially truncated and check it before use.\n- **`tool_use`** hands control back for tool handling. Check permissions and validate tool inputs before any action.\n- **`stop_sequence`** means a configured stop sequence was reached. Your application determines whether that is the expected endpoint.\n- **`refusal`** indicates a refusal.\n- **`pause_turn`** requires the documented continuation flow for a paused server-tool turn.\n- **`model_context_window_exceeded`** means the model reached its context limit.\n\nOther APIs use different field names and values. Check the current [stop-reason documentation](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons).\n\n```python\n# Inspect r from the request made earlier in this chapter.\nif r.stop_reason != \"end_turn\":\n    raise RuntimeError(\n        \"Response needs stop-reason handling: \"\n        f\"{r.stop_reason}\"\n    )\ntext = \"\".join(\n    block.text for block in r.content\n    if block.type == \"text\"\n)\nif not text.strip():\n    raise ValueError(\"The response contained no usable text\")\n```\n\nThis simple text-only path rejects outcomes it does not handle. A tool-using application needs explicit branches for its supported tool and continuation flows. If JSON parsing fails, inspect the stopping condition and retained response before choosing a repair or another request.\n\n## usage, and the four numbers\n\nClaude reports uncached input, output, cache-creation input and cache-read input separately. Rates depend on the selected model, cache lifetime and other applicable pricing. Record the counts alongside the feature and the request identifiers. [Cache usage and prices](https://platform.claude.com/docs/en/build-with-claude/prompt-caching).\n\nThe following helper calculates these four token categories using rates you supply in dollars per million tokens. Use the appropriate rate for each category. If a request mixes cache lifetimes, calculate each write category from its detailed usage before summing them. Include any separately billed tools or features in the complete cost record.\n\n```python\ndef token_cost_usd(usage, *, input_rate, output_rate,\n                   cache_write_rate, cache_read_rate):\n    counts_and_rates = [\n        (usage.input_tokens, input_rate),\n        (usage.output_tokens, output_rate),\n        (getattr(usage, \"cache_creation_input_tokens\", 0) or 0,\n         cache_write_rate),\n        (getattr(usage, \"cache_read_input_tokens\", 0) or 0,\n         cache_read_rate),\n    ]\n    cost = sum(count * rate for count, rate in counts_and_rates)\n    return cost / 1_000_000\n```\n\nStore per-feature usage so you can distinguish changes in traffic, context length, output length and model choice. Keep sensitive request content out of routine cost logs.\n\n## What is not in the response\n\nTwo absences worth naming.\n\nToken probabilities or a self-reported confidence number do not by themselves establish factual correctness. Evaluate the answer against the task and its evidence. When an API exposes log probabilities, interpret them as token-selection information under that API's documented model.\n\nAn uncited plain-text answer does not establish which source supports each claim. Some responses include structured citations or tool results. Inspect those fields and verify that the cited evidence supports the relevant claims. A quote that appears in a document establishes a text match, which still needs a relevance and interpretation check. [Structured citations](https://platform.claude.com/docs/en/build-with-claude/citations)."},"check":{"question":"An extraction service that has run cleanly for months starts throwing `Unexpected end of JSON input` on a handful of documents. What is the first thing to check, and why?","options":[{"text":"Whether the JSON schema needs loosening, since some documents evidently have fields it does not allow.","correct":false,"tempting":"Treats a parse failure as a validation failure; the parser never reached validation because the text was not complete JSON."},{"text":"Whether those documents contain characters that break JSON encoding.","correct":false,"tempting":"Plausible for hand-built strings, but well-formed model output escapes characters correctly, and this would fail consistently rather than on the longest inputs."},{"text":"Whether stop_reason is max_tokens on those calls, indicating that the output cap was reached and truncation may explain the parse error.","correct":true},{"text":"Whether the provider is under load and returning degraded responses.","correct":false,"tempting":"Reaches for an external cause without inspecting the response fields that would identify a local one, and load does not truncate output mid-structure."}]},"prev":{"slug":"streaming-and-perceived-speed","title":"Streaming, and the difference between fast and feeling fast","url":"https://addaly.com/learn/building-with-ai/streaming-and-perceived-speed"},"next":{"slug":"retries-that-do-not-make-it-worse","title":"Errors, retries, and how a retry loop takes down your own service","url":"https://addaly.com/learn/building-with-ai/retries-that-do-not-make-it-worse"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Every field in the response, and the two that catch bugs', in Building with AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/building-with-ai/reading-the-response (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Every field in the response, and the two that catch bugs","courseTitle":"Building with AI","module":{"index":1,"slug":"the-call-underneath-everything","title":"The call underneath everything"},"answer":null,"keyIdea":"Check stop_reason before you parse and log the returned model string and usage on every call, because a truncated answer and a silently swapped model version both look like a working response until they do not.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"most-people-read-one-field","runs":[{"text":"Most people read one field"}]},{"t":"p","runs":[{"text":"Reading only the visible text loses information about how generation ended and what the request consumed. Inspect the schema for the chosen API. The examples below use Claude Messages responses."}]},{"t":"p","runs":[{"text":"Here is what comes back, and what each part is for."}]},{"t":"p","runs":[{"text":"id","b":true,"code":true},{"text":" identifies the message. Log it with your own trace ID and the HTTP request ID. The Python SDK exposes the latter as "},{"text":"_request_id","code":true},{"text":" on a response. These identifiers help correlate failures and support investigations. "},{"text":"SDK request IDs","href":"https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python"},{"text":"."}]},{"t":"p","runs":[{"text":"model","b":true,"code":true},{"text":": the model that actually served the request, which is not always the string you sent. Ask for an alias like "},{"text":"latest","code":true},{"text":" and you get whatever the provider is currently pointing that alias at. Log the returned value, not the requested one. The morning your outputs shift for no reason you changed, this field is the evidence."}]},{"t":"p","runs":[{"text":"role","b":true,"code":true},{"text":" is "},{"text":"assistant","code":true},{"text":" on this Messages response."}]},{"t":"p","runs":[{"text":"content","b":true,"code":true},{"text":": a "},{"text":"list of blocks","b":true},{"text":", not a string. A response can contain a text block, then a tool-use block, then more text. Any code written as "},{"text":"content[0].text","code":true},{"text":" is one tool call away from a crash or, worse, from silently dropping half the answer. Iterate over blocks and switch on the type."}]},{"t":"p","runs":[{"text":"stop_reason","b":true,"code":true},{"text":" (or "},{"text":"finish_reason","code":true},{"text":"): why generation ended. This is the field that catches bugs."}]},{"t":"p","runs":[{"text":"usage","b":true,"code":true},{"text":": token counts. This is the field that controls your bill."}]},{"t":"h2","id":"read-the-stopping-condition","runs":[{"text":"Read the stopping condition"}]},{"t":"p","runs":[{"text":"For Claude Messages, inspect "},{"text":"stop_reason","code":true},{"text":" alongside the content and the task’s validation rules."}]},{"t":"ul","items":[[{"text":"end_turn","b":true,"code":true},{"text":" means the model ended its turn naturally. The response can still be empty, incorrect or unsuitable for the task."}],[{"text":"max_tokens","b":true,"code":true},{"text":" means the output cap was reached. Treat the answer as potentially truncated and check it before use."}],[{"text":"tool_use","b":true,"code":true},{"text":" hands control back for tool handling. Check permissions and validate tool inputs before any action."}],[{"text":"stop_sequence","b":true,"code":true},{"text":" means a configured stop sequence was reached. Your application determines whether that is the expected endpoint."}],[{"text":"refusal","b":true,"code":true},{"text":" indicates a refusal."}],[{"text":"pause_turn","b":true,"code":true},{"text":" requires the documented continuation flow for a paused server-tool turn."}],[{"text":"model_context_window_exceeded","b":true,"code":true},{"text":" means the model reached its context limit."}]]},{"t":"p","runs":[{"text":"Other APIs use different field names and values. Check the current "},{"text":"stop-reason documentation","href":"https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons"},{"text":"."}]},{"t":"code","lang":"python","label":"Python","text":"# Inspect r from the request made earlier in this chapter.\nif r.stop_reason != \"end_turn\":\n    raise RuntimeError(\n        \"Response needs stop-reason handling: \"\n        f\"{r.stop_reason}\"\n    )\ntext = \"\".join(\n    block.text for block in r.content\n    if block.type == \"text\"\n)\nif not text.strip():\n    raise ValueError(\"The response contained no usable text\")"},{"t":"p","runs":[{"text":"This simple text-only path rejects outcomes it does not handle. A tool-using application needs explicit branches for its supported tool and continuation flows. If JSON parsing fails, inspect the stopping condition and retained response before choosing a repair or another request."}]},{"t":"h2","id":"usage-and-the-four-numbers","runs":[{"text":"usage, and the four numbers"}]},{"t":"p","runs":[{"text":"Claude reports uncached input, output, cache-creation input and cache-read input separately. Rates depend on the selected model, cache lifetime and other applicable pricing. Record the counts alongside the feature and the request identifiers. "},{"text":"Cache usage and prices","href":"https://platform.claude.com/docs/en/build-with-claude/prompt-caching"},{"text":"."}]},{"t":"p","runs":[{"text":"The following helper calculates these four token categories using rates you supply in dollars per million tokens. Use the appropriate rate for each category. If a request mixes cache lifetimes, calculate each write category from its detailed usage before summing them. Include any separately billed tools or features in the complete cost record."}]},{"t":"code","lang":"python","label":"Python","text":"def token_cost_usd(usage, *, input_rate, output_rate,\n                   cache_write_rate, cache_read_rate):\n    counts_and_rates = [\n        (usage.input_tokens, input_rate),\n        (usage.output_tokens, output_rate),\n        (getattr(usage, \"cache_creation_input_tokens\", 0) or 0,\n         cache_write_rate),\n        (getattr(usage, \"cache_read_input_tokens\", 0) or 0,\n         cache_read_rate),\n    ]\n    cost = sum(count * rate for count, rate in counts_and_rates)\n    return cost / 1_000_000"},{"t":"p","runs":[{"text":"Store per-feature usage so you can distinguish changes in traffic, context length, output length and model choice. Keep sensitive request content out of routine cost logs."}]},{"t":"h2","id":"what-is-not-in-the-response","runs":[{"text":"What is not in the response"}]},{"t":"p","runs":[{"text":"Two absences worth naming."}]},{"t":"p","runs":[{"text":"Token probabilities or a self-reported confidence number do not by themselves establish factual correctness. Evaluate the answer against the task and its evidence. When an API exposes log probabilities, interpret them as token-selection information under that API’s documented model."}]},{"t":"p","runs":[{"text":"An uncited plain-text answer does not establish which source supports each claim. Some responses include structured citations or tool results. Inspect those fields and verify that the cited evidence supports the relevant claims. A quote that appears in a document establishes a text match, which still needs a relevance and interpretation check. "},{"text":"Structured citations","href":"https://platform.claude.com/docs/en/build-with-claude/citations"},{"text":"."}]}],"check":{"question":[{"text":"An extraction service that has run cleanly for months starts throwing "},{"text":"Unexpected end of JSON input","code":true},{"text":" on a handful of documents. What is the first thing to check, and why?"}],"options":[{"text":[{"text":"Whether the JSON schema needs loosening, since some documents evidently have fields it does not allow."}],"correct":false,"tempting":[{"text":"Treats a parse failure as a validation failure; the parser never reached validation because the text was not complete JSON."}]},{"text":[{"text":"Whether those documents contain characters that break JSON encoding."}],"correct":false,"tempting":[{"text":"Plausible for hand-built strings, but well-formed model output escapes characters correctly, and this would fail consistently rather than on the longest inputs."}]},{"text":[{"text":"Whether stop_reason is max_tokens on those calls, indicating that the output cap was reached and truncation may explain the parse error."}],"correct":true,"tempting":null},{"text":[{"text":"Whether the provider is under load and returning degraded responses."}],"correct":false,"tempting":[{"text":"Reaches for an external cause without inspecting the response fields that would identify a local one, and load does not truncate output mid-structure."}]}],"order":[3,1,0,2],"why":null},"prev":{"slug":"streaming-and-perceived-speed","title":"Streaming, and the difference between fast and feeling fast","minutes":9},"next":{"slug":"retries-that-do-not-make-it-worse","title":"Errors, retries, and how a retry loop takes down your own service","minutes":9}}}