Most people read one field
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.
Here is what comes back, and what each part is for.
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.
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.
role is assistant on this Messages response.
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.
stop_reason (or finish_reason): why generation ended. This is the field that catches bugs.
usage: token counts. This is the field that controls your bill.
Read the stopping condition
For Claude Messages, inspect stop_reason alongside the content and the task’s validation rules.
end_turnmeans the model ended its turn naturally. The response can still be empty, incorrect or unsuitable for the task.max_tokensmeans the output cap was reached. Treat the answer as potentially truncated and check it before use.tool_usehands control back for tool handling. Check permissions and validate tool inputs before any action.stop_sequencemeans a configured stop sequence was reached. Your application determines whether that is the expected endpoint.refusalindicates a refusal.pause_turnrequires the documented continuation flow for a paused server-tool turn.model_context_window_exceededmeans the model reached its context limit.
Other APIs use different field names and values. Check the current stop-reason documentation.
# Inspect r from the request made earlier in this chapter.
if r.stop_reason != "end_turn":
raise RuntimeError(
"Response needs stop-reason handling: "
f"{r.stop_reason}"
)
text = "".join(
block.text for block in r.content
if block.type == "text"
)
if not text.strip():
raise ValueError("The response contained no usable 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.
usage, and the four numbers
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. Cache usage and prices.
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.
def token_cost_usd(usage, *, input_rate, output_rate,
cache_write_rate, cache_read_rate):
counts_and_rates = [
(usage.input_tokens, input_rate),
(usage.output_tokens, output_rate),
(getattr(usage, "cache_creation_input_tokens", 0) or 0,
cache_write_rate),
(getattr(usage, "cache_read_input_tokens", 0) or 0,
cache_read_rate),
]
cost = sum(count * rate for count, rate in counts_and_rates)
return cost / 1_000_000Store 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.
What is not in the response
Two absences worth naming.
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.
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. Structured citations.
Check your understanding
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?
Pick the one you would defend. Your answer stays private.
Your place and first choices stay on this browser. Classroom credit is recorded separately.
Every lesson here is open. Your progress is recorded once you pass the Python, from Zero, for AI exam.
Stuck on something?Ask Sayali, your AI tutor