Streaming Claude Responses
Streaming lets the interface render text before the whole response is complete. It does not make an unfinished answer valid or guarantee a lower total completion time.
#Python example
Requires the anthropic package, ANTHROPIC_API_KEY and an available ANTHROPIC_MODEL. Running it sends a billable provider request.
pythonimport os from anthropic import Anthropic client = Anthropic() with client.messages.stream( model=os.environ["ANTHROPIC_MODEL"], max_tokens=512, messages=[{"role": "user", "content": "Explain a Python generator."}], ) as stream: for text in stream.text_stream: print(text, end="", flush=True) final = stream.get_final_message() print() print(final.stop_reason, final.usage)
The final message is the completed structured response. Keep it for conversation history rather than constructing an assistant message from whichever text happened to reach the screen.
#Understand the event lifecycle
Raw streams include message start, content block start/delta/stop, message delta and message stop events. A response can contain several content blocks. Tool arguments can arrive as partial JSON; never execute a tool while its arguments are still incomplete.
If you use the TypeScript SDK or raw SSE, follow that SDK's documented event types. Network chunks are not necessarily whole events, UTF-8 characters or complete JSON objects.
#Connect a web interface
Proxy the provider stream through your own server so the key stays private. Render an explicit generating state, support cancellation, and distinguish completed, interrupted and failed output. A disconnected client should not silently leave expensive work running indefinitely.
Track time to first token separately from completion time. On failure, do not append a second response to partial text and call the combined result successful. Preserve a request identifier for diagnosis and offer a deliberate retry.