Implement simple text streaming in Python
mainUse the client.messages.stream context manager to receive text incrementally as it is generated. Iterate over stream.text_stream to access the incoming text chunks. This is ideal for chat interfaces or terminal UIs where you want to provide immediate feedback to the user.
from anthropic import Anthropic
client = Anthropic()
with client.messages.stream(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a short release note."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)