Render increments and finalize separately
Streaming lets an application show text as it becomes available. The response also carries events for message boundaries and other content types. Update the display with text increments and mark it complete only after the SDK produces a complete message and you inspect its stop reason.
Stream one short answer
Install the official Python SDK and supply a development API credential through your approved secret manager. Save this as stream_example.py and run it with Python. The sample prints incremental text as it arrives, followed by a stop reason. Expect it to state that Maya owns the checklist and that the due day is Friday.
import os
import anthropic
if not os.environ.get("ANTHROPIC_API_KEY"):
raise SystemExit("Supply ANTHROPIC_API_KEY through your secret manager.")
client = anthropic.Anthropic(timeout=30.0, max_retries=0)
try:
with client.messages.stream(
model=os.environ.get("CLAUDE_MODEL", "claude-sonnet-5-5"),
max_tokens=256,
messages=[{
"role": "user",
"content": "Summarize in one sentence: Maya will send the checklist on Friday.",
}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final_message = stream.get_final_message()
except KeyboardInterrupt:
raise SystemExit("\nStream canceled. Any text shown is partial.") from None
except (anthropic.APIError, RuntimeError) as exc:
raise SystemExit(f"\nStream failed ({type(exc).__name__}). Any text shown is partial.") from None
print("\n[stop:", final_message.stop_reason, "]")
if final_message.stop_reason == "max_tokens":
print("The reply reached its output limit.")Give users meaningful states
Treat arriving text, a complete reply, and partial text as distinct states even when the same message bubble displays them.
- While text arrives, show that the request is in progress and let the reader cancel if appropriate.
- If the request ends at its token limit, mark it as truncated.
- If the connection drops after text starts, retain or discard the partial text according to your product’s policy and label the result accordingly.
- When retrying, create a fresh output buffer. This prevents a second attempt from continuing visually from the stale partial text.
Check completion with two cases
On a normal run, verify the final stop reason appears after the text. Then try canceling a longer, low-risk development request and confirm the incomplete state appears. Use a mocked stream in automated tests to make both results repeatable.