RAG · Lesson 66 of 120
Filters from the Question
Self-querying.
Sometimes the question itself says where to look. In the 2025 price list, how much was the Volt? A self querying retriever uses the model to pull that filter out of the question, then searches only matching chunks.

- The question names a filter
- Model extracts it
- Search only matches
Extracting a filter
Search is a model with the search text, and an optional page. The model fills it from the question, choosing from our page names. Then we search only chunks from that page. Run it. The model picks the 2025 price list, and the search stays inside it.
self_query.pypython
from pydantic import BaseModel
from rag_kit import load_docs, make_chunks, Index
from llm import llm
class Search(BaseModel):
text: str
page: str | None
chunks = make_chunks(load_docs())
pages = sorted({c["source"] for c in chunks})
q = "In the 2025 price list, how much was the Volt?"
s = llm.with_structured_output(Search).invoke(f"Pages: {pages}\nFill the search for: {q}")
print("filter:", s.page)
hits = Index([c for c in chunks if s.page in (None, c["source"])]).search(s.text, 1)
print(hits[0][1]["source"], "|", hits[0][1]["text"][:40])Output
filter: price_list_2025.md price_list_2025.md | # Price list (2025, out of date) This p
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()Summary
A self querying retriever pulls filters out of the question, then searches only the chunks that match. Next, routing.
Key takeaways- Model extracts filter
- Search inside it
- Precise results
Next up: Routing — which source to search