Skip to content

Commit b74e753

Browse files
committed
Add the Advanced RAG harness evaluator
1 parent 79533c2 commit b74e753

17 files changed

Lines changed: 1999 additions & 140 deletions

File tree

‎integrations/agent_pack/examples/advanced_rag_eval.py‎

Lines changed: 43 additions & 136 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
# Run from `integrations/agent_pack` with `OPENAI_API_KEY` set. The corpus requires `datasets`:
2222
#
2323
# hatch run test:python examples/advanced_rag_eval.py
24-
# hatch run test:python examples/advanced_rag_eval.py --max-cases 5
24+
# hatch run test:python examples/advanced_rag_eval.py --max-eval-cases 5
2525
# hatch run test:python examples/advanced_rag_eval.py --store opensearch
2626
#
2727
# `--store opensearch` reuses a populated index across runs, so repeat runs skip re-indexing. Set `OPENSEARCH_URL`
@@ -31,119 +31,32 @@
3131
import re
3232
import time
3333
from collections import Counter
34-
from dataclasses import dataclass, field
3534
from typing import Any
3635

3736
from haystack import Document
3837
from haystack.components.agents import Agent
3938
from haystack.dataclasses import ChatMessage
39+
from haystack.tools import flatten_tools_or_toolsets
4040
from multihop_rag import CORPUS_KEY, LabelledQuestion, build_eval_cases, prepare_corpus
4141
from util import build_bm25_retriever, preview
4242

4343
from haystack_integrations.agent_pack.advanced_rag import create_advanced_rag_agent
44+
from haystack_integrations.agent_pack.evaluation import (
45+
RetrievalEvalCase,
46+
ToolNames,
47+
ToolRunStats,
48+
budgets_exceeded,
49+
resolve_tool_budgets,
50+
)
4451

4552
RETRIEVAL_TOOLS = ("search_documents", "fetch_documents_by_filter")
4653
METADATA_TOOLS = ("list_metadata_fields", "get_metadata_field_values", "get_metadata_field_range")
54+
# Generous on purpose: a MultiHopRAG question needs evidence from several articles, so several searches are the
55+
# expected shape of a good run rather than a sign of floundering.
56+
TOOL_BUDGETS: dict[ToolNames, int] = {METADATA_TOOLS: 8, RETRIEVAL_TOOLS: 12}
4757
_CITATION_RE = re.compile(r"\[doc ([0-9a-f]{4,16})[^]]*\]")
4858

4959

50-
@dataclass
51-
class EvalCase:
52-
"""
53-
One eval case: a question, the documents that answer it, and the budgets the run may spend.
54-
55-
:param question: The question to put to the agent.
56-
:param evidence: Ground truth, as `{chunk id: the quote found in that chunk}`. The keys are the documents the
57-
answer needs, and the values are what the answer should be based on. For example,
58-
{"a1b2c3...": "Tyreek Hill now needs to ...", "d4e5f6...": "The Dolphins went on to ..."}
59-
:param tool_budgets: How many times the run may call a tool, or a group of tools sharing one allowance, as
60-
`{tool name or names: limit}`. Exceeding any of them fails the eval case. Which tools these are depends
61-
on the agent under evaluation, so the caller supplies them.
62-
"""
63-
64-
question: str
65-
evidence: dict[str, str]
66-
tool_budgets: dict[str | tuple[str, ...], int]
67-
68-
@property
69-
def expected_document_ids(self) -> frozenset[str]:
70-
"""The chunks an answer needs, which are the ones its evidence was found in."""
71-
return frozenset(self.evidence)
72-
73-
74-
@dataclass
75-
class ToolRunStats:
76-
"""
77-
The tool calls one agent run made, and what they add up to.
78-
79-
:param calls: Every call the run made, in the order it made them, as `(tool name, the arguments it passed)`:
80-
81-
[("list_metadata_fields", {}), ("search_documents", {"query": "CRISPR", "filters": None})]
82-
83-
:param errors: The calls that came back an error, as `(tool name, what it said)`:
84-
85-
[("get_metadata_field_values", "field 'nope' does not exist in the store")]
86-
"""
87-
88-
calls: list[tuple[str, dict[str, Any]]] = field(default_factory=list)
89-
errors: list[tuple[str, str]] = field(default_factory=list)
90-
91-
@staticmethod
92-
def _named(tools: str | tuple[str, ...]) -> set[str]:
93-
"""
94-
Normalize one tool name or a group of them to a set.
95-
96-
:param tools: A tool name, or several of them.
97-
:returns: The names as a set.
98-
"""
99-
return {tools} if isinstance(tools, str) else set(tools)
100-
101-
def calls_to(self, tools: str | tuple[str, ...]) -> int:
102-
"""
103-
Count the calls made to one tool, or to any of a group of them.
104-
105-
:param tools: A tool name, or several of them.
106-
:returns: How many calls the run made to them.
107-
"""
108-
wanted = self._named(tools=tools)
109-
return sum(1 for name, _ in self.calls if name in wanted)
110-
111-
def called_before(self, tools: str | tuple[str, ...], other: str | tuple[str, ...]) -> bool:
112-
"""
113-
Whether the run reached for one tool before it reached for another.
114-
115-
:param tools: The tool, or tools, that should come first.
116-
:param other: The tool, or tools, they should come before.
117-
:returns: True when one of `tools` was called and none of `other` was called before it. False when
118-
`other` came first, and when neither was called at all.
119-
"""
120-
wanted, after = self._named(tools=tools), self._named(tools=other)
121-
for name, _ in self.calls:
122-
if name in wanted:
123-
return True
124-
if name in after:
125-
return False
126-
return False
127-
128-
129-
def extract_tool_run_stats(messages: list[ChatMessage]) -> ToolRunStats:
130-
"""
131-
Extract tool calls and error results from an agent run.
132-
133-
:param messages: The messages returned by `agent.run(...)`.
134-
:returns: The extracted statistics.
135-
"""
136-
return ToolRunStats(
137-
calls=[(call.tool_name, call.arguments or {}) for message in messages for call in message.tool_calls],
138-
errors=[
139-
(result.origin.tool_name, result.result)
140-
for message in messages
141-
for result in message.tool_call_results
142-
if result.error
143-
],
144-
)
145-
146-
14760
def _sum_usage(total: dict[str, int], usage: dict[str, Any]) -> dict[str, int]:
14861
"""
14962
Accumulate the numeric entries of a token-usage dict into a running total.
@@ -158,62 +71,60 @@ def _sum_usage(total: dict[str, int], usage: dict[str, Any]) -> dict[str, int]:
15871
return total
15972

16073

161-
def run_eval_case(agent: Agent, case: EvalCase, position: int, total: int) -> dict[str, Any]:
74+
def run_eval_case(agent: Agent, eval_case: RetrievalEvalCase, position: int, total: int) -> dict[str, Any]:
16275
"""
16376
Run the agent on one eval case and print its report.
16477
16578
:param agent: The agent under evaluation.
166-
:param case: The eval case to evaluate.
79+
:param eval_case: The eval case to evaluate.
16780
:param position: Which eval case this is, for the report heading.
16881
:param total: How many eval cases there are, for the report heading.
16982
:returns: A dict with `passed` (bool), `usage` (the run's token_usage dict), and `time` (s).
17083
"""
17184
started = time.perf_counter()
172-
result = agent.run(messages=[ChatMessage.from_user(case.question)])
85+
result = agent.run(messages=[ChatMessage.from_user(eval_case.question)])
17386
elapsed = time.perf_counter() - started
17487

17588
# Everything the report needs comes out of the one run: its messages, its answer and its token usage.
176-
tool_run_stats = extract_tool_run_stats(messages=result["messages"])
89+
tool_run_stats = ToolRunStats.from_messages(messages=result["messages"])
17790
answer = result["last_message"].text or ""
17891
usage = result.get("token_usage") or {}
17992

18093
# Recall on the retrieved documents: how many of the expected documents the Agent found.
18194
retrieved_docs = result.get("documents") or []
18295
retrieved_ids = {document.id for document in retrieved_docs}
183-
found = case.expected_document_ids & retrieved_ids
184-
recall = len(found) / len(case.expected_document_ids)
96+
found = eval_case.expected_document_ids & retrieved_ids
18597

18698
# Resolve each [doc <short-id>] the answer uses against what the Agent found. A reference matching nothing
18799
# is a fake citation, and one the answer doesn't use is an uncited document. Both are failures.
188100
cited_refs = _CITATION_RE.findall(answer)
189101
resolved = [ref for ref in cited_refs if any(document.id.startswith(ref) for document in retrieved_docs)]
190102
cited_ids = {document.id for document in retrieved_docs if any(document.id.startswith(r) for r in cited_refs)}
191103
citations_ok = len(resolved) == len(cited_refs)
192-
uncited = case.expected_document_ids - cited_ids
104+
uncited = eval_case.expected_document_ids - cited_ids
193105

194-
# An eval case passes only on all four: it found every expected document, cited every one of them, made no
195-
# citation that does not resolve, and stayed inside its tool budget.
196-
spent = {tools: tool_run_stats.calls_to(tools=tools) for tools in case.tool_budgets}
197-
within_budget = all(used <= case.tool_budgets[tools] for tools, used in spent.items())
198-
passed = recall == 1.0 and not uncited and citations_ok and within_budget
106+
# An eval case passes only when it cited every expected document, made no citation that does not resolve, and
107+
# stayed inside its tool budget. Citing every expected document means every one of them was retrieved too.
108+
budgets = resolve_tool_budgets(
109+
budgets=TOOL_BUDGETS, tool_names=[tool.name for tool in flatten_tools_or_toolsets(tools=agent.tools)]
110+
)
111+
over_budget = budgets_exceeded(stats=tool_run_stats, budgets=budgets)
112+
passed = not uncited and citations_ok and not over_budget
199113

200114
inspected_first = tool_run_stats.called_before(tools="list_metadata_fields", other=RETRIEVAL_TOOLS)
201115
counts = Counter(name for name, _ in tool_run_stats.calls)
202-
filtered_retrievals = sum(
203-
1 for name, args in tool_run_stats.calls if name in RETRIEVAL_TOOLS and args.get("filters")
204-
)
205-
needed = len(case.expected_document_ids)
116+
filtered_retrievals = tool_run_stats.calls_with_argument(tools=RETRIEVAL_TOOLS, argument="filters")
117+
needed = len(eval_case.expected_document_ids)
206118
print(f"\n=== eval case {position}/{total}: {'PASS' if passed else 'FAIL'} ===")
207-
print(f" question: {case.question}")
119+
print(f" question: {eval_case.question}")
208120
print(f" tools called: {dict(counts)}")
209121
print(
210122
f" inspected metadata first: {inspected_first} retrievals with a filter: {filtered_retrievals} "
211123
f"tool errors: {len(tool_run_stats.errors)} steps: {result['step_count']} time: {elapsed:.1f}s"
212124
)
213-
for tools, used in spent.items():
214-
limit = case.tool_budgets[tools]
215-
label = tools if isinstance(tools, str) else " + ".join(tools)
216-
print(f" tool budget: {label} {used}/{limit} -> {'ok' if used <= limit else 'EXCEEDED'}")
125+
for group, limit in budgets.items():
126+
used = tool_run_stats.calls_to(tools=group)
127+
print(f" tool budget: {' + '.join(group)} {used}/{limit} -> {'ok' if used <= limit else 'EXCEEDED'}")
217128
print(f" retrieval: found {len(found)}/{needed} of the documents the answer needs, {len(retrieved_docs)} returned")
218129
print(
219130
f" citations: cited {needed - len(uncited)}/{needed} of them, "
@@ -230,20 +141,20 @@ def run_eval_case(agent: Agent, case: EvalCase, position: int, total: int) -> di
230141
for title, documents in by_article.items():
231142
print(f" Title: {title}")
232143
for document in sorted(documents, key=lambda chunk: chunk.meta.get("split_id", 0)):
233-
needed_here = "-> " if document.id in case.expected_document_ids else " "
144+
needed_here = "-> " if document.id in eval_case.expected_document_ids else " "
234145
snippet = preview(text=document.content or "", limit=80)
235146
print(f" {needed_here}chunk {document.meta.get('split_id'):>2} [doc {document.id[:8]}] {snippet}")
236147
# Naming the quote, since the id alone says nothing about what the run failed to find or failed to use.
237148
print()
238-
for document_id in sorted(case.expected_document_ids - retrieved_ids):
149+
for document_id in sorted(eval_case.expected_document_ids - retrieved_ids):
239150
print(
240151
f" needed but never retrieved: [doc {document_id[:8]}] "
241-
f"{preview(text=case.evidence[document_id], limit=96)}"
152+
f"{preview(text=eval_case.evidence[document_id], limit=96)}"
242153
)
243154
for document_id in sorted(uncited & retrieved_ids):
244155
print(
245156
f" needed and retrieved but not cited: [doc {document_id[:8]}] "
246-
f"{preview(text=case.evidence[document_id], limit=96)}"
157+
f"{preview(text=eval_case.evidence[document_id], limit=96)}"
247158
)
248159

249160
if usage:
@@ -260,33 +171,29 @@ def main() -> None:
260171
"""Run the eval set and print per-eval-case reports plus a summary."""
261172
parser = argparse.ArgumentParser(description="Mini evaluation harness for the Advanced RAG agent.")
262173
parser.add_argument("--store", choices=("in_memory", "opensearch"), default="in_memory")
263-
parser.add_argument("--max-cases", type=int, default=10, help="How many labelled questions to evaluate.")
264-
parser.add_argument("--case-seed", type=int, default=0, help="Selects which eval cases are drawn from the dataset.")
174+
parser.add_argument("--max-eval-cases", type=int, default=10, help="How many labelled questions to evaluate.")
175+
parser.add_argument(
176+
"--eval-case-seed", type=int, default=0, help="Selects which eval cases are drawn from the dataset."
177+
)
265178
arguments = parser.parse_args()
266179

267180
store, articles = prepare_corpus(backend=arguments.store)
268181
chunks = sum(len(article.chunks) for article in articles.values())
269182
print(f"{CORPUS_KEY} on {arguments.store}: {chunks} chunks from {len(articles)} articles")
270183

271184
labelled: list[LabelledQuestion] = build_eval_cases(
272-
articles=articles, limit=arguments.max_cases, seed=arguments.case_seed
185+
articles=articles, limit=arguments.max_eval_cases, seed=arguments.eval_case_seed
273186
)
274-
# Budgets for the tools this agent has. Lenient on purpose: too many retrievals is better than too few.
275-
# Generous on purpose: a MultiHopRAG question needs evidence from several articles, so several searches are
276-
# the expected shape of a good run rather than a sign of floundering.
277-
budgets: dict[str | tuple[str, ...], int] = {METADATA_TOOLS: 8, RETRIEVAL_TOOLS: 12}
278-
eval_cases = [
279-
EvalCase(question=question.question, evidence=question.evidence, tool_budgets=budgets) for question in labelled
280-
]
187+
eval_cases = [RetrievalEvalCase(question=question.question, evidence=question.evidence) for question in labelled]
281188
print(f"eval cases: {len(eval_cases)} labelled from evidence")
282189

283190
# Build the advanced rag agent
284191
agent = create_advanced_rag_agent(document_store=store, retriever=build_bm25_retriever(store=store))
285192

286193
# Run the eval cases
287194
results = [
288-
run_eval_case(agent=agent, case=case, position=position, total=len(eval_cases))
289-
for position, case in enumerate(eval_cases, start=1)
195+
run_eval_case(agent=agent, eval_case=eval_case, position=position, total=len(eval_cases))
196+
for position, eval_case in enumerate(eval_cases, start=1)
290197
]
291198

292199
# Calculate total usage

0 commit comments

Comments
 (0)