Why my RAG kept returning the wrong chunks
One vector search across a mixed corpus returns confident nonsense, because semantic closeness is not topical relevance. Filtering on metadata first, then searching, then reranking fixed it. Here is what each stage actually earns.
On this page
Internal teams kept asking the same kinds of questions of the same long handbooks and policy documents, and kept getting bad answers. Keyword search missed the context. So I reached for the obvious upgrade: single-shot RAG over the whole corpus. Embed every chunk, embed the question, pull the top matches by cosine similarity, put them in the prompt. It demoed well and then fell over on real questions. The fix that held up was metadata-filtered RAG: a retriever that narrows the candidates by metadata before semantic search ever runs.
The failure was specific and frustrating. A question about one section of one document would still pull chunks from several unrelated documents that happened to share vocabulary. A question about parental leave, for example, could come back as a confident, well-written answer half-built from the sabbatical policy. The model wasn't inventing anything; it was faithfully summarising the wrong chunks I handed it. Top-k similarity on a corpus with many topics has no idea which document or section a question belongs to.
It was my first production AI system, and the fix wasn't exotic machine learning. It was plumbing and judgement.
Why single-shot similarity returns junk
Embedding similarity measures semantic closeness, not topical relevance, and those aren't the same thing. "Notice period for resignation" and "notice period for ending a vendor contract" sit close together in vector space, with the same words and the same shape, and a cosine ranker can't tell that one belongs in the HR handbook and the other in the procurement policy.
On a corpus about one topic this rarely bites. On one that spans several departments it bites constantly, because a question's nearest neighbours are scattered across documents that have nothing to do with it. Raising k to compensate just feeds more off-topic chunks to the model and makes the answer worse.
The instinct is to throw a bigger model or a better embedding at it. The real fix is earlier in the pipeline: narrow the candidates before you ever compute similarity.
Attach metadata at ingest, because that's where the work is
The whole pipeline depends on one decision made when documents are ingested: every chunk carries metadata. When I split a document, I don't just store the text and its vector; I store where it came from.
def chunk_document(doc: Document) -> list[Chunk]:
chunks = []
for section in split_into_sections(doc): # respect headings
for piece in window(section.text, size=800, overlap=120):
chunks.append(Chunk(
text=piece,
embedding=None, # filled in batch later
metadata={
"source": doc.filename, # "hr-handbook-2026.pdf"
"section": section.heading, # "Parental Leave"
"tags": doc.tags, # ["hr", "benefits"]
"doc_type": doc.type, # "policy"
},
))
return chunks
Two things matter here. First, chunk on the document's structure, not blindly on character count: splitting along headings keeps section meaningful, so "Parental Leave" stays one coherent unit instead of bleeding into the next policy. Second, the metadata isn't decoration. It is the filter for the first step, and bad metadata at ingest means a useless filter later, so this is the step worth being slow and careful about.
Filter, then search, then rerank
With metadata in place, retrieval becomes three steps instead of one: a metadata filter, vector similarity, then an LLM rerank.
def retrieve(query: str, filters: dict, k: int = 6) -> list[Chunk]:
# Stage 1: cheap metadata pre-filter. Off-topic chunks never
# reach the vector search at all.
candidates = store.where(filters) # e.g. {"tags": "hr"}
# Stage 2: semantic search *within* the filtered set.
q_vec = embed(query)
ranked = top_k(candidates, q_vec, k=k * 3) # over-fetch on purpose
# Stage 3: LLM rerank of the survivors for true relevance.
return llm_rerank(query, ranked)[:k]
The order is the point. The metadata filter runs first, so an off-topic chunk is gone before vector search sees it; it can't sneak into the top results however similar its wording. Vector similarity then does what it's good at: ordering chunks that are already on topic. Finally, a cheap rerank reads the survivors and reorders them by how well each one answers the question, catching the cases where two chunks are equally "close" but only one helps.
Why rerank at all, when the filter has already narrowed things? Because the filter is coarse, it knows the topic but not the intent, and cosine ordering is approximate. The rerank is the precision step, and with a small, bounded input it's affordable. I deliberately over-fetch (k * 3) into it and let it cut down, rather than trusting the raw similarity order.
Where does the filter come from? Sometimes the interface scopes it ("ask within HR"). More often the agent infers it, which is the other half of the system.
An agent loop, not a single RAG call
Even good retrieval is the wrong tool for some questions. "Summarise the parental leave policy" wants retrieval. "List every deadline in section 4" wants deterministic extraction, not fuzzy semantic search, and single-shot RAG is bad at it: it grabs three chunks and misses the fourth.
So retrieval is wrapped in an agent loop (LangChain tools with structured tool calling) that decides how to answer before it answers:
retrieve(query, filters): the filter, search and rerank pipeline above, for open-ended questions.summarize(section): pull a whole section and condense it, when the user names one.extract(schema, section): structured extraction into a typed shape, for "extract X from section Y".
tools = [retrieve_tool, summarize_tool, extract_tool]
llm_with_tools = llm.bind_tools(tools)
def answer(question: str) -> str:
ai = llm_with_tools.invoke(question) # model picks the tool
call = ai.tool_calls[0] # name + parsed args
if call["name"] == "extract":
return run_structured_extraction(call["args"]) # deterministic, schema-bound
return dispatch(call) # retrieve / summarize
The win is letting the model choose the retrieval strategy instead of forcing every question through one pipeline. Structured questions go to a tool whose output is held to a schema, which is far more reliable than hoping the right chunks land in a prompt. It's the same rule I used in the News Desk agent: don't spend a model's fuzziness on a job a typed tool does exactly.
The trade-off: agent loops add latency, and a kind of bug a fixed pipeline doesn't have, where the model picks the wrong tool. For a low-traffic internal tool that's a fine price. On a high-traffic path I'd constrain the routing more tightly.
Make it watchable
The service is a FastAPI app deployed on Render, with streaming responses. Streaming isn't just a nicer interface: like the live activity log on the News Desk, watching an answer arrive, and seeing which tool fired and which chunks came back, is how you debug a probabilistic system in production. When an answer is wrong, you want to know whether the filter was too narrow, the vector search missed, or the rerank mis-ordered, because those are three very different fixes.
Embeddings and chat run on OpenAI, but the provider can be swapped per environment, so a model or pricing change is configuration, not a rewrite.
What I'd do again
- Do the work at ingest. Good metadata on every chunk is what makes the cheap filter possible. Skimp here and no clever retrieval saves you.
- Filter before you rank. A metadata filter that runs before vector search keeps off-topic chunks out of the ranking entirely. That one change of order fixed most of the "confident but wrong" answers.
- Don't force every question through RAG. Let an agent send structured questions to a deterministic extraction tool. Semantic search is for fuzzy intent, not for "list all the dates".
- Make it watchable from day one. You can't debug a retriever you can't see.
The outcome: questions that touch one section of one document now get answers built from that section, because the off-topic chunks never make it past the first step. Same corpus, same models, a different order of operations.
Frequently asked questions
- What is metadata-filtered RAG?
- Metadata-filtered RAG attaches metadata (source, section, tags, document type) to each chunk at ingest, then uses it to pre-filter the candidate set before vector search runs. Off-topic chunks are removed by the metadata filter first, so semantic similarity only ranks chunks that are already on the right topic.
- Why does single-shot RAG return irrelevant chunks on multi-topic corpora?
- Embedding similarity measures semantic closeness, not topical relevance. On a corpus spanning many topics, a query's nearest neighbors are scattered across unrelated documents that share vocabulary, so top-k similarity pulls in off-topic chunks. A metadata pre-filter fixes this by narrowing candidates before similarity is computed.
- What is filter-then-rank retrieval in a RAG pipeline?
- It runs three steps: a cheap metadata pre-filter, then vector similarity search within the filtered set, then an LLM rerank of the survivors. The filter makes sure only on-topic chunks reach the ranking, vector search orders them, and the rerank delivers the final precision.
- When should a RAG system use a tool-using agent instead of plain retrieval?
- Use an agent loop when questions vary in shape. Open-ended questions suit semantic retrieval, but structured questions like 'extract every deadline from section 4' suit a deterministic, schema-bound extraction tool. An agent with tool-calling picks the right strategy per question instead of forcing everything through one RAG pipeline.
An editor used to retype eight fields for every article and hope the table of contents still pointed at the right headings. I built the pipeline that replaced that work, and the most useful decision in it was what I refused to hand to the model.
Most portfolios are a page of links. This one answers questions about my work, keeps its own leads and traffic, manages its own photos and checks itself on every change. Here is every part of it, how each one works, and the problems that decided how it is built.