RAG · Lesson 45 of 120
Streaming the Answer
Word by word.
Waiting several seconds for a full answer feels slow. Streaming shows the answer as it's written, a few words at a time. The total time is the same, but it feels much faster.

- Waiting feels slow
- Show words as they come
- Feels faster
Streaming tokens
Stream works like invoke, but returns pieces as they arrive. We print each piece straight away, with no new line, and count them. Run it. The answer appears in pieces, and we see how many there were.
streaming.pypython
from rag_kit import load_docs, make_chunks, Index
from llm import llm, PROMPT
index = Index(make_chunks(load_docs()))
q = "How should I store the battery if I stop riding for a month? Two sentences."
context = "\n\n".join(c["text"] for s, c in index.search(q))
pieces = 0
for chunk in llm.stream(PROMPT.format(context=context, question=q)):
print(chunk.text, end="", flush=True)
pieces += 1
print(f"\n({pieces} pieces)")Output
Store the battery at about 60 percent charge. Check it every 3 months and top it up to 60 percent if needed. (5 pieces)
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()Streaming in apps
In a web app, send each piece to the browser as it arrives. Retrieval still happens first, so show a searching message while it runs. And with structured output, stream only the answer text.
| key | value |
|---|---|
| Web apps | send each piece |
| Retrieval | happens first |
| Show | searching... |
| Structured | stream the text |
Summary
Streaming prints the answer piece by piece, so users see progress right away. Next, building RAG as a LangChain chain.
Key takeaways- llm.stream
- Print as it comes
- Feels fast
Next up: A RAG Chain — LangChain pipes