""" reliability_eval.py A general-purpose methodology for evaluating agent reliability, applied here to a small synthetic research-assistant agent (not the compliance domain from auditable-agent-demo -- this one is deliberately generic). Two metrics, and why they're measured separately: - Tool-call accuracy: did the agent call the tool the query actually needed? A math question answered by search, or a factual question answered by the calculator, is a tool-selection failure independent of whether the final text happens to be correct. - Hallucination rate: is every claim in the agent's final answer supported by what its tools actually returned? An agent can call the right tool and still fabricate details beyond what the tool gave it -- that's the failure mode that matters most in production, because it's invisible unless you check groundedness specifically, not just end-to-end correctness. Three mock agent policies are included to show the harness actually discriminates between reliability profiles, not just pass/fail on a single implementation. Swapping in a real model means replacing `MockPolicy.answer()` with an actual Claude tool-use loop -- the eval functions don't change. """ from dataclasses import dataclass, field import random # --- Tiny knowledge base + tools ------------------------------------------- DOCS = { "doc_founding": "Anthropic was founded in 2021 by former OpenAI researchers.", "doc_capital": "The capital of France is Paris.", "doc_mission": "Anthropic's mission is to ensure AI systems are safe and beneficial.", } def search_docs(query: str) -> str: """Very small keyword-match 'retriever' over DOCS.""" query_terms = query.lower().split() best, best_score = "", 0 for text in DOCS.values(): score = sum(1 for t in query_terms if t in text.lower()) if score > best_score: best, best_score = text, score return best def calculator(expression: str) -> str: try: # deliberately restricted eval for a small numeric demo allowed = set("0123456789+-*/(). ") if not set(expression) <= allowed: raise ValueError("disallowed characters") return str(eval(expression, {"__builtins__": {}})) except Exception as e: return f"ERROR: {e}" # --- Test set ---------------------------------------------------------------- @dataclass class QA: qid: str question: str expected_tool: str # "search_docs" | "calculator" grounding_terms: list[str] # terms the answer must trace back to the tool output TEST_SET = [ QA("Q1", "When was Anthropic founded?", "search_docs", ["2021"]), QA("Q2", "What is the capital of France?", "search_docs", ["paris"]), QA("Q3", "What is 12 * 7?", "calculator", ["84"]), QA("Q4", "What is Anthropic's mission?", "search_docs", ["safe", "beneficial"]), QA("Q5", "What is 100 / 4?", "calculator", ["25"]), ] # --- Mock agent policies ------------------------------------------------- @dataclass class AgentRecord: qid: str tool_called: str tool_output: str final_answer: str class GoodPolicy: """Calls the right tool and only states what the tool returned.""" name = "good_policy" def answer(self, qa: QA) -> AgentRecord: if qa.expected_tool == "search_docs": out = search_docs(qa.question) else: expr = qa.question.split("What is")[-1].strip(" ?") out = calculator(expr) return AgentRecord(qa.qid, qa.expected_tool, out, out) class WrongToolPolicy: """Sometimes calls the wrong tool for the query type.""" name = "wrong_tool_policy" def answer(self, qa: QA) -> AgentRecord: rng = random.Random(qa.qid) # deterministic per question for reproducibility wrong = rng.random() < 0.4 tool = ("calculator" if qa.expected_tool == "search_docs" else "search_docs") if wrong else qa.expected_tool if tool == "search_docs": out = search_docs(qa.question) else: expr = qa.question.split("What is")[-1].strip(" ?") out = calculator(expr) return AgentRecord(qa.qid, tool, out, out) class HallucinatingPolicy: """Calls the right tool but sometimes pads the answer with invented detail.""" name = "hallucinating_policy" FABRICATIONS = { "Q1": "Anthropic was founded in 2021 in San Francisco by 7 former OpenAI employees.", "Q3": "84, calculated using standard long multiplication in under a second.", } def answer(self, qa: QA) -> AgentRecord: if qa.expected_tool == "search_docs": out = search_docs(qa.question) else: expr = qa.question.split("What is")[-1].strip(" ?") out = calculator(expr) final = self.FABRICATIONS.get(qa.qid, out) return AgentRecord(qa.qid, qa.expected_tool, out, final) # --- Eval metrics ---------------------------------------------------------- def tool_call_accuracy(records: list[AgentRecord], test_set: list[QA]) -> float: by_id = {qa.qid: qa for qa in test_set} correct = sum(1 for r in records if r.tool_called == by_id[r.qid].expected_tool) return correct / len(records) def is_grounded(record: AgentRecord, qa: QA) -> bool: """ An answer is grounded if every claim in it traces back to the tool output. We approximate this cheaply: the final answer shouldn't introduce specific factual content (numbers, named entities) that isn't present in tool_output. This is a deliberately simple stand-in for a real faithfulness check (e.g. NLI-based entailment against tool_output) -- swap this function out, not the harness. """ extra_content = record.final_answer.replace(record.tool_output, "").strip() # crude but effective for this synthetic set: extra digits or # capitalized words beyond the tool output signal fabrication suspicious_tokens = [t for t in extra_content.split() if t.strip(".,") and (t[0].isupper() or t.isdigit())] return len(suspicious_tokens) == 0 def hallucination_rate(records: list[AgentRecord], test_set: list[QA]) -> float: by_id = {qa.qid: qa for qa in test_set} hallucinated = sum(1 for r in records if not is_grounded(r, by_id[r.qid])) return hallucinated / len(records) def evaluate_policy(policy) -> dict: records = [policy.answer(qa) for qa in TEST_SET] return { "policy": policy.name, "tool_call_accuracy": tool_call_accuracy(records, TEST_SET), "hallucination_rate": hallucination_rate(records, TEST_SET), "records": records, }