#!/usr/bin/env python3 """Python SDK streaming helper: client.messages.stream() → text_stream, raw events, get_final_message(). STATUS: LIVE_VERIFIED 2026-09-18 with anthropic 1.7.0. Run: .venv/bin/python examples/anthropic/streaming/sdk_stream.py """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[3])) from scripts import live # noqa: E402 from anthropic import Anthropic # noqa: E402 client = Anthropic() events = [] with client.messages.stream(model="claude-haiku-4-5-20251001", max_tokens=16, messages=[{"role": "user", "content": "Reply with OK."}]) as stream: for event in stream: # raw API events + SDK synthetic events (text, message_stop …) events.append(event.type) if event.type == "text": # SDK convenience event carrying the delta text print(event.text, end="", flush=True) final = stream.get_final_message() # accumulated Message, identical to a non-streaming response print() print("events:", " ".join(events)) print("final:", final.stop_reason, final.usage.output_tokens, "output tokens | request-id", stream.request_id) # low-memory alternative: for ev in client.messages.create(..., stream=True): ... live.log_request("anthropic", "POST", "/v1/messages", 200, 0.00004, "example sdk_stream.py")