Why stream LLM responses, and how do you do it?

Learning path, stage 2 of 5: Prompting and model features · question 10 of 10

Streaming 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 ReadableStream in 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";
3
4const client = new Anthropic();
5
6export async function POST(req: Request) {
7 const { prompt } = await req.json();
8
9 const stream = client.messages.stream({
10 model: "claude-opus-5-5",
11 max_tokens: 8000,
12 messages: [{ role: "user", content: prompt }],
13 });
14
15 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 });
26
27 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.

Open in study app