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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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
"""Shared scoring library for MiniCPM tool-call evaluation.

Stdlib only. Other agents import this module; the public API is:

    parse_calls(text) -> list[dict]
    normalize_value(v) -> Any
    canon_call(call) -> tuple
    canon_calls(calls) -> list[tuple]
    categorize(row) -> str
    failure_bucket(expected, predicted, raw) -> str

Call-dict shape (produced by parse_calls, consumed by canon_call):
    {"name": <tool name str>, "arguments": {<arg str>: <value>}}
"""

import ast
import html
import json
import re
from collections import Counter


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

_FUNCTION_RE = re.compile(
    r"<\s*(?:function|tool_call)\s+name\s*=\s*(?:\"([^\"]+)\"|'([^']+)'|([^\s>]+))\s*>(.*?)<\s*/\s*(?:function|tool_call)\s*>",
    re.DOTALL | re.IGNORECASE,
)
_PARAM_RE = re.compile(
    r"<\s*param\s+name\s*=\s*(?:\"([^\"]+)\"|'([^']+)'|([^\s>]+))\s*>(.*?)<\s*/\s*param\s*>",
    re.DOTALL | re.IGNORECASE,
)
_CDATA_RE = re.compile(r"<!\[CDATA\[(.*?)\]\]>", re.DOTALL)


def _unwrap_value(raw_value):
    """Strip CDATA wrappers and unescape HTML entities."""
    text = _CDATA_RE.sub(lambda m: m.group(1), raw_value)
    text = html.unescape(text)
    return text.strip()


def _coerce_args(args):
    """Return args as a dict. JSON strings that decode to dicts are unpacked."""
    if args is None:
        return {}
    if isinstance(args, dict):
        return dict(args)
    if isinstance(args, str):
        s = args.strip()
        if not s:
            return {}
        try:
            parsed = json.loads(s)
            if isinstance(parsed, dict):
                return parsed
        except Exception:
            pass
        try:
            parsed = ast.literal_eval(s)
            if isinstance(parsed, dict):
                return parsed
        except Exception:
            pass
        return {"value": args}
    return {"value": args}


def _normalize_json_call(item):
    """Normalize one JSON call object to {"name":..., "arguments": {...}}.

    Accepts {"name", "arguments"|"parameters"|"args"|"input"} shapes as well
    as OpenAI-style {"function": {"name":..., "arguments":...}} wrappers.
    Returns None when no usable name is present.
    """
    if not isinstance(item, dict):
        return None
    if isinstance(item.get("function"), dict):
        func = item["function"]
        name = func.get("name", item.get("name"))
        args = func.get("arguments", func.get("parameters", item.get("arguments", {})))
    else:
        name = item.get("name")
        args = item.get("arguments", item.get("parameters", item.get("args", item.get("input", {}))))
    # Some producers nest single-call payloads as {"type":"function","function":{...}}
    if name is None and isinstance(item.get("function"), str):
        return None
    if not isinstance(name, str) or not name.strip():
        return None
    return {"name": name.strip(), "arguments": _coerce_args(args)}


def _parse_json_calls(text):
    """Try to interpret text as JSON holding tool calls. Returns None if N/A."""
    s = text.strip()
    if not s:
        return None
    data = None
    try:
        data = json.loads(s)
    except Exception:
        # Fall back: try decoding the first JSON object/array embedded in prose
        # (e.g. code-fenced ```json blocks or explanatory prefixes).
        start = None
        for i, ch in enumerate(s):
            if ch in "{[":
                start = i
                break
        if start is None:
            return None
        decoder = json.JSONDecoder()
        try:
            data, _ = decoder.raw_decode(s[start:])
        except Exception:
            return None
    if isinstance(data, list):
        calls = []
        for item in data:
            if isinstance(item, str):
                try:
                    item = json.loads(item)
                except Exception:
                    continue
            call = _normalize_json_call(item)
            if call is not None:
                calls.append(call)
        return calls
    if isinstance(data, dict):
        for key in ("tool_calls", "function_calls", "calls"):
            if isinstance(data.get(key), list):
                calls = []
                for item in data[key]:
                    call = _normalize_json_call(item)
                    if call is not None:
                        calls.append(call)
                return calls
        # OpenAI assistant-message shape: {"role":..., "tool_calls":[{"function":{...}}]}
        # is covered above; a bare single call {"name":...} is covered here.
        call = _normalize_json_call(data)
        if call is not None:
            return [call]
        return None
    return None


def parse_calls(text: str) -> list[dict]:
    """Parse MiniCPM XML tool calls out of raw model output.

    XML form (one or more, params may span lines, values may be CDATA)::

        <function name="get_weather"><param name="city">Paris</param></function>

    Also accepts a JSON array of call objects, or a JSON object holding
    ``tool_calls`` (OpenAI assistant-message style included), or a single
    ``{"name": ..., "arguments": {...}}`` object. ``arguments`` given as an
    encoded JSON string is decoded. ``<tool_call name=...>`` tags are
    accepted as an alias of ``<function>``.

    Returns a list of ``{"name": str, "arguments": dict}``; argument values
    stay as strings in the XML path (use :func:`normalize_value` / typed
    comparison downstream). Returns ``[]`` when nothing is found.
    """
    if text is None:
        return []
    if not isinstance(text, str):
        text = str(text)
    if not text.strip():
        return []

    calls = []
    for match in _FUNCTION_RE.finditer(text):
        name = match.group(1) or match.group(2) or match.group(3) or ""
        body = match.group(4) or ""
        args = {}
        for pmatch in _PARAM_RE.finditer(body):
            key = pmatch.group(1) or pmatch.group(2) or pmatch.group(3) or ""
            args[key.strip()] = _unwrap_value(pmatch.group(4) or "")
        calls.append({"name": name.strip(), "arguments": args})
    if calls:
        return calls

    json_calls = _parse_json_calls(text)
    if json_calls:
        return json_calls
    return []


# ---------------------------------------------------------------------------
# normalize_value / canon_call / canon_calls
# ---------------------------------------------------------------------------

def normalize_value(v):
    """Map a value to a hashable ``(tag, normalised)`` pair.

    - bool -> ``("bool", bool(v))`` (checked before int: bool is an int subclass)
    - int/float -> ``("num", float(v))``
    - list/tuple -> ``("list", tuple(normalize_value(x) ...))``
    - dict -> ``("dict", tuple(sorted((k, normalize_value(x)) ...)))``
    - None -> ``("none", None)``
    - str -> the string is stripped, then tried in order: ``json.loads``,
      ``ast.literal_eval``, case-insensitive ``true``/``false``/``null``
      (plus ``none``/``nil``) handling; otherwise ``("str", stripped)``.
      Decoded results are normalised recursively, so ``"1"``, ``1`` and
      ``"1.0"`` all become ``("num", 1.0)`` and ``"true"``/``"True"``/``True``
      all become ``("bool", True)``.
    - anything else -> ``("str", str(v).strip())``.
    """
    if isinstance(v, bool):
        return ("bool", bool(v))
    if isinstance(v, (int, float)):
        return ("num", float(v))
    if isinstance(v, (list, tuple)):
        return ("list", tuple(normalize_value(x) for x in v))
    if isinstance(v, dict):
        return ("dict", tuple(sorted(
            ((k, normalize_value(x)) for k, x in v.items()),
            key=lambda kv: str(kv[0]),
        )))
    if v is None:
        return ("none", None)
    if isinstance(v, str):
        s = v.strip()
        try:
            parsed = json.loads(s)
            if not (isinstance(parsed, str) and parsed == s):
                return normalize_value(parsed)
        except Exception:
            pass
        try:
            parsed = ast.literal_eval(s)
            if not (isinstance(parsed, str) and parsed == s):
                return normalize_value(parsed)
        except Exception:
            pass
        low = s.lower()
        if low == "true":
            return ("bool", True)
        if low == "false":
            return ("bool", False)
        if low in ("null", "none", "nil"):
            return ("none", None)
        return ("str", s)
    return ("str", str(v).strip())


def canon_call(call: dict) -> tuple:
    """Canonical form: ``(name, tuple(sorted((key, normalize_value(val)))))``.

    Accepts ``arguments`` under the aliases ``parameters``/``args``/``input``;
    a JSON-encoded string there is decoded first. The name is stripped.
    """
    if not isinstance(call, dict):
        return ("", ())
    name = call.get("name", "")
    name = name.strip() if isinstance(name, str) else str(name)
    args = call.get("arguments", call.get("parameters", call.get("args", call.get("input", {}))))
    args = _coerce_args(args)
    items = tuple(sorted(
        ((k, normalize_value(val)) for k, val in args.items()),
        key=lambda kv: str(kv[0]),
    ))
    return (name, items)


def canon_calls(calls: list) -> list:
    """Return ``sorted([canon_call(c) for c in calls])`` (``[]`` for empty)."""
    if not calls:
        return []
    canon = [canon_call(c) for c in calls]
    try:
        return sorted(canon)
    except TypeError:
        return sorted(canon, key=repr)


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

def _assistant_messages(messages):
    return [m for m in messages if isinstance(m, dict) and m.get("role") == "assistant"]


def _message_tool_calls(message):
    """Return the tool_calls list of a message (OpenAI + flat shapes)."""
    tc = message.get("tool_calls", [])
    if tc is None:
        return []
    if isinstance(tc, dict):
        tc = [tc]
    return list(tc) if isinstance(tc, list) else []


def _call_arguments(call):
    if not isinstance(call, dict):
        return {}
    func = call.get("function")
    if isinstance(func, dict):
        args = func.get("arguments", func.get("parameters", {}))
    else:
        args = call.get("arguments", call.get("parameters", call.get("args", call.get("input", {}))))
    return _coerce_args(args)


def _schema_properties(tool):
    """Extract the {prop: schema} mapping from a tool definition, or {}."""
    if not isinstance(tool, dict):
        return {}
    node = tool.get("function", tool) if isinstance(tool.get("function"), dict) else tool
    for key in ("parameters", "input_schema", "inputSchema", "schema"):
        params = node.get(key, None)
        if isinstance(params, dict):
            props = params.get("properties", params if "properties" not in params else None)
            if isinstance(props, dict):
                return props
    return {}


def categorize(row: dict) -> str:
    """Bucket a dataset row by structural difficulty.

    Priority (first hit wins): ``abstention`` > ``multi_call`` >
    ``nested_args`` > ``enum_args`` > ``long_tools`` > ``single_call``.

    - ``abstention``: the last assistant message has no ``tool_calls`` (also
      when there is no assistant message at all).
    - ``multi_call``: the last assistant message holds > 1 ``tool_calls``.
    - ``nested_args``: any property schema in any tool has
      ``type`` ``object``/``array``, or any actual argument value in any
      assistant message's tool calls is a dict/list (JSON-encoded strings
      that decode to dict/list count too).
    - ``enum_args``: any property schema in any tool defines ``enum``.
    - ``long_tools``: ``len(tools) >= 10``.
    - ``single_call``: none of the above.
    """
    tools = row.get("tools", []) or []
    messages = row.get("messages", []) or []

    assistants = _assistant_messages(messages)
    target = assistants[-1] if assistants else None
    target_calls = _message_tool_calls(target) if target is not None else []

    if not target_calls:
        return "abstention"
    if len(target_calls) > 1:
        return "multi_call"

    nested_schema = False
    enum_schema = False
    for tool in tools:
        for prop_schema in _schema_properties(tool).values():
            if not isinstance(prop_schema, dict):
                continue
            if prop_schema.get("type") in ("object", "array"):
                nested_schema = True
            if "enum" in prop_schema:
                enum_schema = True

    nested_values = False
    for message in assistants:
        for call in _message_tool_calls(message):
            for val in _call_arguments(call).values():
                if isinstance(val, (dict, list)):
                    nested_values = True
                elif isinstance(val, str):
                    s = val.strip()
                    if s[:1] in "{[":
                        try:
                            if isinstance(json.loads(s), (dict, list)):
                                nested_values = True
                        except Exception:
                            pass

    if nested_schema or nested_values:
        return "nested_args"
    if enum_schema:
        return "enum_args"
    if len(tools) >= 10:
        return "long_tools"
    return "single_call"


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

def _name_counter(calls):
    names = []
    for call in calls or []:
        if isinstance(call, dict):
            name = call.get("name", "")
            names.append(name.strip() if isinstance(name, str) else str(name))
    return Counter(names)


def _is_strict_sub(a: Counter, b: Counter) -> bool:
    """True when multiset a is a strict sub-multiset of b."""
    if a == b:
        return False
    for key, count in a.items():
        if b.get(key, 0) < count:
            return False
    return any(b.get(key, 0) > a.get(key, 0) for key in set(a) | set(b))


def _str_norm(v) -> str:
    if isinstance(v, str):
        return v.strip().lower()
    if isinstance(v, bool):
        return str(v).lower()
    if v is None:
        return "null"
    return str(v).strip().lower()


def _value_typing_match(expected, predicted) -> bool:
    """Names (as multisets) and per-call arg keys match, typed canon differs,
    but every paired value agrees under case-insensitive str-normalization."""
    exp_canon = canon_calls(expected)
    pred_canon = canon_calls(predicted)
    if exp_canon == pred_canon:
        return False
    exp_by_name = sorted(((c[0], c[1]) for c in exp_canon), key=repr)
    pred_by_name = sorted(((c[0], c[1]) for c in pred_canon), key=repr)
    if [n for n, _ in exp_by_name] != [n for n, _ in pred_by_name]:
        return False
    # Compare raw values pairwise (sorted-by-name order aligns duplicates).
    exp_raw = sorted((canon_call(c) for c in (expected or [])), key=repr)
    pred_raw = sorted((canon_call(c) for c in (predicted or [])), key=repr)
    exp_args = [dict((k, v) for k, v in items) for _, items in exp_by_name]
    _ = (exp_raw, pred_raw)  # pairing is by sorted canon order; raw order unused
    exp_calls = sorted(expected or [], key=lambda c: repr(c.get("name", "")))
    pred_calls = sorted(predicted or [], key=lambda c: repr(c.get("name", "")))
    for e_call, p_call in zip(exp_calls, pred_calls):
        e_args = _coerce_args(
            e_call.get("arguments", e_call.get("parameters", e_call.get("args", e_call.get("input", {}))))
            if isinstance(e_call, dict) else {}
        )
        p_args = _coerce_args(
            p_call.get("arguments", p_call.get("parameters", p_call.get("args", p_call.get("input", {}))))
            if isinstance(p_call, dict) else {}
        )
        if set(e_args) != set(p_args):
            return False
        for key in e_args:
            if _str_norm(e_args[key]) != _str_norm(p_args[key]):
                return False
    return True


def failure_bucket(expected: list, predicted: list, raw: str) -> str:
    """Classify one prediction. Check order (first hit wins):

    1. ``ok`` -- canonically equal (``canon_calls`` equal; includes both empty).
    2. ``unparsed`` -- not ok, ``predicted`` empty, and ``raw`` contains
       ``"<function"`` or ``"tool_call"`` (evidence of an attempted call).
    3. ``no_call`` -- ``expected`` non-empty, ``predicted`` empty.
    4. ``spurious_call`` -- ``expected`` empty, ``predicted`` non-empty.
    5. ``wrong_tool`` -- name multisets differ with neither a strict
       sub-/super-multiset of the other (disjoint or partially overlapping).
    6. ``missing_call`` -- predicted names are a strict sub-multiset.
    7. ``extra_call`` -- predicted names are a strict super-multiset.
    8. ``value_typing`` -- names and per-call arg keys match, typed canon
       differs, but all values agree under case-insensitive str-normalization
       (narrower sub-case of arg_mismatch, so checked first).
    9. ``arg_mismatch`` -- anything else with matching names but differing args.

    Note on steps 5-7 and 8-9: the spec lists ``wrong_tool`` before the
    subset cases and ``arg_mismatch`` before ``value_typing``, but both
    pairs are general-then-narrow, so the narrow case is evaluated first
    within its pair; otherwise ``missing_call``/``extra_call``/``value_typing``
    would be unreachable. Multiset (Counter) semantics reduce to set
    semantics when no tool name repeats.
    """
    exp = list(expected or [])
    pred = list(predicted or [])
    raw_text = raw if isinstance(raw, str) else ("" if raw is None else str(raw))

    if canon_calls(exp) == canon_calls(pred):
        return "ok"
    if not pred and ("<function" in raw_text or "tool_call" in raw_text):
        return "unparsed"
    if exp and not pred:
        return "no_call"
    if not exp and pred:
        return "spurious_call"

    exp_names = _name_counter(exp)
    pred_names = _name_counter(pred)
    if exp_names != pred_names:
        if _is_strict_sub(pred_names, exp_names):
            return "missing_call"
        if _is_strict_sub(exp_names, pred_names):
            return "extra_call"
        return "wrong_tool"

    if _value_typing_match(exp, pred):
        return "value_typing"
    return "arg_mismatch"