RAG · Lesson 62 of 120
Query Decomposition
Split big questions.
Some questions ask two things at once, like delivery costs and refund times. One search can't find both well. Query decomposition splits the question into simple parts, and searches for each.

- Two things at once
- One search struggles
- Split it up
Splitting a question
Parts is a list of simple questions, filled by the model. We search for each part on its own. Run it. Each part finds exactly its own page.
decompose.pypython
from pydantic import BaseModel
from rag_kit import load_docs, make_chunks, Index
from llm import llm
class Parts(BaseModel):
questions: list[str]
index = Index(make_chunks(load_docs()))
q = "How much is UK delivery, and how long do refunds take?"
parts = llm.with_structured_output(Parts).invoke(f"Split into simple, separate questions: {q}")
for p in parts.questions:
print(p, "->", index.search(p, 1)[0][1]["source"])Output
How much is UK delivery? -> shipping.md How long do refunds take? -> returns.md
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()Decompose, then answer
The big question goes in. The model splits it into parts. We retrieve chunks for each part. We pool all the chunks. And the model answers the whole question at once.
- Big question
- Split
- Retrieve each
- Pool chunks
- Answer

Summary
Split multi part questions, retrieve for each part, then answer with all the chunks together. Next, parent documents.
Key takeaways- Split parts
- Search each
- Answer once
Next up: Parent Documents — find small, read big