
Why Long Claude API Requests Need Streaming, Not Just for the Typing Effect
- كاتب موثّق
- Claude API
محتويات المقال
stop_reason: "max_tokens", so someone raised max_tokens from 16000 to 64000. The next run failed before sending a single request: the Python SDK raised a ValueError, refusing a non-streaming request that large. The quick fix, timeout=1800, made the error disappear. Now some nights a report takes an hour, some nights it fails with no response from Anthropic at all, and nobody can reproduce it on a laptop.
The common misconception
Every streaming demo is a chat box with text appearing word by word, so streaming looks like a front-end feature. Both calls end with the same Messageobject, so the difference seems to be only when you see the text.In development, prompts are short and answers come back in seconds, so a connection is never idle for long. Handling events looks like extra work for a background job that nobody watches.
What actually happens
A non-streaming call is one long silence
messages.create(), the API sends the response when the last token is generated. Until then the HTTP connection carries nothing. A long output takes time to generate: Claude Opus 5.5 accepts max_tokens up to 128K, and its adaptive thinking is always on, so it can also spend part of that time reasoning before the first word. The docs list what silence does on real networks: "Some networks might drop idle connections after a variable period of time, which can cause the request to fail or time out without receiving a response from Anthropic."
ValueError "if a non-streaming request is expected to take longer than approximately 10 minutes"; the thinking docs put that line at a max_tokens above 21,333 and call it "a client-side validation, not an API restriction". And when a request outlives its timeout, the client ends the connection and retries "without receiving a response". That retry is a new request, so the generation starts again from the beginning.
Streaming keeps the connection busy
stream=True, or the SDK's messages.stream(), the API starts answering right away with . A stream is a fixed sequence: message_start, then for each content block a content_block_start, its deltas and a content_block_stop, then message_delta and a final message_stop, with ping events possibly in between. In the docs' words, the .stream() call "keeps the HTTP connection alive with server-sent events". The SDK also sets TCP keep-alive on its sockets, and the errors page recommends streaming or the Message Batches API "for long-running requests, especially those over 10 minutes".
You don't need a UI to stream
stream.get_final_message() returns "the complete Message object, identical to what client.messages.create() returns". The docs call this "especially useful for requests with large max_tokens values". Your code after the call stays the same: read the , then the content blocks.
Errors can arrive after the 200
error event inside the stream; the docs' example is an overloaded_error, "which would normally correspond to an HTTP 529 in a non-streaming context". If you parse events yourself, two more details matter: the usage counts in message_delta are cumulative, so don't add them up, and new event types may appear, so ignore the ones you don't know.
Fixing the report job
Message:
import anthropicclient = anthropic.Anthropic()def write_report(diff: str) -> str: # The SDK raised ValueError at 64000 tokens, so: "give it 30 minutes" reply = client.with_options(timeout=1800).messages.create( model="claude-opus-5-5", max_tokens=64000, messages=[{"role": "user", "content": f"Report for:\n{diff}"}], ) # nothing arrives on this connection until the last token return next(b.text for b in reply.content if b.type == "text")print(write_report(DIFF)[:40])import anthropicclient = anthropic.Anthropic()def write_report(diff: str) -> str: with client.messages.stream( model="claude-opus-5-5", max_tokens=64000, messages=[{"role": "user", "content": f"Report for:\n{diff}"}], ) as stream: # events keep the connection busy message = stream.get_final_message() # same Message as create() if message.stop_reason == "max_tokens": raise ReportTruncated(message.usage.output_tokens) return next(b.text for b in message.content if b.type == "text")print(write_report(DIFF)[:40])text block, not content[0]: with thinking on, a thinking block can come first, and on Claude Opus 5.5 its text is empty by default.
When a stream breaks halfway
create() | stream() | ||
|---|---|---|---|
max_tokens | |||
error event after the 200 | |||
Message | get_final_message() | ||
How to apply it in your project
Find the silent calls Search for messages.createcalls with a largemax_tokens, and fortimeout=overrides added only to silence the SDK'sValueError.Stream them, even without a UI Replace create()withmessages.stream()andget_final_message(). The code that reads the response stays as it is.Keep reading the stop reason A stream that finished cleanly can still end with max_tokens. Checkstop_reasonbefore you save the result.Plan for a broken stream Save the text you received. On Claude 4.6 and later, continue with a user message that includes it, not an assistant prefill, and redo tool calls and thinking from scratch. Move unattended work to Batches If nobody reads the output right away, send it through the Message Batches API and poll for results.
Key takeaways
A non-streaming call keeps the connection idle until the last token, and idle connections get dropped. The Python SDK raises a ValueErrorwhen a non-streaming request is expected to pass about 10 minutes; treat it as advice, not an obstacle to bypass with a bigger timeout.messages.stream()withget_final_message()gives you the sameMessagewith no UI and no event handling.In a stream, errors can arrive after the 200 as errorevents.To resume a broken stream on Claude 4.6 and later, send the partial text in a user message, not as a prefill.
التعليقات (0)