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
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
- Lab 1, Your first LLM call: the setup (uv, Ollama, the model) and the
config.pyidea carry over. - Generators (
yield) help a lot: Iterators and generators. The server usesasyncandawait: async and await. - FastAPI basics are useful but not required: FastAPI.
- Why history must be trimmed: Tokens and context windows.
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.
uv --version
ollama list 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).
curl --versioncurl --versioncurl.exe --version 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.
brew install openjdk@21 mavensudo apt install openjdk-21-jdk mavenwinget install Microsoft.OpenJDK.21 Apache.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.
ollama run llama3.2:3b "Count from 1 to 20, separated by commas." 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
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.
uv init streaming-chat
cd streaming-chat
uv add openai python-dotenv fastapi uvicorn
uv add --dev pytest 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).
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).
# 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 - Ollama's OpenAI-compatible API. Streaming works through the same endpoint.line 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
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")),
) load_dotenv()copies.envintoos.environ. Variables already set in your shell win, which is what you want on a server.line 6- The new field.
frozen=True(the line above the class) keeps settings read-only.line 14 - Environment variables are always strings, so
int(...)converts it, likeInteger.parseIntin Java.line 22
.venv/
__pycache__/
.env - Never commit
.env: it will hold a real key one day.line 3
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.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).
{
"model": "llama3.2:3b",
"stream": true,
"messages": [
{"role": "user", "content": "Name three sorting algorithms."}
]
} - The only difference from a normal call. Leave it out and you get one JSON reply at the end.line 3
curl -N http://localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d @ask.jsoncurl -N http://localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d @ask.jsoncurl.exe -N http://localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d "@ask.json" 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] Stuck on this step?
- Everything prints at once at the end
- You left out
-N, or"stream": trueis missing fromask.json. - Windows:
A parameter cannot be found that matches parameter name 'N' - You typed
curl, which PowerShell turned intoInvoke-WebRequest. Typecurl.exe. Warning: Couldn't read data from file "ask.json"- Run the command in the folder that holds
ask.json(the project folder).
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*.
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 - 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
-> Iterator[str]: returns an iterator of strings.list[dict]is a list of message dictionaries, the format from lab 1.line 11- The only change to the call: the SDK now returns a
Streaminstead of a finishedChatCompletion.line 17 - 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
- Some chunks carry no text (the first can carry only the role, the last only
finish_reason), so skip those.delta.contentis the new piece only, never the whole answer so far.line 21 - Hand this piece to the caller and pause here until the caller asks for the next one.line 22
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]") - The words after the script name, joined into one question.
orsupplies a default when there are none.line 6 time.perf_counter()is a precise clock for measuring durations, likeSystem.nanoTime()orperformance.now().line 12end="": 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 withoutflushyou would see the answer line by line instead of word by word.line 18- If the model sent nothing,
first_token_atis stillNone;or 0prints 0 instead of crashing.line 22
uv run stream_demo.py "What is a cache?" 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=Truein theprint. 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.
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.
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 - Each message also costs a few tokens for its role and the separators around it.line 3
- Round up: 5 characters count as 2 tokens. Overestimating a little is the safe side for a budget.line 8
- Always keep the system message: it holds the rules.
messages[:1]is a new list with just the first item (a slice, likesubList(0, 1)). Thex if condition else yform is Python'scondition ? x : y.line 17 - Walk from the newest message backwards, adding messages while they fit.line 22
- 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
- If trimming dropped a question but kept its answer, drop that orphan answer too, so the history starts with a user message.line 30
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() input()prints the prompt and reads one line from the keyboard, likeScanner.nextLine()..strip()removes spaces and the newline around it.line 17- Ctrl+D (Ctrl+Z then Enter on Windows) raises
EOFError, Ctrl+C raisesKeyboardInterrupt. At the prompt, both end the chat cleanly.line 18 /resetkeeps only the system message.line 26- Trim before every call, so no request goes over the budget.line 31
- Ctrl+C while the answer streams stops only this answer. Leaving the loop runs the
withblock's cleanup instream_reply, which closes the connection, and Ollama stops generating.line 39 - The server could not be reached: remove the unanswered question so the history stays question, answer, question, answer.line 43
- Save the answer, even a stopped one, so the next question has context.
"".join(pieces)glues the pieces together, likeString.join("", pieces).line 46 - Run
main()only when this file is started directly, not when another file imports it. Python's version ofpublic static void main.line 49
uv run chat.py 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 /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 thatHISTORY_TOKENSis 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.
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:
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 - The async client: same settings, but its calls are awaited.line 9
- An **async generator**:
async defplusyield. Callers loop over it withasync for. Python's answer toAsyncIteratorin JavaScript, or aFluxin Reactor.line 26 - This
awaitsends the request and waits for the response headers, not for the whole answer.line 28 - Closes the connection to the model when the loop ends, fails or is cancelled. Step 8 relies on this.line 34
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"}) - The application object. uvicorn finds it by the name you give on the command line:
server:app.line 14 - 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
- Only these two roles are accepted. Clients may not send their own
systemmessage: the rules stay on the server.line 18 - Limits stop one huge request from running up your bill.
messagesbelow accepts 1 to 100 entries.line 19 - The whole SSE format:
data:, the payload on one line, then an empty line (the\n\n) to end the event.json.dumpsnever writes a raw newline, so the payload always stays on one line.line 26 - Like
@PostMapping("/chat"). Because of the type hintreq: ChatRequest, FastAPI parses and validates the JSON body intoreq.line 31 - The server puts its own system message first.
model_dump()turns each Pydantic object back into a plain dict for the SDK.line 33 - An async generator defined inside the endpoint, so it can use
messages. Nothing in it runs until FastAPI starts reading from it.line 36 text/event-streamtells clients this is SSE.Cache-Control: no-cachestops caches from keeping the response;X-Accel-Buffering: noasks nginx, if you put it in front later, not to hold the stream back.line 41
{
"messages": [
{"role": "user", "content": "Say hello and name one sorting algorithm."}
]
} curl -N http://localhost:8000/chat -H "Content-Type: application/json" -d @hi.jsoncurl -N http://localhost:8000/chat -H "Content-Type: application/json" -d @hi.jsoncurl.exe -N http://localhost:8000/chat -H "Content-Type: application/json" -d "@hi.json" data: {"type": "token", "text": "Hello"}
data: {"type": "token", "text": "!"}
data: {"type": "token", "text": " One"}
data: {"type": "token", "text": " sorting"}
...
data: {"type": "done"} 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 8001and use that port in the URL. - curl prints
{"detail":[...]}with a 422 - The body does not match
ChatRequest. Thedetailnames the field, for example a role other thanuserorassistant.
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:
<!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> - The whole conversation, sent with each question. The server is stateless.line 34
- An
AbortControllerper request. Itsabort()cancels thefetchit is attached to.line 35 - Always
textContentfor model output.innerHTMLwould run any HTML the model writes, and a prompt injection can make it write some.line 40 response.bodyis aReadableStream. Eachreader.read()resolves with the next bytes that arrived, or withdone: trueat the end.line 52- Bytes to text.
stream: truecorrectly joins a character (an é, an emoji) whose bytes were split across two reads.line 58 - Whatever comes after the last empty line is an unfinished event: keep it for the next read.line 60
- Strip
data:and parse the JSON.JSON.parseskips the space after the colon, so this also reads servers that writedata:with no space, as Spring does.line 62 - Sends
{"messages": [...]}, the shapeChatRequestexpects.line 83 - Ties this request to the controller, so the Stop button can cancel it.line 84
- Each token is appended and the bubble is redrawn: this is the word-by-word effect.line 89
- Stop was clicked:
fetchorreader.read()rejects with anAbortError. Keep what arrived and mark it as stopped.line 96 - 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
- Aborting closes the connection. The next step makes sure the server, and the model, notice.line 107
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"}) - The page next to
server.py, wherever you start the server from. Inpathlib,/joins path parts.line 14 - The same server serves the page, so the page's
fetch("/chat")goes to the same origin and needs no CORS setup.line 33
open http://localhost:8000xdg-open http://localhost:8000start http://localhost:8000 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:8000index.htmlmust be in the same folder asserver.py, andserver.pymust 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.htmlas a file shows[Failed to fetch] - The page must come from the server (http://localhost:8000), not from
file://, sofetch("/chat")reaches FastAPI.
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:
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"}) - uvicorn prints this logger (despite the name, it is uvicorn's general log), so your lines appear next to the request lines.line 19
- A dependency: FastAPI calls it for each request and passes the result to the endpoint. Tests replace it through
app.dependency_overrides, much like@MockBeanin a Spring test.line 37 - Order matters:
APITimeoutErroris a subclass ofAPIConnectionError, so check it first or it can never match.line 43 - FastAPI fills
streamerwith whateverget_streamer()returns.line 58 - 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
- Anything else, before or after the first token.
CancelledErroris not a subclass ofException, so it never lands here.line 72 - The real error goes to your log.
%rprints the exception with its type.line 73 - The client gets a safe, typed error event and keeps the partial answer it already has.line 74
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.5</version>
</parent>
<groupId>dev.algorung</groupId>
<artifactId>streaming-chat</artifactId>
<version>0.1.0</version>
<properties>
<java.version>21</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project> - Spring Boot 3.4 with Java 21. Spring AI 1.0 needs Spring Boot 3.4 or newer.line 8
- WebFlux, Spring's reactive web stack (on Netty). A controller can return a
Fluxand Spring writes each element as it is emitted.line 30 - The same Ollama starter as lab 1.line 34
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.options.model=llama3.2:3b
spring.ai.ollama.chat.options.temperature=0.7
server.port=8000 - Spring AI talks to Ollama's own API, so no
/v1at the end.line 1 - Port 8000, like the Python server, so the commands and the page stay the same.line 4
package dev.algorung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class StreamingChat {
public static void main(String[] args) {
SpringApplication.run(StreamingChat.class, args);
}
} package dev.algorung;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
@RestController
public class ChatController {
record ChatMessage(String role, String content) {}
record ChatRequest(List<ChatMessage> messages) {}
@JsonInclude(JsonInclude.Include.NON_NULL) // leave out fields that are null
record Event(String type, String text, String message) {}
private static final Logger log = LoggerFactory.getLogger(ChatController.class);
private static final int HISTORY_TOKENS = 2000;
private final ChatClient chat;
private final ObjectMapper json;
ChatController(ChatClient.Builder builder, ObjectMapper json) {
this.chat = builder.defaultSystem("You are a friendly, concise assistant for software developers.").build();
this.json = json;
}
@PostMapping(path = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<String> chat(@RequestBody ChatRequest req) {
List<Message> history = trim(req.messages()).stream()
.map(m -> m.role().equals("assistant")
? (Message) new AssistantMessage(m.content())
: new UserMessage(m.content()))
.toList();
return chat.prompt().messages(history).stream().content()
.filter(token -> !token.isEmpty())
.map(token -> sse(new Event("token", token, null)))
.concatWithValues(sse(new Event("done", null, null)))
.onErrorResume(err -> {
log.warn("Stream failed: {}", err.toString());
return Flux.just(sse(new Event("error", null, "The model failed while answering.")));
})
.doOnCancel(() -> log.info("Client disconnected: stopped the model"));
}
// The same rule as history.py: keep the newest messages that fit, about 4 characters per token.
static List<ChatMessage> trim(List<ChatMessage> messages) {
List<ChatMessage> kept = new ArrayList<>();
int used = 0;
for (int i = messages.size() - 1; i >= 0; i--) {
int cost = (messages.get(i).content().length() + 3) / 4 + 4;
if (!kept.isEmpty() && used + cost > HISTORY_TOKENS) break;
kept.addFirst(messages.get(i));
used += cost;
}
while (kept.size() > 1 && kept.getFirst().role().equals("assistant")) kept.removeFirst();
return kept;
}
private String sse(Event event) {
try {
return json.writeValueAsString(event); // Spring adds "data:" and the blank line
} catch (JsonProcessingException e) {
throw new IllegalStateException(e);
}
}
} - The JSON body
{"messages": [...]}, the same shape the page sends to the Python server.line 24 - Our event shape:
{"type":"token","text":"..."}. Null fields are left out, so a done event is just{"type":"done"}.line 26 - The system message lives on the server, as in Python.line 36
- With
text/event-stream, Spring writes eachStringof theFluxas one SSE event:data:plus the string, then an empty line. No space after the colon; the page handles both.line 40 - Turn the client's messages into Spring AI messages. The cast makes both branches of
? :the same type.line 44 .stream()instead of lab 1's.call(): aFlux<String>that emits each piece of text as Ollama produces it.line 48- Skip empty pieces: the last message from Ollama can carry no text.line 49
- Wrap every token in our JSON event, like
sse({"type": "token", ...})in Python. JSON keeps leading spaces: a rawdata: worldwould lose its space in the browser's parser.line 50 - After the last token, one more element: the done event.line 51
- An error after 200 OK: replace the rest of the stream with one error event, the same idea as
except Exceptionin Python.line 52 - The browser disconnected. Cancelling the
Fluxalso cancels the request to Ollama, so it stops generating.line 56 - The same trimming rule as
history.py.(length + 3) / 4is integer division rounding up.line 60
<!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> - The same
index.htmlas the Python version. Spring Boot servesstatic/index.htmlat/by itself.line 6
Java (Spring AI) version of this step:
LLM_MODEL=no-such-model uv run uvicorn server:appLLM_MODEL=no-such-model uv run uvicorn server:app$env:LLM_MODEL="no-such-model"; uv run uvicorn server:app 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] mvn -q spring-boot:run
# then, in a second terminal (Windows: curl.exe ... -d "@hi.json"):
curl -N http://localhost:8000/chat -H "Content-Type: application/json" -d @hi.json data:{"type":"token","text":"Hello"}
data:{"type":"token","text":"!"}
data:{"type":"token","text":" One"}
...
data:{"type":"done"} Stuck on this step?
- Windows: the wrong model name stays set
- After the test, run
Remove-Item Env:LLM_MODELin 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.
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.
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 - A message of
n_charscharacters."x" * 40repeats the string, which makes token counts easy: 40 / 4 + 4 = 14 tokens.line 4 - 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
ischecks it is the very same object, like==on references in Java.messages[-1]is the last item.line 25
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 - Calls the app in-process, like Spring's
WebTestClientor supertest in Node.line 7 - The same parsing as the page: keep the
data:lines and parse their JSON.line 10 - From now on every request gets
fakeinstead ofastream_reply.lambda: fakeis a function with no parameters that returnsfake.line 16 - 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
- The same shape as
astream_reply: an async generator that takes the messages. It also records what it received.line 26 - Read the response as a stream, the way the page does.line 32
- The leading space survives, thanks to JSON. Join the tokens and you get "Hello there".line 40
- The server added its system message; the client never sends one.line 43
- 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
- Validation runs before any streaming, so a bad body still gets a proper error status.line 62
uv run pytest -q ........ [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 importserver.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.
uv run pytest -q && uv run stream_demo.py "In one sentence, what is streaming?" 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 :.
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).
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.