evalsuite-python 0.6.0__cp39-abi3-win_arm64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- evalsuite/__init__.py +268 -0
- evalsuite/__main__.py +5 -0
- evalsuite/_bench_metrics.py +2080 -0
- evalsuite/_core.pyd +0 -0
- evalsuite/_lazy.py +32 -0
- evalsuite/_native.py +60 -0
- evalsuite/api.py +275 -0
- evalsuite/benchmarks.py +946 -0
- evalsuite/calibration.py +392 -0
- evalsuite/classification/__init__.py +51 -0
- evalsuite/classification/_common.py +111 -0
- evalsuite/classification/metrics.py +945 -0
- evalsuite/cli/__init__.py +5 -0
- evalsuite/cli/main.py +606 -0
- evalsuite/clinical/__init__.py +18 -0
- evalsuite/clinical/metrics.py +342 -0
- evalsuite/clinical/report.py +366 -0
- evalsuite/core/__init__.py +1 -0
- evalsuite/core/context.py +199 -0
- evalsuite/core/exceptions.py +52 -0
- evalsuite/core/export.py +100 -0
- evalsuite/core/registry.py +90 -0
- evalsuite/core/result.py +379 -0
- evalsuite/core/types.py +23 -0
- evalsuite/core/validation.py +256 -0
- evalsuite/llmsys/__init__.py +189 -0
- evalsuite/llmsys/_common.py +215 -0
- evalsuite/llmsys/agents.py +384 -0
- evalsuite/llmsys/code.py +923 -0
- evalsuite/llmsys/efficiency.py +346 -0
- evalsuite/llmsys/longcontext.py +361 -0
- evalsuite/llmsys/multilingual.py +339 -0
- evalsuite/llmsys/robustness.py +504 -0
- evalsuite/llmsys/safety.py +509 -0
- evalsuite/llmsys/uncertainty.py +229 -0
- evalsuite/plot.py +651 -0
- evalsuite/py.typed +0 -0
- evalsuite/regression/__init__.py +41 -0
- evalsuite/regression/metrics.py +629 -0
- evalsuite/reporting.py +241 -0
- evalsuite/stats/__init__.py +46 -0
- evalsuite/stats/_resolve.py +229 -0
- evalsuite/stats/compare.py +420 -0
- evalsuite/stats/effect.py +159 -0
- evalsuite/stats/hypothesis.py +593 -0
- evalsuite/stats/intervals.py +338 -0
- evalsuite/stats/paired.py +214 -0
- evalsuite/stats/results.py +129 -0
- evalsuite/text/__init__.py +154 -0
- evalsuite/text/_common.py +97 -0
- evalsuite/text/factuality.py +469 -0
- evalsuite/text/generation.py +1346 -0
- evalsuite/text/judge.py +556 -0
- evalsuite/text/qa.py +108 -0
- evalsuite/text/rag.py +235 -0
- evalsuite/text/reasoning.py +215 -0
- evalsuite/text/report.py +158 -0
- evalsuite/text/retrieval.py +238 -0
- evalsuite/text/semantic.py +499 -0
- evalsuite/text/spice.py +162 -0
- evalsuite/text/structured.py +793 -0
- evalsuite/version.py +3 -0
- evalsuite/vision/__init__.py +47 -0
- evalsuite/vision/detection.py +696 -0
- evalsuite/vision/segmentation.py +1028 -0
- evalsuite_python-0.6.0.dist-info/METADATA +509 -0
- evalsuite_python-0.6.0.dist-info/RECORD +72 -0
- evalsuite_python-0.6.0.dist-info/WHEEL +4 -0
- evalsuite_python-0.6.0.dist-info/entry_points.txt +2 -0
- evalsuite_python-0.6.0.dist-info/licenses/LICENSE +21 -0
- evalsuite_python-0.6.0.dist-info/licenses/LICENSE-APACHE +191 -0
- evalsuite_python-0.6.0.dist-info/sboms/evalsuite-py.cyclonedx.json +576 -0
|
@@ -0,0 +1,793 @@
|
|
|
1
|
+
"""Instruction following and structured output: JSON validity and JSON Schema compliance, XML validity,
|
|
2
|
+
required-field accuracy, tool-call selection and arguments, API-call success, format compliance, constraint
|
|
3
|
+
satisfaction, multi-turn instruction retention and unwanted extra content.
|
|
4
|
+
|
|
5
|
+
JSON Schema validation is built in (the common Draft 2020-12 keywords listed in ``SUPPORTED_KEYWORDS``), so no
|
|
6
|
+
extra dependency is needed; unknown keywords raise an error instead of being ignored silently.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
import re
|
|
14
|
+
import xml.etree.ElementTree as ET
|
|
15
|
+
from collections.abc import Mapping, Sequence
|
|
16
|
+
from typing import Any, Optional
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
from ..core.exceptions import InputValidationError
|
|
21
|
+
from ..core.registry import register
|
|
22
|
+
from ..core.result import MetricResult
|
|
23
|
+
from ._common import per_item
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"SUPPORTED_KEYWORDS",
|
|
27
|
+
"api_call_success_rate",
|
|
28
|
+
"constraint_satisfaction_rate",
|
|
29
|
+
"extract_json",
|
|
30
|
+
"extra_content_rate",
|
|
31
|
+
"format_compliance",
|
|
32
|
+
"instruction_compliance_rate",
|
|
33
|
+
"instruction_retention",
|
|
34
|
+
"json_schema_compliance",
|
|
35
|
+
"json_validity",
|
|
36
|
+
"required_field_accuracy",
|
|
37
|
+
"tool_argument_accuracy",
|
|
38
|
+
"tool_call_f1",
|
|
39
|
+
"tool_selection_accuracy",
|
|
40
|
+
"validate_json_schema",
|
|
41
|
+
"xml_validity",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
_C = "text"
|
|
45
|
+
_REF_IFEVAL = (
|
|
46
|
+
"Zhou J, Lu T, Mishra S, et al. Instruction-following evaluation for large language models (IFEval). "
|
|
47
|
+
"arXiv:2311.07911. 2023."
|
|
48
|
+
)
|
|
49
|
+
_REF_BFCL = (
|
|
50
|
+
"Patil SG, Mao H, Yan F, et al. The Berkeley Function Calling Leaderboard (BFCL): from tool use to agentic "
|
|
51
|
+
"evaluation of large language models. ICML. 2025."
|
|
52
|
+
)
|
|
53
|
+
_REF_JSONSCHEMA = "JSON Schema: a media type for describing JSON documents. Draft 2020-12. json-schema.org."
|
|
54
|
+
_REF_XML = "Extensible Markup Language (XML) 1.0, 5th ed. W3C Recommendation. 2008."
|
|
55
|
+
_REF_MULTI = (
|
|
56
|
+
"Kwan WC, Zeng X, Jiang Y, et al. MT-Eval: a multi-turn capabilities evaluation benchmark for large "
|
|
57
|
+
"language models. EMNLP. 2024."
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _outputs(outputs: Any) -> list[str]:
|
|
62
|
+
if isinstance(outputs, (str, bytes)) or outputs is None:
|
|
63
|
+
raise InputValidationError("outputs must be a list of strings (one model output per example).")
|
|
64
|
+
items = list(outputs)
|
|
65
|
+
if not items:
|
|
66
|
+
raise InputValidationError("outputs is empty.")
|
|
67
|
+
for i, o in enumerate(items):
|
|
68
|
+
if not isinstance(o, str):
|
|
69
|
+
raise InputValidationError(f"outputs[{i}] must be a string; got {type(o).__name__}.")
|
|
70
|
+
return items
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _rate(
|
|
74
|
+
metric: str,
|
|
75
|
+
name: str,
|
|
76
|
+
ok: Sequence[bool],
|
|
77
|
+
extra: Optional[dict[str, Any]] = None,
|
|
78
|
+
average: Optional[str] = "mean",
|
|
79
|
+
) -> MetricResult:
|
|
80
|
+
arr = np.asarray(ok, dtype=float)
|
|
81
|
+
if average not in ("mean", None):
|
|
82
|
+
raise InputValidationError("average must be 'mean' or None (per example).")
|
|
83
|
+
value: Any = arr if average is None else float(arr.mean())
|
|
84
|
+
return MetricResult(metric, name, value, {"n": int(arr.size), **(extra or {})})
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
_FENCE = re.compile(r"```(?:json|JSON)?\s*\n?(.*?)```", re.S)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def extract_json(text: str, *, mode: str = "strict") -> Any:
|
|
91
|
+
"""Parse JSON from a model output. ``mode="strict"``: the whole output (surrounding whitespace allowed);
|
|
92
|
+
``"fenced"``: the first ```json code block if present, else the whole output; ``"lenient"``: also the
|
|
93
|
+
first balanced ``{...}`` or ``[...]`` span. Raises ``ValueError`` when nothing parses."""
|
|
94
|
+
if mode not in ("strict", "fenced", "lenient"):
|
|
95
|
+
raise InputValidationError("mode must be 'strict', 'fenced' or 'lenient'.")
|
|
96
|
+
candidates = [text.strip()]
|
|
97
|
+
if mode in ("fenced", "lenient"):
|
|
98
|
+
m = _FENCE.search(text)
|
|
99
|
+
if m:
|
|
100
|
+
candidates.insert(0, m.group(1).strip())
|
|
101
|
+
if mode == "lenient":
|
|
102
|
+
for opener, closer in (("{", "}"), ("[", "]")):
|
|
103
|
+
start = text.find(opener)
|
|
104
|
+
end = text.rfind(closer)
|
|
105
|
+
if 0 <= start < end:
|
|
106
|
+
candidates.append(text[start : end + 1])
|
|
107
|
+
for c in candidates:
|
|
108
|
+
try:
|
|
109
|
+
return json.loads(c)
|
|
110
|
+
except (ValueError, RecursionError):
|
|
111
|
+
continue
|
|
112
|
+
raise ValueError("no valid JSON found")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _try_json(text: str, mode: str) -> tuple[bool, Any]:
|
|
116
|
+
try:
|
|
117
|
+
return True, extract_json(text, mode=mode)
|
|
118
|
+
except ValueError:
|
|
119
|
+
return False, None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@register(
|
|
123
|
+
category=_C,
|
|
124
|
+
task="structured-output",
|
|
125
|
+
name="JSON validity",
|
|
126
|
+
definition="Share of outputs that parse as JSON (the whole output, or the fenced / embedded JSON in lenient "
|
|
127
|
+
"modes).",
|
|
128
|
+
formula="parseable outputs / outputs",
|
|
129
|
+
range="[0, 1]",
|
|
130
|
+
input_requirements=("outputs",),
|
|
131
|
+
references=("Bray T. The JavaScript Object Notation (JSON) data interchange format. RFC 8259. 2017.",),
|
|
132
|
+
)
|
|
133
|
+
@per_item
|
|
134
|
+
def json_validity(outputs: Any, *, mode: str = "strict", average: Optional[str] = "mean") -> MetricResult:
|
|
135
|
+
"""JSON validity. ``mode``: ``"strict"`` (default), ``"fenced"`` or ``"lenient"`` (see ``extract_json``)."""
|
|
136
|
+
outs = _outputs(outputs)
|
|
137
|
+
return _rate("json_validity", "JSON validity", [_try_json(o, mode)[0] for o in outs], {"mode": mode}, average)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# ---------------------------------------------------------------- JSON Schema (built-in validator)
|
|
141
|
+
SUPPORTED_KEYWORDS = frozenset(
|
|
142
|
+
{
|
|
143
|
+
"$schema",
|
|
144
|
+
"$id",
|
|
145
|
+
"$comment",
|
|
146
|
+
"title",
|
|
147
|
+
"description",
|
|
148
|
+
"default",
|
|
149
|
+
"examples",
|
|
150
|
+
"deprecated",
|
|
151
|
+
"readOnly",
|
|
152
|
+
"writeOnly",
|
|
153
|
+
"type",
|
|
154
|
+
"enum",
|
|
155
|
+
"const",
|
|
156
|
+
"properties",
|
|
157
|
+
"required",
|
|
158
|
+
"additionalProperties",
|
|
159
|
+
"patternProperties",
|
|
160
|
+
"minProperties",
|
|
161
|
+
"maxProperties",
|
|
162
|
+
"propertyNames",
|
|
163
|
+
"items",
|
|
164
|
+
"prefixItems",
|
|
165
|
+
"minItems",
|
|
166
|
+
"maxItems",
|
|
167
|
+
"uniqueItems",
|
|
168
|
+
"contains",
|
|
169
|
+
"minLength",
|
|
170
|
+
"maxLength",
|
|
171
|
+
"pattern",
|
|
172
|
+
"minimum",
|
|
173
|
+
"maximum",
|
|
174
|
+
"exclusiveMinimum",
|
|
175
|
+
"exclusiveMaximum",
|
|
176
|
+
"multipleOf",
|
|
177
|
+
"allOf",
|
|
178
|
+
"anyOf",
|
|
179
|
+
"oneOf",
|
|
180
|
+
"not",
|
|
181
|
+
"format",
|
|
182
|
+
"$defs",
|
|
183
|
+
"definitions",
|
|
184
|
+
"$ref",
|
|
185
|
+
}
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _json_type(v: Any) -> str:
|
|
190
|
+
if v is None:
|
|
191
|
+
return "null"
|
|
192
|
+
if isinstance(v, bool):
|
|
193
|
+
return "boolean"
|
|
194
|
+
if isinstance(v, int):
|
|
195
|
+
return "integer"
|
|
196
|
+
if isinstance(v, float):
|
|
197
|
+
return "integer" if v.is_integer() else "number"
|
|
198
|
+
if isinstance(v, str):
|
|
199
|
+
return "string"
|
|
200
|
+
if isinstance(v, list):
|
|
201
|
+
return "array"
|
|
202
|
+
if isinstance(v, dict):
|
|
203
|
+
return "object"
|
|
204
|
+
return type(v).__name__
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _json_equal(a: Any, b: Any) -> bool:
|
|
208
|
+
if isinstance(a, bool) or isinstance(b, bool):
|
|
209
|
+
return type(a) is type(b) and a == b
|
|
210
|
+
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
|
|
211
|
+
return a == b
|
|
212
|
+
if isinstance(a, list) and isinstance(b, list):
|
|
213
|
+
return len(a) == len(b) and all(_json_equal(x, y) for x, y in zip(a, b))
|
|
214
|
+
if isinstance(a, dict) and isinstance(b, dict):
|
|
215
|
+
return a.keys() == b.keys() and all(_json_equal(a[k], b[k]) for k in a)
|
|
216
|
+
return type(a) is type(b) and a == b
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _resolve(ref: str, root: Mapping[str, Any]) -> Any:
|
|
220
|
+
if not ref.startswith("#"):
|
|
221
|
+
raise InputValidationError(f"Only local $ref (starting with '#') is supported; got {ref!r}.")
|
|
222
|
+
node: Any = root
|
|
223
|
+
for part in [p for p in ref[1:].split("/") if p]:
|
|
224
|
+
part = part.replace("~1", "/").replace("~0", "~")
|
|
225
|
+
if not isinstance(node, Mapping) or part not in node:
|
|
226
|
+
raise InputValidationError(f"$ref {ref!r} cannot be resolved.")
|
|
227
|
+
node = node[part]
|
|
228
|
+
return node
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _errors(inst: Any, schema: Any, root: Mapping[str, Any], path: str, depth: int = 0) -> list[str]:
|
|
232
|
+
if depth > 100:
|
|
233
|
+
raise InputValidationError("Schema recursion is too deep (cyclic $ref?).")
|
|
234
|
+
if schema is True:
|
|
235
|
+
return []
|
|
236
|
+
if schema is False:
|
|
237
|
+
return [f"{path}: no value is allowed here"]
|
|
238
|
+
if not isinstance(schema, Mapping):
|
|
239
|
+
raise InputValidationError(f"Invalid schema at {path}: expected an object or boolean.")
|
|
240
|
+
unknown = set(schema) - SUPPORTED_KEYWORDS
|
|
241
|
+
if unknown:
|
|
242
|
+
raise InputValidationError(f"Unsupported JSON Schema keyword(s) {sorted(unknown)} at {path}.")
|
|
243
|
+
errs: list[str] = []
|
|
244
|
+
if "$ref" in schema:
|
|
245
|
+
errs += _errors(inst, _resolve(schema["$ref"], root), root, path, depth + 1)
|
|
246
|
+
t = _json_type(inst)
|
|
247
|
+
if "type" in schema:
|
|
248
|
+
allowed = schema["type"] if isinstance(schema["type"], list) else [schema["type"]]
|
|
249
|
+
if not any(a == t or (a == "number" and t == "integer") for a in allowed):
|
|
250
|
+
errs.append(f"{path}: expected {'/'.join(allowed)}, got {t}")
|
|
251
|
+
return errs
|
|
252
|
+
if "enum" in schema and not any(_json_equal(inst, e) for e in schema["enum"]):
|
|
253
|
+
errs.append(f"{path}: {inst!r} is not one of the allowed values")
|
|
254
|
+
if "const" in schema and not _json_equal(inst, schema["const"]):
|
|
255
|
+
errs.append(f"{path}: must equal {schema['const']!r}")
|
|
256
|
+
if t in ("integer", "number"):
|
|
257
|
+
x = inst
|
|
258
|
+
if "minimum" in schema and x < schema["minimum"]:
|
|
259
|
+
errs.append(f"{path}: {x} < minimum {schema['minimum']}")
|
|
260
|
+
if "maximum" in schema and x > schema["maximum"]:
|
|
261
|
+
errs.append(f"{path}: {x} > maximum {schema['maximum']}")
|
|
262
|
+
if "exclusiveMinimum" in schema and x <= schema["exclusiveMinimum"]:
|
|
263
|
+
errs.append(f"{path}: {x} <= exclusiveMinimum {schema['exclusiveMinimum']}")
|
|
264
|
+
if "exclusiveMaximum" in schema and x >= schema["exclusiveMaximum"]:
|
|
265
|
+
errs.append(f"{path}: {x} >= exclusiveMaximum {schema['exclusiveMaximum']}")
|
|
266
|
+
if "multipleOf" in schema:
|
|
267
|
+
q = x / schema["multipleOf"]
|
|
268
|
+
if not math.isclose(q, round(q), rel_tol=0, abs_tol=1e-9):
|
|
269
|
+
errs.append(f"{path}: not a multiple of {schema['multipleOf']}")
|
|
270
|
+
if t == "string":
|
|
271
|
+
n = len(inst)
|
|
272
|
+
if "minLength" in schema and n < schema["minLength"]:
|
|
273
|
+
errs.append(f"{path}: shorter than {schema['minLength']}")
|
|
274
|
+
if "maxLength" in schema and n > schema["maxLength"]:
|
|
275
|
+
errs.append(f"{path}: longer than {schema['maxLength']}")
|
|
276
|
+
if "pattern" in schema and not re.search(schema["pattern"], inst):
|
|
277
|
+
errs.append(f"{path}: does not match pattern {schema['pattern']!r}")
|
|
278
|
+
if t == "array":
|
|
279
|
+
if "minItems" in schema and len(inst) < schema["minItems"]:
|
|
280
|
+
errs.append(f"{path}: fewer than {schema['minItems']} items")
|
|
281
|
+
if "maxItems" in schema and len(inst) > schema["maxItems"]:
|
|
282
|
+
errs.append(f"{path}: more than {schema['maxItems']} items")
|
|
283
|
+
if schema.get("uniqueItems"):
|
|
284
|
+
for i in range(len(inst)):
|
|
285
|
+
if any(_json_equal(inst[i], inst[j]) for j in range(i)):
|
|
286
|
+
errs.append(f"{path}: items are not unique")
|
|
287
|
+
break
|
|
288
|
+
prefix = schema.get("prefixItems", [])
|
|
289
|
+
for i, (item, sub) in enumerate(zip(inst, prefix)):
|
|
290
|
+
errs += _errors(item, sub, root, f"{path}[{i}]", depth + 1)
|
|
291
|
+
if "items" in schema:
|
|
292
|
+
for i in range(len(prefix), len(inst)):
|
|
293
|
+
errs += _errors(inst[i], schema["items"], root, f"{path}[{i}]", depth + 1)
|
|
294
|
+
if "contains" in schema and not any(
|
|
295
|
+
not _errors(x, schema["contains"], root, path, depth + 1) for x in inst
|
|
296
|
+
):
|
|
297
|
+
errs.append(f"{path}: no item matches 'contains'")
|
|
298
|
+
if t == "object":
|
|
299
|
+
props = schema.get("properties", {})
|
|
300
|
+
for k in schema.get("required", []):
|
|
301
|
+
if k not in inst:
|
|
302
|
+
errs.append(f"{path}: missing required property {k!r}")
|
|
303
|
+
if "minProperties" in schema and len(inst) < schema["minProperties"]:
|
|
304
|
+
errs.append(f"{path}: fewer than {schema['minProperties']} properties")
|
|
305
|
+
if "maxProperties" in schema and len(inst) > schema["maxProperties"]:
|
|
306
|
+
errs.append(f"{path}: more than {schema['maxProperties']} properties")
|
|
307
|
+
pattern_props = schema.get("patternProperties", {})
|
|
308
|
+
for k, v in inst.items():
|
|
309
|
+
matched = False
|
|
310
|
+
if k in props:
|
|
311
|
+
matched = True
|
|
312
|
+
errs += _errors(v, props[k], root, f"{path}.{k}", depth + 1)
|
|
313
|
+
for pat, sub in pattern_props.items():
|
|
314
|
+
if re.search(pat, k):
|
|
315
|
+
matched = True
|
|
316
|
+
errs += _errors(v, sub, root, f"{path}.{k}", depth + 1)
|
|
317
|
+
if not matched and "additionalProperties" in schema:
|
|
318
|
+
errs += _errors(v, schema["additionalProperties"], root, f"{path}.{k}", depth + 1)
|
|
319
|
+
if "propertyNames" in schema:
|
|
320
|
+
errs += _errors(k, schema["propertyNames"], root, f"{path} (name {k!r})", depth + 1)
|
|
321
|
+
if "allOf" in schema:
|
|
322
|
+
for sub in schema["allOf"]:
|
|
323
|
+
errs += _errors(inst, sub, root, path, depth + 1)
|
|
324
|
+
if "anyOf" in schema and all(_errors(inst, sub, root, path, depth + 1) for sub in schema["anyOf"]):
|
|
325
|
+
errs.append(f"{path}: matches none of anyOf")
|
|
326
|
+
if "oneOf" in schema:
|
|
327
|
+
n_ok = sum(not _errors(inst, sub, root, path, depth + 1) for sub in schema["oneOf"])
|
|
328
|
+
if n_ok != 1:
|
|
329
|
+
errs.append(f"{path}: matches {n_ok} of oneOf (exactly one required)")
|
|
330
|
+
if "not" in schema and not _errors(inst, schema["not"], root, path, depth + 1):
|
|
331
|
+
errs.append(f"{path}: must not match 'not'")
|
|
332
|
+
return errs
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def validate_json_schema(instance: Any, schema: Mapping[str, Any]) -> list[str]:
|
|
336
|
+
"""Return the list of validation errors of ``instance`` against ``schema`` (empty if valid). ``format`` is
|
|
337
|
+
annotation-only, as in Draft 2020-12 by default."""
|
|
338
|
+
return _errors(instance, schema, schema, "$")
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
@register(
|
|
342
|
+
category=_C,
|
|
343
|
+
task="structured-output",
|
|
344
|
+
name="JSON Schema compliance",
|
|
345
|
+
definition="Share of outputs that parse as JSON and validate against a JSON Schema (types, required and "
|
|
346
|
+
"additional properties, enums, ranges, patterns, arrays, combinators, local $ref).",
|
|
347
|
+
formula="outputs valid against the schema / outputs",
|
|
348
|
+
range="[0, 1]",
|
|
349
|
+
input_requirements=("outputs", "schema"),
|
|
350
|
+
references=(_REF_JSONSCHEMA,),
|
|
351
|
+
)
|
|
352
|
+
@per_item
|
|
353
|
+
def json_schema_compliance(
|
|
354
|
+
outputs: Any, schema: Mapping[str, Any], *, mode: str = "strict", average: Optional[str] = "mean"
|
|
355
|
+
) -> MetricResult:
|
|
356
|
+
"""JSON Schema compliance; unparseable outputs count as non-compliant. ``params["errors"]`` keeps the first
|
|
357
|
+
error of each failing output, for error analysis."""
|
|
358
|
+
if not isinstance(schema, Mapping):
|
|
359
|
+
raise InputValidationError("schema must be a JSON Schema object (a dict).")
|
|
360
|
+
outs = _outputs(outputs)
|
|
361
|
+
ok, errors = [], {}
|
|
362
|
+
for i, o in enumerate(outs):
|
|
363
|
+
parsed, value = _try_json(o, mode)
|
|
364
|
+
if not parsed:
|
|
365
|
+
ok.append(False)
|
|
366
|
+
errors[i] = "not valid JSON"
|
|
367
|
+
continue
|
|
368
|
+
e = validate_json_schema(value, schema)
|
|
369
|
+
ok.append(not e)
|
|
370
|
+
if e:
|
|
371
|
+
errors[i] = e[0]
|
|
372
|
+
return _rate("json_schema_compliance", "JSON Schema compliance", ok, {"mode": mode, "errors": errors}, average)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
@register(
|
|
376
|
+
category=_C,
|
|
377
|
+
task="structured-output",
|
|
378
|
+
name="XML validity",
|
|
379
|
+
definition="Share of outputs that are well-formed XML (one root element); document type declarations are "
|
|
380
|
+
"rejected so that untrusted output cannot trigger entity expansion.",
|
|
381
|
+
formula="well-formed outputs / outputs",
|
|
382
|
+
range="[0, 1]",
|
|
383
|
+
input_requirements=("outputs",),
|
|
384
|
+
references=(_REF_XML,),
|
|
385
|
+
)
|
|
386
|
+
@per_item
|
|
387
|
+
def xml_validity(outputs: Any, *, root_tag: Optional[str] = None, average: Optional[str] = "mean") -> MetricResult:
|
|
388
|
+
"""Well-formedness (and, with ``root_tag``, the expected root element)."""
|
|
389
|
+
outs = _outputs(outputs)
|
|
390
|
+
ok = []
|
|
391
|
+
for o in outs:
|
|
392
|
+
text = o.strip()
|
|
393
|
+
if "<!DOCTYPE" in text.upper() or "<!ENTITY" in text.upper():
|
|
394
|
+
ok.append(False)
|
|
395
|
+
continue
|
|
396
|
+
try:
|
|
397
|
+
root = ET.fromstring(text) # noqa: S314 (DOCTYPE/ENTITY rejected above)
|
|
398
|
+
except ET.ParseError:
|
|
399
|
+
ok.append(False)
|
|
400
|
+
continue
|
|
401
|
+
ok.append(root_tag is None or root.tag == root_tag)
|
|
402
|
+
return _rate("xml_validity", "XML validity", ok, {"root_tag": root_tag}, average)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _get(obj: Any, path: str) -> tuple[bool, Any]:
|
|
406
|
+
node = obj
|
|
407
|
+
for part in path.split("."):
|
|
408
|
+
if isinstance(node, Mapping) and part in node:
|
|
409
|
+
node = node[part]
|
|
410
|
+
elif isinstance(node, list) and part.isdigit() and int(part) < len(node):
|
|
411
|
+
node = node[int(part)]
|
|
412
|
+
else:
|
|
413
|
+
return False, None
|
|
414
|
+
return True, node
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
@register(
|
|
418
|
+
category=_C,
|
|
419
|
+
task="structured-output",
|
|
420
|
+
name="Required-field accuracy",
|
|
421
|
+
definition="Share of expected fields (dotted paths) present in the parsed output with the expected value, "
|
|
422
|
+
"pooled over all examples; a missing field or unparseable output counts as wrong.",
|
|
423
|
+
formula="correct fields / expected fields",
|
|
424
|
+
range="[0, 1]",
|
|
425
|
+
input_requirements=("expected", "outputs"),
|
|
426
|
+
references=(_REF_BFCL,),
|
|
427
|
+
)
|
|
428
|
+
@per_item
|
|
429
|
+
def required_field_accuracy(
|
|
430
|
+
expected: Any, outputs: Any, *, mode: str = "strict", normalize: Any = None, average: Optional[str] = "micro"
|
|
431
|
+
) -> MetricResult:
|
|
432
|
+
"""``expected`` holds one dict per example mapping dotted field paths (``"address.city"``) to the expected
|
|
433
|
+
value; ``outputs`` the model outputs (JSON strings or already parsed objects). ``normalize`` optionally maps
|
|
434
|
+
values before comparison (e.g. ``str.lower`` for strings)."""
|
|
435
|
+
exp = list(expected)
|
|
436
|
+
outs = list(outputs)
|
|
437
|
+
if not exp or len(exp) != len(outs):
|
|
438
|
+
raise InputValidationError("expected and outputs must be non-empty and the same length.")
|
|
439
|
+
hits, totals = [], []
|
|
440
|
+
for i, (e, o) in enumerate(zip(exp, outs)):
|
|
441
|
+
if not isinstance(e, Mapping) or not e:
|
|
442
|
+
raise InputValidationError(f"expected[{i}] must be a non-empty dict of field path -> value.")
|
|
443
|
+
if isinstance(o, str):
|
|
444
|
+
parsed, obj = _try_json(o, mode)
|
|
445
|
+
else:
|
|
446
|
+
parsed, obj = True, o
|
|
447
|
+
n_ok = 0
|
|
448
|
+
if parsed:
|
|
449
|
+
for path, want in e.items():
|
|
450
|
+
found, got = _get(obj, path)
|
|
451
|
+
if found:
|
|
452
|
+
a, b = (normalize(got), normalize(want)) if callable(normalize) else (got, want)
|
|
453
|
+
n_ok += _json_equal(a, b)
|
|
454
|
+
hits.append(n_ok)
|
|
455
|
+
totals.append(len(e))
|
|
456
|
+
h, t = np.asarray(hits, float), np.asarray(totals, float)
|
|
457
|
+
if average == "micro":
|
|
458
|
+
value: Any = float(np.sum(h)) / float(np.sum(t))
|
|
459
|
+
elif average in ("macro", None):
|
|
460
|
+
per = h / t
|
|
461
|
+
value = per if average is None else float(per.mean())
|
|
462
|
+
else:
|
|
463
|
+
raise InputValidationError("average must be 'micro', 'macro' or None.")
|
|
464
|
+
return MetricResult(
|
|
465
|
+
"required_field_accuracy", "Required-field accuracy", value, {"average": average, "n_fields": int(t.sum())}
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
# ---------------------------------------------------------------- tool calls
|
|
470
|
+
def _calls(x: Any, name: str) -> list[list[dict[str, Any]]]:
|
|
471
|
+
items = list(x)
|
|
472
|
+
out = []
|
|
473
|
+
for i, ex in enumerate(items):
|
|
474
|
+
calls = [ex] if isinstance(ex, Mapping) else list(ex or [])
|
|
475
|
+
norm = []
|
|
476
|
+
for j, c in enumerate(calls):
|
|
477
|
+
if not isinstance(c, Mapping) or "name" not in c:
|
|
478
|
+
raise InputValidationError(
|
|
479
|
+
f"{name}[{i}][{j}] must be a dict with 'name' and optional 'arguments'."
|
|
480
|
+
)
|
|
481
|
+
args = c.get("arguments", {})
|
|
482
|
+
if isinstance(args, str):
|
|
483
|
+
try:
|
|
484
|
+
args = json.loads(args) if args.strip() else {}
|
|
485
|
+
except ValueError:
|
|
486
|
+
args = {"__unparseable__": args}
|
|
487
|
+
norm.append({"name": c["name"], "arguments": dict(args) if isinstance(args, Mapping) else args})
|
|
488
|
+
out.append(norm)
|
|
489
|
+
return out
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def _pair_calls(exp: list[list[dict[str, Any]]], pred: list[list[dict[str, Any]]]) -> None:
|
|
493
|
+
if not exp or len(exp) != len(pred):
|
|
494
|
+
raise InputValidationError("expected_calls and predicted_calls must be non-empty and the same length.")
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
@register(
|
|
498
|
+
category=_C,
|
|
499
|
+
task="tool-use",
|
|
500
|
+
name="Tool-selection accuracy",
|
|
501
|
+
definition="Share of examples whose predicted tool calls name exactly the expected tools (as a multiset; "
|
|
502
|
+
"order ignored unless ordered=True).",
|
|
503
|
+
formula="mean[tools(predicted) = tools(expected)]",
|
|
504
|
+
range="[0, 1]",
|
|
505
|
+
input_requirements=("expected_calls", "predicted_calls"),
|
|
506
|
+
references=(_REF_BFCL,),
|
|
507
|
+
)
|
|
508
|
+
@per_item
|
|
509
|
+
def tool_selection_accuracy(
|
|
510
|
+
expected_calls: Any, predicted_calls: Any, *, ordered: bool = False, average: Optional[str] = "mean"
|
|
511
|
+
) -> MetricResult:
|
|
512
|
+
"""Each example is a call ``{"name": ..., "arguments": {...}}`` or a list of calls (``[]`` = no call
|
|
513
|
+
expected)."""
|
|
514
|
+
exp, pred = _calls(expected_calls, "expected_calls"), _calls(predicted_calls, "predicted_calls")
|
|
515
|
+
_pair_calls(exp, pred)
|
|
516
|
+
ok = []
|
|
517
|
+
for e, p in zip(exp, pred):
|
|
518
|
+
en, pn = [c["name"] for c in e], [c["name"] for c in p]
|
|
519
|
+
ok.append(en == pn if ordered else sorted(map(str, en)) == sorted(map(str, pn)))
|
|
520
|
+
return _rate("tool_selection_accuracy", "Tool-selection accuracy", ok, {"ordered": ordered}, average)
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
@register(
|
|
524
|
+
category=_C,
|
|
525
|
+
task="tool-use",
|
|
526
|
+
name="Tool-argument accuracy",
|
|
527
|
+
definition="Share of expected tool calls reproduced with the right tool and exactly the expected arguments "
|
|
528
|
+
"(JSON equality after optional normalisation); calls are matched by tool name in order.",
|
|
529
|
+
formula="expected calls matched with equal arguments / expected calls",
|
|
530
|
+
range="[0, 1]",
|
|
531
|
+
input_requirements=("expected_calls", "predicted_calls"),
|
|
532
|
+
references=(_REF_BFCL,),
|
|
533
|
+
)
|
|
534
|
+
@per_item
|
|
535
|
+
def tool_argument_accuracy(expected_calls: Any, predicted_calls: Any, *, normalize: Any = None) -> MetricResult:
|
|
536
|
+
"""Pooled over all expected calls. ``normalize`` maps argument dicts before comparison (for example to
|
|
537
|
+
lowercase strings or round numbers)."""
|
|
538
|
+
exp, pred = _calls(expected_calls, "expected_calls"), _calls(predicted_calls, "predicted_calls")
|
|
539
|
+
_pair_calls(exp, pred)
|
|
540
|
+
hits = total = 0
|
|
541
|
+
for e, p in zip(exp, pred):
|
|
542
|
+
pool = list(p)
|
|
543
|
+
for call in e:
|
|
544
|
+
total += 1
|
|
545
|
+
for k, cand in enumerate(pool):
|
|
546
|
+
if cand["name"] == call["name"]:
|
|
547
|
+
a, b = cand["arguments"], call["arguments"]
|
|
548
|
+
if callable(normalize):
|
|
549
|
+
a, b = normalize(a), normalize(b)
|
|
550
|
+
if _json_equal(a, b):
|
|
551
|
+
hits += 1
|
|
552
|
+
pool.pop(k)
|
|
553
|
+
break
|
|
554
|
+
if total == 0:
|
|
555
|
+
raise InputValidationError("No expected tool calls to score.")
|
|
556
|
+
return MetricResult(
|
|
557
|
+
"tool_argument_accuracy", "Tool-argument accuracy", hits / total, {"n_expected_calls": total}
|
|
558
|
+
)
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
@register(
|
|
562
|
+
category=_C,
|
|
563
|
+
task="tool-use",
|
|
564
|
+
name="Tool-call precision, recall and F1",
|
|
565
|
+
definition="Matching of predicted to expected calls (same tool, and same arguments unless "
|
|
566
|
+
"match='name'), pooled over examples: precision over predicted calls, recall over expected calls.",
|
|
567
|
+
formula="F1 = 2PR/(P+R), P = matched/predicted, R = matched/expected",
|
|
568
|
+
range="[0, 1]",
|
|
569
|
+
input_requirements=("expected_calls", "predicted_calls"),
|
|
570
|
+
references=(_REF_BFCL,),
|
|
571
|
+
)
|
|
572
|
+
@per_item
|
|
573
|
+
def tool_call_f1(expected_calls: Any, predicted_calls: Any, *, match: str = "arguments") -> MetricResult:
|
|
574
|
+
"""Tool-call F1 with precision and recall in ``params``; ``params["invalid_call_rate"]`` counts predicted
|
|
575
|
+
calls whose arguments were not valid JSON."""
|
|
576
|
+
if match not in ("arguments", "name"):
|
|
577
|
+
raise InputValidationError("match must be 'arguments' or 'name'.")
|
|
578
|
+
exp, pred = _calls(expected_calls, "expected_calls"), _calls(predicted_calls, "predicted_calls")
|
|
579
|
+
_pair_calls(exp, pred)
|
|
580
|
+
matched = n_pred = n_exp = invalid = 0
|
|
581
|
+
for e, p in zip(exp, pred):
|
|
582
|
+
n_exp += len(e)
|
|
583
|
+
n_pred += len(p)
|
|
584
|
+
invalid += sum("__unparseable__" in c["arguments"] for c in p if isinstance(c["arguments"], dict))
|
|
585
|
+
pool = list(p)
|
|
586
|
+
for call in e:
|
|
587
|
+
for k, cand in enumerate(pool):
|
|
588
|
+
if cand["name"] == call["name"] and (
|
|
589
|
+
match == "name" or _json_equal(cand["arguments"], call["arguments"])
|
|
590
|
+
):
|
|
591
|
+
matched += 1
|
|
592
|
+
pool.pop(k)
|
|
593
|
+
break
|
|
594
|
+
precision = matched / n_pred if n_pred else (1.0 if n_exp == 0 else 0.0)
|
|
595
|
+
recall = matched / n_exp if n_exp else 1.0
|
|
596
|
+
f1 = 0.0 if precision + recall == 0 else 2 * precision * recall / (precision + recall)
|
|
597
|
+
return MetricResult(
|
|
598
|
+
"tool_call_f1",
|
|
599
|
+
"Tool-call F1",
|
|
600
|
+
f1,
|
|
601
|
+
{
|
|
602
|
+
"precision": precision,
|
|
603
|
+
"recall": recall,
|
|
604
|
+
"match": match,
|
|
605
|
+
"invalid_call_rate": invalid / n_pred if n_pred else 0.0,
|
|
606
|
+
"n_expected": n_exp,
|
|
607
|
+
"n_predicted": n_pred,
|
|
608
|
+
},
|
|
609
|
+
)
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
@register(
|
|
613
|
+
category=_C,
|
|
614
|
+
task="tool-use",
|
|
615
|
+
name="API-call success rate",
|
|
616
|
+
definition="Share of tool or API calls that completed successfully (status flags, HTTP status codes below "
|
|
617
|
+
"400, or exceptions recorded as failures).",
|
|
618
|
+
formula="successful calls / calls",
|
|
619
|
+
range="[0, 1]",
|
|
620
|
+
input_requirements=("results",),
|
|
621
|
+
references=(_REF_BFCL,),
|
|
622
|
+
)
|
|
623
|
+
@per_item
|
|
624
|
+
def api_call_success_rate(results: Any) -> MetricResult:
|
|
625
|
+
"""``results``: booleans, HTTP status codes, or ``None`` / exception objects for failures."""
|
|
626
|
+
items = list(results)
|
|
627
|
+
if not items:
|
|
628
|
+
raise InputValidationError("results is empty.")
|
|
629
|
+
ok = []
|
|
630
|
+
for r in items:
|
|
631
|
+
if isinstance(r, (bool, np.bool_)):
|
|
632
|
+
ok.append(bool(r))
|
|
633
|
+
elif isinstance(r, (int, np.integer)):
|
|
634
|
+
ok.append(100 <= int(r) < 400)
|
|
635
|
+
elif r is None or isinstance(r, BaseException):
|
|
636
|
+
ok.append(False)
|
|
637
|
+
else:
|
|
638
|
+
raise InputValidationError(
|
|
639
|
+
f"Unrecognised call result {r!r}: use bool, an HTTP status, None or an exception."
|
|
640
|
+
)
|
|
641
|
+
return _rate("api_call_success_rate", "API-call success rate", ok)
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
# ---------------------------------------------------------------- instructions and format
|
|
645
|
+
def _check_matrix(checks: Any, name: str) -> list[list[bool]]:
|
|
646
|
+
rows = list(checks)
|
|
647
|
+
if not rows:
|
|
648
|
+
raise InputValidationError(f"{name} is empty.")
|
|
649
|
+
out = []
|
|
650
|
+
for i, r in enumerate(rows):
|
|
651
|
+
vals = [bool(v) for v in (r if isinstance(r, (list, tuple, np.ndarray)) else [r])]
|
|
652
|
+
if not vals:
|
|
653
|
+
raise InputValidationError(f"{name}[{i}] has no checks.")
|
|
654
|
+
out.append(vals)
|
|
655
|
+
return out
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
@register(
|
|
659
|
+
category=_C,
|
|
660
|
+
task="instruction-following",
|
|
661
|
+
name="Instruction compliance rate",
|
|
662
|
+
definition="Share of outputs that satisfy every instruction checked for them (IFEval prompt-level strict "
|
|
663
|
+
"accuracy).",
|
|
664
|
+
formula="outputs with all checks passed / outputs",
|
|
665
|
+
range="[0, 1]",
|
|
666
|
+
input_requirements=("checks",),
|
|
667
|
+
references=(_REF_IFEVAL,),
|
|
668
|
+
)
|
|
669
|
+
@per_item
|
|
670
|
+
def instruction_compliance_rate(checks: Any) -> MetricResult:
|
|
671
|
+
"""``checks`` holds, per output, the list of pass/fail results of its verifiable instructions."""
|
|
672
|
+
m = _check_matrix(checks, "checks")
|
|
673
|
+
return _rate("instruction_compliance_rate", "Instruction compliance rate", [all(r) for r in m])
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
@register(
|
|
677
|
+
category=_C,
|
|
678
|
+
task="instruction-following",
|
|
679
|
+
name="Constraint satisfaction rate",
|
|
680
|
+
definition="Share of individual constraints satisfied, pooled over all outputs (IFEval instruction-level "
|
|
681
|
+
"accuracy).",
|
|
682
|
+
formula="satisfied constraints / constraints",
|
|
683
|
+
range="[0, 1]",
|
|
684
|
+
input_requirements=("checks",),
|
|
685
|
+
references=(_REF_IFEVAL,),
|
|
686
|
+
)
|
|
687
|
+
@per_item
|
|
688
|
+
def constraint_satisfaction_rate(checks: Any) -> MetricResult:
|
|
689
|
+
"""Same input as ``instruction_compliance_rate``; every constraint counts once."""
|
|
690
|
+
m = _check_matrix(checks, "checks")
|
|
691
|
+
flat = [v for r in m for v in r]
|
|
692
|
+
return MetricResult(
|
|
693
|
+
"constraint_satisfaction_rate",
|
|
694
|
+
"Constraint satisfaction rate",
|
|
695
|
+
float(np.mean(flat)),
|
|
696
|
+
{"n_constraints": len(flat), "n_outputs": len(m)},
|
|
697
|
+
)
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
@register(
|
|
701
|
+
category=_C,
|
|
702
|
+
task="instruction-following",
|
|
703
|
+
name="Format compliance",
|
|
704
|
+
definition="Share of outputs that fully match a required format, given as a regular expression (for "
|
|
705
|
+
"example a refusal template or an answer line such as 'Answer: <letter>').",
|
|
706
|
+
formula="outputs matching the format / outputs",
|
|
707
|
+
range="[0, 1]",
|
|
708
|
+
input_requirements=("outputs", "pattern"),
|
|
709
|
+
references=(_REF_IFEVAL,),
|
|
710
|
+
)
|
|
711
|
+
@per_item
|
|
712
|
+
def format_compliance(
|
|
713
|
+
outputs: Any, pattern: str, *, flags: int = re.S, average: Optional[str] = "mean"
|
|
714
|
+
) -> MetricResult:
|
|
715
|
+
"""``re.fullmatch(pattern, output.strip())`` per output.
|
|
716
|
+
|
|
717
|
+
The pattern is compiled with Python's backtracking ``re`` engine; patterns with nested quantifiers such as
|
|
718
|
+
``(a+)+$`` can take exponential time on some outputs, so only pass patterns you trust.
|
|
719
|
+
"""
|
|
720
|
+
outs = _outputs(outputs)
|
|
721
|
+
try:
|
|
722
|
+
rx = re.compile(pattern, flags)
|
|
723
|
+
except re.error as exc:
|
|
724
|
+
raise InputValidationError(f"Invalid pattern: {exc}") from exc
|
|
725
|
+
return _rate(
|
|
726
|
+
"format_compliance",
|
|
727
|
+
"Format compliance",
|
|
728
|
+
[bool(rx.fullmatch(o.strip())) for o in outs],
|
|
729
|
+
{"pattern": pattern},
|
|
730
|
+
average,
|
|
731
|
+
)
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
@register(
|
|
735
|
+
category=_C,
|
|
736
|
+
task="instruction-following",
|
|
737
|
+
name="Multi-turn instruction retention",
|
|
738
|
+
definition="Share of later turns in which instructions given earlier in the conversation are still "
|
|
739
|
+
"satisfied, pooled over conversations.",
|
|
740
|
+
formula="later-turn checks passed / later-turn checks",
|
|
741
|
+
range="[0, 1]",
|
|
742
|
+
input_requirements=("turn_checks",),
|
|
743
|
+
references=(_REF_MULTI,),
|
|
744
|
+
)
|
|
745
|
+
@per_item
|
|
746
|
+
def instruction_retention(turn_checks: Any) -> MetricResult:
|
|
747
|
+
"""``turn_checks``: per conversation, a list over turns (after the instruction was given) of booleans or
|
|
748
|
+
lists of booleans (one per earlier instruction still in force)."""
|
|
749
|
+
convs = list(turn_checks)
|
|
750
|
+
if not convs:
|
|
751
|
+
raise InputValidationError("turn_checks is empty.")
|
|
752
|
+
flat = [
|
|
753
|
+
bool(v) for conv in convs for turn in conv for v in (turn if isinstance(turn, (list, tuple)) else [turn])
|
|
754
|
+
]
|
|
755
|
+
if not flat:
|
|
756
|
+
raise InputValidationError("No later-turn checks to score.")
|
|
757
|
+
return MetricResult(
|
|
758
|
+
"instruction_retention",
|
|
759
|
+
"Instruction retention",
|
|
760
|
+
float(np.mean(flat)),
|
|
761
|
+
{"n_checks": len(flat), "n_conversations": len(convs)},
|
|
762
|
+
)
|
|
763
|
+
|
|
764
|
+
|
|
765
|
+
@register(
|
|
766
|
+
category=_C,
|
|
767
|
+
task="structured-output",
|
|
768
|
+
name="Unwanted extra-content rate",
|
|
769
|
+
definition="Share of outputs that contain text beyond the requested payload, e.g. prose or code fences "
|
|
770
|
+
"around JSON that should stand alone.",
|
|
771
|
+
formula="outputs with extra content / outputs",
|
|
772
|
+
range="[0, 1]",
|
|
773
|
+
input_requirements=("outputs",),
|
|
774
|
+
references=(_REF_IFEVAL,),
|
|
775
|
+
higher_is_better=False,
|
|
776
|
+
)
|
|
777
|
+
@per_item
|
|
778
|
+
def extra_content_rate(outputs: Any, *, payload: str = "json", pattern: Optional[str] = None) -> MetricResult:
|
|
779
|
+
"""``payload="json"``: extra content means the output is not JSON on its own but JSON can be found inside it
|
|
780
|
+
(fenced or embedded); outputs with no JSON at all are not counted here (see ``json_validity``).
|
|
781
|
+
``payload="regex"`` with ``pattern``: extra content means the pattern matches a part but not the whole."""
|
|
782
|
+
outs = _outputs(outputs)
|
|
783
|
+
flags = []
|
|
784
|
+
if payload == "json":
|
|
785
|
+
for o in outs:
|
|
786
|
+
strict = _try_json(o, "strict")[0]
|
|
787
|
+
flags.append(not strict and _try_json(o, "lenient")[0])
|
|
788
|
+
elif payload == "regex" and pattern:
|
|
789
|
+
rx = re.compile(pattern, re.S)
|
|
790
|
+
flags = [bool(rx.search(o)) and not rx.fullmatch(o.strip()) for o in outs]
|
|
791
|
+
else:
|
|
792
|
+
raise InputValidationError("payload must be 'json', or 'regex' together with a pattern.")
|
|
793
|
+
return _rate("extra_content_rate", "Extra-content rate", flags, {"payload": payload})
|