RAG FAQ¶
The top questions, short answers with pointers to the code. New questions are added as they come up. Run stories (what a lab run showed, and the lesson) and smaller details are in FAQ-more.md.
Embeddings and search¶
What is an embedding?¶
- A list of numbers (768 for nomic-embed-text) that summarises what a piece of text means.
- Similar meaning gives vectors pointing the same way, so cosine similarity is close to 1.
- See
01_embeddings.py.
How do I read the similarity scores?¶
- Look at the gap to the next result, not the number itself.
- In the 01 run, "When will my parcel arrive?" scored 0.693 for delivery and 0.666 for invoices: the right answer barely won.
- Never use a fixed cut-off such as "above 0.6 is relevant".
- Fetch more chunks than you need, then rerank (
08_reranking.py).
What is hybrid search?¶
- Run two searches on the same question and merge the results.
- Keyword search (BM25) matches exact words: good at SKUs, standards, order IDs; bad at paraphrases ("send back" vs "returns").
- Vector search matches meaning: good at paraphrases; bad at codes.
- Scores are on different scales, so merge by rank with Reciprocal Rank Fusion: each list gives a chunk
1 / (60 + rank), and chunks ranked well in both lists win. - See
hybrid_search()andrrf()inrag.py, and05_hybrid_search.py.
What does BM25 mean, and why is keyword search BM25?¶
"Best Matching 25", the 25th version of a ranking formula from the Okapi search system (City University London, 1990s). It is the default ranking in Lucene, Elasticsearch, OpenSearch and Solr, so "keyword search" today usually means BM25.
| Factor | Idea |
|---|---|
| Rarity (IDF) | Rare words count more. HARNESS-6P in 1 chunk beats orders in 10. |
| Frequency, with saturation | More mentions help, with diminishing returns, so keyword stuffing doesn't win. |
| Chunk length | A match in a short chunk counts more than one buried in a long chunk. |
| Trade-off | No model, fast, explainable, exact. Blind to meaning. |
If vectors understand meaning, why can't they match a SKU even more easily?¶
- A SKU has almost no meaning, and an embedding is a summary of meaning, not a copy of the characters.
- The model splits
BOLT-M8-40into fragments (BOL,T,-M,8,40); numbers carry little meaning. - Look-alike codes get near-identical vectors:
BOLT-M8-40,BOLT-M8-45,BOLT-M10-40all read as "some bolt".ORD-0042vsORD-0043is pure noise. - In the 01 run, the query
BOLT-M8-40ranked the gloves sentence first, all scores within 0.11. - BM25 treats the code as one exact token. Many teams skip search entirely when a regex says the query is a SKU, order ID or GSTIN, and look it up directly.
How do I tell when nothing relevant was found?¶
- Vector search always returns k results, even for questions the docs don't cover.
- Two signals in the 03 run: a low top score (solar panels 0.54 vs about 0.80 for real matches) and a flat list (0.542, 0.516, 0.515, no clear winner).
- A minimum score works, but tune it per embedding model on real queries; the numbers shift when the model changes.
- Back it up with the prompt's exact "I don't know" reply, and measure refusals in
09_evaluation.py --answers.
Chunking¶
Why chunk at all? Is it so the model can take it in one go?¶
- Only partly. The input limit (about 8K tokens for nomic-embed-text) matters only for very long documents.
- Precision: one vector per document is a blurred average of every topic in it; a chunk about one thing matches exactly.
- Cost and accuracy: 3 to 5 chunks are cheaper and faster than whole documents, and models miss facts buried in long prompts.
- Citations and access control work per section, not per file.
- Exception: a small corpus (under 50 to 100 pages) that rarely changes and everyone may see can go straight into the prompt, with prompt caching.
What is overlap for, and how do I choose it?¶
Overlap repeats the end of one chunk at the start of the next, so a fact cut at a boundary is whole in at least one chunk. In the 02 run, chunk 0 ended with "Bulk orders (more than 5", and chunk 1 still had the full rule. Measured on returns-policy.md with 300-character chunks:
| Overlap | Chunks | Policy lines intact |
|---|---|---|
| 0 | 4 | 7/10 |
| 50 | 5 | 9/10 |
| 100 | 6 | 10/10 |
| 150 | 8 | 10/10, almost 2x the storage |
Start at 10 to 20% of chunk size, at least as long as your longest important sentence. Cutting on structure (chunk_by_heading) removes most of the need. Confirm with 09_evaluation.py.
What chunk size should I use?¶
- 200 to 800 tokens is the usual range: too small loses context, too big dilutes the match.
- Cut on the document's own structure first: headings, FAQ entries, table rows.
- Add a "Title > Section" header to every chunk so it makes sense on its own.
- Measure on your golden set.
How do I chunk tables and PDFs?¶
- Tables: one chunk per row (or a few rows), repeating the column headers in each.
- PDFs: the hard part is extracting clean text with headings. Check the extracted text before tuning chunk size.
- Lab 11 does both:
messy.pydrops running headers, carries a table's header across a page break and fills Excel's merged cells.
Storing and updating¶
Why store and retrieve? Is storing just for reuse?¶
Two separate jobs. Store is for reuse: embed every chunk once, offline. Retrieve is for selection: per question, pick the few chunks worth sending.
| Ingest (store) | Query (retrieve) | |
|---|---|---|
| When | Once, then on doc changes | Every question |
| Embeds | Every chunk (slow at scale) | Only the question (one call) |
| Code | ingest() |
hybrid_search() then generate() |
- Without storing, every question would re-embed the whole corpus: seconds for 33 chunks, hours for a million.
- The store also gives a search index, metadata filters, and one shared copy for every user and server.
- Retrieval is the point of RAG, not an optimisation: it is how only 3 to 5 relevant chunks reach the model.
What happens when a document changes?¶
ingest()stores a hash of each document with its chunks.- Unchanged docs are skipped; changed docs have old chunks deleted and new ones added; deleted files are removed.
- See
03_ingest_and_search.py.
Why a vector database? Why not SQL or NoSQL?¶
- The data is ordinary (id, text, metadata, a list of 768 numbers); any database can store it.
- The query is the hard part: "find the 5 vectors closest to this one". A normal B-tree index can't answer that, so the database compares against every row.
- Brute force is fine up to tens of thousands of chunks; at millions, each query scans gigabytes.
- A vector index (HNSW, IVF) finds near neighbours in milliseconds by checking a small part of the data. It is approximate: it can miss a few true matches (recall around 95 to 99%).
- "Vector database" is a capability, not always a separate product: pgvector (Postgres), MongoDB Atlas, OpenSearch, Elasticsearch and Solr 9.x all add vector indexes.
- Chroma is used here because it is a pip install with no server.
Which should we use in production?¶
- Already on Postgres and under a few million chunks: pgvector. Joins, filters, transactions and backups come free.
- Already running Elasticsearch, OpenSearch or Solr: use their vector support, and get BM25 and hybrid in one place.
- Hundreds of millions of vectors, or heavy filtered search at scale: a dedicated store (Qdrant, Weaviate, Milvus, Pinecone).
- Avoid a new database just for RAG unless scale demands it: one more system to sync, secure and back up.
Answers and quality¶
Which retrieved chunks does the LLM use? Is it based on the score?¶
- Two decisions. Code decides what is sent: the top k by score (
k=4inanswer()); there is no score cut-off in this repo. - The LLM never sees the scores.
build_prompt()sends only the source name and the text. - The LLM decides what to use by reading: it matches the question against each chunk's text and ignores the rest.
- In the 04 run, the gold pricing chunk was sent for the shipping question and the model ignored it.
- Every irrelevant chunk is noise that can mislead a small model, so improve what is sent: better search (05), filters (06), reranking (08), a minimum score.
When is reranking worth it?¶
- When search returns the right chunk but ranks it low (say 4th to 10th), so it would miss the top 3.
- In the 08 run, hybrid search already had the answer first; reranking only reshuffled places 2 and 3, for an extra LLM call.
- Measure first: if hit@3 is already high on your golden set, reranking mostly adds latency.
- An LLM reranker takes seconds; a dedicated cross-encoder (bge-reranker, Cohere Rerank) takes tens of milliseconds.
- Common setup: retrieve 20 to 50, rerank, keep 3 to 5.
How do I stop the model making things up?¶
- Tell it to answer only from the context, with an exact reply for "not found" (
NO_ANSWERinrag.py). - Don't call the model at all when nothing was retrieved.
- Check citations in code.
- Measure how often it still happens with
09_evaluation.py --answers. Prompts reduce hallucination; they don't remove it.
How do I keep one customer from seeing another's data?¶
- Filter inside the database query, using metadata on every chunk (tier, tenant_id).
- Never rely on a prompt instruction, and never take identity from the user's message.
- See
06_metadata_filters.py.
Retrieval was right, so why was the answer still wrong?¶
- In the 06 run, the silver customer got exactly the right chunk, and the model still answered "8% discount ... but excluded", contradicting itself.
- Small models are weak at exceptions and negation ("all items, excluding safety gear").
- Filters fix what the model sees, not how well it reasons. Debug retrieval first, then generation.
- Fixes: clearer source text ("Safety gear gets no silver discount"), a stronger model or
think=True, and an eval case for every exception rule.
How should documents be written so RAG answers well?¶
- State exceptions as their own plain sentence: "Safety gear gets no silver discount" beats "all items, excluding safety gear".
- In the 06 run, that one-line change fixed the silver answer with no code change.
- One fact per sentence, with the product or rule named in it, so a chunk makes sense on its own.
- Avoid two documents that state the same rule differently; pick one source of truth and link to it.
- Treat content as part of the system: review policy docs for RAG the way you review code.
Should prices and discounts come from RAG?¶
- No. Rules that produce a number (discounts, tax, credit limits) belong in code or a pricing service, called as a tool.
- RAG explains policy ("why is there no discount on helmets?"); a tool computes the price for this customer.
- Code gives the same answer every time and can be unit-tested; an LLM reading prose can't promise either.
- See
../llm-api/catalog.py(get_price) and10_agentic_rag.pyfor both together.
Why is example 10 called "agentic" RAG?¶
"Agentic" means the model, not your code, decides the steps. Same search function, different driver:
| Pipeline RAG (04) | Agentic RAG (10) | |
|---|---|---|
| Who decides to search | Code, always, once | The model, only if it thinks it needs to |
| Search query | The user's exact words | Written by the model ("return fee") |
| Number of searches | Exactly one | Zero, one or several, in a loop |
| Other sources | None | Can also call get_stock, get_price |
| Trade-off | Predictable, cheap, easy to test | Flexible, but slower and more ways to fail |
Use a pipeline when every question needs the same steps; go agentic when questions mix sources or need several steps.
How do I apply tier or tenant filters when retrieval is a tool?¶
- The model calls
search_docs(query), so it can't be trusted to pass the right filter, and in the 10 run search returned a silver pricing chunk with no filter at all. - Build the tool per request in server-side code, with the customer's filter fixed inside it; the model only supplies the query.
def make_search_docs(tier: str):
def search_docs(query: str) -> dict:
"""Search company documents ... (same docstring as before)"""
hits = hybrid_search(query, k=3, where=tier_filter(tier)) # filter bound here, not by the model
return {"results": [{"source": h.meta["source"], "text": h.text} for h in hits]}
return search_docs
run_agent(question, [make_search_docs(session.tier), get_stock, get_price], SYSTEM)
How do I know if my RAG is any good?¶
- Keep a golden set of real questions with the section that answers each.
- Measure retrieval (hit@k, MRR) and answers (key facts present, refuses when it should) separately.
- Start with 30 to 50 questions from support tickets or search logs; run on every change.
- See
09_evaluation.py.
RAG or tool calling?¶
- RAG for text that explains: policies, manuals, specs.
- Tool calls for live data: stock, prices, order status.
- Real assistants use both; see
10_agentic_rag.py.
Messy files and databases¶
What about scanned PDFs and photos?¶
- A scan has no text layer, so a text parser returns nothing;
scanned_pages()inmessy.pyfinds those pages. - Route them to OCR (Tesseract, a cloud document AI) or a vision model, as in
../whatsapp-agent/09_photo_order.py. - Never index a file that produced no text without saying so: a silent gap looks like "the answer isn't in our documents".
RAG or text-to-SQL?¶
| Question | Use | Why |
|---|---|---|
| "What is the return window for bulk orders?" | RAG (04) | The answer is a passage in a document |
| "What was revenue in September?" | Text-to-SQL (12) | The answer is a SUM over rows; no chunk holds it |
| "Is BOLT-M8-40 in stock?" | A tool (10) | One live value from a system you own |
How do I evaluate text-to-SQL?¶
- Run the model's SQL and a hand-written gold query, then compare the rows (execution accuracy). Don't compare SQL text: two different queries can both be right.
same_result()intext_to_sql.pyignores row order and extra columns.- A query that runs but answers the wrong thing raises no error. Only the golden set catches it.
- Grow the set from real questions, and keep ones whose gold answer is unambiguous.
How do I stop text-to-SQL leaking another customer's data?¶
- Not with a prompt rule: the model can be talked out of it (lab 13, part 2).
- Rewrite the SQL in code: every customer table becomes "only this customer's rows", with the ID from the login (
scope_to_customer()insql_guard.py). - In Postgres, use row-level security with a per-request setting, and a read-only database user.
- Scoping stops the leak, not a wrong answer: asked about another company, the model ran on the user's own rows and named them as the other company's.
names_other_customer()refuses those questions first.
Why parse the SQL when the connection is already read-only?¶
- Read-only stops writes, not reads:
sqlite_master, other customers' rows and a never-ending query are all reads. - Each layer catches what another misses, so one bug doesn't become a breach (
sql_guard.pylists all four). - Refusals are not retried: a retry asks the model to find a way around the guard.
Free SQL or a semantic layer?¶
- Free SQL answers anything, including what you didn't mean to allow. Good for internal analysts who read the SQL.
- A semantic layer (
semantic.py) answers only the metrics you defined, the way finance defined them, and says "can't answer" otherwise. - Customer-facing: semantic layer. Internal: free SQL behind the guards. Many teams start with the second and move to the first.