Skip to content
AI Playbooks · 10 min read

Streaming LLM Responses for Beginners: The Playbook on Showing AI Answers as They Are Written

Learn streaming LLM responses step by step: show AI answers as they are written, pass them safely to the browser, and handle Stop and errors.

Meera is a developer in Pune. Her team has built a help-desk chatbot, and it gives good answers. The problem is the wait. Customers stare at an empty box for eight seconds (an illustrative number) before the whole answer drops in. Half the testers clicked “send” again, thinking it had frozen.

Her lead, Arjun, smiles. “The answer is fine. The feeling is wrong. We need streaming LLM responses, so the words appear as the model writes them.” This playbook follows Meera from “what is streaming?” to a chat box that feels quick, can be stopped, and survives a bad network.

Last verified: 23 November 2026. AI tools change fast; check the linked sources for anything newer.

Who this is for: beginners who can call an AI model from code (or want to) and have a chat screen that feels slow. No front-end expertise needed. Time needed: about 30-45 minutes.

What are streaming LLM responses, in simple words

A language model writes its answer one small piece at a time. Those pieces are called tokens: chunks of text, often part of a word. (Our How LLMs Work playbook explains tokens in detail.)

Without streaming, your app waits until every token is ready and then shows the whole answer. With streaming LLM responses, the model sends each small piece the moment it is written, and your app shows it straight away.

Think of a restaurant. Without streaming, the waiter brings nothing until all five courses are cooked. With streaming, the soup arrives while the main course is still on the stove. The total cooking time is the same, but you are eating, not waiting.

The precise version: streaming does not make the model finish sooner. It cuts the time to first token, the wait before the first word appears, which is what people actually feel.

How the pieces travel: server-sent events

Most AI providers send streaming LLM responses using server-sent events (SSE). It is a simple web standard: the server keeps one normal web response open and keeps writing small text messages into it, each one separated by a blank line. The browser reads them as they arrive. Traffic goes one way only, server to browser, which suits an AI answer well.

The playbook at a glance

  1. Decide where streaming helps (and where it does not).
  2. Switch it on with one setting or one SDK helper.
  3. Pass the stream through your server to the browser, keeping your key secret.
  4. Show partial text safely and wait for complete pieces before acting.
  5. Handle the stop button and errors without losing the answer.
  6. Test it like a real user on a slow connection.

Play 1: Decide where streaming helps

Goal: use streaming LLM responses where a person is watching, and skip them where nobody is.

  1. List every place your app calls the model.
  2. Mark each one: does a human wait and watch the answer appear?
  3. Stream the “yes” ones: chat boxes, writing helpers, long explanations.
  4. Keep the “no” ones simple: nightly reports, labelling, background jobs. A normal call is easier there.

Meera’s list has three calls. Only the chat reply has a waiting customer, so only that one gets streaming. The ticket-tagging job stays as it is.

You are done when: you have a short list of the calls that will stream, and a reason for each.

Play 2: Switch it on

Goal: get the pieces arriving in your own code first, before touching the browser.

  1. Find the streaming option in your provider’s docs. It is usually a setting such as stream: true, or a helper in the official SDK (software development kit, the provider’s ready-made library).
  2. Print each piece as it arrives, without a new line, so you can watch the answer type itself.
  3. Notice the stream is a series of small events: a start message, many text pieces, then a stop message with the reason it ended.

Here is a small illustration in Python using Anthropic’s official SDK, adapted from its streaming docs. Other providers look different but follow the same idea.

import anthropic

client = anthropic.Anthropic()  # reads your API key from the environment

with client.messages.stream(
    model="claude-sonnet-5-5",
    max_tokens=512,
    messages=[{"role": "user", "content": "How do I reset my password?"}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)  # show each piece at once

In plain steps: open a stream, loop over the pieces as they arrive, and print each one immediately. The SDK handles the raw events for you.

Meera runs it in her terminal and watches the reply appear word by word. “Already better,” she says, “and I have not even touched the website.”

You are done when: your terminal shows an answer typing itself out, and you can see the final stop reason.

Play 3: Pass the stream through your server

Goal: carry streaming LLM responses from the model to the browser, without ever putting your API key in the browser.

  1. Keep the model call on your own server. The browser talks to your server, never to the AI provider directly. This keeps your key secret.
  2. Your server reads each piece from the model and forwards it to the browser as a server-sent event, with the content type text/event-stream.
  3. In the browser, read the stream and add each piece to the screen. The built-in EventSource tool only makes simple GET requests, so for a chat message you will usually send a POST with fetch() and read its body as a stream.
  4. Check that nothing in between holds the response back. Some servers and proxies collect the whole output before sending it, which quietly turns streaming off. Look for “buffering” settings.

Meera’s first try still lands all at once. The cause is a proxy that buffers responses. She switches buffering off for the chat route, and the words start flowing.

You are done when: the browser shows text appearing gradually, and the network tab shows a single long response that grows over time.

Play 4: Show partial text safely

Goal: display unfinished text without confusing the user or your own code.

  1. Add each new piece to the end of the message. Do not redraw the whole page each time.
  2. Be careful with formatting. Half-written Markdown (an open code block, a half table) can look broken for a moment. Many teams format the text simply while streaming and tidy it once the stop message arrives.
  3. Never act on half an answer. If the model is asking to use a tool, its instructions arrive as partial JSON, broken bits of data. Wait until that piece is marked complete before running anything. (See the Function Calling playbook.)
  4. Only save the message to your database once it is complete, or mark it clearly as partial.

Meera adds a small blinking cursor while the answer is still coming, and removes it when the stop message arrives. Customers now know at a glance whether the bot is still “typing”.

You are done when: answers render cleanly while streaming, and no tool runs before its instructions are complete.

Play 5: Handle the stop button and errors

Goal: let people stop an answer, and stay calm when a stream breaks halfway.

  1. Add a “Stop” button. When clicked, close the connection in the browser and tell your server to stop reading from the model, so you are not paying for tokens nobody will read.
  2. Expect errors in the middle of a stream, not only at the start. Anthropic’s docs, for example, describe an overloaded_error event that can arrive during busy periods, after some text has already been shown.
  3. Keep what already arrived. Show a short note such as “Connection lost. Retry?” next to the partial answer instead of wiping it.
  4. For a retry, the provider docs describe a simple pattern: save the partial answer, then send a new request asking the model to continue from where it stopped.

Meera’s logs (from her observability setup) show a handful of broken streams on a busy afternoon. Because the partial text stays on screen with a retry link, no customer has to type the question again.

You are done when: the Stop button really stops the model call, and a broken stream leaves a readable partial answer with a way to continue.

Play 6: Test it like a real user

Goal: prove your streaming LLM responses feel fast, on real connections, before launch.

  1. Measure two times for a set of test questions: time to first token, and total time.
  2. Use your browser’s developer tools to slow the network down, then try again.
  3. Try the awkward cases: a very long answer, the Stop button in the middle, a lost connection, a tool call.
  4. Open the app in several tabs. Over older HTTP/1.1 connections, MDN notes browsers allow only six SSE connections per site, shared across tabs. HTTP/2 raises this limit a lot.

Meera’s illustrative numbers: total time is still about eight seconds, but the first words now appear in under one second. In the next test round, nobody clicks “send” twice.

You are done when: the first words appear quickly for every test question, and every awkward case behaves sensibly.

Do you need streaming LLM responses?

SituationStream?Why
Chat box or writing helperYesA person is watching; the first words matter most.
Long answers or large token limitsUsually yesAvoids long silent waits and some request timeouts.
Background job or reportNoNobody is watching; a normal call is simpler.
Strict JSON for your codeOften noYour code needs the full, valid result anyway. See Structured Outputs.
Agent that uses toolsYes, with careShow progress, but run each tool only when its input is complete.

Mistakes to avoid

  • Calling the AI provider straight from the browser. Your key leaks. Fix: always go through your own server.
  • A proxy that buffers the response. Streaming silently stops working. Fix: switch off buffering for the streaming route and test in a real browser.
  • Running a tool on partial JSON. Broken input, strange actions. Fix: wait for the piece to be complete, then check it.
  • A Stop button that only hides the text. The model keeps writing and you keep paying. Fix: cancel the request on the server too.

How to know it is working

  • The first words appear in about a second for normal questions (measure your own target).
  • Fewer users re-send the same question or refresh the page.
  • The Stop button ends the server call, and your token usage shows it.

Your checklist

  • ☐ I listed which model calls a human watches, and stream only those.
  • ☐ Streaming works in my terminal first.
  • ☐ My server forwards events; the API key never reaches the browser.
  • ☐ No proxy or server is buffering the stream.
  • ☐ Partial text displays cleanly, and tools wait for complete input.
  • ☐ The Stop button cancels the server call.
  • ☐ Mid-stream errors keep the partial answer and offer a retry.
  • ☐ I measured time to first token on a slow connection.

Frequently asked questions

Do streaming LLM responses make the AI faster?

Not really. The model takes roughly the same total time. Streaming shows the first words much sooner, so the app feels faster and people can start reading straight away.

Does streaming cost more?

Streaming LLM responses do not change how tokens are counted. A working Stop button can even save money, because you stop paying for words nobody reads. For more ways to cut cost, see the LLM Cost Optimization playbook.

Should I use server-sent events or WebSockets?

For streaming an AI answer, server-sent events are usually enough, because data only needs to flow from server to browser. WebSockets suit apps where both sides keep sending messages, such as live voice or multiplayer tools.

Back to Meera: the chat that feels alive

A week later, Meera watches a customer ask about a late refund. The first words appear before the customer has even moved the mouse. Halfway through, the customer finds the answer, clicks Stop, and closes the chat happy. The model call ends too.

Nothing about the model changed, only how the answer travels. That is what streaming LLM responses are about.

Your next step: pick one chat screen in your own app and make the first word appear in under a second. Then continue with the next chapter on the CodeSpy AI Roadmap, on small models and quantization, to make those answers cheaper as well.

Sources: Anthropic, Streaming messages (event types, error events, partial JSON for tools, error recovery); MDN, Using server-sent events (event format, EventSource, connection limits).

Leave a Reply

Your email address will not be published. Required fields are marked *

Newsletter

Get the next guide before anyone else.

One email a week with new playbooks and tutorials. No spam, unsubscribe anytime.