Skip to content
Visual explainer 2h to learn 3 steps

Streaming responses

Stream tokens to a terminal or web client and handle partial output.

By Invicly Tech, , in AI Engineering with Python. About 10 minutes to read.

Topic 5 of 33

In short

Streaming returns the response as small chunks while the model generates, instead of one block at the end. Users see output almost immediately, which makes apps feel much faster.

Explained simply

Without streaming, your app asks a question and waits until the model has written the whole answer, which can take 10 seconds or more. Only then does anything appear on screen. Users stare at a spinner and often think the app is broken.

With streaming, the API sends the answer in small pieces while the model is still writing. The first words can appear in under a second, and the rest flows in like someone typing. The total time is about the same, but it feels much faster.

To show the stream in a browser, your server passes each piece on as it arrives. A common way is server-sent events (SSE): one long HTTP response that the server keeps writing small messages into.

Streams can break. The user closes the tab, the network drops, or the model hits its length limit. Good streaming code keeps the text received so far, knows whether the answer actually finished, and stops paying for tokens nobody will read.

Press Play on a diagram to walk through it one step at a time.

SequenceStreaming to a web client
Browser
Your server
LLM API
  1. 1POST /chat
    Browser to Your server: POST /chat
  2. 2Request with stream enabled
    Your server to LLM API: Request with stream enabled
  3. 3Chunk: 'The'
    LLM API to Your server: Chunk: 'The'
  4. 4Forward chunk via SSE
    Your server to Browser: Forward chunk via SSE
  5. 5More chunks...
    LLM API to Your server: More chunks...
  6. 6Final event with usage
    LLM API to Your server: Final event with usage
  7. 7Done event
    Your server to Browser: Done event
FlowLife of one streamed reply
  1. 1
    Open connection

    Request sent with streaming on

  2. 2
    First token

    Time to first token ends here

  3. 3
    Text deltas

    Append each to a buffer and display

  4. 4
    Final event

    Stop reason and token usage

  5. 5
    Close and save

    Store full text, mark complete or not

In depth

What a stream looks like on the wire

Most LLM APIs stream using server-sent events. The response has the content type text/event-stream and stays open. Each event is a few text lines, such as an optional event: line naming the type and a data: line holding JSON, followed by a blank line that ends the event.

A typical stream starts with a start event, then many delta events that each carry a few new characters of text, then a final event with the stop reason and token usage. Exact event names and shapes differ by provider, and the SDK hides them: you loop over a stream object and read the text deltas.

Usage numbers often arrive only at the end, and some APIs require an option to include them. If you need cost tracking, make sure you capture that last event and do not stop reading early.

  • Content type: text/event-stream
  • Each event ends with a blank line
  • Deltas carry new text only, not the whole reply
  • Stop reason and usage usually come last

Passing the stream on to a browser

Your server sits in the middle: it reads chunks from the model and writes them to the browser as they arrive. In FastAPI, return a StreamingResponse with media_type text/event-stream and an async generator that yields lines like data: {...} followed by a blank line. Set Cache-Control: no-cache.

Buffering is the usual reason a stream arrives all at once at the end. Reverse proxies such as nginx buffer responses by default; turn it off with proxy_buffering off for that route, or send the header X-Accel-Buffering: no.

In the browser, the built-in EventSource is simplest, but it only makes GET requests and reconnects automatically when the stream ends, so close it when you receive your done event. For POST requests with a JSON body, use fetch and read response.body with a stream reader, splitting events on blank lines yourself.

  • FastAPI: StreamingResponse(gen(), media_type="text/event-stream")
  • nginx: proxy_buffering off, or X-Accel-Buffering: no
  • EventSource: GET only, auto-reconnects
  • fetch + reader: any method, parse events yourself

Partial and interrupted output

A stream can end in four ways: the model finished normally, it hit the max output token limit, an error arrived mid-stream, or the connection dropped. Only the first is a complete answer. Keep appending deltas to a buffer and check the final stop reason before you mark the message as done.

If the stream breaks, keep what you received. Save it marked as incomplete, show the user what arrived, and offer a retry button. Retrying usually means a fresh request, because most APIs cannot resume a stream where it stopped.

When the user closes the tab, stop the model call too. In FastAPI (built on Starlette), a disconnect cancels your streaming generator, so put cleanup in a finally block and close the upstream stream, for example by using the SDK stream inside async with. Otherwise the model keeps generating tokens that you pay for and nobody sees.

SequenceUser closes the tab mid-answer
Browser
Your server
LLM API
  1. 1Ask a question
    Browser to Your server: Ask a question
  2. 2Streaming request
    Your server to LLM API: Streaming request
  3. 3Text deltas
    LLM API to Your server: Text deltas
  4. 4Forward deltas
    Your server to Browser: Forward deltas
  5. 5Tab closed: connection drops
    Browser to Your server: Tab closed: connection drops
  6. 6Close stream: stop generating
    Your server to LLM API: Close stream: stop generating
  7. 7Save partial text as incomplete
    Your server to Your server: Save partial text as incomplete

Streaming JSON and tool calls

When the model streams JSON, each chunk is a fragment such as {"na, which is not valid JSON on its own. Do not parse until the stream has finished, then validate the whole thing. If you want to show fields as they fill in, use a parser that tolerates incomplete JSON, but treat the result as a preview, not as data.

Tool calls stream the same way: the tool name usually arrives first, then the arguments as JSON fragments. Join all fragments, parse once, validate, and only then run the tool.

Streaming also makes output checks harder. If you filter replies for unsafe or private content, text has already reached the screen before you see the whole answer. Options are checking in small windows as text arrives, or not streaming for high-risk features.

Learn it in 3 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Stream tokens to the terminal~40m
  2. 2
    Stream to a web client~40m
  3. 3
    Handle partial and interrupted output~40m

Key points

  • Streaming cuts time to first token, not total generation time.
  • Server-sent events are a simple, common way to push chunks to browsers.
  • Accumulate chunks to get the full text for logging and storage.
  • Handle client disconnects and stop the upstream request to save tokens.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
import time
from typing import Iterator

def fake_stream() -> Iterator[str]:
    # Stands in for your SDK's streaming iterator
    for piece in ['Streaming ', 'feels ', 'fast.']:
        time.sleep(0.3)
        yield piece

parts: list[str] = []
for chunk in fake_stream():
    print(chunk, end='', flush=True)
    parts.append(chunk)

full_text = ''.join(parts)  # keep the whole reply for logs

Print chunks as they arrive and keep the full text.

An SSE endpoint in FastAPI

You want a /chat endpoint that streams to the browser. Step 1: write an async generator that reads chunks from the model (faked here). Step 2: wrap each chunk as an SSE event: a data: line with JSON and a blank line. Step 3: send a final done event so the browser knows the answer is complete. Step 4: return a StreamingResponse with the SSE media type and headers that stop caching and proxy buffering. Run it with uvicorn app:app and open /chat?q=hi to watch the events arrive.

python
import asyncio, json
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
async def fake_llm(q: str):
    for word in ["Streaming ", "over ", "SSE ", "works."]:
        await asyncio.sleep(0.2)
        yield word
@app.get("/chat")
async def chat(q: str):
    async def events():
        async for piece in fake_llm(q):
            yield f"data: {json.dumps({'text': piece})}\n\n"
        yield "event: done\ndata: {}\n\n"
    return StreamingResponse(events(), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})

Showing the stream in the browser

The page must display text as it arrives from the endpoint above. Step 1: open an EventSource to /chat with the question in the URL. Step 2: on each default message event, parse the JSON and append the text. Step 3: listen for the custom done event and close the connection, because EventSource otherwise reconnects and asks the same question again. Step 4: on error, close it and tell the user the answer may be incomplete.

javascript
const output = document.querySelector("#answer");
const es = new EventSource("/chat?q=" + encodeURIComponent("What is SSE?"));

es.onmessage = (e) => {
  output.textContent += JSON.parse(e.data).text;
};
es.addEventListener("done", () => es.close()); // stop auto-reconnect
es.onerror = () => {
  es.close();
  output.textContent += " [connection lost, answer may be incomplete]";
};

Quick reference

  • Streaming lowers time to first token; total generation time stays about the same
  • SSE event format: data: {json} followed by a blank line
  • FastAPI: StreamingResponse(generator, media_type="text/event-stream")
  • Turn off proxy buffering: nginx proxy_buffering off or header X-Accel-Buffering: no
  • EventSource is GET-only and auto-reconnects: close it on your done event
  • Check the final stop reason before marking a streamed answer complete
  • Parse streamed JSON only after the stream ends
  • On client disconnect, close the upstream stream so you stop paying for tokens

Common mistakes

  • Buffering the whole stream on the server before sending, losing the benefit.
  • Parsing structured JSON before the stream has finished.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Your SSE stream works locally but arrives all at once in production behind nginx. What is the likely cause?

Question 2

2Why should the browser close its EventSource when it gets the done event?

Question 3

3A stream ends normally, but the final stop reason says the token limit was hit. What should you do?

Question 4

4What usually arrives in the last event of a streamed response?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Stream a reply from your SDK to the terminal, printing each piece as it arrives, then print the time to first token and the total time.

  2. Exercise 2medium

    Change the FastAPI example so that if the client disconnects, the server logs how many characters were sent and stops reading from the model.

  3. Exercise 3hard

    Write a browser client that sends a POST with a JSON body to a streaming endpoint and displays SSE data events, using fetch instead of EventSource.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Does streaming cost more?
No. You pay for the same input and output tokens whether or not you stream.
Should I use SSE or WebSockets for a chat app?
SSE is enough when the server only pushes the reply and the client sends each new question as a normal request. WebSockets help when both sides must send messages over one long connection, such as live voice or collaborative editing.
Can I stream structured JSON output?
Yes, but each chunk is an incomplete fragment. Parse and validate only after the stream finishes, or use a partial-JSON parser for a preview.
ShareXLinkedInWhatsApp