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

Why Long Claude API Requests Need Streaming, Not Just for the Typing Effect

A non-streaming call sends nothing until the whole answer is done. For long outputs that silence is what fails, and the SDK can stream for you without any UI.

ReadIn

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

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

Your nightly job asks Claude Opus 5.5 to turn each merged pull request into a migration report. Long reports kept stopping halfway with 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

"Streaming is only a UX nicety, and a non-streaming call works the same for any request size." It's easy to believe:

  • 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 Message object, 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.

The half-truth: for a short request, the difference really is mostly about how the text appears. But the two calls use the connection differently, and that difference grows with the length of the response.

What actually happens

A non-streaming call is one long silence

With 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."

The Python SDK protects you in three ways. Requests time out after 10 minutes by default. It raises a 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

With 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

This is what makes the switch cheap. If you don't care about the text as it arrives, the SDK reads the stream for you: 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

A stream starts with HTTP 200, so a problem that happens later can't change the status code. It comes as an 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

The first version hides the SDK's warning with a bigger timeout. The second streams and still gets one Message:

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

The text is taken from the first 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

A stream can still be cut off by the network. For Claude 4.6 and later models, the docs' recovery is to keep what you received, then send a new request with a user message that contains the partial response and asks Claude to continue where it left off. Putting the partial text in an assistant turn, the older approach, is a prefill, and Claude 4.6 and later models reject it with a 400. Only text resumes this way: "Tool use and thinking blocks cannot be partially recovered."

Non-streaming create()Streaming stream()Message Batches
During generationNothing travelsEvents and pingsNo open connection: you poll
Largest max_tokensSDK refuses above 21,333128K on Claude Opus 5.5300K on Opus 5.5, with a beta header
How errors arriveAs the HTTP statusAlso as an error event after the 200Per request, in the results
Getting a MessageReturned directlyget_final_message()Read from the results
FitsShort answersLong outputs, users waitingBulk work nobody waits on

How to apply it in your project

  1. Find the silent callsSearch for messages.create calls with a large max_tokens, and for timeout= overrides added only to silence the SDK's ValueError.
  2. Stream them, even without a UIReplace create() with messages.stream() and get_final_message(). The code that reads the response stays as it is.
  3. Keep reading the stop reasonA stream that finished cleanly can still end with max_tokens. Check stop_reason before you save the result.
  4. Plan for a broken streamSave 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.
  5. Move unattended work to BatchesIf 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 ValueError when 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() with get_final_message() gives you the same Message with no UI and no event handling.
  • In a stream, errors can arrive after the 200 as error events.
  • To resume a broken stream on Claude 4.6 and later, send the partial text in a user message, not as a prefill.

📚 المصادر

  1. Streaming Messages — Claude API Docs
  2. Claude API errors: Long requests — Claude API Docs
  3. Python SDK: Timeouts and long requests — Claude API Docs
  4. Building with thinking: Output limits and long requests — Claude API Docs

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