AI Engineering · Build lab 2 of 14

Build a streaming chat: SDK streaming, FastAPI and Server-Sent Events

Make answers appear word by word. Stream tokens with the SDK into a terminal chat that remembers the conversation within a token budget, serve the same stream from FastAPI as Server-Sent Events to a web page with a working Stop button, and test it all without a model.

⏱ 60 minIntermediate💸 Free (local model)9 stepsPython + Java

Python 3.12uvOllamallama3.2:3bopenai SDKFastAPIuvicornServer-Sent EventsSpring AI + WebFlux (optional)

Overview video

1 / 7

0 of 9 steps done

What you will build

A chat that shows the answer while it is being written, token by token, in two places: a command-line chat that remembers the conversation, and a web page served by your own FastAPI server.

On the way you handle what every real chat product has to: a history that would outgrow the context window, a user who clicks Stop halfway (the model must stop too, or you keep paying for tokens nobody reads), and an error after half the answer has already been sent. The tests run in about a second, with no model.

Before you start

Setup

S1Same tools as lab 1

You need uv, Ollama running, and the llama3.2:3b model, exactly as in lab 1's setup. These two commands check all three. If the model is missing from the list, run ollama pull llama3.2:3b.

Run
uv --version
ollama list
You should see
uv 0.x.y
NAME           ID              SIZE      MODIFIED
llama3.2:3b    a80c4f17acd5    2.0 GB    2 days ago

S2curl, to watch raw streams

macOS and Linux already have curl. Windows 10 and 11 ship it as curl.exe. In Windows PowerShell, type curl.exe every time: plain curl there can be an alias for a different command (Invoke-WebRequest).

Run
curl --version
You should see
curl 8.x.x (...) libcurl/8.x.x ...

S3Java only (optional): JDK 21 and Maven

Only if you want the Spring AI version of the server (switch to Java at the top of the steps). Put the Java files from step 8 in a folder of their own.

Run
brew install openjdk@21 maven

S4See streaming with your own eyes

Ollama's own command line streams. Watch the numbers appear one after another instead of all at once: that is what you will build.

Run
ollama run llama3.2:3b "Count from 1 to 20, separated by commas."
You should seeyour text will differ: the model writes it
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
1

Create the project

A fresh project with the SDK, FastAPI and the server that runs it.

uv init creates the project folder and pyproject.toml (the project file, like package.json or pom.xml). uv add installs packages into the project's own virtual environment and records them there.

New compared with lab 1: fastapi, the web framework (think Express, or Spring Web), and uvicorn, the server process that runs it (the job Tomcat or Netty does for Spring). There is no httpx this time: the SDK installs its own HTTP client, and FastAPI's test client uses that same one.

This lab was tested with Python 3.12, openai 3.60, fastapi 0.165 and uvicorn 0.55. uv init also creates a main.py; delete it, this lab does not use it.

Run
uv init streaming-chat
cd streaming-chat
uv add openai python-dotenv fastapi uvicorn
uv add --dev pytest
You should see
Initialized project `streaming-chat` at `.../streaming-chat`
Resolved 23 packages in 260ms
Installed 21 packages in 26ms
 + fastapi==0.165.0
 + openai==3.60.0
 + python-dotenv==1.2.4
 + uvicorn==0.55.0
 ...
Stuck on this step?
uv: command not found
Open a new terminal so the PATH change from the uv installer applies, or run source $HOME/.local/bin/env (macOS and Linux).
2

Settings in one place

URL, key and model come from `.env` like in lab 1, plus one new setting: the history budget.

Same three settings as lab 1, so the same code runs against the free local model or a hosted API. The new one, HISTORY_TOKENS, is how much earlier conversation we send with each question (step 5 explains why it must be limited).

.env
# Local model through Ollama (free). Ollama ignores the key, but the SDK needs a value.
LLM_BASE_URL=http://localhost:11434/v1
LLM_API_KEY=ollama
LLM_MODEL=llama3.2:3b

# How many tokens of chat history to send with each question (rough estimate).
HISTORY_TOKENS=2000

# A hosted API instead: change the first three lines, nothing else.
# LLM_BASE_URL=https://api.your-provider.com/v1
# LLM_API_KEY=sk-...
# LLM_MODEL=the-model-name
  1. Ollama's OpenAI-compatible API. Streaming works through the same endpoint.line 2
  2. Ollama runs a model with a context window of a few thousand tokens by default, smaller than the model's maximum. A longer prompt is cut without an error, and the model quietly forgets the start of the chat. 2,000 tokens of history leaves room for the answer.line 7
config.py
import os
from dataclasses import dataclass

from dotenv import load_dotenv

load_dotenv()  # read .env into environment variables (real env vars win)


@dataclass(frozen=True)
class Settings:
    base_url: str
    api_key: str
    model: str
    history_tokens: int


def settings() -> Settings:
    return Settings(
        base_url=os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1"),
        api_key=os.environ.get("LLM_API_KEY", "ollama"),
        model=os.environ.get("LLM_MODEL", "llama3.2:3b"),
        history_tokens=int(os.environ.get("HISTORY_TOKENS", "2000")),
    )
  1. load_dotenv() copies .env into os.environ. Variables already set in your shell win, which is what you want on a server.line 6
  2. The new field. frozen=True (the line above the class) keeps settings read-only.line 14
  3. Environment variables are always strings, so int(...) converts it, like Integer.parseInt in Java.line 22
.gitignore
.venv/
__pycache__/
.env
  1. Never commit .env: it will hold a real key one day.line 3
Why this way? Every later step reads settings(), so moving from your laptop to a hosted API, or giving a bigger model a bigger history budget, is an edit to .env and nothing else.
3

Watch a raw stream

See what streaming really sends: many small `data:` events instead of one JSON reply.

In lab 1 the server sent the whole answer as one JSON response. Add "stream": true and the same endpoint answers with Server-Sent Events (SSE): one long HTTP response with the type text/event-stream, in which the server writes a small event each time the model produces a little more text.

The format is plain text. Each event is a line that starts with data: , followed by an empty line. Here the data is a JSON chunk whose choices[0].delta.content holds only the new piece of text, the delta. The last event is data: [DONE].

The request body goes in a file, so the command is the same on every operating system. Save it in the project folder, then run curl. -N turns off curl's output buffering so each event prints the moment it arrives, and -d @ask.json sends the file as the body (with -d, curl makes a POST).

ask.json
{
  "model": "llama3.2:3b",
  "stream": true,
  "messages": [
    {"role": "user", "content": "Name three sorting algorithms."}
  ]
}
  1. The only difference from a normal call. Leave it out and you get one JSON reply at the end.line 3
Run
curl -N http://localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d @ask.json
You should seeyour text will differ: the model writes it
data: {"id":"chatcmpl-112","object":"chat.completion.chunk","created":1764400000,"model":"llama3.2:3b","system_fingerprint":"fp_ollama","choices":[{"index":0,"delta":{"role":"assistant","content":"Here"},"finish_reason":null}]}

data: {"id":"chatcmpl-112",...,"choices":[{"index":0,"delta":{"role":"assistant","content":" are"},"finish_reason":null}]}

...

data: {"id":"chatcmpl-112",...,"choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":"stop"}]}

data: [DONE]
Why this way? People judge speed by when the first words appear (time to first token), not by when the last one does. A 10-second answer that starts after half a second feels fast. The same answer shown all at once after 10 seconds feels broken.
Stuck on this step?
Everything prints at once at the end
You left out -N, or "stream": true is missing from ask.json.
Windows: A parameter cannot be found that matches parameter name 'N'
You typed curl, which PowerShell turned into Invoke-WebRequest. Type curl.exe.
Warning: Couldn't read data from file "ask.json"
Run the command in the folder that holds ask.json (the project folder).
4

Stream with the SDK

Print the answer while it arrives, and measure the time to the first token.

With stream=True the SDK no longer returns one finished response. It returns a stream object you loop over, and each item is one parsed chunk. The SDK reads the data: lines you just saw and stops at [DONE], so you never parse SSE from the model yourself.

stream_reply is a generator: a function containing yield. Calling it starts nothing; it hands back an iterator. Each time the caller's for loop asks for the next item, the function runs until the next yield, hands over that piece and pauses there. In Java terms it returns an Iterator<String> whose next() reads from the network; in JavaScript it is a function*.

llm.py
from collections.abc import Iterator

from openai import OpenAI

from config import settings

_s = settings()
client = OpenAI(base_url=_s.base_url, api_key=_s.api_key, timeout=60, max_retries=2)


def stream_reply(messages: list[dict]) -> Iterator[str]:
    """Send the conversation, yield the answer piece by piece as it is generated."""
    stream = client.chat.completions.create(
        model=_s.model,
        messages=messages,
        temperature=0.7,
        stream=True,
    )
    with stream:
        for chunk in stream:
            if chunk.choices and chunk.choices[0].delta.content:
                yield chunk.choices[0].delta.content
  1. For a stream, the timeout is per wait: it fires when no new data arrives for 60 seconds, not when the whole answer takes longer than that.line 8
  2. -> Iterator[str]: returns an iterator of strings. list[dict] is a list of message dictionaries, the format from lab 1.line 11
  3. The only change to the call: the SDK now returns a Stream instead of a finished ChatCompletion.line 17
  4. Closes the HTTP connection when the loop ends, also when the caller stops early or an error happens. Like Java's try-with-resources.line 19
  5. Some chunks carry no text (the first can carry only the role, the last only finish_reason), so skip those. delta.content is the new piece only, never the whole answer so far.line 21
  6. Hand this piece to the caller and pause here until the caller asks for the next one.line 22
stream_demo.py
import sys
import time

from llm import stream_reply

question = " ".join(sys.argv[1:]) or "Explain what a cache is in three sentences."
messages = [
    {"role": "system", "content": "You are a concise tutor."},
    {"role": "user", "content": question},
]

start = time.perf_counter()
first_token_at = None
chunks = 0
for piece in stream_reply(messages):
    if first_token_at is None:
        first_token_at = time.perf_counter() - start
    print(piece, end="", flush=True)
    chunks += 1

total = time.perf_counter() - start
print(f"\n\n[first token after {first_token_at or 0:.2f}s, {chunks} chunks in {total:.2f}s]")
  1. The words after the script name, joined into one question. or supplies a default when there are none.line 6
  2. time.perf_counter() is a precise clock for measuring durations, like System.nanoTime() or performance.now().line 12
  3. end="": no newline after each piece. flush=True: write it to the screen now. In a terminal Python writes text out only when a line ends, so without flush you would see the answer line by line instead of word by word.line 18
  4. If the model sent nothing, first_token_at is still None; or 0 prints 0 instead of crashing.line 22
Run
uv run stream_demo.py "What is a cache?"
You should seeyour text will differ: the model writes it
A cache keeps a copy of data that is slow to get in a place that is fast to read, such as memory. The next request for the same data is served from the copy...

[first token after 0.31s, 58 chunks in 1.92s]
Stuck on this step?
The whole answer appears at once
Check flush=True in the print. Some IDE consoles buffer output anyway: run it in a real terminal.
The first token takes 15 seconds or more
Normal for the first call: Ollama is loading the model into memory. Run it again and it starts in well under a second on most laptops.
5

A chat loop that remembers

A terminal chat with history, trimmed to a token budget so long chats keep working.

The model remembers nothing between calls. A chat feels like it remembers because you send the whole conversation every time: the system message, every earlier question and answer, then the new question. So the messages list grows by two entries per turn.

Left alone, it grows past the context window, and every turn costs more, because you pay for the whole history on every call. trim_history keeps the system message plus as many of the newest messages as fit in the budget. An exact count needs the model's own tokenizer; for a budget, about 4 characters per token (for English) is close enough.

history.py
import math

PER_MESSAGE = 4  # rough cost of the role and separators around each message


def estimate_tokens(text: str) -> int:
    """A rough token count: about 4 characters per token for English text."""
    return math.ceil(len(text) / 4)


def message_tokens(message: dict) -> int:
    return estimate_tokens(message["content"]) + PER_MESSAGE


def trim_history(messages: list[dict], budget: int) -> list[dict]:
    """Keep the system message plus the newest messages that fit in `budget` tokens."""
    system = messages[:1] if messages and messages[0]["role"] == "system" else []
    rest = messages[len(system):]
    used = sum(message_tokens(m) for m in system)

    kept = []
    for m in reversed(rest):  # newest first
        cost = message_tokens(m)
        if kept and used + cost > budget:
            break  # the newest message is always kept, even if it is too long
        kept.append(m)
        used += cost
    kept.reverse()  # back to oldest-first

    while len(kept) > 1 and kept[0]["role"] == "assistant":
        kept.pop(0)  # never start with an answer whose question was dropped
    return system + kept
  1. Each message also costs a few tokens for its role and the separators around it.line 3
  2. Round up: 5 characters count as 2 tokens. Overestimating a little is the safe side for a budget.line 8
  3. Always keep the system message: it holds the rules. messages[:1] is a new list with just the first item (a slice, like subList(0, 1)). The x if condition else y form is Python's condition ? x : y.line 17
  4. Walk from the newest message backwards, adding messages while they fit.line 22
  5. An empty list counts as false, so the first message checked (the new question) is always kept, even when it alone is over budget.line 24
  6. If trimming dropped a question but kept its answer, drop that orphan answer too, so the history starts with a user message.line 30
chat.py
import openai

from config import settings
from history import trim_history
from llm import stream_reply

SYSTEM = "You are a friendly, concise assistant for software developers."


def main() -> None:
    s = settings()
    messages = [{"role": "system", "content": SYSTEM}]
    print(f"Chatting with {s.model}. Commands: /reset clears the history, /exit quits.")

    while True:
        try:
            user = input("\nyou> ").strip()
        except (EOFError, KeyboardInterrupt):  # Ctrl+D or Ctrl+C at the prompt
            print()
            break
        if not user:
            continue
        if user == "/exit":
            break
        if user == "/reset":
            messages = messages[:1]
            print("(history cleared)")
            continue

        messages.append({"role": "user", "content": user})
        messages = trim_history(messages, s.history_tokens)

        print("bot> ", end="", flush=True)
        pieces = []
        try:
            for piece in stream_reply(messages):
                print(piece, end="", flush=True)
                pieces.append(piece)
        except KeyboardInterrupt:  # Ctrl+C while it is answering: stop this answer only
            print(" [stopped]", end="")
        except openai.APIConnectionError:
            print("\n(cannot reach the model server: is Ollama running?)")
            messages.pop()  # forget the question that got no answer
            continue
        print()
        messages.append({"role": "assistant", "content": "".join(pieces)})


if __name__ == "__main__":
    main()
  1. input() prints the prompt and reads one line from the keyboard, like Scanner.nextLine(). .strip() removes spaces and the newline around it.line 17
  2. Ctrl+D (Ctrl+Z then Enter on Windows) raises EOFError, Ctrl+C raises KeyboardInterrupt. At the prompt, both end the chat cleanly.line 18
  3. /reset keeps only the system message.line 26
  4. Trim before every call, so no request goes over the budget.line 31
  5. Ctrl+C while the answer streams stops only this answer. Leaving the loop runs the with block's cleanup in stream_reply, which closes the connection, and Ollama stops generating.line 39
  6. The server could not be reached: remove the unanswered question so the history stays question, answer, question, answer.line 43
  7. Save the answer, even a stopped one, so the next question has context. "".join(pieces) glues the pieces together, like String.join("", pieces).line 46
  8. Run main() only when this file is started directly, not when another file imports it. Python's version of public static void main.line 49
Run
uv run chat.py
You should seeyour text will differ: the model writes it
Chatting with llama3.2:3b. Commands: /reset clears the history, /exit quits.

you> What is a hash map? One sentence.
bot> A hash map stores key-value pairs and uses a hash of each key to find its value in about constant time.

you> Show one in Java, two lines max.
bot> Map<String, Integer> ages = new HashMap<>();
ages.put("Ada", 36);

you> /exit
Why this way? The second question says "one" and the model knows you mean a hash map only because the first question and answer went along with it. Type /reset and ask the second question again: the model has to guess.
Stuck on this step?
The bot forgets what I said a moment ago
Check that both the user message and the assistant answer are appended to messages, and that HISTORY_TOKENS is not tiny.
Ctrl+C ends the whole program
That happens when you press it at the you> prompt, by design. Pressed while an answer is streaming, it stops only that answer.
6

Stream over HTTP with Server-Sent Events

A `POST /chat` endpoint that streams the answer as SSE events any client can read.

Now the same stream goes to a browser. The browser must never call the model provider itself: the API key would be visible to anyone who opens the developer tools. So the browser calls your server, and your server streams the answer on.

Two new pieces. First, an async version of stream_reply. A web server serves many users at once on one thread, and each await lets other requests run while this one waits for its next token (the same idea as Node's event loop or Spring WebFlux). Second, the endpoint returns a StreamingResponse: FastAPI sends the status and headers at once, then sends each string your generator yields as soon as it is yielded.

The server sends its own small events instead of passing on the provider's chunks: {"type": "token", "text": "..."} for each piece, then {"type": "done"}. Encoding the text as JSON keeps it safe: a token that contains a newline, or starts with a space, arrives exactly as sent.

Start the server in one terminal and leave it running. server:app means "the app object in server.py", and --reload restarts it whenever you save a file:

uv run uvicorn server:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

Then open a second terminal in the same folder and send hi.json to it:

llm.py 15 new or changed lines
from collections.abc import AsyncIterator, Iterator

from openai import AsyncOpenAI, OpenAI

from config import settings

_s = settings()
client = OpenAI(base_url=_s.base_url, api_key=_s.api_key, timeout=60, max_retries=2)
aclient = AsyncOpenAI(base_url=_s.base_url, api_key=_s.api_key, timeout=60, max_retries=2)


def stream_reply(messages: list[dict]) -> Iterator[str]:
    """Send the conversation, yield the answer piece by piece as it is generated."""
    stream = client.chat.completions.create(
        model=_s.model,
        messages=messages,
        temperature=0.7,
        stream=True,
    )
    with stream:
        for chunk in stream:
            if chunk.choices and chunk.choices[0].delta.content:
                yield chunk.choices[0].delta.content


async def astream_reply(messages: list[dict]) -> AsyncIterator[str]:
    """The same, for async code such as the web server: it never blocks other requests."""
    stream = await aclient.chat.completions.create(
        model=_s.model,
        messages=messages,
        temperature=0.7,
        stream=True,
    )
    async with stream:
        async for chunk in stream:
            if chunk.choices and chunk.choices[0].delta.content:
                yield chunk.choices[0].delta.content
  1. The async client: same settings, but its calls are awaited.line 9
  2. An **async generator**: async def plus yield. Callers loop over it with async for. Python's answer to AsyncIterator in JavaScript, or a Flux in Reactor.line 26
  3. This await sends the request and waits for the response headers, not for the whole answer.line 28
  4. Closes the connection to the model when the loop ends, fails or is cancelled. Step 8 relies on this.line 34
server.py
import json
from typing import Literal

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field

from config import settings
from history import trim_history
from llm import astream_reply

SYSTEM = "You are a friendly, concise assistant for software developers."

app = FastAPI(title="Streaming chat")


class Message(BaseModel):
    role: Literal["user", "assistant"]
    content: str = Field(max_length=8000)


class ChatRequest(BaseModel):
    messages: list[Message] = Field(min_length=1, max_length=100)


def sse(data: dict) -> str:
    """One Server-Sent Event: a `data:` line holding JSON, then a blank line."""
    return f"data: {json.dumps(data)}\n\n"


@app.post("/chat")
async def chat(req: ChatRequest):
    messages = [{"role": "system", "content": SYSTEM}] + [m.model_dump() for m in req.messages]
    messages = trim_history(messages, settings().history_tokens)

    async def events():
        async for token in astream_reply(messages):
            yield sse({"type": "token", "text": token})
        yield sse({"type": "done"})

    return StreamingResponse(events(), media_type="text/event-stream",
                             headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
  1. The application object. uvicorn finds it by the name you give on the command line: server:app.line 14
  2. A Pydantic model describes and validates the JSON body, like a Java record with Bean Validation. A body that does not match gets a 422 response before any model call.line 17
  3. Only these two roles are accepted. Clients may not send their own system message: the rules stay on the server.line 18
  4. Limits stop one huge request from running up your bill. messages below accepts 1 to 100 entries.line 19
  5. The whole SSE format: data: , the payload on one line, then an empty line (the \n\n) to end the event. json.dumps never writes a raw newline, so the payload always stays on one line.line 26
  6. Like @PostMapping("/chat"). Because of the type hint req: ChatRequest, FastAPI parses and validates the JSON body into req.line 31
  7. The server puts its own system message first. model_dump() turns each Pydantic object back into a plain dict for the SDK.line 33
  8. An async generator defined inside the endpoint, so it can use messages. Nothing in it runs until FastAPI starts reading from it.line 36
  9. text/event-stream tells clients this is SSE. Cache-Control: no-cache stops caches from keeping the response; X-Accel-Buffering: no asks nginx, if you put it in front later, not to hold the stream back.line 41
hi.json
{
  "messages": [
    {"role": "user", "content": "Say hello and name one sorting algorithm."}
  ]
}
Run
curl -N http://localhost:8000/chat -H "Content-Type: application/json" -d @hi.json
You should seeyour text will differ: the model writes it
data: {"type": "token", "text": "Hello"}

data: {"type": "token", "text": "!"}

data: {"type": "token", "text": " One"}

data: {"type": "token", "text": " sorting"}

...

data: {"type": "done"}
Why this way? Why SSE and not WebSockets? A chat answer flows one way, from server to browser, once per question. SSE is ordinary HTTP, so it passes through proxies, load balancers and your authentication like any other request. WebSockets suit two-way, long-lived traffic such as live collaboration or games. FastAPI also has a built-in EventSourceResponse that formats events for you; writing the three-line sse() yourself shows exactly what goes over the wire.
Stuck on this step?
ERROR: Error loading ASGI app. Could not import module "server"
Start uvicorn from the project folder, the one that contains server.py.
[Errno 48] Address already in use (98 on Linux, 10048 on Windows)
Another program holds port 8000. Stop it, or start uvicorn with --port 8001 and use that port in the URL.
curl prints {"detail":[...]} with a 422
The body does not match ChatRequest. The detail names the field, for example a role other than user or assistant.
7

A web page that shows tokens live

A small page, served by the same FastAPI app, that reads the stream with `fetch` and shows each token as it arrives.

Browsers have EventSource for SSE, but it can only make GET requests without a body, and we need to POST the conversation. So the page uses fetch and reads the body itself: response.body.getReader() hands over the bytes piece by piece, as they arrive.

A piece of bytes is not an event: one read can hold half an event, or three of them. So the page keeps a text buffer, splits it at each empty line (the end of an event), and keeps the unfinished last part for the next read. It is the job the SDK did for you in step 4, done by hand.

The page keeps the conversation in a history array and sends all of it with every question, exactly like messages in the terminal chat. The server stores nothing between requests, so any copy of the server can answer any request.

Save index.html next to server.py and update server.py. uvicorn restarts by itself when you save. Then open the page:

index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Streaming chat</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 680px; margin: 2rem auto; padding: 0 1rem; }
    #log { display: grid; gap: 0.6rem; margin-bottom: 1rem; }
    .msg { padding: 0.6rem 0.8rem; border-radius: 10px; white-space: pre-wrap; }
    .user { background: #e8f0fe; justify-self: end; }
    .assistant { background: #f1f3f4; }
    .error { color: #b00020; }
    form { display: flex; gap: 0.5rem; }
    input { flex: 1; padding: 0.6rem; font: inherit; }
  </style>
</head>
<body>
  <h1>Streaming chat</h1>
  <div id="log"></div>
  <form id="form">
    <input id="question" autocomplete="off" placeholder="Ask something..." required>
    <button id="send">Send</button>
    <button id="stop" type="button" disabled>Stop</button>
  </form>

  <script>
    const log = document.getElementById("log");
    const form = document.getElementById("form");
    const input = document.getElementById("question");
    const sendButton = document.getElementById("send");
    const stopButton = document.getElementById("stop");

    const history = [];    // every {role, content} so far: the server is stateless
    let controller = null; // lets the Stop button cancel the request in progress

    function bubble(role, text) {
      const div = document.createElement("div");
      div.className = "msg " + role;
      div.textContent = text; // textContent, never innerHTML: model output is untrusted
      log.append(div);
      return div;
    }

    function showError(div, answer, message) {
      div.classList.add("error");
      div.textContent = (answer ? answer + "\n" : "") + "[" + message + "]";
    }

    // Read the response body as it arrives and call onEvent for each SSE event.
    async function readEvents(response, onEvent) {
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let buffer = "";
      while (true) {
        const { value, done } = await reader.read();
        if (done) break;
        buffer += decoder.decode(value, { stream: true });
        const events = buffer.split("\n\n"); // a blank line ends each event
        buffer = events.pop();               // the last piece may be incomplete: keep it
        for (const event of events) {
          if (event.startsWith("data:")) onEvent(JSON.parse(event.slice(5)));
        }
      }
    }

    form.addEventListener("submit", async (e) => {
      e.preventDefault();
      const question = input.value.trim();
      input.value = "";
      history.push({ role: "user", content: question });
      bubble("user", question);
      const out = bubble("assistant", "...");
      let answer = "";

      controller = new AbortController();
      sendButton.disabled = true;
      stopButton.disabled = false;
      try {
        const response = await fetch("/chat", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ messages: history }),
          signal: controller.signal,
        });
        if (!response.ok) throw new Error("HTTP " + response.status);
        await readEvents(response, (event) => {
          if (event.type === "token") {
            answer += event.text;
            out.textContent = answer;
          } else if (event.type === "error") {
            showError(out, answer, event.message);
          }
        });
      } catch (err) {
        if (err.name === "AbortError") out.textContent = answer + " [stopped]";
        else showError(out, answer, err.message);
      } finally {
        if (answer) history.push({ role: "assistant", content: answer });
        else history.pop(); // no answer at all: forget the question too
        sendButton.disabled = false;
        stopButton.disabled = true;
        input.focus();
      }
    });

    stopButton.addEventListener("click", () => controller.abort());
  </script>
</body>
</html>
  1. The whole conversation, sent with each question. The server is stateless.line 34
  2. An AbortController per request. Its abort() cancels the fetch it is attached to.line 35
  3. Always textContent for model output. innerHTML would run any HTML the model writes, and a prompt injection can make it write some.line 40
  4. response.body is a ReadableStream. Each reader.read() resolves with the next bytes that arrived, or with done: true at the end.line 52
  5. Bytes to text. stream: true correctly joins a character (an é, an emoji) whose bytes were split across two reads.line 58
  6. Whatever comes after the last empty line is an unfinished event: keep it for the next read.line 60
  7. Strip data: and parse the JSON. JSON.parse skips the space after the colon, so this also reads servers that write data: with no space, as Spring does.line 62
  8. Sends {"messages": [...]}, the shape ChatRequest expects.line 83
  9. Ties this request to the controller, so the Stop button can cancel it.line 84
  10. Each token is appended and the bubble is redrawn: this is the word-by-word effect.line 89
  11. Stop was clicked: fetch or reader.read() rejects with an AbortError. Keep what arrived and mark it as stopped.line 96
  12. No answer at all (an error before the first token): remove the question too, so the history never has a question without an answer.line 100
  13. Aborting closes the connection. The next step makes sure the server, and the model, notice.line 107
server.py 6 new or changed lines
import json
from pathlib import Path
from typing import Literal

from fastapi import FastAPI
from fastapi.responses import FileResponse, StreamingResponse
from pydantic import BaseModel, Field

from config import settings
from history import trim_history
from llm import astream_reply

SYSTEM = "You are a friendly, concise assistant for software developers."
PAGE = Path(__file__).parent / "index.html"

app = FastAPI(title="Streaming chat")


class Message(BaseModel):
    role: Literal["user", "assistant"]
    content: str = Field(max_length=8000)


class ChatRequest(BaseModel):
    messages: list[Message] = Field(min_length=1, max_length=100)


def sse(data: dict) -> str:
    """One Server-Sent Event: a `data:` line holding JSON, then a blank line."""
    return f"data: {json.dumps(data)}\n\n"


@app.get("/")
def page():
    return FileResponse(PAGE)


@app.post("/chat")
async def chat(req: ChatRequest):
    messages = [{"role": "system", "content": SYSTEM}] + [m.model_dump() for m in req.messages]
    messages = trim_history(messages, settings().history_tokens)

    async def events():
        async for token in astream_reply(messages):
            yield sse({"type": "token", "text": token})
        yield sse({"type": "done"})

    return StreamingResponse(events(), media_type="text/event-stream",
                             headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
  1. The page next to server.py, wherever you start the server from. In pathlib, / joins path parts.line 14
  2. The same server serves the page, so the page's fetch("/chat") goes to the same origin and needs no CORS setup.line 33
Run
open http://localhost:8000
You should see
A page titled "Streaming chat". Ask a question: it appears on the right, and the answer grows word by word on the left. Ask a follow-up ("show an example"): the answer uses the earlier messages.
Stuck on this step?
{"detail":"Not Found"} at http://localhost:8000
index.html must be in the same folder as server.py, and server.py must have the @app.get("/") route. Check the uvicorn terminal for a reload error.
The answer appears all at once
Something between the page and the server is buffering: a proxy, a VPN or a browser extension. Open http://localhost:8000 directly, in a private window.
Opening index.html as a file shows [Failed to fetch]
The page must come from the server (http://localhost:8000), not from file://, so fetch("/chat") reaches FastAPI.
8

Stop and errors in the middle of a stream

When the user clicks Stop the model stops too, and a failure halfway through reaches the user as a message, not a broken page.

Two problems exist only with streaming. Cancellation: the user clicks Stop or closes the tab. If your server keeps reading from the model, you pay for tokens nobody will see, and a busy server fills up with abandoned work. Errors mid-stream: when something fails, the server has already sent 200 OK and maybe half an answer. It cannot change the status code any more; the only way to tell the client is an event in the stream.

Cancellation is mostly free here. When the browser disconnects, Starlette (the toolkit under FastAPI) notices and cancels the task running your generator: Python raises asyncio.CancelledError at the await where it waits for the next token. That exception travels up through async with stream in astream_reply, which closes the connection to the model server, and Ollama stops generating. You catch it only to log it, then raise it again.

For errors, wrap the loop in try/except and turn the exception into a {"type": "error"} event with a message that is safe to show. Never send the raw exception text: it can contain internal URLs or details. The page from step 7 already shows error events in red.

One more change, for the tests in the next step: the endpoint now gets its streaming function through Depends(get_streamer), FastAPI's dependency injection. Normally it gives astream_reply; a test can swap in a fake.

Try both. Restart nothing (uvicorn reloads). In the page, ask for something long ("Write 40 lines about databases") and click Stop after a few words. The uvicorn terminal shows:

INFO:     Client disconnected after 12 tokens: stopped the model

Then stop the server with Ctrl+C, start it with a model name that does not exist, and ask anything in the page:

server.py 29 new or changed lines
import asyncio
import json
import logging
from pathlib import Path
from typing import Literal

import openai
from fastapi import Depends, FastAPI
from fastapi.responses import FileResponse, StreamingResponse
from pydantic import BaseModel, Field

from config import settings
from history import trim_history
from llm import astream_reply

SYSTEM = "You are a friendly, concise assistant for software developers."
PAGE = Path(__file__).parent / "index.html"

log = logging.getLogger("uvicorn.error")  # uvicorn already prints this logger
app = FastAPI(title="Streaming chat")


class Message(BaseModel):
    role: Literal["user", "assistant"]
    content: str = Field(max_length=8000)


class ChatRequest(BaseModel):
    messages: list[Message] = Field(min_length=1, max_length=100)


def sse(data: dict) -> str:
    """One Server-Sent Event: a `data:` line holding JSON, then a blank line."""
    return f"data: {json.dumps(data)}\n\n"


def get_streamer():
    """Which function streams the reply. Tests replace it with a fake."""
    return astream_reply


def friendly(err: Exception) -> str:
    if isinstance(err, openai.APITimeoutError):  # check before APIConnectionError: it is a subclass
        return "The model took too long to answer."
    if isinstance(err, openai.APIConnectionError):
        return "Cannot reach the model server. Is Ollama running?"
    if isinstance(err, openai.NotFoundError):
        return f"Model '{settings().model}' not found. Run: ollama list"
    return "The model failed while answering."


@app.get("/")
def page():
    return FileResponse(PAGE)


@app.post("/chat")
async def chat(req: ChatRequest, streamer=Depends(get_streamer)):
    messages = [{"role": "system", "content": SYSTEM}] + [m.model_dump() for m in req.messages]
    messages = trim_history(messages, settings().history_tokens)

    async def events():
        sent = 0
        try:
            async for token in streamer(messages):
                yield sse({"type": "token", "text": token})
                sent += 1
            yield sse({"type": "done"})
        except asyncio.CancelledError:
            log.info("Client disconnected after %d tokens: stopped the model", sent)
            raise  # always re-raise: the server is cancelling this task
        except Exception as err:
            log.warning("Stream failed after %d tokens: %r", sent, err)
            yield sse({"type": "error", "message": friendly(err)})

    return StreamingResponse(events(), media_type="text/event-stream",
                             headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
  1. uvicorn prints this logger (despite the name, it is uvicorn's general log), so your lines appear next to the request lines.line 19
  2. A dependency: FastAPI calls it for each request and passes the result to the endpoint. Tests replace it through app.dependency_overrides, much like @MockBean in a Spring test.line 37
  3. Order matters: APITimeoutError is a subclass of APIConnectionError, so check it first or it can never match.line 43
  4. FastAPI fills streamer with whatever get_streamer() returns.line 58
  5. The client went away and the server is cancelling this task. Log it, then re-raise: swallowing a cancellation leaves the task running.line 69
  6. Anything else, before or after the first token. CancelledError is not a subclass of Exception, so it never lands here.line 72
  7. The real error goes to your log. %r prints the exception with its type.line 73
  8. The client gets a safe, typed error event and keeps the partial answer it already has.line 74
Run
LLM_MODEL=no-such-model uv run uvicorn server:app
You should seeyour text will differ: the model writes it
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     127.0.0.1:52860 - "POST /chat HTTP/1.1" 200 OK
WARNING:  Stream failed after 0 tokens: NotFoundError('Error code: 404 - ...model "no-such-model" not found...')

In the page, in red: [Model 'no-such-model' not found. Run: ollama list]
Stuck on this step?
Windows: the wrong model name stays set
After the test, run Remove-Item Env:LLM_MODEL in that PowerShell window, then start the server again.
No "Client disconnected" line after Stop
The answer had already finished: ask for something longer and click Stop sooner.
9

Test it without a model

Fast tests for the trimming and for the whole streaming endpoint, with a fake model.

Two kinds of tests. trim_history is plain logic: call it with small lists and check what it keeps. The endpoint is tested through FastAPI's TestClient, which calls your app in memory (no server, no port), with a fake streamer: an async generator that yields fixed tokens, swapped in through app.dependency_overrides.

The fakes are the point. One yields three tokens. Another yields a token and then raises, the way a model server that crashes halfway would. You cannot make a real model fail on cue; a fake does it every time, in milliseconds.

test_history.py
from history import estimate_tokens, trim_history


def msg(role, n_chars):
    return {"role": role, "content": "x" * n_chars}


def test_estimate_rounds_up():
    assert estimate_tokens("") == 0
    assert estimate_tokens("abcd") == 1
    assert estimate_tokens("abcde") == 2


def test_keeps_everything_under_budget():
    messages = [msg("system", 40), msg("user", 40), msg("assistant", 40)]
    assert trim_history(messages, budget=1000) == messages


def test_drops_oldest_first_and_keeps_system():
    # each message costs 10 + 4 = 14 tokens
    messages = [msg("system", 40), msg("user", 40), msg("assistant", 40), msg("user", 40)]
    trimmed = trim_history(messages, budget=42)
    assert trimmed[0]["role"] == "system"
    assert [m["role"] for m in trimmed] == ["system", "user"]  # the dangling answer went too
    assert trimmed[-1] is messages[-1]


def test_newest_message_kept_even_if_too_long():
    messages = [msg("system", 40), msg("user", 4000)]
    assert trim_history(messages, budget=50) == messages
  1. A message of n_chars characters. "x" * 40 repeats the string, which makes token counts easy: 40 / 4 + 4 = 14 tokens.line 4
  2. System (14) + the newest question (14) + the answer before it (14) = 42 fits; the oldest question does not. The answer then starts the history, so it is dropped too.line 22
  3. is checks it is the very same object, like == on references in Java. messages[-1] is the last item.line 25
test_server.py
import json

from fastapi.testclient import TestClient

from server import app, get_streamer

client = TestClient(app)


def read_events(response):
    """Parse the SSE body into a list of dicts (one per `data:` line)."""
    return [json.loads(line[len("data: "):]) for line in response.iter_lines() if line.startswith("data: ")]


def use_fake(fake):
    app.dependency_overrides[get_streamer] = lambda: fake


def teardown_function():
    app.dependency_overrides.clear()  # runs after every test


def test_streams_tokens_then_done():
    seen = {}

    async def fake(messages):
        seen["messages"] = messages
        for token in ["Hel", "lo", " there"]:
            yield token

    use_fake(fake)
    with client.stream("POST", "/chat", json={"messages": [{"role": "user", "content": "hi"}]}) as r:
        assert r.status_code == 200
        assert r.headers["content-type"].startswith("text/event-stream")
        events = read_events(r)

    assert events == [
        {"type": "token", "text": "Hel"},
        {"type": "token", "text": "lo"},
        {"type": "token", "text": " there"},  # the leading space survives
        {"type": "done"},
    ]
    assert seen["messages"][0]["role"] == "system"
    assert seen["messages"][-1] == {"role": "user", "content": "hi"}


def test_error_mid_stream_becomes_an_error_event():
    async def broken(messages):
        yield "Half an ans"
        raise RuntimeError("model crashed")

    use_fake(broken)
    with client.stream("POST", "/chat", json={"messages": [{"role": "user", "content": "hi"}]}) as r:
        events = read_events(r)

    assert events[0] == {"type": "token", "text": "Half an ans"}
    assert events[-1] == {"type": "error", "message": "The model failed while answering."}


def test_bad_request_is_rejected_before_streaming():
    r = client.post("/chat", json={"messages": [{"role": "robot", "content": "hi"}]})
    assert r.status_code == 422


def test_page_is_served():
    r = client.get("/")
    assert r.status_code == 200
    assert "getReader" in r.text
  1. Calls the app in-process, like Spring's WebTestClient or supertest in Node.line 7
  2. The same parsing as the page: keep the data: lines and parse their JSON.line 10
  3. From now on every request gets fake instead of astream_reply. lambda: fake is a function with no parameters that returns fake.line 16
  4. pytest runs a function with this name after each test in the file, so one test's fake never leaks into the next.line 19
  5. The same shape as astream_reply: an async generator that takes the messages. It also records what it received.line 26
  6. Read the response as a stream, the way the page does.line 32
  7. The leading space survives, thanks to JSON. Join the tokens and you get "Hello there".line 40
  8. The server added its system message; the client never sends one.line 43
  9. Fails after the first token. The test proves the client gets the partial answer and then an error event, not a broken connection.line 50
  10. Validation runs before any streaming, so a bad body still gets a proper error status.line 62
Run
uv run pytest -q
You should see
........                                                                 [100%]
8 passed in 0.41s
Stuck on this step?
ModuleNotFoundError: No module named 'server'
Run pytest from the project folder with uv run pytest, so the test files can import server.py.

Check it works

Two checks: the tests pass, and a real question streams from your local model. Then open the page once more and try a question, a follow-up and the Stop button.

Test
uv run pytest -q && uv run stream_demo.py "In one sentence, what is streaming?"
You should see
8 passed in 0.41s
Streaming sends data in small pieces as it is produced, so the receiver can use it right away.

[first token after 0.28s, 21 chunks in 0.95s]

Troubleshooting

Tokens arrive in big bursts behind nginx or a load balancer

Proxies buffer responses by default. For nginx, set proxy_buffering off; on this route (the X-Accel-Buffering: no header already asks for it). Compression also holds small chunks back: leave text/event-stream responses uncompressed.

Long answers stop after about 60 seconds behind a proxy

Many proxies close a connection that sends nothing for a while. Tokens keep it busy, but a slow first token can hit the limit. Raise the proxy's read timeout, or send an SSE comment every 15 seconds: a line starting with a colon, like : ping, then an empty line. Clients ignore it, and the page here does too.

The page shows "[Cannot reach the model server. Is Ollama running?]"

Ollama is not running or LLM_BASE_URL is wrong. Open the Ollama app (or run ollama serve) and check .env. The uvicorn terminal shows the real error on its WARNING: line.

The model forgets the start of a long chat

Trimming is working as designed. Raise HISTORY_TOKENS only if the model's context window is larger too: Ollama sets it with the OLLAMA_CONTEXT_LENGTH environment variable on the Ollama server. Production apps also summarise old turns instead of dropping them.

Two browser tabs answering at once are each slower

One local model on one laptop shares its compute between requests. That is expected locally; hosted APIs and serving tools such as vLLM batch requests to handle many users.

What changes in production

  • Stop the model when the client leaves. Check that your stack really does it, as this lab does by closing the SDK stream on cancellation. A server that stops sending but keeps reading from the model pays for every abandoned answer.
  • Decide what an error looks like after 200 OK. Send a typed error event with a safe message, log the real cause with a request id, and let the client keep the partial answer.
  • Keep the history on the server in a real product, under a conversation id. Here the browser sends the history, so a user could edit what "the assistant said" earlier. On the server you can also trim or summarise it in one place.
  • Measure time to first token and tokens per second, not only total time. They are what users feel, and they show whether the model or your code is slow.
  • Limit every request: message length, history size, answer length (max_tokens) and requests per user.

Interview angle

“How would you stream LLM responses to a web client, and what can go wrong?”

I call the model with streaming on and relay each delta to the client over Server-Sent Events from my own server, so the key never reaches the browser. SSE fits because the answer flows one way and it is plain HTTP, so proxies and auth just work; I encode each token as JSON so spaces and newlines survive. The client reads the body with fetch and a stream reader, since it needs a POST. Three things need care. Cancellation: when the client disconnects I cancel the upstream call, otherwise I keep paying for tokens. Errors after the 200 is sent: I send a typed error event and keep the partial answer. And buffering: proxies and compression can hold the stream back, so I turn buffering off for that route and send keep-alive comments if the first token can be slow. I test it with a fake streamer injected into the endpoint, including one that fails halfway.

Clean up

Stop the server with Ctrl+C in its terminal. Keep the project: later labs build on llm.py and history.py.

Practice

No model needed: these run in your browser and check your answer.

Fix the SSE parser

This parse_sse splits each network chunk on its own, so an event that the network cut in two is lost, and an unfinished event at the end is returned as if it were complete. Fix it with a buffer, like readEvents in the page. Return the text after data: for each complete event (remove one space after the colon if there is one), and skip comment lines that start with :.

Exercise
def parse_sse(chunks):
    """chunks: pieces of an SSE body, in the order they arrived."""
    events = []
    for chunk in chunks:
        for event in chunk.split("\n\n"):
            if event.startswith("data: "):
                events.append(event[len("data: "):])
    return events


print(parse_sse(['data: {"a": 1}\n\ndata: {"b"', ': 2}\n\n']))
Hint

Keep a `buffer` string. Add each chunk to it, split it on "\n\n", handle every part except the last, and keep the last part as the new buffer.

Time to first token and tokens per second

Write stream_stats(start, token_times). start is when the request was sent and token_times the time each token arrived, in seconds. Return a dict with "ttft": the first token's time minus start (None if there are no tokens), and "tokens_per_second": the tokens after the first divided by the time from the first to the last token (0.0 with fewer than two tokens).

Exercise
def stream_stats(start, token_times):
    ttft = None
    tokens_per_second = 0.0
    # your code here
    return {"ttft": ttft, "tokens_per_second": tokens_per_second}


print(stream_stats(10.0, [10.5, 10.6, 10.7, 10.9]))
Hint

`token_times[0] - start` is the time to first token. For the rate, use `len(token_times) - 1` and `token_times[-1] - token_times[0]`.

The full project

Every file from this lab, as it is after the last step.

Download Python project (.zip) Download Java project (.zip)