AI Agents & LLMsMedium
Why stream LLM responses, and how do you do it?
Learning path, stage 2 of 5: Prompting and model features · question 10 of 10Streaming sends tokens to the client as they are generated, usually over Server-Sent Events, instead of waiting for the whole response. Users see text within a second (low time-to-first-token) even when the full answer takes much longer, and long requests avoid HTTP timeouts.
When to stream
- Any chat or UI where a person is waiting.
- Long outputs or high
max_tokens, where a single non-streaming request may hit timeouts. - Agents, so you can show progress and tool calls as they happen.
Things to handle
- Partial state: collect deltas into a buffer. Tool-call arguments arrive as partial JSON and must be parsed once complete.
- Errors mid-stream: a stream can fail after sending some tokens. Decide whether to retry or show what you have.
- Cancellation: abort when the user navigates away, to stop paying for tokens nobody reads.
- Backpressure in your server: pipe the stream through (for example a
ReadableStreamin a Next.js route handler). Don't buffer it.
Sources
Code example
tsx
1// Next.js route handler that streams Claude's text to the browser.2import Anthropic from "@anthropic-ai/sdk";34const client = new Anthropic();56export async function POST(req: Request) {7 const { prompt } = await req.json();89 const stream = client.messages.stream({10 model: "claude-opus-5-5",11 max_tokens: 8000,12 messages: [{ role: "user", content: prompt }],13 });1415 const body = new ReadableStream({16 start(controller) {17 const enc = new TextEncoder();18 stream.on("text", (delta) => controller.enqueue(enc.encode(delta)));19 stream.on("end", () => controller.close());20 stream.on("error", (err) => controller.error(err));21 },22 cancel() {23 stream.abort(); // user left: stop generating (and paying)24 },25 });2627 return new Response(body, { headers: { "Content-Type": "text/plain; charset=utf-8" } });28}
To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.