File size: 10,600 Bytes
17b0632
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
"""Tests for metrics_lib. Run: .venv\\Scripts\\python.exe pipeline\\test_metrics_lib.py

Pytest-compatible (test_* functions) AND runnable as a script with a
non-zero exit code on failure.
"""

import sys
import os

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from metrics_lib import (
    parse_calls,
    normalize_value,
    canon_call,
    canon_calls,
    categorize,
    failure_bucket,
)


def _assistant(content="hi", tool_calls=None):
    m = {"role": "assistant", "content": content}
    if tool_calls is not None:
        m["tool_calls"] = tool_calls
    return m


def _tool(name, props):
    return {"function": {"name": name, "parameters": {"type": "object", "properties": props}}}


# ---------------- parse_calls ----------------

def test_xml_single():
    calls = parse_calls('<function name="get_weather"><param name="city">Paris</param></function>')
    assert calls == [{"name": "get_weather", "arguments": {"city": "Paris"}}], calls


def test_xml_multiple():
    text = ('<function name="a"><param name="x">1</param></function> '
            'some prose '
            '<function name="b"><param name="y">2</param><param name="z">3</param></function>')
    calls = parse_calls(text)
    assert len(calls) == 2, calls
    assert calls[0]["name"] == "a" and calls[1]["name"] == "b"
    assert calls[1]["arguments"] == {"y": "2", "z": "3"}


def test_xml_multiline_param():
    text = '<function name="search"><param name="query">line one\nline two\nline three</param></function>'
    calls = parse_calls(text)
    assert calls[0]["arguments"]["query"] == "line one\nline two\nline three", calls


def test_xml_cdata():
    text = '<function name="run"><param name="code"><![CDATA[if x < 3 && y > 1 {"a": 1}]]></param></function>'
    calls = parse_calls(text)
    assert calls[0]["arguments"]["code"] == 'if x < 3 && y > 1 {"a": 1}', calls


def test_xml_single_quotes():
    calls = parse_calls("<function name='f'><param name='k'>v</param></function>")
    assert calls == [{"name": "f", "arguments": {"k": "v"}}], calls


def test_json_array():
    calls = parse_calls('[{"name": "a", "arguments": {"x": 1}}, {"name": "b", "arguments": {}}]')
    assert calls == [{"name": "a", "arguments": {"x": 1}}, {"name": "b", "arguments": {}}], calls


def test_json_tool_calls_object():
    calls = parse_calls('{"tool_calls": [{"name": "a", "arguments": {"x": 1}}]}')
    assert calls == [{"name": "a", "arguments": {"x": 1}}], calls


def test_json_openai_wrapper():
    text = ('{"role": "assistant", "tool_calls": '
            '[{"id": "1", "type": "function", "function": {"name": "a", "arguments": "{\\"x\\": 1}"}}]}')
    calls = parse_calls(text)
    assert calls == [{"name": "a", "arguments": {"x": 1}}], calls


def test_json_single_object():
    calls = parse_calls('{"name": "solo", "arguments": {"k": "v"}}')
    assert calls == [{"name": "solo", "arguments": {"k": "v"}}], calls


def test_json_args_string():
    calls = parse_calls('{"name": "a", "arguments": "{\\"x\\": 2}"}')
    assert calls == [{"name": "a", "arguments": {"x": 2}}], calls


def test_parse_empty():
    assert parse_calls("") == []
    assert parse_calls("no calls here, just prose") == []


# ---------------- normalize_value ----------------

def test_norm_true_variants():
    assert normalize_value(True) == ("bool", True)
    assert normalize_value("true") == ("bool", True)
    assert normalize_value("True") == ("bool", True)
    assert normalize_value("TRUE") == ("bool", True)
    assert normalize_value("false") == ("bool", False)
    assert normalize_value(False) == ("bool", False)


def test_norm_numeric_strings():
    assert normalize_value("1") == normalize_value(1) == normalize_value("1.0") == ("num", 1.0)
    assert normalize_value(1.5) == ("num", 1.5)
    assert normalize_value("[1, 2]") == ("list", (("num", 1.0), ("num", 2.0)))
    assert normalize_value([1, 2]) == ("list", (("num", 1.0), ("num", 2.0)))


def test_norm_bool_is_not_num():
    assert normalize_value(True) != normalize_value(1)
    assert normalize_value(True)[0] == "bool" and normalize_value(1)[0] == "num"


def test_norm_dict_and_none():
    assert normalize_value({"b": 1, "a": "x"}) == (
        "dict", (("a", ("str", "x")), ("b", ("num", 1.0))))
    assert normalize_value("null") == ("none", None)
    assert normalize_value(None) == ("none", None)
    assert normalize_value("Paris") == ("str", "Paris")


def test_canon_sort_and_coercion():
    c1 = canon_call({"name": "f", "arguments": {"b": "1", "a": 2}})
    c2 = canon_call({"name": "f", "arguments": {"a": "2", "b": 1}})
    assert c1 == c2
    assert canon_calls([{"name": "b", "arguments": {}}]) > canon_calls([{"name": "a", "arguments": {}}])
    assert canon_calls([]) == []


# ---------------- failure_bucket ----------------

def test_bucket_ok():
    exp = [{"name": "a", "arguments": {"x": 1}}]
    pred = [{"name": "a", "arguments": {"x": "1"}}]  # typed-equal after coercion
    assert failure_bucket(exp, pred, "raw") == "ok"
    assert failure_bucket([], [], "nothing") == "ok"


def test_bucket_unparsed():
    exp = [{"name": "a", "arguments": {}}]
    assert failure_bucket(exp, [], 'I will call <function name="a"> now') == "unparsed"
    assert failure_bucket(exp, [], "using tool_call id=1 ...") == "unparsed"


def test_bucket_no_call():
    exp = [{"name": "a", "arguments": {}}]
    assert failure_bucket(exp, [], "plain text, no attempt") == "no_call"


def test_bucket_spurious():
    assert failure_bucket([], [{"name": "a", "arguments": {}}], "raw") == "spurious_call"


def test_bucket_wrong_tool():
    exp = [{"name": "a", "arguments": {}}]
    assert failure_bucket(exp, [{"name": "b", "arguments": {}}], "raw") == "wrong_tool"
    exp2 = [{"name": "a", "arguments": {}}, {"name": "b", "arguments": {}}]
    pred2 = [{"name": "a", "arguments": {}}, {"name": "c", "arguments": {}}]
    assert failure_bucket(exp2, pred2, "raw") == "wrong_tool"


def test_bucket_missing_extra():
    exp = [{"name": "a", "arguments": {}}, {"name": "b", "arguments": {}}]
    assert failure_bucket(exp, [{"name": "a", "arguments": {}}], "raw") == "missing_call"
    assert failure_bucket([{"name": "a", "arguments": {}}], exp, "raw") == "extra_call"


def test_bucket_arg_mismatch():
    exp = [{"name": "a", "arguments": {"city": "Paris"}}]
    assert failure_bucket(exp, [{"name": "a", "arguments": {"city": "London"}}], "raw") == "arg_mismatch"
    assert failure_bucket(exp, [{"name": "a", "arguments": {"town": "Paris"}}], "raw") == "arg_mismatch"


def test_bucket_value_typing():
    exp = [{"name": "a", "arguments": {"city": "Paris"}}]
    assert failure_bucket(exp, [{"name": "a", "arguments": {"city": "paris"}}], "raw") == "value_typing"


# ---------------- categorize ----------------

def test_cat_abstention():
    row = {"tools": [], "messages": [{"role": "user", "content": "hi"}, _assistant("no tools")]}
    assert categorize(row) == "abstention"


def test_cat_multi():
    tc = [{"name": "a", "arguments": {}}, {"name": "b", "arguments": {}}]
    row = {"tools": [], "messages": [{"role": "user", "content": "q"}, _assistant("x", tc)]}
    assert categorize(row) == "multi_call"


def test_cat_nested_schema():
    row = {"tools": [_tool("f", {"obj": {"type": "object"}})],
           "messages": [{"role": "user", "content": "q"},
                        _assistant("x", [{"name": "f", "arguments": {"obj": "s"}}])]}
    assert categorize(row) == "nested_args"


def test_cat_nested_values():
    row = {"tools": [_tool("f", {"s": {"type": "string"}})],
           "messages": [{"role": "user", "content": "q"},
                        _assistant("x", [{"name": "f", "arguments": {"s": {"deep": 1}}}])]}
    assert categorize(row) == "nested_args"


def test_cat_enum():
    row = {"tools": [_tool("f", {"c": {"type": "string", "enum": ["r", "g"]}})],
           "messages": [{"role": "user", "content": "q"},
                        _assistant("x", [{"name": "f", "arguments": {"c": "r"}}])]}
    assert categorize(row) == "enum_args"


def test_cat_long_and_single():
    tools = [_tool("f%d" % i, {"s": {"type": "string"}}) for i in range(10)]
    row = {"tools": tools, "messages": [{"role": "user", "content": "q"},
                                        _assistant("x", [{"name": "f0", "arguments": {}}])]}
    assert categorize(row) == "long_tools"
    row2 = {"tools": [_tool("f", {"s": {"type": "string"}})],
            "messages": [{"role": "user", "content": "q"},
                         _assistant("x", [{"name": "f", "arguments": {"s": "v"}}])]}
    assert categorize(row2) == "single_call"


def test_cat_priority():
    # abstention beats multi_call history: earlier assistant had 2 calls, last has none
    tc = [{"name": "a", "arguments": {}}, {"name": "b", "arguments": {}}]
    row = {"tools": [], "messages": [{"role": "user", "content": "q"},
                                     _assistant("x", tc),
                                     {"role": "user", "content": "q2"},
                                     _assistant("none")] }
    assert categorize(row) == "abstention"
    # multi beats nested schema
    row = {"tools": [_tool("f", {"o": {"type": "object"}})],
           "messages": [{"role": "user", "content": "q"}, _assistant("x", tc)]}
    assert categorize(row) == "multi_call"
    # nested beats enum
    row = {"tools": [_tool("f", {"o": {"type": "object"}, "c": {"type": "string", "enum": ["a"]}})],
           "messages": [{"role": "user", "content": "q"},
                        _assistant("x", [{"name": "f", "arguments": {"o": "v", "c": "a"}}])]}
    assert categorize(row) == "nested_args"
    # enum beats long_tools
    tools = [_tool("f%d" % i, {"s": {"type": "string"}}) for i in range(10)]
    tools[0]["function"]["parameters"]["properties"]["s"] = {"type": "string", "enum": ["a"]}
    row = {"tools": tools, "messages": [{"role": "user", "content": "q"},
                                        _assistant("x", [{"name": "f0", "arguments": {"s": "a"}}])]}
    assert categorize(row) == "enum_args"


def main():
    tests = sorted([(k, v) for k, v in sorted(globals().items())
                    if k.startswith("test_") and callable(v)])
    failed = 0
    for name, fn in tests:
        try:
            fn()
        except Exception as e:
            failed += 1
            print("FAIL %s: %r" % (name, e))
        else:
            print("PASS %s" % name)
    print("%d passed, %d failed, %d total" % (len(tests) - failed, failed, len(tests)))
    return 1 if failed else 0


if __name__ == "__main__":
    sys.exit(main())