Download metrics_lib.py from DevGwardo/minicpm5-toolcall-code: direct link, hf CLI and curl.
- Browser
- Download file 18.6 kB
-
https://huggingface.co/datasets/DevGwardo/minicpm5-toolcall-code/resolve/main/metrics_lib.py
- Command line
-
hf download hf://datasets/DevGwardo/minicpm5-toolcall-code/metrics_lib.py
-
curl -L -o metrics_lib.py https://huggingface.co/datasets/DevGwardo/minicpm5-toolcall-code/resolve/main/metrics_lib.py
18.6 kB
| """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" | |