
Handling stop_reason: Why a Successful Claude API Response Can Still Be Incomplete
- كاتب موثّق
- Claude API
محتويات المقال
IndexError: list index out of range, again after a 200. Both bugs come from the same field nobody reads. The long tickets came back with stop_reason: "max_tokens", and the crash was a "refusal" whose content list was empty.
The common misconception
In most APIs, a 200 means success and the body is the result you asked for. The SDKs raise exceptions for failed requests, so no exception feels like no problem. In development, prompts are short and almost every response ends naturally. A truncated answer still reads like an answer, and a cut-off sentence is easy to miss in a log.
What actually happens
Errors and stop reasons answer different questions
stop_reason tells you why Claude completed its response generation." In a non-streaming response it's never null, and the API reference lists seven values:
end_turn | |||
max_tokens, model_context_window_exceeded | |||
stop_sequence | stop_sequences | stop_sequence to see which one | |
tool_use, pause_turn | |||
refusal | stop_details, discard partial output, try a fallback |
max_tokens is a ceiling, not a target
max_tokens is "the maximum number of to generate before stopping", and the reference adds that models "may stop before reaching this maximum". When the answer needs more, generation stops at the cap, and the response is still a 200 with whatever text fit. model_context_window_exceeded is the same situation one level up: the output filled the model's whole context window, and the docs' advice is to treat the response as truncated.
max_tokens so complete answers fit. Mark the output as truncated, as the docs' own example does with a note appended to the text. Or continue it: the docs show a loop that sends the original prompt, the partial text as an assistant turn and a user message asking Claude to continue, for a few attempts at most.
Your move: tool_use and pause_turn
tool_use, Claude asked for one of your tools; you run it and send back a tool_result for every tool_use block. With pause_turn, a server tool such as web search hit its iteration limit, 10 per request by default, and you send the response back as-is to let Claude finish. Saving either one as the final answer drops the actual work.
A refusal is a normal response
stop_details names the policy category, and content can be empty when the refusal arrives before any output, which is exactly what crashed content[0]. A refusal can also arrive mid-stream after partial text; the docs say to "treat any partial output as incomplete and discard it". On current models, retrying the same request on another Claude model can usually serve it.
Checking it in code
import anthropicclient = anthropic.Anthropic()reply = client.messages.create( model="claude-opus-5-5", max_tokens=512, messages=[{"role": "user", "content": f"Summarize:\n{ticket}"}],)# A 200 every time. Long tickets end mid-sentence ("max_tokens"), and a# refusal with empty content raises IndexError on this line.save_summary(reply.content[0].text)import anthropicclient = anthropic.Anthropic()reply = client.messages.create( model="claude-opus-5-5", max_tokens=4096, messages=[{"role": "user", "content": f"Summarize:\n{ticket}"}],)text = next((b.text for b in reply.content if b.type == "text"), "")match reply.stop_reason: case "end_turn": save_summary(text) case "max_tokens" | "model_context_window_exceeded": log.warning("Summary truncated: %s", reply.stop_reason) save_summary(text + " [truncated]", complete=False) case "refusal": # discard any partial text log.warning("Refused: %s", reply.stop_details) queue_for_fallback(ticket) case other: # no tools or stop sequences here, so this is a bug raise RuntimeError(f"Unexpected stop_reason: {other}")content[0], gives the summary room to finish, and turns each non-finished outcome into an explicit state. The last case matters too: if a future change adds tools to this call, a tool_use response fails loudly instead of being saved as a summary.
end_turn deserves a glance. The docs note that Claude sometimes returns an empty response with end_turn, typically right after tool results, and that resending the empty response unchanged won't help.
How to apply it in your project
Find every call site Search for messages.createandmessages.stream, and note which ones readstop_reasonat all.Branch on it explicitly Handle each value the call can produce, and make an unexpected value fail loudly instead of passing as success. Size max_tokens for the task Set the cap from what complete answers actually need, and treat a truncated response as its own state in your data. Treat refusals as data Log stop_details, discard partial output, and decide on a fallback model or a human path.Watch the distribution Count stop reasons per endpoint in your metrics, so truncation shows up on a dashboard before it shows up in a bug.
Key takeaways
A 200 means the request was processed; stop_reasontells you whether the answer is complete.max_tokensandmodel_context_window_exceededmean truncated, even though the text looks normal.refusalis a 200 too, withstop_detailsand possibly emptycontent, so never assumecontent[0].tool_useandpause_turnmean the turn isn't over: your code has to continue it.Branch on every value, fail loudly on unexpected ones, and track the mix in your metrics.
التعليقات (0)