الانتقال إلى المحتوى
Claude وأدوات الـ AI للبرمجةClaude API و Tool Use· 6 دقائق للقراءة

Handling stop_reason: Why a Successful Claude API Response Can Still Be Incomplete

A 200 means the request was processed. The stop_reason tells you whether Claude finished, was cut off, refused or is waiting on you.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • Claude API
محتويات المقال

Your support dashboard shows an AI summary of each ticket. QA files a bug: some summaries stop mid-sentence, like "The customer was charged twice and asked for". The logs show HTTP 200 for every call, no exceptions, no retries. A week later, the summary worker crashes on one ticket with 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

"If the Claude API returned a response without an error, the answer is complete." It's the rule most HTTP APIs teach:

  • 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.

The half-truth: a 200 really does mean the request succeeded. But "the API processed your request" and "Claude gave you the whole answer you wanted" are two different facts, and the API reports the second one separately.

What actually happens

Errors and stop reasons answer different questions

Errors come back as HTTP 4xx or 5xx with error details, and they mean the request failed. The is part of every successful response. In the docs' words, "Unlike errors, which indicate failures in processing your request, 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:

GroupValuesWhat it meansWhat to do
Finishedend_turnClaude reached a natural stopping pointUse the response
Truncatedmax_tokens, model_context_window_exceededOutput hit your cap or the model's context windowDon't treat it as complete: raise the cap, continue, or mark it
Your signalstop_sequenceClaude generated one of your stop_sequencesRead stop_sequence to see which one
Your movetool_use, pause_turnClaude called your tool, or a server-tool loop pausedRun the tool and send results, or send the response back
DeclinedrefusalA safety classifier declined the requestRead 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.

You have three honest options. Raise 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

Two values mean the turn isn't over and Claude is waiting on your code. With 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

"Safety classifiers return this stop reason as a normal HTTP 200 response, not an error." On a refusal, 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

Here's the summary worker before and after it reads the field:

Python summarize.py
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)

The second version reads text by block type instead of assuming 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.

Even 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

  1. Find every call siteSearch for messages.create and messages.stream, and note which ones read stop_reason at all.
  2. Branch on it explicitlyHandle each value the call can produce, and make an unexpected value fail loudly instead of passing as success.
  3. Size max_tokens for the taskSet the cap from what complete answers actually need, and treat a truncated response as its own state in your data.
  4. Treat refusals as dataLog stop_details, discard partial output, and decide on a fallback model or a human path.
  5. Watch the distributionCount 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_reason tells you whether the answer is complete.
  • max_tokens and model_context_window_exceeded mean truncated, even though the text looks normal.
  • refusal is a 200 too, with stop_details and possibly empty content, so never assume content[0].
  • tool_use and pause_turn mean 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.

📚 المصادر

  1. Stop reasons and fallback — Claude API Docs
  2. Create a Message — Claude API Reference
  3. Refusals and fallback — Claude API Docs

التعليقات (0)