AI and machine learning · Intermediate · 20 min
Handle every stop reason the Claude API can return
By Padding · Updated 18 Nov 2026
python:3.15-slim · Python 3.15 · anthropic 2.14.0 · pytest 9.2.0 · claude-opus-5-5
You will have one Python function that turns any Claude API response into a finished reply, a truncated reply or a safe fallback, branching on all seven stop reasons, with a pytest test for each branch.
On this page
A Claude API response is not always a finished answer. The stop_reason field says why the model stopped, and only some of the values mean "here is your text". The others mean the text was cut off, a tool is waiting to run, the server paused a long turn, or the model declined. Code that reads response.content[0].text and moves on will show customers half a sentence, crash on a reply that holds only a thinking block, or print the first words of an answer that was refused partway through.
The anthropic 2.14.0 Python SDK lists seven values: end_turn, stop_sequence, max_tokens, tool_use, pause_turn, refusal and model_context_window_exceeded. In this tutorial you write one function, get_reply, for a small shop's support assistant on claude-opus-5-5. It loops until it has something safe to show and returns a Reply with a status your interface can act on: done, truncated, refused, context_full or gave_up. Then you write one pytest test per branch, run against a local stand-in for the Messages API, so the whole suite runs offline in seconds.
This page is about the code. What the customer sees on screen when a reply is refused or cut short is covered in /tutorials/design-error-refusal-and-fallback-states-for-ai.
Step 1 · Create the project
Make a throwaway project folder and add the SDK and pytest at exact versions. The tests check field names and a beta header value, which a later SDK release could change:
mkdir -p ~/stop-reasons-demo
cd ~/stop-reasons-demo
uv init --no-package
uv add "anthropic==2.14.0"
uv add --dev "pytest==9.2.0"Confirm the SDK knows every stop reason this tutorial handles. The list comes from the SDK's own type, so it is what your installed version can return:
cd ~/stop-reasons-demo
uv run python -c "import typing, anthropic.types as t; print(typing.get_args(t.StopReason))"Check it worked
The last command prints a tuple of seven strings, starting ('end_turn', 'max_tokens', 'stop_sequence', 'tool_use', 'pause_turn', 'refusal', 'model_context_window_exceeded'). If refusal or pause_turn is missing, you have an older SDK: check pyproject.toml lists anthropic==2.14.0.
Step 2 · Write the reply function
Create support_reply.py. Read it once top to bottom first; the next steps test it one branch at a time.
cd ~/stop-reasons-demo
cat > support_reply.py <<'PY'
"""Get one finished support reply from Claude, whatever the stop reason."""
from dataclasses import dataclass, field
MODEL = "claude-opus-5-5"
MAX_TOKENS = 4000
MAX_TOKENS_CEILING = 16000
MAX_CONTINUATIONS = 5
END_MARKER = "###END###"
FALLBACK_BETA = "server-side-fallback-2026-07-01"
SYSTEM = (
"You answer customer questions for a small online shop. Keep replies under "
f"120 words. Write {END_MARKER} on its own line when the customer-facing reply is done."
)
REFUSAL_TEXT = (
"Sorry, I can't help with that here. A member of the team will reply by email."
)
TOOLS = [
{
"name": "get_order_status",
"description": "Look up the delivery status of one order by its number.",
"input_schema": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
"additionalProperties": False,
},
"strict": True,
},
{"type": "web_search_20260209", "name": "web_search", "max_uses": 3},
]
def get_order_status(order_id: str) -> str:
"""Stand-in for your order database."""
return f"Order {order_id}: dispatched, arriving Thursday."
@dataclass
class Reply:
status: str # done | truncated | refused | context_full | gave_up
text: str
stop_reason: str | None
detail: dict = field(default_factory=dict)
requests: int = 0
def text_of(message) -> str:
return "".join(b.text for b in message.content if b.type == "text").strip()
def get_reply(client, question: str, *, use_fallbacks: bool = False) -> Reply:
messages = [{"role": "user", "content": question}]
max_tokens = MAX_TOKENS
continuations = 0
requests = 0
while True:
params = dict(
model=MODEL,
max_tokens=max_tokens,
system=SYSTEM,
tools=TOOLS,
stop_sequences=[END_MARKER],
output_config={"effort": "medium"},
messages=messages,
)
if use_fallbacks:
response = client.beta.messages.create(
**params, betas=[FALLBACK_BETA], fallbacks="default"
)
else:
response = client.messages.create(**params)
requests += 1
reason = response.stop_reason
text = text_of(response)
if reason == "end_turn":
return Reply("done", text, reason, {"model": response.model}, requests)
if reason == "stop_sequence":
# The marker itself is not in the text; stop_sequence says which one matched.
return Reply("done", text, reason, {"matched": response.stop_sequence}, requests)
if reason == "max_tokens":
if text:
return Reply("truncated", text, reason, {"max_tokens": max_tokens}, requests)
# Thinking used the whole budget before any text: retry once with more room.
if max_tokens >= MAX_TOKENS_CEILING:
return Reply("gave_up", "", reason, {"max_tokens": max_tokens}, requests)
max_tokens = MAX_TOKENS_CEILING
continue
if reason == "tool_use":
messages.append({"role": "assistant", "content": response.content})
results = []
for block in response.content:
if block.type == "tool_use" and block.name == "get_order_status":
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": get_order_status(**block.input),
})
elif block.type == "tool_use":
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": f"Unknown tool {block.name}",
"is_error": True,
})
messages.append({"role": "user", "content": results})
continue
if reason == "pause_turn":
continuations += 1
if continuations > MAX_CONTINUATIONS:
return Reply("gave_up", text, reason, {"continuations": continuations - 1}, requests)
# Send the paused turn back as it is; the server picks up where it stopped.
messages.append({"role": "assistant", "content": response.content})
continue
if reason == "refusal":
details = response.stop_details
return Reply(
"refused",
REFUSAL_TEXT, # never show partial text from a refused turn
reason,
{
"category": details.category if details else None,
"explanation": details.explanation if details else None,
"model": response.model,
},
requests,
)
if reason == "model_context_window_exceeded":
return Reply("context_full", text, reason, {}, requests)
raise RuntimeError(f"Unhandled stop_reason: {reason!r}")
PY
uv run python -m py_compile support_reply.py && echo "support_reply.py compiles"What each branch does:
end_turnandstop_sequenceare both finished replies. Withstop_sequences, the API stops as soon as the model writes###END###, leaves the marker out of the text and puts it inresponse.stop_sequence. Here the marker stops the model adding anything after the customer-facing reply.max_tokensmeans the output budget ran out. If some text came back, it is returned astruncatedso your interface can say so. On Opus 5.5 thinking is always on, and thinking tokens count againstmax_tokensand are billed as output. A reply can spend the whole budget thinking and contain no text at all, so that case is retried once with a larger budget, then given up on. Each retry is paid for, which is why there is a ceiling.tool_usemeans a tool call is waiting. The function runs it, sends back atool_resultwith the sametool_use_id, and loops. An unknown tool name gets anis_errorresult instead of being dropped.pause_turncomes from server tools such as web search: the server stopped a long turn early. The paused assistant content goes back unchanged, with no new "please continue" user message, and the server resumes.MAX_CONTINUATIONSstops a turn that never finishes.refusalmeans the model or a safety classifier declined. It arrives as a normal HTTP 200, not an exception. The function readsstop_detailswithout assuming it exists, keeps the category for your logs, and replaces any partial text withREFUSAL_TEXT.model_context_window_exceededmeans the conversation filled the model's context window. Treat the text as truncated and start a shorter conversation.- Anything else raises, so a value added in a future SDK fails loudly in your tests rather than showing a blank reply.
If your shop answers in more than one language, as many do across Nigeria, Kenya or South Africa, keep REFUSAL_TEXT in each language you support and pick it from the customer's language, not the model's output. The model wrote nothing usable on a refusal, so the fallback must come from your code.
Check it worked
The command prints support_reply.py compiles. Count the if reason == lines in the file: there are seven, one per value from the previous step.
Step 3 · Add a stand-in Messages API for the tests
The tests need responses with each stop reason on demand, which the real API will not give you. Add a pytest fixture that starts a small HTTP server on a free local port, answers each POST /v1/messages with the next queued body, and records every request so the tests can read what your code sent. The SDK talks to it through base_url, so the SDK's own response parsing runs as it would against the real API:
cd ~/stop-reasons-demo
cat > conftest.py <<'PY'
"""A local stand-in for POST /v1/messages that replays queued replies."""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import anthropic
import pytest
def message(stop_reason, content, **extra):
"""Build a Messages API response body in the documented shape."""
body = {
"id": "msg_stub",
"type": "message",
"role": "assistant",
"model": "claude-opus-5-5",
"content": content,
"stop_reason": stop_reason,
"stop_sequence": None,
"stop_details": None,
"usage": {"input_tokens": 120, "output_tokens": 40},
}
body.update(extra)
return body
class Stub:
def __init__(self):
self.replies = []
self.requests = []
@pytest.fixture
def stub():
state = Stub()
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
length = int(self.headers["content-length"])
state.requests.append({
"path": self.path,
"headers": dict(self.headers),
"body": json.loads(self.rfile.read(length)),
})
data = json.dumps(state.replies.pop(0)).encode()
self.send_response(200)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, *args):
pass
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
state.client = anthropic.Anthropic(
api_key="stub-key",
base_url=f"http://127.0.0.1:{server.server_port}",
max_retries=0,
)
yield state
server.shutdown()
PY
uv run python -c "import conftest, support_reply; print('fixture module loads')"max_retries=0 matters: with the default retries, a mistake in a test would be hidden behind repeated requests. The API key is a dummy string, because nothing leaves your machine. For a fuller stand-in with recorded fixtures and error responses, see /tutorials/test-llm-code-offline-with-a-stub-messages-api.
Check it worked
The command prints fixture module loads, which proves conftest.py and support_reply.py import cleanly. The tests come next.
Step 4 · Test the finished and truncated replies
Start the test file with the two finished cases and the three max_tokens cases. THINKING is a thinking block as Opus 5.5 returns it by default: present, with empty text.
cd ~/stop-reasons-demo
cat > test_support_reply.py <<'PY'
from conftest import message
from support_reply import END_MARKER, MAX_TOKENS_CEILING, REFUSAL_TEXT, get_reply
THINKING = {"type": "thinking", "thinking": "", "signature": "sig_stub"}
def text(t):
return {"type": "text", "text": t}
def test_end_turn_returns_the_text(stub):
stub.replies = [message("end_turn", [THINKING, text("We open at 9am.")])]
reply = get_reply(stub.client, "When do you open?")
assert (reply.status, reply.text, reply.requests) == ("done", "We open at 9am.", 1)
def test_stop_sequence_is_a_finished_reply(stub):
stub.replies = [message("stop_sequence", [text("Returns are free for 30 days.\n")],
stop_sequence=END_MARKER)]
reply = get_reply(stub.client, "Can I return shoes?")
assert reply.status == "done"
assert reply.detail["matched"] == END_MARKER
assert END_MARKER in stub.requests[0]["body"]["stop_sequences"]
def test_max_tokens_with_text_is_marked_truncated(stub):
stub.replies = [message("max_tokens", [THINKING, text("First, open the app and")])]
reply = get_reply(stub.client, "How do I change my address?")
assert reply.status == "truncated"
assert reply.text == "First, open the app and"
def test_max_tokens_with_only_thinking_retries_with_more_room(stub):
stub.replies = [
message("max_tokens", [THINKING]),
message("end_turn", [THINKING, text("Yes, we ship to Ghana.")]),
]
reply = get_reply(stub.client, "Do you ship to Ghana?")
assert reply.text == "Yes, we ship to Ghana."
sent = [r["body"]["max_tokens"] for r in stub.requests]
assert sent == [4000, MAX_TOKENS_CEILING]
def test_max_tokens_with_only_thinking_gives_up_at_the_ceiling(stub):
stub.replies = [message("max_tokens", [THINKING]), message("max_tokens", [THINKING])]
reply = get_reply(stub.client, "Explain everything.")
assert (reply.status, reply.text, reply.requests) == ("gave_up", "", 2)
PY
uv run pytest -qThe retry test reads the max_tokens value from each recorded request, so it proves the second call really asked for more room rather than repeating the first.
Check it worked
pytest prints 5 passed. To see a test catch a bug, change if text: to if True: in the max_tokens branch of support_reply.py and run uv run pytest -q again: the two thinking-only tests fail. Change it back.
Step 5 · Test tool calls and paused turns
Append the tool_use and pause_turn tests. The paused turn ends with a server_tool_use block, as a web search that has not finished does:
cd ~/stop-reasons-demo
cat >> test_support_reply.py <<'PY'
def test_tool_use_runs_the_tool_and_sends_the_result(stub):
stub.replies = [
message("tool_use", [THINKING, {"type": "tool_use", "id": "toolu_1",
"name": "get_order_status", "input": {"order_id": "1042"}}]),
message("end_turn", [text("Order 1042 arrives Thursday.")]),
]
reply = get_reply(stub.client, "Where is order 1042?")
assert reply.text == "Order 1042 arrives Thursday."
result = stub.requests[1]["body"]["messages"][-1]["content"][0]
assert result["tool_use_id"] == "toolu_1"
assert "dispatched" in result["content"]
def test_pause_turn_sends_the_turn_back_without_a_new_user_message(stub):
paused = [text("Let me check the courier's site."),
{"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search",
"input": {"query": "courier delays Lagos"}}]
stub.replies = [message("pause_turn", paused),
message("end_turn", [text("No delays reported today.")])]
reply = get_reply(stub.client, "Are deliveries to Lagos delayed?")
assert reply.text == "No delays reported today."
resent = stub.requests[1]["body"]["messages"]
assert [m["role"] for m in resent] == ["user", "assistant"]
assert resent[-1]["content"][-1]["type"] == "server_tool_use"
def test_pause_turn_stops_after_the_continuation_limit(stub):
stub.replies = [message("pause_turn", [text("Still searching.")]) for _ in range(6)]
reply = get_reply(stub.client, "Search everything.")
assert (reply.status, reply.requests) == ("gave_up", 6)
PY
uv run pytest -qThe pause test checks the roles of the second request: user then assistant, with no extra user message. An added "Continue." would start a new turn instead of resuming the paused one. The limit test queues six paused replies and expects the function to stop after the sixth, so a turn that never finishes costs you six requests at most.
Check it worked
pytest prints 8 passed. The tool test also confirms the tool_result carries toolu_1, the ID from the tool call it answers.
Step 6 · Test refusals, fallbacks and a full context window
Append the last four tests. One refusal carries stop_details and some partial text; the other has neither, which the API allows:
cd ~/stop-reasons-demo
cat >> test_support_reply.py <<'PY'
def test_refusal_shows_the_fallback_and_drops_partial_text(stub):
stub.replies = [message("refusal", [text("Here is how to")], stop_details={
"type": "refusal", "category": "cyber", "explanation": "Stub explanation."})]
reply = get_reply(stub.client, "Write me some malware.")
assert reply.status == "refused"
assert reply.text == REFUSAL_TEXT
assert reply.detail["category"] == "cyber"
def test_refusal_without_stop_details_is_still_handled(stub):
stub.replies = [message("refusal", [])]
reply = get_reply(stub.client, "Anything.")
assert (reply.status, reply.detail["category"]) == ("refused", None)
def test_fallbacks_send_the_beta_header_and_default_mode(stub):
stub.replies = [message("end_turn", [text("Done.")], model="claude-opus-5")]
reply = get_reply(stub.client, "Hello", use_fallbacks=True)
request = stub.requests[0]
assert request["body"]["fallbacks"] == "default"
assert "server-side-fallback-2026-07-01" in request["headers"]["anthropic-beta"]
assert reply.detail["model"] == "claude-opus-5"
def test_context_window_exceeded_is_reported(stub):
stub.replies = [message("model_context_window_exceeded", [text("Partial")])]
reply = get_reply(stub.client, "Long chat.")
assert reply.status == "context_full"
PY
uv run pytest -qAbout the fallback option: with use_fallbacks=True, the request goes through client.beta.messages.create with the beta header server-side-fallback-2026-07-01 and fallbacks="default". If Opus 5.5 declines, the API retries the same request on the fallback model Anthropic recommends for that refusal category, inside the same call. When that happens, response.model names the model that answered, which is why the function keeps it in detail. Some categories have no recommended fallback, and those still come back as refusal, so the refusal branch stays necessary. This option is a beta on the Claude API and on Claude Models on Google Cloud (Anthropic managed); check the refusals documentation before you rely on it elsewhere.
Check it worked
pytest prints 12 passed. Run uv run pytest -q -k refusal to run only the refusal tests; it reports 2 passed, 10 deselected.
Step 7 · Try it against the real API and review what comes back
Add a small script that asks one question with fallbacks on and prints the status next to the text:
cd ~/stop-reasons-demo
cat > ask.py <<'PY'
import sys
import anthropic
from support_reply import get_reply
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
reply = get_reply(client, sys.argv[1], use_fallbacks=True)
print(f"status={reply.status} stop_reason={reply.stop_reason} requests={reply.requests}")
print(f"detail={reply.detail}")
print(reply.text)
if reply.status != "done":
print("NEEDS REVIEW: do not send this reply without a person reading it.")
PY
uv run python -m py_compile ask.py && echo "ask.py compiles"Run it with your key from the private file made in /tutorials/call-an-llm-api-from-python. Each run is at least one paid call, and a tool call or a paused search adds more:
cd ~/stop-reasons-demo
uv run --env-file ~/.config/llm-demo/env ask.py "Where is order 1042?"You should see status=done, requests=2 or more (the first request calls get_order_status) and a short reply mentioning Thursday. The wording will differ from run to run.
A done status means the reply is complete, not that it is correct. Before you let replies go to customers without review, read a sample of real ones against your own order data, and send every truncated, refused, context_full and gave_up reply to a person. Log stop_reason, detail and the request ID for each one; the counts tell you whether MAX_TOKENS is too low or a system prompt change has started causing refusals.
Check it worked
The verified part prints ask.py compiles. After a live run, the first line of output starts with status= and names one of the five statuses. If it says NEEDS REVIEW, the stop_reason on the same line tells you which branch fired.
Next steps
- Decide what the customer sees for each status in /tutorials/design-error-refusal-and-fallback-states-for-ai.
- Handle the same stop reasons when replies arrive as a stream in /tutorials/stream-claude-responses-in-python.
When you are finished, remove the project with rm -rf ~/stop-reasons-demo.
Related tutorials
- How to Call a Large Language Model API from PythonYou will store an API key safely, install Anthropic's Python SDK 2.8.0, send Claude Sonnet 5.5 a first request, give it instructions and a conversation history, handle the errors an API call can raise, and work out what each call costs.
- Design error, refusal and fallback states for AI featuresYou will have a failure matrix for an AI booking assistant that covers wrong answers, refusals, outages and rate limits, with a non-AI way forward for every row and a set of state frames that keep people moving.
- Stream Claude responses token by token in PythonYou will stream Claude Sonnet 5.5 replies with Anthropic's Python SDK 2.14.0, read the raw event sequence, handle thinking, max_tokens stops and Ctrl+C, and finish with a terminal chat that prints each reply as it arrives.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials