Evaluating Semantic Search Quality

Ma Mahalakshmi V Updated 16 Sep 2026
8 min read ·Lesson 123 of 224
In this post

Evaluating Semantic Search Quality Every design decision in this unit — which embedding model, what chunk size, whether to add metadata filtering, which similarity threshold to use — is ultimately a g

Evaluating Semantic Search Quality

Every design decision in this unit — which embedding model, what chunk size, whether to add metadata filtering, which similarity threshold to use — is ultimately a guess unless it is checked against measured results. Unit 13 introduced the general methodology for evaluating and improving LLM-based systems: build a labeled dataset, run the system against it, score the output with a grader, and track the score as changes are made. This lesson applies that exact methodology to retrieval specifically, using metrics designed for ranked search results rather than the free-text grading covered in Unit 13.

Why "It Looks Right" Is Not Evaluation

A developer testing a search feature by typing in a few queries and eyeballing the results will reliably miss two kinds of problems: queries that are subtly worse than they appear (a relevant document ranked 4th instead of 1st looks "fine" at a glance but represents a real quality gap), and regressions introduced by a later change (a new chunking strategy improves some queries and quietly worsens others, and manual spot-checking rarely catches both directions at once). A measured evaluation, run the same way every time against the same fixed dataset, catches both.

Building a Retrieval Evaluation Dataset

Following the same pattern Unit 13 used for building eval datasets, a retrieval eval dataset is a set of realistic queries, each paired with the set of documents that are actually relevant to it — established by a human, not by the system being evaluated (grading a system using its own opinion of what is relevant is circular).

from dataclasses import dataclass


@dataclass
class RetrievalExample:
    query: str
    relevant_doc_ids: set[str]   # ground truth, labeled independently of the search system


eval_dataset = [
    RetrievalExample(
        query="how do I get a refund on a broken item",
        relevant_doc_ids={"returns-policy", "damaged-goods-process"},
    ),
    RetrievalExample(
        query="when will my order arrive",
        relevant_doc_ids={"shipping-times", "order-tracking"},
    ),
    RetrievalExample(
        query="can I change my shipping address after ordering",
        relevant_doc_ids={"order-tracking", "shipping-times"},
    ),
]

Why must relevant_doc_ids come from independent human judgment? The entire point of evaluation is to measure whether the system finds what a real user would consider relevant. If "relevant" is instead defined as "whatever the current system already returns," the evaluation can never detect that the system is missing genuinely relevant documents — it would only ever confirm the system agrees with itself. In practice, this dataset is built by having someone (a domain expert, or the developer acting carefully) review each query against the full document set once, independent of any particular search run, and record which documents actually answer it.

Core Retrieval Metrics

Three metrics, all computed from the same basic input — a ranked list of retrieved document IDs compared against a set of known-relevant IDs — cover most practical evaluation needs.

Precision@k — of the top k results returned, what fraction are actually relevant?

def precision_at_k(retrieved_ids: list[str], relevant_ids: set[str], k: int) -> float:
    top_k = retrieved_ids[:k]
    if not top_k:
        return 0.0
    relevant_in_top_k = sum(1 for doc_id in top_k if doc_id in relevant_ids)
    return relevant_in_top_k / len(top_k)

Recall@k — of all the documents that are actually relevant, what fraction were found in the top k results?

def recall_at_k(retrieved_ids: list[str], relevant_ids: set[str], k: int) -> float:
    if not relevant_ids:
        return 0.0
    top_k = retrieved_ids[:k]
    relevant_in_top_k = sum(1 for doc_id in top_k if doc_id in relevant_ids)
    return relevant_in_top_k / len(relevant_ids)

Why track both, instead of just one? They measure different failure modes. A search that returns one correct result and nine irrelevant ones in its top 10 has poor precision but might have fine recall for a query with only one relevant document. A search that returns five correct results but misses five other equally relevant ones has fine precision but poor recall. A system that ranks well on precision but poorly on recall is systematically failing to surface some relevant content — often a signal to revisit chunking (Lesson 8) or check whether relevant content was indexed at all.

Mean Reciprocal Rank (MRR) — for queries with one clearly best answer, how high up the ranking does the first relevant result appear?

def reciprocal_rank(retrieved_ids: list[str], relevant_ids: set[str]) -> float:
    for position, doc_id in enumerate(retrieved_ids, start=1):
        if doc_id in relevant_ids:
            return 1.0 / position
    return 0.0


def mean_reciprocal_rank(all_retrieved: list[list[str]], all_relevant: list[set[str]]) -> float:
    scores = [reciprocal_rank(r, rel) for r, rel in zip(all_retrieved, all_relevant)]
    return sum(scores) / len(scores) if scores else 0.0

Why does MRR matter separately from precision and recall? For search interfaces where users typically only look at the first result or two (a "did you mean" style suggestion, an autocomplete), what matters most is how quickly the first relevant result appears, not the overall composition of the top 10. A reciprocal rank of 1.0 means the first result was relevant; 0.5 means the first relevant result was in position 2; a score approaching 0 means it took many results to find one relevant document, or none appeared at all.

Running the Evaluation

def test_retrieval_metrics_with_fake_results():
    example = RetrievalExample(
        query="how do I get a refund on a broken item",
        relevant_doc_ids={"returns-policy", "damaged-goods-process"},
    )
    # A fake, hand-constructed ranked result list standing in for a real search call.
    retrieved = ["damaged-goods-process", "shipping-times", "returns-policy", "order-tracking"]

    p_at_2 = precision_at_k(retrieved, example.relevant_doc_ids, k=2)
    r_at_2 = recall_at_k(retrieved, example.relevant_doc_ids, k=2)
    rr = reciprocal_rank(retrieved, example.relevant_doc_ids)

    assert p_at_2 == 0.5      # 1 of the top 2 results is relevant
    assert r_at_2 == 0.5      # 1 of 2 relevant docs found in the top 2
    assert rr == 1.0          # the very first result is relevant

    print("PASS: retrieval metrics computed correctly against fixed fake results")


test_retrieval_metrics_with_fake_results()

This test does not call the search engine at all — it works directly against a hand-written retrieved list, which is the right level to test the metric functions themselves: their correctness should not depend on what any particular embedding model actually returns. A separate evaluation run — shown next — is what exercises the real search engine against the full eval dataset.

def evaluate_search_engine(engine, dataset: list[RetrievalExample], k: int = 5) -> dict:
    """Run the full eval dataset through a real search engine and
    aggregate metrics. `engine` must expose `.search(query, top_k)`
    returning a list of (document, score) pairs whose documents have
    a `.doc_id` attribute (matching SemanticSearchEngine from Lesson 5).
    """
    precisions, recalls, reciprocal_ranks = [], [], []

    for example in dataset:
        results = engine.search(example.query, top_k=k)
        retrieved_ids = [doc.doc_id for doc, _ in results]

        precisions.append(precision_at_k(retrieved_ids, example.relevant_doc_ids, k))
        recalls.append(recall_at_k(retrieved_ids, example.relevant_doc_ids, k))
        reciprocal_ranks.append(reciprocal_rank(retrieved_ids, example.relevant_doc_ids))

    return {
        "avg_precision_at_k": sum(precisions) / len(precisions),
        "avg_recall_at_k": sum(recalls) / len(recalls),
        "mean_reciprocal_rank": sum(reciprocal_ranks) / len(reciprocal_ranks),
        "num_queries": len(dataset),
    }

Running evaluate_search_engine against the same fixed eval_dataset before and after a change — a new chunking strategy, a different embedding model, an added metadata filter — produces a direct, numeric before/after comparison. This is the same core discipline Unit 13 established for grading generated text: fix the dataset, run the system, record the score, change one thing at a time, and re-measure.

When Metrics Alone Are Not Enough: Using a Grader

Precision, recall, and MRR require a labeled set of "correct" document IDs, which works well when relevance is fairly clear-cut. Some queries have fuzzier relevance — a document might be partially relevant, or relevant in a way a strict ID-matching label does not capture. For these cases, Unit 13's grader pattern (using a capable model to judge quality against a rubric) can be adapted to retrieval by asking the grader to judge whether a retrieved chunk actually helps answer the query, rather than only asking whether its ID matches a predetermined label.

def grade_relevance(client, query: str, retrieved_text: str) -> bool:
    """Ask a model to judge whether a retrieved chunk is relevant to a query.

    This mirrors Unit 13's grader pattern applied specifically to
    retrieval: the grader answers one narrow, binary question rather
    than producing open-ended commentary, which keeps grading
    consistent and easy to aggregate across many examples.
    """
    prompt = (
        f"Query: {query}\n\n"
        f"Retrieved passage:\n{retrieved_text}\n\n"
        "Does this passage contain information that helps answer the query? "
        "Answer with exactly one word: yes or no."
    )
    response = client.responses.create(model="gpt-5.6-terra", input=prompt)
    return response.output_text.strip().lower().startswith("y")

Note: The exact response field (output_text) and request shape shown here follow the pattern introduced in Unit 1; confirm current field names against the official API reference, since response object structure can change between SDK versions.

Why use a binary yes/no question rather than asking for a relevance score out of 10? Unit 13 established that narrow, well-defined grading questions produce more consistent results than open-ended scoring, because a model asked for a precise numeric score tends to give inconsistent numbers for similar inputs, while a binary judgment is easier for both a model and a human reviewer to apply consistently. A grader like this is best used to spot-check queries that the ID-based metrics above cannot label cleanly (novel queries without a pre-built ground truth set), not as a wholesale replacement for the labeled dataset — a fixed labeled dataset remains cheaper, faster, and fully reproducible for tracking changes over time.

Common Mistakes

  • Evaluating with only a handful of queries chosen informally. A tiny, non-representative eval set can show an improvement on the queries it happens to contain while missing regressions elsewhere; Unit 13's guidance on building a sufficiently sized, representative dataset applies here without modification.
  • Deriving "relevant" labels from the system's own current output. This makes the evaluation circular and unable to detect missed, genuinely relevant documents, as explained above.
  • **Changing more than one variable (chunk size and embedding model and similarity threshold) between evaluation runs.** This makes it impossible to attribute a metric change to a specific cause — change one variable at a time, exactly as Unit 13 recommends for iterative improvement.

Best Practices

  • Build the eval dataset once, keep it under version control, and reuse it for every future change — a stable dataset is what makes before/after comparisons meaningful.
  • Report precision, recall, and MRR together, not a single blended number, since each exposes a different kind of failure, as shown above.
  • Reserve model-based grading for cases the labeled dataset cannot cleanly cover, using the narrow binary-question pattern from Unit 13 rather than open-ended scoring.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Evaluating Semantic Search Quality and get answers drawn from it.

Signed-in readers only.