Streaming
Generating a long answer can take many seconds. Without streaming, the user stares at a spinner until the very last token is ready. With streaming, the API sends tokens as soon as they are generated, so text appears almost immediately and grows word by word — the "typing" effect you know from chat apps. The total time is about the same; the perceived wait is much shorter.
Streaming with the SDK
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-sonnet-5-5",
max_tokens=500,
messages=[{"role": "user", "content": "Write a haiku about rain."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True) # show each chunk as it arrives
final = stream.get_final_message() # full message incl. usage, when done(Reference code — not runnable here.) The loop receives small text fragments — often a word or part of a word — and prints them immediately. When the stream ends you can still get the complete message with its usage and stop_reason.
What travels over the wire: server-sent events
Under the hood, streaming APIs typically use server-sent events (SSE): a long HTTP response made of small text events, each with an event: line and a data: line of JSON. The sample below is hand-written to show the structure of an Anthropic stream (fields shortened); the parser is real:
import json
sample_stream = """event: message_start
data: {"type": "message_start", "message": {"usage": {"input_tokens": 14}}}
event: content_block_delta
data: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Soft"}}
event: content_block_delta
data: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": " rain on"}}
event: content_block_delta
data: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": " the roof"}}
event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 5}}
event: message_stop
data: {"type": "message_stop"}
"""
def parse_sse(raw):
for block in raw.strip().split("\n\n"):
fields = dict(line.split(": ", 1) for line in block.splitlines())
yield fields["event"], json.loads(fields["data"])
text = ""
for event, data in parse_sse(sample_stream):
if event == "content_block_delta":
text += data["delta"]["text"]
print(f"chunk {data['delta']['text']!r:12} -> so far: {text!r}")
elif event == "message_delta":
print("stop reason:", data["delta"]["stop_reason"])
print("final text:", text)chunk 'Soft' -> so far: 'Soft'
chunk ' rain on' -> so far: 'Soft rain on'
chunk ' the roof' -> so far: 'Soft rain on the roof'
stop reason: end_turn
final text: Soft rain on the roof
Simulating a stream with a generator
In Python, a stream is naturally modelled as a generator that yields chunks. Your UI code consumes it the same way whether the chunks come from a network or, as here, from a fake model:
def fake_stream(text, chunk_size=6):
for i in range(0, len(text), chunk_size):
yield text[i:i + chunk_size]
received = []
for chunk in fake_stream("Streaming makes long answers feel fast."):
received.append(chunk)
print(f"[{len(received):2}] {chunk!r}")
print("assembled:", "".join(received))[ 1] 'Stream'
[ 2] 'ing ma'
[ 3] 'kes lo'
[ 4] 'ng ans'
[ 5] 'wers f'
[ 6] 'eel fa'
[ 7] 'st.'
assembled: Streaming makes long answers feel fast.
Perceived latency
Two numbers describe how fast a response feels:
- Time to first token (TTFT) — how long until the first chunk arrives (prompt processing + network).
- Output speed — tokens per second once generation runs.
def timeline(ttft_s, tokens, tokens_per_s):
total = ttft_s + tokens / tokens_per_s
return total
# Illustrative numbers, not measurements of any real model
ttft, n_tokens, speed = 0.6, 400, 50
total = timeline(ttft, n_tokens, speed)
print(f"without streaming: user sees text after {total:.1f} s")
print(f"with streaming: user sees text after {ttft:.1f} s, finished after {total:.1f} s")without streaming: user sees text after 8.6 s
with streaming: user sees text after 0.6 s, finished after 8.6 s
Things to handle when streaming
| Issue | Approach |
|---|---|
| Partial words or markdown | render progressively; fix formatting when the stream ends |
| Errors mid-stream | show what arrived, mark it as incomplete, offer retry |
| User presses "stop" | close the connection; you usually pay only for tokens generated so far |
| Structured output (JSON) | wait for the end before parsing, or use an incremental parser |
| Safety checks / moderation | decide whether to check chunks as they arrive or the final text |
| Tool calls | tool arguments also arrive in pieces; act only when the block is complete |
Tip: Stream whenever a person is waiting for the answer. For background jobs (classification, batch extraction) plain requests are simpler.
Test yourself
What does streaming mainly improve?
- The total tokens generated
- The perceived latency — text appears as soon as the first tokens are ready
- The accuracy of the answer
- The price per token
Which web technology do streaming LLM APIs commonly use?
- FTP
- Server-sent events (SSE)
- WebRTC video
You stream a response that must be valid JSON. When is it safe to parse it with json.loads?
- After the first chunk
- After every chunk
- When the stream has finished (or with an incremental parser)
- Never