Reference · API
Anthropic streaming messages
Last updated
Stream Claude replies **token-by-token** for faster perceived latency in chat UIs.
Stream Claude replies **token-by-token** for faster perceived latency in chat UIs.
#When to use
Use non-streaming when you need the full response atomically for parsing or tool routing.
#Endpoint
POST https://api.anthropic.com/v1/messagesSet `"stream": true` in the JSON body (or use SDK stream helpers).
#Request shape (sketch)
{
"model": "claude-sonnet-4-20250514",
"max_tokens": 1024,
"stream": true,
"messages": [{"role": "user", "content": "Explain RAG briefly."}]
}#Python sketch
with client.messages.stream(
model="claude-sonnet-4-20250514",
max_tokens=512,
messages=[{"role": "user", "content": "Hello"}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)#Event types
Stream emits `message_start`, `content_block_delta`, `message_delta`, `message_stop` — handle partial JSON if you parse tool use mid-stream.
#Common pitfalls
| Pitfall | Fix |
|---------|-----|
| Dropping partial tokens on error | Flush buffers; show retry UI |
| Parsing tools before stream ends | Wait for `message_stop` or use SDK helpers |
| Missing `max_tokens` | Required on every Anthropic request |
| Streaming from browser with raw key | Proxy through your server |