Skip to chapter content
navan✳THE BUILD LABAI ENGINEERING / GUIDE
0/21 read
CHAPTER 12 / 21 · KNOWLEDGE AND ACTION

Search, embeddings, and ranking.

Understand lexical search, vector similarity, reranking, and why retrieval quality is a separate metric.

BY NAVAN SAMILONG READTHEORY FIRST
01 / FROM THE BEGINNING

Start with the meaning.

A search system must find the right evidence before a model can use it. Lexical search compares words or terms. Embedding search converts text into numeric vectors so nearby vectors can represent related meanings. These are different signals. A query for an exact invoice number may fail in a purely semantic index; a paraphrased policy question may fail in a purely keyword index.

An embedding is a list of numbers produced by a model. Similarity calculations compare vectors, often using cosine similarity or distance. Close vectors suggest related text, but closeness does not prove that a passage answers the question. The embedding model, document processing, and query wording all affect the result.

02 / THE SYSTEM

How the idea works.

Candidate retrieval favors recall: include likely relevant passages. Reranking favors precision: place the most useful among those candidates first. A system may combine lexical and vector candidates, then use a reranker or rules to select a few. It must also remove duplicates, respect document versions, and filter permissions. These steps happen before generation.

Measure retrieval separately. Recall at k asks whether a needed passage appears in the top k results. Precision asks how many returned passages are relevant. If the right source never appears, changing the generation prompt cannot repair the missing evidence. Conversely, high retrieval recall does not prove the model reads the passage correctly. Diagnose the stage that fails.

Indexes become stale. When a document is updated or deleted, its passages and metadata must change in the index. An answer from an obsolete policy can be more harmful than no answer. Make ingestion and deletion observable and keep a link back to the canonical source.

Lexical and semantic search solve different matching problems. A user may ask “How do I regain access?” while the document says “Reset your password”; an embedding may connect them. A user may ask for invoice INV-4837, where the exact identifier matters more than semantic similarity. Hybrid retrieval can take candidates from both methods, but it still needs a final ranking that favors passages useful for the specific question.

Evaluate the retrieval stage with known relevant document IDs. If the right passage is absent from the top results, inspect ingestion, chunking, permissions, query wording, and index freshness. If it is present but the answer is wrong, inspect prompt packing and generation. This separation prevents teams from spending days tuning a model to compensate for a missing source. Retrieval metrics diagnose opportunity; answer metrics diagnose use of that opportunity.

01DocumentsVersioned source02SearchFind candidates03RankSelect passages04AnswerCheck citations
Search and ranking decide what the model is allowed to see.
03 / PYTHON, EXPLAINED

Follow the code.

search-and-ranking.py
def recall_at_k(results, required_ids, k=3):
    top = {item["id"] for item in results[:k]}
    needed = set(required_ids)
    return len(top & needed) / len(needed) if needed else 1.0

ranked = [{"id": "guide-2"}, {"id": "policy-7"}, {"id": "faq-4"}]
print(recall_at_k(ranked, ["policy-7"], k=2))

The function compares the IDs in the first k results with the set of required evidence IDs. The example prints 1.0 because policy-7 appears in the top two. If it appeared fourth, recall at two would be zero even if the index contained it. This metric asks whether the model had a chance to see the right passage.

The calculation assumes required_ids is a reliable annotation. A real question may have several equally valid sources or need more than one passage. Evaluation labels must reflect that task.

04 / THE BOUNDARY

What the result does not say.

Vector stores are indexes, not a source of truth. Keep canonical documents and permission rules outside the index and make updates traceable.

Reranking adds latency. Use evaluation to decide whether its gain in evidence quality is worth the cost for the actual application.

05 / KEEP THIS

One clear idea.

Measure whether the right evidence reaches the model before judging the model's answer.

THE CODE IN CONTEXT

The AI cookbook

Complete, explained local workflows sit alongside this reading course.

Browse the cookbook
Finished reading?
Built with curiosity. By Navan Sami. ↗AI engineering · From model calls to reliable systems.