AI & prompting

How to Stream OpenAI and Claude API Responses in Python

To stream a response, set stream=True (OpenAI) or use client.messages.stream() (Anthropic), then loop over the events and print each text piece as it arrives. Both APIs send the answer as server-sent events, so the first words show up within moments instead of after the whole reply is finished.

# OpenAI Responses API
stream = client.responses.create(model="gpt-6-astra", input="Hello", stream=True)
for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)

# Anthropic Messages API
with client.messages.stream(model="claude-opus-5-5", max_tokens=1024,
                            messages=[{"role": "user", "content": "Hello"}]) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

The model IDs are the ones used in each vendor's documentation as of October 2026. Swap in the model you actually use. Both snippets assume you created a client with your key in an environment variable (OPENAI_API_KEY or ANTHROPIC_API_KEY), never hard-coded.

What streaming actually changes

Without streaming, the HTTP request stays open while the model writes the entire answer, and you get one JSON body at the end. A long answer can take tens of seconds, and the user stares at a spinner the whole time. With streaming, the server sends small pieces (deltas) as they are generated, and you show them immediately.

The total time to finish is about the same. What improves is the time until the first word appears, which is what makes chat interfaces feel responsive. You pay for the same tokens either way.

There is a second, practical reason. Anthropic's documentation says its SDK requires streaming for requests with large max_tokens values, to avoid HTTP timeouts on long generations. If you don't want to handle events, the SDK can stream internally and hand you the finished message:

with client.messages.stream(model="claude-opus-5-5", max_tokens=128000,
                            messages=[{"role": "user", "content": "Write a detailed analysis..."}]) as stream:
    message = stream.get_final_message()

The wire format: server-sent events

Both APIs use server-sent events (SSE), a simple text format defined in the WHATWG HTML Standard. The response has the content type text/event-stream, and each event is a few field: value lines followed by a blank line. The recognised fields are event, data, id and retry. A line starting with a colon is a comment and is ignored.

This is a shortened version of the raw stream shown in Anthropic's documentation (example output):

event: message_start
data: {"type": "message_start", "message": {"id": "msg_...", "role": "assistant", "content": [], "usage": {"input_tokens": 25, "output_tokens": 1}}}

event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}

event: ping
data: {"type": "ping"}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello"}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "!"}}

event: content_block_stop
data: {"type": "content_block_stop", "index": 0}

event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": null}, "usage": {"output_tokens": 15}}

event: message_stop
data: {"type": "message_stop"}

The SDKs parse this for you. You only need to know the format if you're writing your own client, debugging with curl, or forwarding events through a proxy.

Event types: OpenAI vs Anthropic

What happensOpenAI Responses APIAnthropic Messages API
Response beginsresponse.createdmessage_start (a Message with empty content)
A piece of textresponse.output_text.delta, text in event.deltacontent_block_delta with a text_delta, text in delta.text
Block boundariesresponse.output_item.added, response.output_item.donecontent_block_start, content_block_stop
Tool call argumentsresponse.function_call_arguments.deltainput_json_delta with partial_json
Response finishedresponse.completedmessage_delta (stop reason, usage), then message_stop
Keep-aliveNot listed in the guideping, any number of times
Failureerror, response.failederror event

OpenAI's guide lists response.created, response.output_text.delta, response.completed and error as the common events for text, and points to the API reference for the full set. Anthropic's flow is fixed: one message_start, then each content block as start, one or more deltas, stop, then one or more message_delta events and a final message_stop.

Streaming with OpenAI Chat Completions

If your code still uses Chat Completions rather than the Responses API, streaming returns a series of chat.completion.chunk objects. The text is in choices[0].delta.content, which can be null on some chunks, so skip empty values:

stream = client.chat.completions.create(
    model="gpt-6-astra",
    messages=[{"role": "user", "content": "Hello"}],
    stream=True,
    stream_options={"include_usage": True},
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:
        print("\n", chunk.usage)

Each chunk's finish_reason tells you why generation stopped (stop, length, tool_calls or content_filter). With include_usage set, the API reference says usage is null on every chunk except the last, which carries the totals and can have an empty choices array. That is why the loop checks chunk.choices before indexing it.

Token usage and stop reasons in a stream

A streamed response doesn't hand you a usage object up front. Where it shows up (OpenAI's Responses streaming guide doesn't cover usage, so check the API reference for the response.completed event):

  • Anthropic: message_start includes the input token count. message_delta carries stop_reason and an output token count. The documentation warns that the token counts in message_delta are cumulative, so don't add them up across events.
  • OpenAI Chat Completions: only when you set stream_options={"include_usage": True}, and only if the stream isn't interrupted.

Check the stop reason every time. A reply that ended because it hit the token limit (max_tokens on Anthropic, length on Chat Completions) looks normal in a UI but is cut off mid-sentence. See how many tokens a word is for sizing limits.

Handling errors mid-stream

A non-streaming request either succeeds or returns an HTTP error. A stream can start successfully with a 200 status and fail halfway. Anthropic's documentation gives the example of an overloaded_error sent as an event during periods of high usage, which would normally be an HTTP 529 in a non-streaming request:

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}

So your code has to cope with a partial answer. Practical rules:

  • Keep the text you've already received, and mark the message as incomplete in the UI rather than silently showing half an answer as final.
  • Retry the whole request if you need a complete answer. There is no resume-from-here in either API's streaming guide.
  • For rate-limit rejections (HTTP 429), back off before retrying; see how to handle 429 errors.
  • Tool calls stream as partial JSON strings. Accumulate them and parse once the block is finished, not on every delta. More on that in function calling explained.

OpenAI's streaming guide adds a moderation point: partial completions are harder to evaluate, and moderation results arrive only after the full output exists. If you filter output, you either filter the finished text after displaying it, or buffer before showing it, which gives up some of the benefit of streaming.

Sending the stream on to a browser

Keep the API key on your server. Your server calls the LLM API with streaming on, then forwards the text pieces to the browser over its own response, as SSE, a chunked HTTP response or a WebSocket.

The browser's built-in EventSource is the obvious receiver, with one limit. Its constructor in the HTML Standard takes only a URL and a withCredentials flag, so it can't send a request body or custom headers. For a chat app that needs to POST the conversation, most front ends use fetch() and read the response body as a stream instead. MDN also notes that over HTTP/1.1, browsers allow only 6 SSE connections per domain across all tabs; over HTTP/2 the limit is negotiated and defaults to 100 streams. If you're weighing SSE against a two-way socket, see WebSocket vs HTTP.

If streaming doesn't seem to stream

If text still arrives in one lump, something between the API and the screen is buffering. Check, in order: that you print with flush=True (Python buffers stdout); that your web framework returns a streaming response rather than collecting the generator into a string; and that a reverse proxy in front of your app isn't buffering responses. Test from the server itself with curl -N, which turns off curl's output buffering, to see which layer holds the data back.

Frequently asked questions

Does streaming make an LLM response faster?
It does not make the model generate the whole answer faster. It makes the first words appear sooner, because you display each piece as it is generated instead of waiting for the complete response. Total generation time is about the same.
Does streaming cost more tokens?
No. You are billed for the same input and output tokens whether you stream or not. Streaming only changes how the response is delivered over the connection.
How do I get token usage when streaming?
With Anthropic, the message_start event carries input token counts and the message_delta event near the end carries cumulative output tokens. With OpenAI Chat Completions, set stream_options to include_usage and the last chunk carries the usage totals with an empty choices array. If the stream is interrupted, that final usage chunk may never arrive.
Can I call the LLM API directly from the browser with EventSource?
Not sensibly. EventSource only takes a URL and a withCredentials flag, so it cannot send a request body or an API key header, and an API key in browser code is visible to anyone. Call the API from your server and forward the text to the browser.

Sources