RAG · Lesson 102 of 120
Streaming over HTTP
Text as it arrives.
A web page can show the answer as it's written, just like in the terminal. FastAPI's streaming response sends each piece to the browser as soon as the model produces it.

- Show text as written
- Streaming response
- Piece by piece
A streaming endpoint
Pieces is a generator. It retrieves first, then yields each piece of the model's answer. Streaming response sends them as they come. The test client reads the stream piece by piece. Run it. The answer arrives in several pieces.
stream_api.pypython
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from fastapi.testclient import TestClient
from rag_kit import load_docs, make_chunks, Index
from llm import llm, PROMPT
app = FastAPI()
index = Index(make_chunks(load_docs()))
def pieces(q):
context = "\n\n".join(c["text"] for s, c in index.search(q))
for chunk in llm.stream(PROMPT.format(context=context, question=q)):
yield chunk.text
@app.get("/stream")
def stream(q: str):
return StreamingResponse(pieces(q), media_type="text/plain")
q = "How should I store the battery for a month? Two sentences."
with TestClient(app).stream("GET", "/stream", params={"q": q}) as r:
print(len(list(r.iter_text())), "pieces received")Output
3 pieces received
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter
def load_docs(folder="data/rag/northwind"):
return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]
def make_chunks(docs, size=300, overlap=50):
splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
return [{"source": d["source"], "text": t.replace("\n", " ")}
for d in docs for t in splitter.split_text(d["text"])]
embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
def embed(texts):
return embedder.encode(texts, normalize_embeddings=True)
class Index:
def __init__(self, chunks):
self.chunks = chunks
self.vectors = embed([c["text"] for c in chunks])
def search(self, query, k=3):
scores = self.vectors @ embed([query])[0]
top = np.argsort(-scores)[:k]
return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]Also uses llm.py
from langchain.chat_models import init_chat_model
llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".
Context:
{context}
Question: {question}"""
def answer(question, chunks):
context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()In the browser
In the browser, read the response with fetch, and a stream reader. Add each piece to the page as it arrives. Send sources at the end, or in a separate request.
| key | value |
|---|---|
| Server | StreamingResponse |
| Browser | fetch + reader |
| Show | each piece |
| Sources | at the end |
Summary
Streaming responses send the answer piece by piece, so users see it right away. Next, monitoring.
Key takeaways- Generator
- StreamingResponse
- Read the stream
Next up: Monitoring — log questions and misses