Topic 3 of 5 · 5 min read
Reading content blocks, stop reason and usage
Goal: Extract the answer from a response, detect a truncated answer from its stop reason, and record its token usage and request id.
A response is more than a string: read the content, check why the model stopped, and log the token usage and request id before you use the answer.
Check yourself · 1 of 3
A Claude response has stop_reason "max_tokens". What does that tell you?
Why it matters
An answer that was cut off by the output limit looks like a normal answer. It is just shorter, and sometimes ends mid-sentence or mid-JSON. If your code only prints the text, you will ship a truncated reply and never know. Usage numbers tell you what each call costs, and the request id lets the provider's support find one specific call when something odd happens.
What a response contains
- Content blocks. In the Claude Messages API
contentis a list of blocks. A plain reply has one block of typetext, and the answer iscontent[0].text. With tools or extended thinking there can be several blocks of different types, so look for the type instead of assuming position zero. OpenAI's Responses API gives a convenienceoutput_text, and Gemini puts text undercandidates[0].content.parts. - Stop reason. Claude returns
stop_reason:end_turnmeans the model finished,max_tokensmeans it hit your limit and was cut off. OpenAI marks the responseincompletewith a reason such asmax_output_tokens. Gemini returnsfinishReasonvalues likeSTOPandMAX_TOKENS. - Usage. Claude reports
usage.input_tokensandusage.output_tokens. OpenAI reports input and output token counts. Gemini reportsusageMetadatawith prompt and candidate counts. Multiply by the model's price to get the cost of the call. - Request id. Claude sends it in the
request-idresponse header and exposes it in the SDK. Log it with every call.
How to do it
r = client.messages.create(model=MODEL, max_tokens=200, messages=msgs)
text = "".join(b.text for b in r.content if b.type == "text")
log.info("req=%s in=%d out=%d stop=%s", r._request_id, r.usage.input_tokens, r.usage.output_tokens, r.stop_reason)
if r.stop_reason == "max_tokens":
raise TruncatedReply("raise max_tokens or ask for a shorter answer")
Before and after
Weak: print(r.content[0].text). A 200-token limit cuts a JSON answer after the third field, and the parser fails later with no clue why. Fixed: the stop reason is checked first, so the failure says "truncated" at the source.
What goes wrong
- Assuming one text block. With tools or thinking enabled, the first block may not be text.
- Ignoring the stop reason. Truncated output is parsed or shown as if complete.
- Not logging usage. A bug that loops calls shows up as a surprise bill.
- Logging the prompt but not the request id, so support cannot find the call.
Examples
The truncated JSON
A call asks for a JSON list of 40 products with max_tokens=150. The text ends with {"name": "Desk lamp", "pr and stop_reason is max_tokens. The fix is to raise the limit, request fewer items per call, or handle the truncated case explicitly, not to try to repair the JSON.
Same field, three names
Claude: stop_reason = "max_tokens" usage.output_tokens
OpenAI: status = "incomplete" usage.output_tokens
Gemini: finishReason = "MAX_TOKENS" usageMetadata.candidatesTokenCount
Wrap them in one small function in your code so the rest of the app sees a single "was truncated" flag.
Key points
- Read the answer from the content blocks, filtering by block type, not by a fixed position.
- A stop reason of max_tokens (or MAX_TOKENS in Gemini) means the answer was cut off.
- Log input and output token counts for every call so cost is visible.
- Log the request id with each call so the provider can trace a specific request.
- Check the stop reason before parsing or showing the text.
Common mistakes
- Printing content[0].text without checking the block type or the stop reason.
- Treating a truncated answer as a complete one because it "looks fine".
- Throwing away the usage object, so cost per feature cannot be measured later.
- Logging the whole prompt and response but not the request id.
Check yourself · 2 of 3
Which fields let you work out what a single API call cost?
Check yourself · 3 of 3
Your code does print(reply.content[0].text) and sometimes crashes when tools are enabled. What is the likely cause?
Practice items, not counted towards your mastery.
Start here
- Claude API overview (opens in a new tab)DocsFree
Authentication headers, the Messages endpoint and the official SDK list in one place.
- Working with messages (Claude docs) (opens in a new tab)DocsFree
Roles, multi-turn requests, response fields and stop reasons with runnable examples.
- OpenAI developer quickstart (opens in a new tab)DocsFree
The same first call in the Responses API, with its SDK setup and key handling.
More for this topic
- Errors (Claude API) (opens in a new tab)DocsFree
HTTP error codes, the error body shape and the request id to log for support.