File size: 6,649 Bytes
194fbd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""
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,
    }