{
  "id": "recipe:retrieval-and-rag",
  "kind": "recipe",
  "title": "My retrieval returns the wrong chunk and I cannot see why it ranked. I want retrieval my agent can search with, not a one-shot pipeline.",
  "job": "We see the same failure repeatedly. Retrieval returns the wrong chunk, and nothing in the trace explains why that chunk won. There is no way to tell whether the chunker cut the answer in half, whether the embedding missed an exact identifier, or whether the right chunk was never retrieved at all. What we want instead is a retrieval substrate the agent can search with, as a loop, rather than a pipeline that fires once and hands back whatever it found.",
  "approach": "We build the substrate first, then expose it as a loop.\n\nParse every document to text plus structure, keeping titles and headings. Chunk on structure, not raw token counts, and prepend a short blurb that situates each chunk in its document before it is embedded or lexically indexed. Contextual chunking is the highest-leverage step: Anthropic measured 49 percent fewer retrieval failures from contextual embeddings plus contextual BM25, and 67 percent with a reranker on top.\n\nIndex the same contextualised chunks twice, dense and lexical BM25. Fuse the two candidate sets, rerank with a cross-encoder or hosted reranker, and deduplicate by chunk id before returning.\n\nOnly then wrap retrieval in tools (search, read, optionally list and grep over a mirrored tree) and let the agent iterate under a search cap.\n\nAlternatives and why not:\n\n- Single-shot dense RAG is the default and it is the thing to move off. It divorces the answer from its context, misses exact identifiers like error codes and SKUs, and gives no recovery path.\n- Retrieval plus rerank alone, without the tool loop, is the strongest substrate but still one shot.\n- Model-centric fine-tuning is ruled out because it ages faster than the data and does nothing for the substrate underneath.\n- A cached prompt beats all of it under roughly 200,000 tokens.",
  "components": [
    {
      "name": "pgvector (Postgres extension)",
      "version": "extension v0.8.7",
      "license": "PostgreSQL licence (LICENSE file)",
      "url": "https://github.com/pgvector/pgvector"
    },
    {
      "name": "pgvector Python client",
      "version": "0.5.1",
      "license": "unconfirmed",
      "url": "https://pypi.org/project/pgvector/"
    },
    {
      "name": "Qdrant",
      "version": "v1.19.2 server, qdrant-client 1.19.1",
      "license": "Apache-2.0",
      "url": "https://github.com/qdrant/qdrant"
    },
    {
      "name": "Weaviate",
      "version": "v1.40.1",
      "license": "mixed: BSD-3-Clause outside `wl/`, proprietary \"Weaviate License\" inside `wl/`",
      "url": "https://github.com/weaviate/weaviate"
    },
    {
      "name": "Milvus",
      "version": "v3.0.3 server, pymilvus 3.0.2",
      "license": "Apache-2.0",
      "url": "https://github.com/milvus-io/milvus"
    },
    {
      "name": "Chroma",
      "version": "chromadb 1.5.9",
      "license": "Apache-2.0",
      "url": "https://github.com/chroma-core/chroma"
    },
    {
      "name": "LanceDB",
      "version": "lancedb 0.40.0 stable, repo tag 0.41.0-beta.6",
      "license": "Apache-2.0",
      "url": "https://github.com/lancedb/lancedb"
    },
    {
      "name": "SQLite FTS5 (lexical / BM25)",
      "version": "ships with SQLite, per-version unconfirmed",
      "license": "public domain",
      "url": "https://www.sqlite.org/fts5.html"
    },
    {
      "name": "turbopuffer",
      "version": "commercial service, versioned internally",
      "license": "commercial",
      "url": "https://turbopuffer.com"
    },
    {
      "name": "sentence-transformers",
      "version": "v6.1.0",
      "license": "Apache-2.0",
      "url": "https://github.com/UKPLab/sentence-transformers"
    },
    {
      "name": "FlagEmbedding / BGE-M3",
      "version": "1.4.2",
      "license": "MIT (model card licence unconfirmed)",
      "url": "https://github.com/FlagOpen/FlagEmbedding"
    },
    {
      "name": "OpenAI embedding models",
      "version": "API, no public semver",
      "license": "commercial",
      "url": "https://openai.com/index/new-embedding-models-and-api-updates/"
    },
    {
      "name": "bge-reranker-v2-m3",
      "version": "cross-encoder, no semver",
      "license": "unconfirmed",
      "url": "https://huggingface.co/BAAI/bge-reranker-v2-m3"
    },
    {
      "name": "Cohere Rerank",
      "version": "cohere SDK 7.2.0",
      "license": "commercial (SDK MIT)",
      "url": "https://docs.cohere.com/docs/rerank-overview"
    },
    {
      "name": "Voyage rerank-2.5",
      "version": "voyageai SDK 0.5.0",
      "license": "commercial (SDK MIT)",
      "url": "https://blog.voyageai.com/2025/08/11/rerank-2-5/"
    },
    {
      "name": "Docling",
      "version": "2.139.0",
      "license": "MIT",
      "url": "https://github.com/docling-project/docling"
    },
    {
      "name": "Unstructured",
      "version": "0.27.25",
      "license": "Apache-2.0",
      "url": "https://github.com/Unstructured-IO/unstructured"
    },
    {
      "name": "Chonkie",
      "version": "1.7.0",
      "license": "MIT",
      "url": "https://github.com/chonkie-inc/chonkie"
    },
    {
      "name": "MarkItDown",
      "version": "0.1.8",
      "license": "MIT",
      "url": "https://github.com/microsoft/markitdown"
    },
    {
      "name": "LlamaIndex",
      "version": "0.14.25",
      "license": "MIT",
      "url": "https://github.com/run-llama/llama_index"
    },
    {
      "name": "LangChain",
      "version": "1.4.6",
      "license": "MIT",
      "url": "https://github.com/langchain-ai/langchain"
    },
    {
      "name": "Haystack",
      "version": "haystack-ai 3.3.0 stable, repo tag v3.5.0-rc0",
      "license": "Apache-2.0",
      "url": "https://github.com/deepset-ai/haystack"
    },
    {
      "name": "DSPy",
      "version": "3.4.1",
      "license": "MIT",
      "url": "https://github.com/stanfordnlp/dspy"
    },
    {
      "name": "rank_bm25",
      "version": "0.2.2 (last release 2022-02-16, unmaintained)",
      "license": "Apache-2.0",
      "url": "https://github.com/dorianbrown/rank_bm25"
    },
    {
      "name": "RAGAS",
      "version": "0.4.3",
      "license": "Apache-2.0",
      "url": "https://github.com/explodinggradients/ragas"
    },
    {
      "name": "DeepEval",
      "version": "4.2.8",
      "license": "Apache-2.0",
      "url": "https://github.com/confident-ai/deepeval"
    },
    {
      "name": "TruLens",
      "version": "2.15.0",
      "license": "MIT",
      "url": "https://github.com/truera/trulens"
    },
    {
      "name": "Model Context Protocol",
      "version": "spec revision pinned per deployment",
      "license": "see repo",
      "url": "https://modelcontextprotocol.io/introduction"
    },
    {
      "name": "BGE-M3 model card",
      "version": "no semver",
      "license": "unconfirmed",
      "url": "https://huggingface.co/BAAI/bge-m3"
    },
    {
      "name": "SQLite copyright terms",
      "version": "per-version unconfirmed",
      "license": "public domain",
      "url": "https://www.sqlite.org/copyright.html"
    }
  ],
  "steps": [
    "Measure the corpus. If the whole knowledge base is under roughly 200,000 tokens, stop: use a cached prompt and skip retrieval entirely.",
    "Parse and normalise every document to text plus structure with Docling or Unstructured (MarkItDown for simple cases). Preserve headings, titles, document identity.",
    "Chunk on structure with context. Generate a short blurb situating each chunk in its document (title, section, what the document is) and prepend it before embedding or lexical indexing.",
    "Build two indexes over the same contextualised chunks: one dense, one lexical BM25 (store built-in, SQLite FTS5, or Postgres full-text). Never ship dense-only.",
    "Retrieve top-k from each index, fuse with reciprocal rank fusion, rerank the fused set with a cross-encoder or hosted reranker, deduplicate by chunk identity, and cap the returned set to the context budget.",
    "Expose retrieval as tools, not a pipeline. At minimum `search` (steps 4 and 5) and `read` (fetch a whole document or section by id). If the corpus is navigable, mirror it as a filesystem tree and add `list` and `grep`. Describe the tools so the model can choose between them.",
    "Let the agent iterate with a bound: a maximum number of searches per turn and a rule for when to answer with what it has.",
    "Instrument retrieval quality (did the right chunk come back, at what rank) separately from answer quality. Log fused scores and, where the store allows, per-index component scores.",
    "Isolate per tenant by partitioning the index, and treat ingestion as an attack surface, not a trusted path."
  ],
  "traps": [
    "**Chunking without context.** Agents make this because the chunker has no view of the document it is cutting up. Fix: step 3, prepend the situating blurb. This is the biggest measured loss and the cheapest fix.",
    "**Expecting a reranker to rescue a weak retriever.** Agents reach for reranking because it is a one-line swap and looks like a quality knob. A reranker only reorders what stage one returned; it cannot surface a chunk never retrieved. Fix: recall problems belong to steps 3 and 4.",
    "**Dense-only retrieval over exact identifiers.** Embeddings are the default and cosine similarity quietly fails on error codes, SKUs, version strings and function names. Fix: the lexical index in step 4.",
    "**One-shot retrieval.** The pipeline runs once, returns junk, and the agent answers anyway, because nothing in the pipeline can decide to retry. Fix: the bounded loop in steps 6 and 7.",
    "**Fused scores you cannot decompose.** Agents log the final ranking because that is what the API returns. Fix: instrument at fusion time and log component scores (Qdrant issue 10282 is builders asking for exactly this), not after the incident.",
    "**Chunks that split the answer.** Fixed-size chunking cuts through tables, code blocks and lists because it counts tokens, not structure. Fix: respect structure in step 2 and chunk on boundaries.",
    "**No deduplication after fusion.** The same passage arrives via both indexes and eats the context budget twice. Fix: dedupe by chunk id before returning.",
    "**Silently truncating the retrieved context.** Truncation looks like success in the trace. Fix: say so in the trace when the retrieved set exceeds the budget.",
    "**Cross-tenant leakage through the index.** A shared index with a filter applied at query time reads as isolation but is not (Chroma issue 7588, open cross-tenant IDOR). Fix: partition the index per tenant at design time.",
    "**Ingestion poisoning.** Anything that writes to the index can steer every future retrieval (Chroma issue 7248). Fix: treat ingestion as an attack surface.",
    "**Picking an unmaintained dependency.** `rank_bm25` has had no release since 2022-02-16 and tutorials still recommend it. Fix: use the lexical search built into your store.",
    "**Reading a licence off the registry.** Weaviate's LICENSE file, not the registry metadata, says `wl/` is under a separate enterprise licence. Fix: read the file."
  ],
  "scope": "**Covers:** the retrieval substrate for a single agent (parse to text plus structure, contextual chunking, dense plus lexical index, rank fusion, reranking, deduplication) and the shape of the loop that exposes retrieval to the agent as bounded tools. It names components with real versions and licences, and gives ordered steps and traps for that job.\n\n**Does not cover:** prompt or answer-generation design beyond how retrieved context is handed over; agent orchestration outside the retrieval loop (planning, delegation, memory, tool selection); model fine-tuning or the model-centric approach, named only to be ruled out; graph retrieval and knowledge-graph construction beyond citing LightRAG as a direction; multimodal and image-based retrieval beyond citing the \"just use images\" argument as a live alternative; infrastructure sizing, hosting and cost modelling for the vector store; evaluation methodology in depth, since this stops at naming evaluation tools and requiring retrieval metrics be split from answer metrics.\n\nNothing in the source brief was run end to end. This recipe is curated, not tested: the steps above are what we would do for this job, not a record of doing them.",
  "use_case": "retrieval-and-rag",
  "sources": [
    "Reddit threads returned HTTP 403.",
    "The OpenAI embedding page returned HTTP 403 on 2026-10-14. It is cited but was not read.",
    "GitHub `archived` and `pushed_at` fields could not be read (GitHub core API limit exhausted), so we do not assert that `rank_bm25` is archived. It is unmaintained, not archived.",
    "BGE-M3 and bge-reranker-v2-m3 model-card licences.",
    "The pgvector Python client licence.",
    "Per-version SQLite status.",
    "Chroma version: PyPI chromadb is 1.5.9 dated 2026-05-05 while the repo carries a \"Latest\" tag dated 2026-10-14. Both are retained, because a builder installs the package version. Discrepancy not resolved.",
    "Haystack, LanceDB and pgvector each have a package version and a repo tag that disagree. Both are given, as the brief gave both.",
    "\"Weaviate License\" for `wl/` is recorded as proprietary, not as a named SPDX licence, because the LICENSE file does not give one. We did not substitute \"Enterprise\" as a licence name.",
    "No versions, dates or licences were invented."
  ],
  "status": "curated",
  "superseded_by": null,
  "citation": "My retrieval returns the wrong chunk and I cannot see why it ranked. I want retrieval my agent can search with, not a one-shot pipeline.. Recipe by alexndr.ai. https://alexndr.ai/recipes/retrieval-and-rag",
  "human_page": "https://alexndr.ai/recipes/retrieval-and-rag"
}