Skip to content

RAG FAQ: more questions

The long tail of FAQ.md: run stories (what a lab run showed, and the lesson) and smaller details. Start with FAQ.md.

What do #0, #1, #2 after a file name mean?

  • The chunk ID: file name plus the chunk's position in that file, counting from 0. datasheet-helmet-yel.md#2 is its third chunk, the "Replacement" section.
  • Set in chunk_by_heading(): f"{doc.name}#{len(chunks)}".
  • Unique IDs let the store update or delete chunks, let RRF merge the same chunk from two lists, and make citations traceable.
  • Production systems often use stable IDs such as returns-policy.md#bulk-orders, so adding a section doesn't renumber the rest.

Why did keyword search rank the helmet chunk first for a refund question?

  • The question "how long until my money comes back after a return" shares almost no exact words with the Refunds section.
  • BM25 has no stemming here: "return" doesn't match "returned", "refund" doesn't match "money".
  • The helmet chunk is short and says "after" twice, so a filler word won.
  • Vector search matched the meaning (Refunds first), and hybrid kept that result on top.
  • Fix the keyword side with stemming and stopwords (a search engine's analyzer does both).
  • They are RRF scores, not similarity: each list adds 1 / (60 + rank).
  • Rank 1 in both lists gives the maximum, 2/61 = 0.0328. Rank 1 in one list only gives about 0.0164.
  • They say how strongly the two searches agree, not how relevant a chunk is.
  • So don't use them for a "nothing found" cut-off; use the vector similarity for that.

Why did a bolt datasheet come up for "Do you sell solar panels?"

  • Keyword search matched the word "do" ("Do not mix with zinc-plated nuts").
  • Common words (do, you, the, for) create junk keyword matches when nothing better exists.
  • Fix: drop stopwords in tokens() before BM25; Elasticsearch, OpenSearch and Solr do this with an analyzer.
  • The prompt's "I don't know" rule still saved the answer, which is why you need more than one defence.

Are Solr synonyms the keyword-search answer to meaning?

  • Yes. Synonyms are hand-written meaning: TMT bar, rebar, sariya expands the query to all three, then BM25 scores as usual.
  • Embeddings learn similarity automatically but are weak on trade jargon and local terms.
  • Best of both: curated synonyms (MS, GI, HR/CR, Fe 500D, local names) on the keyword side, embeddings on the vector side, merged with RRF.
  • Mine zero-result queries from search logs to find missing synonyms.
  • Solr 9.x also supports vector and hybrid search natively.

Why do the scripts add "search_query:" and "search_document:" to the text?

  • nomic-embed-text was trained with these task prefixes; leaving them out quietly lowers retrieval quality.
  • Other models use different conventions or none, so check the model card.
  • See embed() in rag.py.

Chunking

How does the chunker know where a section starts and ends?

  • It doesn't understand the text. It follows the markers the author already wrote: every line starting with ## starts a section.
  • re.split(r"^## +", body, flags=re.M) cuts the body at each ##; the first line of each piece is the heading, the rest is the section text.
  • A section longer than max_chars is split again on sentence ends (. ! ?) by pack_sentences(), never mid-sentence.
  • The header line ("Returns Policy > Bulk orders") is added by code from the doc title and the heading.
  • No markers to follow: use HTML <h2>, Word heading styles or PDF font sizes; else paragraphs (blank lines), then sentences; or semantic chunking (cut where embedding similarity between neighbouring sentences drops).

Storing and updating

When do I need to re-embed everything?

When you change the embedding model or the chunker: delete store/ and run again.

What does vector search look like in SQL?

With pgvector, it is one column, one index and an ORDER BY on distance (<=> is cosine distance):

CREATE EXTENSION vector;
CREATE TABLE chunks (id text PRIMARY KEY, text text, tier text, embedding vector(768));
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);

SELECT id, text, 1 - (embedding <=> $1) AS similarity
FROM chunks
WHERE tier IN ('all', 'gold')          -- metadata filter, plain SQL
ORDER BY embedding <=> $1              -- nearest first, uses the HNSW index
LIMIT 5;

Answers and quality

The model cited with 【】 instead of [ ]. Does that matter?

Not if your check parses loosely. gpt-oss on Groq writes 【returns-policy.md】 even when the prompt asks for square brackets: models follow formatting loosely.

  • cited() in rag.py accepts any bracket style; check_citations() stays strict on the file name (it must be a retrieved source).
  • Lab 04 prints the check per answer (answer(q, check=True)).
  • Rule of thumb: parse loosely, check strictly. Never make a fact check depend on the exact punctuation a model chose.

Why did hybrid search score worse than vector search in the evaluation?

  • In the 09 run: vector 100% hit@3, hybrid 83%. Keyword search returned junk for two questions, and RRF gave that junk an equal vote.
  • The junk came from a weak keyword side: no stopwords ("the", "after" matched), no stemming ("storage" vs "stored"), and no synonyms ("drill" vs "power tools").
  • Fix the keyword side first (analyzer: stopwords, stemming, synonyms), or weight the vector list higher in rrf().
  • The golden set has only two code-style questions, so it favours vectors; add SKU, order ID and standard-number questions before deciding.
  • The lesson: "hybrid is better" is a default, not a law. Measure on your own data.

Does turning on thinking (think=True) fix reasoning errors?

  • Often. In the 06 run, it fixed the silver "excluding safety gear" answer with the original wording.
  • It costs latency and tokens: answers come back slower and longer, often in heavy markdown.
  • It doesn't stop new mistakes: the gold answer invented "Rs 300 if order value below Rs 25,000" by merging two rules, and one citation pointed to the wrong file.
  • Fix the content first (cheap, permanent); use thinking for questions that need multi-step reasoning; keep evals for both.

Why does the answer say "depends on your tier" when we already filtered by tier?

  • The filter limits which chunks the model sees; it doesn't tell the model who is asking.
  • Pass the customer context from server-side code into the prompt, for example "Customer tier: gold", next to the question.
  • Never take that context from the user's message; it comes from your session or auth.

What if the follow-up rewrite fails?

  • It can fail silently: in the 07 run, "And for bulk orders?" came back unchanged, so search used the bare follow-up.
  • It still worked only because "bulk orders" were the right keywords; "Is there a fee for that?" would not have.
  • Always log the rewritten query; it is the first thing to check when a chat answer is wrong.
  • One example in the rewrite prompt fixed it: the rerun turned "And for bulk orders?" into "What is the return window for bulk orders?". Examples (few-shot) beat extra instructions for small models.
  • Without rewriting, the model saw shipping and credit fees and asked the user to clarify: a safe failure, but a worse experience.

Is an "agent" mainly about decision-making?

  • Yes: an agent is an LLM that decides its next step, in a loop, using tools, until a goal is met.
  • Decisions alone aren't enough; it also needs tools to act and a loop to keep going.
  • Autonomy is a dial, not a switch: fixed pipeline -> router (picks one path) -> tool loop (example 10) -> multi-step planner -> multi-agent.
  • More autonomy means more flexibility, but also more cost, latency, testing effort and guardrails.
  • Covered in depth in the Agents topic.

Why did the agent cite files that don't exist?

  • In the 10 run, it cited [stock-check.md] and [price-quote.md] for numbers that came from get_stock and get_price.
  • The prompt said "cite sources in brackets", so the model invented a file name for every fact, including tool results.
  • Tell it how to cite tool data ("say 'live stock' or 'live price'; cite only files returned by search_docs").
  • Validate in code: every cited name must be in the sources actually returned, else flag or strip it.
import re
def bad_citations(answer: str, returned_sources: set[str]) -> list[str]:
    return [c for c in re.findall(r"\[([^\]]+\.md)\]", answer) if c not in returned_sources]