Search RU
Tasks / AI / LLM / Evaluating RAG on a golden set
Statement hard

Evaluating RAG on a golden set

Implement `evaluate_rag(golden_set, runs)` — an evaluation of a RAG run on a
golden set.

`golden_set` is a list of cases:

```python
{
"id": "refund-window",
"question": "How many days do I have to return an item?",
"expected_doc_ids": ["policy-refunds", "faq-returns"],
"expected_citation": "policy-refunds",
"answer_must_include": ["14 days"],
"answer_must_not_include": ["30 days"],
}
```

`runs` maps `id -> model run`:

```python
{
"refund-window": {
"retrieved_doc_ids": ["policy-refunds", "faq-shipping"],
"citations": ["policy-refunds"],
"answer": "You can return an item within 14 days.",
}
}
```

Each metric is computed per case and reported as a pass rate:

- `retrieval hit` — `retrieved_doc_ids` contains at least one document from
`expected_doc_ids`;
- `citation accuracy` — `expected_citation` is cited, **every** citation is in
`expected_doc_ids`, and **every** citation is among `retrieved_doc_ids`;
citing a document that was never retrieved is a hallucination, not accuracy;
- `answer pass` — the answer contains every phrase from
`answer_must_include` and none from `answer_must_not_include`; matching is
case-insensitive substring search.

Return the report:

```python
{
"total": 3,
"retrieval_hit_rate": 1.0,
"citation_accuracy": 2 / 3,
"answer_pass_rate": 1.0,
"failed": {
"retrieval": [],
"citation": ["warranty"],
"answer": [],
},
}
```

- `total` is the number of golden-set cases;
- the rates are the share of passing cases, without rounding;
- `failed` holds ids in `golden_set` order, separately for each metric.

Rules:

- a missing run fails all three metrics for the case, without raising;
- a malformed run (non-string `answer`, `retrieved_doc_ids` or `citations`
not a list of strings) also fails all three metrics, without raising;
- extra ids in `runs` are ignored;
- an empty golden set, a duplicate `id`, empty `expected_doc_ids`, a duplicate
document in it, `expected_citation` outside `expected_doc_ids`, an empty
phrase, an overlap between `answer_must_include` and
`answer_must_not_include`, an unknown key in a case, or `runs` not being a
dict raises `ValueError`;
- `question` is optional, but when present it must be a non-empty string.

The metrics do not replace each other: you can retrieve the right document but
cite the wrong one; you can answer correctly without citing a source. The
report keeps them separate.

Python
airagevaluationgolden-setretrieval
solution.py Python 3.14
AI mentor

The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.

Log in and ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

Why does the report keep three separate metrics instead of one "share of good
answers"? What does the citation check catch that the answer check does not?

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts