RAG · Lesson 83 of 120
Condensing the Question
Stand-alone queries.
The fix is to condense. Before searching, the model rewrites the follow up into a question that stands on its own, using the history. Then search and answer work as usual.

- Rewrite first
- Use the history
- Then search
Condense, then answer
Condense gives the model the history, and asks for a standalone question. We search and answer with that question. Run it. The condensed question is about renting an e-bike in York for a week, and the answer has the real price.
condense.pypython
from rag_kit import load_docs, make_chunks, Index
from llm import llm, answer
index = Index(make_chunks(load_docs()))
history = ["Customer: Can I rent an e-bike in York?",
"Assistant: Yes, you can rent bikes from our Leeds and York stores."]
def condense(follow_up):
chat = "\n".join(history)
return llm.invoke(f"{chat}\n\nRewrite this follow-up as a standalone question. "
f"Reply with the question only.\nFollow-up: {follow_up}").text.strip()
q = condense("And how much for a week?")
print("condensed:", q)
print("answer: ", answer(q, [c for s, c in index.search(q)]))Output
condensed: How much does it cost to rent an e-bike for a week in York? answer: Based on the provided context, it costs £120 per week to rent an e-bike.
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()Condensing tips
Only condense when there is history. Keep the last few turns, not the whole chat. Show the customer an answer to what they actually asked. And log the condensed question, it helps when debugging.
| key | value |
|---|---|
| First turn | no need |
| History | last few turns |
| Answer | their real question |
| Log | the condensed one |
Summary
Condense each follow up into a standalone question, then search and answer as usual. Next, agentic RAG.
Key takeaways- Use history
- Standalone question
- Search as usual
Next up: Agentic RAG — retrieval as a tool