// TypeScript SDK streaming helper: client.messages.stream() with .on('text') and finalMessage(). // STATUS: LIVE_VERIFIED 2026-09-18 with @anthropic-ai/sdk 0.126.0. // Run: node --env-file=.env --experimental-strip-types examples/anthropic/streaming/sdk_stream.ts import Anthropic from "@anthropic-ai/sdk"; import { appendFileSync } from "node:fs"; const client = new Anthropic(); const types: string[] = []; const stream = client.messages .stream({ model: "claude-haiku-4-5-20251001", max_tokens: 16, messages: [{ role: "user", content: "Reply with OK." }] }) .on("streamEvent", (ev) => types.push(ev.type)) .on("text", (t) => process.stdout.write(t)); const final = await stream.finalMessage(); console.log("\nevents:", types.join(" ")); console.log("final:", final.stop_reason, final.usage.output_tokens, "output tokens | request-id", stream.request_id); // low-memory alternative: for await (const ev of await client.messages.create({ ..., stream: true })) { ... } appendFileSync("reports/live-requests.jsonl", JSON.stringify({ ts: new Date().toISOString().replace(/\.\d+Z$/, "Z"), provider: "anthropic", method: "POST", path: "/v1/messages", status: 200, est_cost_usd: 0.00004, note: "example sdk_stream.ts" }) + "\n");