SPB Git forge

spb/doc-api

Public
2commits 1branches 0releases
15.7 MBsize
maindefault branch
14 days agolast push
Python 88.3% TypeScript 7.6% Shell 4.1%
1.3 KB · 26 lines python
Raw Blame History
1#!/usr/bin/env python32"""Python SDK streaming helper: client.messages.stream() → text_stream, raw events, get_final_message().34STATUS: LIVE_VERIFIED 2026-09-18 with anthropic 1.7.0. Run: .venv/bin/python examples/anthropic/streaming/sdk_stream.py5"""6import sys7from pathlib import Path89sys.path.insert(0, str(Path(__file__).resolve().parents[3]))10from scripts import live  # noqa: E40211from anthropic import Anthropic  # noqa: E4021213client = Anthropic()14events = []15with client.messages.stream(model="claude-haiku-4-5-20251001", max_tokens=16, messages=[{"role": "user", "content": "Reply with OK."}]) as stream:16    for event in stream:            # raw API events + SDK synthetic events (text, message_stop …)17        events.append(event.type)18        if event.type == "text":    # SDK convenience event carrying the delta text19            print(event.text, end="", flush=True)20    final = stream.get_final_message()  # accumulated Message, identical to a non-streaming response21print()22print("events:", " ".join(events))23print("final:", final.stop_reason, final.usage.output_tokens, "output tokens | request-id", stream.request_id)24# low-memory alternative: for ev in client.messages.create(..., stream=True): ...25live.log_request("anthropic", "POST", "/v1/messages", 200, 0.00004, "example sdk_stream.py")26