Step 9 of 11· AI Customer Support Chatbot
Retrieval evals
Measure how often each search method finds the right chunk, with recall and MRR on a fixed set of questions, and choose the search mode by the numbers.
Purpose#
Measure search quality with numbers instead of trying a few questions by hand. A retrieval eval runs a fixed set of questions with known correct chunks through search and reports how often the correct chunk is found.
In this step:
- Write eval cases: question and expected chunk
- Compute recall@1, recall@k and MRR
- Find the questions search misses, and fix them
- Compare keyword, vector and hybrid search to confirm the search mode
Why measure retrieval separately#
When the desk gives a wrong answer, there are two possible causes:
- Search did not find the right chunk. The model never saw the answer.
- Search found it, but the model answered badly.
A retrieval eval measures cause 1 alone. It needs no answer model, costs almost nothing (one embedding request for all questions) and runs in seconds. Step 10 measures cause 2.
Eval cases#
Each case is a question with the article (doc, the file name without .md) and the section (heading) that answers it:
{"q": "I need to move my appointment to another day, does that cost anything?", "doc": "cancellation", "heading": "Free cancellation"}Writing cases:
- Use the words customers use, not the words of the article: "move my appointment" instead of "reschedule", "sick" instead of "illness".
- Include short and vague questions ("price??"), typos, and other languages.
- Take real questions from your support inbox when you have them. 30 to 50 cases are enough to compare methods.
The full set, 30 questions:
[
{"q": "How do I book a cleaning?", "doc": "booking", "heading": "How to book"},
{"q": "Can someone come today? I need a cleaner this afternoon.", "doc": "booking", "heading": "Lead time"},
{"q": "How far in advance do I have to reserve?", "doc": "booking", "heading": "Lead time"},
{"q": "What happens on the first appointment?", "doc": "booking", "heading": "First visit"},
{"q": "Can I cancel for free?", "doc": "cancellation", "heading": "Free cancellation"},
{"q": "I need to move my appointment to another day, does that cost anything?", "doc": "cancellation", "heading": "Free cancellation"},
{"q": "What do you charge if I cancel two hours before?", "doc": "cancellation", "heading": "Late cancellation"},
{"q": "The cleaners came but I forgot to leave the key and nobody was there. Will I be billed?", "doc": "cancellation", "heading": "No-show and lockout"},
{"q": "What is the hourly rate for a normal home cleaning?", "doc": "pricing", "heading": "Home cleaning"},
{"q": "Is there a discount if you come every week?", "doc": "pricing", "heading": "Recurring discounts"},
{"q": "How much is a deep clean?", "doc": "pricing", "heading": "Deep cleaning"},
{"q": "Do you charge extra for driving to my place?", "doc": "pricing", "heading": "Extra charges"},
{"q": "The bathroom was still dirty after the visit. What can I do?", "doc": "guarantee", "heading": "Satisfaction guarantee"},
{"q": "A cleaner broke my lamp. How do I make a claim?", "doc": "guarantee", "heading": "Damage"},
{"q": "Can I get my money back?", "doc": "guarantee", "heading": "Refunds"},
{"q": "Do you clean on Sundays?", "doc": "hours", "heading": "Cleaning hours"},
{"q": "When can I reach customer service?", "doc": "hours", "heading": "Support hours"},
{"q": "My regular visit falls on a bank holiday. What happens?", "doc": "hours", "heading": "Public holidays"},
{"q": "wat is ur cancelation polcy", "doc": "cancellation", "heading": "Free cancellation"},
{"q": "price??", "doc": "pricing", "heading": "Home cleaning"},
{"q": "Can I switch my cleaning from Tuesday to Thursday?", "doc": "booking", "heading": "Changing a booking"},
{"q": "Where do I go to cancel my visit?", "doc": "cancellation", "heading": "How to cancel"},
{"q": "What if your cleaner is sick and you can't come?", "doc": "cancellation", "heading": "When we cancel"},
{"q": "How much do you charge to clean an office?", "doc": "pricing", "heading": "Office cleaning"},
{"q": "Where do I report a problem with my cleaning?", "doc": "guarantee", "heading": "How to report"},
{"q": "Is there a fee for the first walkthrough?", "doc": "booking", "heading": "First visit"},
{"q": "Do I pay for parking?", "doc": "pricing", "heading": "Extra charges"},
{"q": "Are you open on Saturday?", "doc": "hours", "heading": "Cleaning hours"},
{"q": "Mennyibe kerül egy órányi takarítás?", "doc": "pricing", "heading": "Home cleaning"},
{"q": "Up to what amount are you insured?", "doc": "guarantee", "heading": "Damage"}
]Metrics#
| Metric | Meaning |
|---|---|
| recall@1 | % of questions where the correct chunk is the first result |
| recall@k | % of questions where the correct chunk is in the top k. The answer model receives k chunks, so this is the share of questions it can answer at all. |
| MRR | Mean reciprocal rank: 1 for position 1, 0.5 for position 2, 0.33 for position 3, 0 if missing; averaged. 1.0 means always first. |
Eval script#
"""Eval: does search find the right chunk?
Run: python -m evals.retrieval
python -m evals.retrieval --compare (also compares keyword, vector and hybrid search)
"""
import argparse
import datetime as dt
import json
from pathlib import Path
from support_desk import config
from support_desk.db import connect
from support_desk.embeddings import embed
from support_desk.search import CANDIDATES, Hit, fuse, keyword_search, vector_search
CASES = json.loads((Path(__file__).parent / "retrieval_cases.json").read_text())
REPORTS = Path(__file__).parent / "reports"
MODES = ("keyword", "vector", "hybrid")
def rank_of(case: dict, hits: list[Hit]) -> int | None:
"""Position (1 = first) of the expected chunk in the results, or None if it is missing."""
for position, hit in enumerate(hits, start=1):
if hit.doc == case["doc"] and hit.heading == case["heading"]:
return position
return None
def metrics(ranks: list[int | None], k: int) -> dict:
n = len(ranks)
return {
"recall@1": round(100 * sum(r == 1 for r in ranks) / n, 1),
f"recall@{k}": round(100 * sum(r is not None and r <= k for r in ranks) / n, 1),
"mrr": round(sum(1 / r for r in ranks if r) / n, 3), # mean reciprocal rank: 1.0 = always first
}
def run(k: int, embed_fn=embed, cases: list[dict] = CASES) -> dict:
vectors = embed_fn([c["q"] for c in cases]) # one request for all questions
ranks: dict[str, list] = {mode: [] for mode in MODES}
with connect() as conn:
for case, vector in zip(cases, vectors):
results = {
"keyword": keyword_search(conn, case["q"], k),
"vector": vector_search(conn, vector, k),
"hybrid": fuse([keyword_search(conn, case["q"], CANDIDATES), vector_search(conn, vector, CANDIDATES)], k),
}
for mode in MODES:
ranks[mode].append(rank_of(case, results[mode]))
return {
"date": dt.datetime.now().isoformat(timespec="seconds"),
"embedding_model": config.EMBEDDING_MODEL,
"cases": len(cases),
"k": k,
"modes": {mode: metrics(ranks[mode], k) for mode in MODES},
"misses": {mode: [c["q"] for c, r in zip(cases, ranks[mode]) if r is None] for mode in MODES},
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--k", type=int, default=config.TOP_K, help="how many chunks the answer step receives")
parser.add_argument("--compare", action="store_true", help="also compare keyword, vector and hybrid search")
args = parser.parse_args()
report = run(args.k)
mode, cases = config.SEARCH_MODE, report["cases"]
misses = report["misses"][mode]
m = report["modes"][mode]
print(f"{mode} search, {cases} questions, top {args.k}")
print(f" {f'found in the top {args.k}:':<20} {cases - len(misses)} of {cases} ({m[f'recall@{args.k}']}%)")
print(f" {'found first:':<20} {m['recall@1']}%")
print(f" {'mrr:':<20} {m['mrr']}")
print(f"\nTo fix (not found in the top {args.k}):")
print("\n".join(f" - {q}" for q in misses) or " nothing")
if args.compare:
print(f"\nComparison, embeddings: {report['embedding_model']}")
print(f"{'mode':<10}{'recall@1':>10}{f'recall@{args.k}':>10}{'mrr':>8}")
for name, r in report["modes"].items():
print(f"{name:<10}{r['recall@1']:>9}%{r[f'recall@{args.k}']:>9}%{r['mrr']:>8}")
REPORTS.mkdir(exist_ok=True)
out = REPORTS / f"{dt.date.today()}-retrieval-k{args.k}.json"
out.write_text(json.dumps(report, indent=2))
print(f"\nSaved {out}")
if __name__ == "__main__":
main()Every question runs through search, and the report shows how often the expected section was found and which questions were missed.
Checkpoint#
uv run python -m evals.retrievalOutput from a real run with text-embedding-3-small:
vector search, 30 questions, top 5
found in the top 5: 29 of 30 (96.7%)
found first: 80.0%
mrr: 0.861
To fix (not found in the top 5):
- What if your cleaner is sick and you can't come?Search finds the right section for 29 of 30 questions. The question under "To fix" is the work to do; see "Improving recall" below.
Choosing the search mode#
Compare the three search methods on the same questions:
uv run python -m evals.retrieval --compareComparison, embeddings: text-embedding-3-small
mode recall@1 recall@5 mrr
keyword 46.7% 66.7% 0.551
vector 80.0% 96.7% 0.861
hybrid 60.0% 90.0% 0.717- Vector search finds the right chunk in the top 5 for 29 of 30 questions.
- Keyword search misses 10 questions. Customers rarely use the words of the article.
- Hybrid search is worse than vector search alone. RRF gives the keyword list equal weight, and on this dataset the keyword list adds more wrong chunks than right ones.
Giving the keyword list a lower weight in the fusion improves hybrid, but in our measurements it did not beat vector search alone. Postgres full-text ranking has no IDF (it does not know that a rare word matters more than a common one), so it is weaker than the BM25 ranking that search engines use.
Decision: SEARCH_MODE=vector. This is the default in config.py.
Hybrid search is a common recommendation, but whether it helps depends on the data. It helps when customers search for exact terms: product codes, error messages, names. Measure with your own questions before you add it.
Improving recall#
Misses are fixed in the articles, not in the code. "What if your cleaner is sick and you can't come?" is answered in "When we cancel", which says "because of illness or severe weather". Add the customer's words, for example "If your cleaner is sick or the weather is too severe, we cancel the visit".
Change the article, run uv run python -m support_desk.index, then run the eval again. Only the changed chunks are embedded.
Troubleshooting#
- All modes 0%: the index is empty. Run
uv run python -m support_desk.indexfirst. - A case is never found: check that
docis the file name without.mdandheadingmatches the##heading exactly. - Numbers differ slightly from the output above: the HNSW index is approximate, and articles you changed give different chunks. Differences of a few percent are normal.