AI and machine learning · Intermediate · 16 min
Stream Claude responses token by token in Python
By Padding · Updated 18 Nov 2026
Python 3.15 · anthropic SDK 2.14.0 · Claude Sonnet 5.5
You 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.
On this page
A call to messages.create waits until Claude has written the whole reply, then returns it in one piece. For a two-line answer that is fine. For a long answer the person waiting sees nothing for many seconds, and a reply that takes minutes can outlast an HTTP timeout somewhere between you and the API. Streaming fixes both. The API sends the reply as a series of server-sent events (SSE) while the model writes it, so the first words reach you within a second or two and the connection stays busy the whole time.
Two numbers describe the difference. Time to first token is how long until the first text arrives. Total time is how long the whole reply takes. Streaming barely changes the total, but it cuts the time to first token from "the whole reply" to "the first few words". On a slow or prepaid mobile connection, common in many African markets, that early feedback matters even more, and a reader who stops a stream they do not need also stops downloading the rest of it.
You will write six short scripts in ~/stream-demo: one that streams text, one that prints the raw events, one that reads the finished message, one that shows thinking, one that handles a reply cut off by max_tokens, and one that you stop with Ctrl+C. The last step puts it together as a terminal chat. The model is claude-sonnet-5-5.
Step 1 · Create the project and load your key
Load the key you saved in the earlier tutorial into this terminal. set -a exports every variable the file defines, so the SDK can read ANTHROPIC_API_KEY:
set -a
. ~/.config/llm-demo/env
set +aCreate the project and add the SDK at the exact version this tutorial uses:
mkdir -p ~/stream-demo
cd ~/stream-demo
uv init --no-package
uv add "anthropic==2.14.0"Check it worked
uv run python -c "import anthropic; print(anthropic.__version__)"The command prints 2.14.0. If it fails with an import error, check that you are inside ~/stream-demo.
Step 2 · Stream the text as it arrives
client.messages.stream() takes the same arguments as messages.create() and returns a context manager. Inside the with block, stream.text_stream yields each new piece of text as soon as it arrives. Create stream_text.py, which also times the first piece and the whole reply:
cat > stream_text.py <<'PY'
import time
import anthropic
client = anthropic.Anthropic()
start = time.perf_counter()
first = None
with client.messages.stream(
model="claude-sonnet-5-5",
max_tokens=16000,
messages=[{"role": "user", "content": "In three sentences, explain why chat apps stream their answers."}],
) as stream:
for text in stream.text_stream:
if first is None:
first = time.perf_counter() - start
print(text, end="", flush=True)
total = time.perf_counter() - start
print()
if first is None:
print("(no text in the reply)")
else:
print(f"first text after {first:.2f} s, whole reply after {total:.2f} s")
PY
uv run stream_text.pyflush=True matters. Without it Python holds printed text in a buffer, and the reply appears in bursts instead of word by word. The with block also matters: when it ends, normally or because of an error, the SDK closes the HTTP connection.
max_tokens=16000 is a ceiling, not a target. With streaming you can set it high without the risk of a long request hitting a timeout. Anthropic's SDK refuses a non-streaming request that it expects to run longer than its 10 minute default timeout, and tells you to stream instead.
Check it worked
The answer appears a few words at a time, then a line such as first text after 1.40 s, whole reply after 4.90 s. Your numbers differ. The first number should be a small part of the second. If you see (no text in the reply), the step on max_tokens explains why.
Step 3 · Look at the raw events
Under text_stream sits a fixed sequence of events. Seeing it once makes the rest of this tutorial, and any streaming bug you meet later, easier to follow. Passing stream=True to messages.create() gives you the events one by one, with no helper on top. Create events.py, which prints each event type and folds runs of the same type into one line:
cat > events.py <<'PY'
from itertools import groupby
import anthropic
client = anthropic.Anthropic()
types = []
for event in client.messages.create(
model="claude-sonnet-5-5",
max_tokens=16000,
messages=[{"role": "user", "content": "Say what an HTTP 404 status means, in one sentence."}],
stream=True,
):
types.append(event.type)
if event.type == "content_block_start":
types[-1] += f" ({event.content_block.type})"
elif event.type == "message_delta":
print("stop reason:", event.delta.stop_reason, "| output tokens so far:", event.usage.output_tokens)
for name, run in groupby(types):
count = len(list(run))
print(name if count == 1 else f"{name} x{count}")
PY
uv run events.pyRead the output from the top:
message_startcarries a message with an emptycontentlist, the model name and the input token count.- Each content block, such as a thinking block or a text block, opens with
content_block_start, grows throughcontent_block_deltaevents and closes withcontent_block_stop. Each block has anindexthat matches its place in the finalcontentlist. message_deltacarries thestop_reasonand theusage. Its token counts are cumulative, so the last one is the total.message_stopends the stream.
The API may also send ping events at any point. The Python SDK drops them, so you never see them. If the API sends an error event mid-stream, for example overloaded_error when it is busy, the SDK raises it as an exception from the loop. New event types can be added over time, so code that reads raw events should ignore types it does not know rather than fail.
Check it worked
The output starts with stop reason: end_turn, then a list like this one, with different counts:
message_start
content_block_start (thinking)
content_block_delta x2
content_block_stop
content_block_start (text)
content_block_delta x14
content_block_stop
message_delta
message_stopA reply may have no thinking block at all, because Claude Sonnet 5.5 decides on each request whether to think first. In that case the list starts straight at content_block_start (text).
Step 4 · Get the finished message
Printing text is half the job. Your program usually also needs the stop reason, the token usage and the full list of content blocks, for example to save the reply in a conversation history. stream.get_final_message() gives you the same Message object that messages.create() returns, built from the events the stream received. Create final.py:
cat > final.py <<'PY'
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-sonnet-5-5",
max_tokens=16000,
messages=[{"role": "user", "content": "Give one reason to stream long answers."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
message = stream.get_final_message()
print()
print("blocks:", [block.type for block in message.content])
print("stop reason:", message.stop_reason)
print("tokens in/out:", message.usage.input_tokens, message.usage.output_tokens)
PY
uv run final.pyCall get_final_message() inside the with block. If you only need the finished message and not the live text, you can call it without the loop: it reads the rest of the stream for you. That pattern is a good default for any request with a large max_tokens, because it gives you a normal Message without the timeout risk of a long non-streaming request.
Check it worked
After the streamed text you see three lines such as:
blocks: ['thinking', 'text']
stop reason: end_turn
tokens in/out: 18 160The block list may be only ['text'] when the model did not think. output_tokens includes any thinking, so it can be much larger than the visible answer.
Step 5 · Show or hide thinking
Claude Sonnet 5.5 uses adaptive thinking by default: on each request it decides whether to reason before it answers. By default the API does not show that reasoning. The thinking block still opens and closes in the stream, but its text arrives as an empty string. If your interface streams to a person, that looks like a pause before the answer starts.
To get a readable summary of the reasoning, set display to "summarized" in the thinking setting. Create thinking.py, which turns that on when you pass summarized on the command line:
cat > thinking.py <<'PY'
import sys
import anthropic
client = anthropic.Anthropic()
extra = {}
if sys.argv[1:] == ["summarized"]:
extra["thinking"] = {"type": "adaptive", "display": "summarized"}
thinking_chars = 0
with client.messages.stream(
model="claude-sonnet-5-5",
max_tokens=16000,
messages=[{"role": "user", "content": "Is 391 a prime number? Answer in one sentence."}],
**extra,
) as stream:
for event in stream:
if event.type == "content_block_start":
print(f"\n[{event.content_block.type}]")
elif event.type == "content_block_delta":
if event.delta.type == "thinking_delta":
thinking_chars += len(event.delta.thinking)
print(event.delta.thinking, end="", flush=True)
elif event.delta.type == "text_delta":
print(event.delta.text, end="", flush=True)
print(f"\nthinking characters shown: {thinking_chars}")
PY
uv run thinking.py
uv run thinking.py summarizedIterating over the stream object itself, instead of text_stream, gives you every event, so you can label each block and print thinking and text differently. A chat interface would show the thinking summary in a smaller, collapsible area.
The display setting changes only what you see. The model thinks, and you pay for the thinking tokens, the same way under every setting. Keep thinking blocks in your conversation history as they came back, even when they are empty: the API uses them, and the signature they carry, on later turns.
Check it worked
The first run prints [thinking], then [text] and the answer, and ends with thinking characters shown: 0. The second run prints a short summary of the reasoning under [thinking] and a number above 0. When the model decides not to think, neither run has a [thinking] line. Ask a harder question to see one.
Step 6 · Handle a reply cut off by max_tokens
A stream ends normally even when max_tokens cuts the reply short. Nothing raises an error, so your code has to look at the stop reason. Thinking counts toward max_tokens too, so a low ceiling can be used up before any text appears, and the stream ends with a thinking block and no text at all. Create limits.py, which sets a ceiling far too low on purpose:
cat > limits.py <<'PY'
import anthropic
client = anthropic.Anthropic()
parts = []
with client.messages.stream(
model="claude-sonnet-5-5",
max_tokens=50,
messages=[{"role": "user", "content": "Explain how DNS resolution works, step by step."}],
) as stream:
for text in stream.text_stream:
parts.append(text)
print(text, end="", flush=True)
message = stream.get_final_message()
print()
if message.stop_reason == "max_tokens":
if not parts:
print("cut off before any text: thinking used the whole max_tokens; raise it")
else:
print("cut off part way: the text above is incomplete; raise max_tokens or ask for less")
else:
print("complete, stop reason:", message.stop_reason)
PY
uv run limits.pyTreat a cut-off reply as incomplete. Do not store it as if it were a full answer, and do not parse it as JSON or code. Raise max_tokens, ask for a shorter answer, or tell the person that the answer was cut short.
Check it worked
The output is one of the two cut off lines. With a ceiling of 50 tokens it is often cut off before any text, because thinking takes the whole allowance. Change max_tokens=50 to max_tokens=16000 and run it again: the last line becomes complete, stop reason: end_turn.
Step 7 · Stop a stream cleanly with Ctrl+C
Pressing Ctrl+C in a terminal raises KeyboardInterrupt inside your Python program, wherever it is at that moment. When that happens inside the with block, the block exits and the SDK closes the HTTP connection, so no more text arrives. Catch the exception outside the block to finish tidily. Create cancel.py, which asks for a long answer:
cat > cancel.py <<'PY'
import anthropic
client = anthropic.Anthropic()
received = []
try:
with client.messages.stream(
model="claude-sonnet-5-5",
max_tokens=16000,
messages=[{"role": "user", "content": "Write the numbers from one to forty in words, slowly, one per line."}],
) as stream:
for text in stream.text_stream:
received.append(text)
print(text, end="", flush=True)
except KeyboardInterrupt:
print(f"\n[stopped by you after {len(''.join(received))} characters]")
else:
print("\n[reply finished]")
PYRun it and press Ctrl+C after a few lines appear:
uv run cancel.pyThere is no get_final_message() after a cancel, because the message never finished. If you need what arrived, keep it yourself, as received does here. Do not add a cancelled reply to a conversation history as if it were complete.
Check it worked
The numbers stop within a moment of Ctrl+C, the script prints a line such as [stopped by you after 212 characters] and you get your prompt back with no traceback. If you let it run to the end, it prints [reply finished] instead.
Step 8 · Build a terminal chat that streams
Now combine the pieces. The chat keeps a history, streams each reply, stores the full content blocks of finished replies (thinking blocks included), and treats Ctrl+C during a reply as "stop this answer", not "quit". Ctrl+C or Ctrl+D at the prompt quits. Create chat.py:
cat > chat.py <<'PY'
import anthropic
client = anthropic.Anthropic()
SYSTEM = "You are a concise assistant in a terminal. Answer in a few short sentences."
history = []
def stream_reply():
with client.messages.stream(
model="claude-sonnet-5-5",
max_tokens=16000,
system=SYSTEM,
messages=history,
) as stream:
print("claude> ", end="", flush=True)
for text in stream.text_stream:
print(text, end="", flush=True)
print()
return stream.get_final_message()
print("Type a question. Ctrl+C stops a reply; Ctrl+D or Ctrl+C at the prompt quits.")
while True:
try:
question = input("\nyou> ").strip()
except (EOFError, KeyboardInterrupt):
print("\nbye")
break
if not question:
continue
history.append({"role": "user", "content": question})
try:
message = stream_reply()
except KeyboardInterrupt:
history.pop()
print("\n[reply stopped; it is not kept in the history]")
continue
except anthropic.APIError as err:
history.pop()
print(f"\n[request failed: {err}]")
continue
if message.stop_reason == "max_tokens":
history.pop()
print("[reply cut off by max_tokens; it is not kept in the history]")
continue
history.append({"role": "assistant", "content": message.content})
print(f"[{message.usage.output_tokens} output tokens, {len(history)} messages in the history]")
PYStart it and ask a couple of questions. The second can refer to the first, because the whole history goes with every request:
uv run chat.pyhistory.pop() removes the question when a reply is stopped, fails or is cut off, so the history never holds two user turns in a row or a half-finished answer. message.content goes into the history whole, rather than just its text, so any thinking blocks travel back to the API unchanged. Each turn resends the whole history, so input tokens and cost grow with the length of the chat.
Check it worked
Each reply starts printing within a second or two after claude>, followed by a line such as [180 output tokens, 4 messages in the history] after your second question. Press Ctrl+C during a long reply: you see [reply stopped; it is not kept in the history] and a fresh you> prompt. Press Ctrl+D at the prompt and the chat prints bye and exits.
Step 9 · Clean up
Delete the demo project. The key file stays for the other LLM tutorials:
cd ~
rm -rf ~/stream-demoCheck it worked
test ! -e ~/stream-demo && echo "demo removed"The output is demo removed.
Next steps
- Send the stream on to a web page: stream LLM answers to a web page through FastAPI.
- Design what the person sees while they wait: design for streaming AI answers and long waits.
- Go back over keys, errors and cost: call a large language model API from Python.
Related tutorials
- Write a system prompt that sets the role, the rules and the output formatYou will turn a one-line prompt into a structured system prompt for a solar installer's support assistant, keep it in a template file that Python renders, and prove with deterministic tests that it is built correctly, stays cacheable and has a format your code can parse.
- Tune model settings with grid search and random searchYou will tune a gradient-boosting churn model with GridSearchCV, RandomizedSearchCV and HalvingRandomSearchCV, compare what each costs and finds, read cv_results_ to see how flat the top is, and report an honest score with nested cross-validation and an untouched test set.
- Train a small convolutional network to read handwritten digitsYou will train a two-layer convolutional network in PyTorch on scikit-learn's bundled 8x8 digits, compare it with logistic regression, read its confusion matrix and mistakes, and make it robust to shifted digits with data augmentation.
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