Coverage for app / services / evaluation / dataset.py: 92%
314 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Dataset resolution for evaluation runs.
4Both benchmarking and experiments evaluate a *dataset* — an ordered list of
5inputs, each optionally paired with a reference answer. A test suite is the
6persistent form of one; an experiment may either point at a test suite (so the
7same cases grade every prompt variant) or carry its own inline cases for a
8quick throwaway comparison.
9"""
11from __future__ import annotations
13import csv
14import io
15import json
16import logging
17from dataclasses import dataclass, field
18from typing import Any, Iterable, Optional
19from uuid import UUID
21from sqlalchemy.orm import Session
23from app.db.postgres.models import TestCase, TestSuite
24from app.services.evaluation.criteria import BEHAVIOURS
25from app.services.evaluation.criteria import facts as criteria_facts
26from app.services.evaluation.criteria import items as criteria_items
28logger = logging.getLogger(__name__)
30# Safety valve: an unbounded matrix (variants × cases) can issue thousands of
31# provider calls from one click, so every run is capped.
32MAX_CASES_PER_RUN = 500
35@dataclass
36class DatasetCase:
37 """One case as the runner sees it: a question and what correct looks like.
39 Everything that says what is correct is here, and nothing else is:
40 ``expected_output`` (the reference answer), ``criteria`` as items — the
41 dataset's, inherited as ``dataset_criteria``, plus the case's own —
42 ``examples`` graded in advance, and ``expectation``, the mechanical checks
43 (format, schema, must / must not contain, pattern). ``situation`` is the
44 conversation the question arrives in and its variables. None of it says
45 how strictly to judge or who answers: those are the experiment's and the
46 variant's, and a case that carried them would let the same dataset be
47 graded two ways.
48 """
50 input: str
51 name: str = ""
52 expected_output: Optional[str] = None
53 case_id: Optional[str] = None
54 tags: list[str] = field(default_factory=list)
55 criteria: list[dict[str, Any]] = field(default_factory=list)
56 dataset_criteria: list[dict[str, Any]] = field(default_factory=list)
57 examples: list[dict[str, Any]] = field(default_factory=list)
58 #: ``answer`` / ``clarify`` / ``decline``, or None when unstated.
59 behaviour: Optional[str] = None
60 expectation: dict[str, Any] = field(default_factory=dict)
61 situation: dict[str, Any] = field(default_factory=dict)
63 def describe(self) -> dict[str, Any]:
64 """The identity of this case, persisted on each run's ``input`` column.
66 Includes the label the cell was graded against, so a result reads
67 back as "this answer, judged against this" even after the case is
68 edited.
69 """
70 described: dict[str, Any] = {
71 "prompt": self.input,
72 "name": self.name,
73 "case_id": self.case_id,
74 "expected_output": self.expected_output,
75 }
76 if self.criteria:
77 described["criteria"] = self.criteria
78 if self.dataset_criteria:
79 described["dataset_criteria"] = self.dataset_criteria
80 if self.examples:
81 described["examples"] = [dict(e) for e in self.examples]
82 if self.behaviour:
83 described["expected_behaviour"] = self.behaviour
84 if self.expectation:
85 described["expectation"] = dict(self.expectation)
86 return described
89class DatasetError(ValueError):
90 """Raised when a dataset spec cannot be resolved into cases."""
93def case_input_text(raw: Any) -> str:
94 """Extract the prompt text from a test case's ``input`` JSON.
96 ``TestCase.input`` is a free-form object so structured inputs stay
97 possible; the conventional key is ``prompt``, and a plain string or a
98 single-valued object are both accepted so hand-written and imported cases
99 behave the same.
100 """
101 if isinstance(raw, str):
102 return raw
103 if isinstance(raw, dict):
104 for key in ("prompt", "input", "text", "question", "query"):
105 value = raw.get(key)
106 if isinstance(value, str) and value.strip():
107 return value
108 # A structured input with no conventional key is still runnable — send
109 # it as JSON so schema-driven prompts work.
110 return json.dumps(raw, ensure_ascii=False)
111 return "" if raw is None else str(raw)
114def cases_from_dataset(db: Session, dataset_id: UUID) -> list[DatasetCase]:
115 """Load a dataset's cases in stable creation order.
117 Raises :class:`DatasetError` when the dataset does not exist, has no
118 cases, or has more than a run may take — so a caller validating a request
119 gets a message it can show, and the background task never meets an empty
120 matrix.
121 """
122 suite = db.get(TestSuite, dataset_id)
123 if suite is None:
124 raise DatasetError(f"Dataset {dataset_id} not found.")
125 shared = criteria_items(getattr(suite, "criteria", None))
126 rows = (
127 db.query(TestCase)
128 .filter(TestCase.test_suite_id == dataset_id)
129 .order_by(TestCase.created_at, TestCase.id)
130 .all()
131 )
132 cases = [
133 DatasetCase(
134 input=case_input_text(row.input),
135 name=row.name or f"Case {index + 1}",
136 expected_output=row.expected_output,
137 case_id=str(row.id),
138 tags=list(row.tags or []),
139 criteria=criteria_items(row.criteria),
140 dataset_criteria=shared,
141 examples=clean_examples(row.examples),
142 behaviour=_behaviour(getattr(row, "expected_behaviour", None)),
143 expectation=dict(row.expectation or {}),
144 situation=dict(row.situation or {}),
145 )
146 for index, row in enumerate(rows)
147 ]
148 if not cases:
149 raise DatasetError("This dataset has no cases. Add or import some first.")
150 if len(cases) > MAX_CASES_PER_RUN:
151 raise DatasetError(
152 f"Dataset has {len(cases)} cases; the limit per run is {MAX_CASES_PER_RUN}."
153 )
154 return cases
157def _behaviour(value: Any) -> Optional[str]:
158 text = str(value or "").strip().lower()
159 return text if text in BEHAVIOURS else None
162def clean_examples(raw: Any) -> list[dict[str, Any]]:
163 """Graded examples as stored, keeping only well-formed ones.
165 Written through a validated schema, so this only ever drops rows that
166 predate it — but a judge prompt built from a malformed row would fail the
167 cell, and one bad example must not cost a case its score.
168 """
169 out: list[dict[str, Any]] = []
170 for example in raw if isinstance(raw, list) else []:
171 if (
172 not isinstance(example, dict)
173 or not str(example.get("output") or "").strip()
174 ):
175 continue
176 try:
177 score = max(0.0, min(1.0, float(example.get("score"))))
178 except (TypeError, ValueError):
179 continue
180 entry: dict[str, Any] = {"output": str(example["output"]), "score": score}
181 if example.get("note"):
182 entry["note"] = str(example["note"])
183 out.append(entry)
184 return out
187def cases_from_inline(raw_cases: Iterable[Any]) -> list[DatasetCase]:
188 """Build cases from an inline list of prompts or case objects."""
189 cases: list[DatasetCase] = []
190 for index, entry in enumerate(raw_cases or []):
191 if isinstance(entry, str):
192 if not entry.strip():
193 continue
194 cases.append(DatasetCase(input=entry, name=f"Case {index + 1}"))
195 continue
196 if not isinstance(entry, dict):
197 continue
198 text = case_input_text(entry.get("input", entry.get("prompt")))
199 if not text.strip():
200 continue
201 cases.append(
202 DatasetCase(
203 input=text,
204 name=entry.get("name") or f"Case {index + 1}",
205 expected_output=entry.get("expected_output"),
206 case_id=entry.get("case_id"),
207 tags=list(entry.get("tags") or []),
208 criteria=criteria_items(entry.get("criteria")),
209 dataset_criteria=criteria_items(entry.get("dataset_criteria")),
210 examples=clean_examples(entry.get("examples")),
211 behaviour=_behaviour(entry.get("expected_behaviour")),
212 expectation=dict(entry.get("expectation") or {}),
213 situation=dict(entry.get("situation") or {}),
214 )
215 )
216 return cases
219# ── Bulk import ───────────────────────────────────────────────────────────────
221# Column aliases accepted by the importer, so a file exported from another
222# eval tool imports without the user renaming headers first.
223_INPUT_KEYS = ("input", "prompt", "question", "query", "text")
224_EXPECTED_KEYS = ("expected_output", "expected", "answer", "output", "reference")
225_NAME_KEYS = ("name", "id", "case", "title")
226_CRITERIA_KEYS = ("criteria", "rubric", "grading_criteria", "success_criteria")
227_TAG_KEYS = ("tags", "tag", "labels")
228_EXAMPLE_KEYS = ("examples", "graded_examples")
229_BEHAVIOUR_KEYS = ("expected_behaviour", "expected_behavior", "behaviour", "behavior")
230_CHECK_KEYS = ("expectation", "checks")
231_SITUATION_KEYS = ("situation",)
232#: Classifications that become ``key:value`` tags, so a file that files its
233#: cases by category and difficulty keeps that filing.
234_TAGGED_FIELDS = ("category", "difficulty")
235#: Check keys, accepted inside ``expectation`` or at the top level of a row.
236_CHECK_FIELDS = (
237 "format",
238 "schema",
239 "must_contain",
240 "must_not_contain",
241 "pattern",
242 "facts",
243 "must_use_tools",
244 "must_not_use_tools",
245)
246_FORMATS = ("text", "json", "markdown")
248#: Fields other tools put on a case that this model does not take, and why —
249#: so the import says where the information has to go instead of dropping it.
250UNSUPPORTED_FIELDS: dict[str, str] = {
251 "tools_allowed": "Tools are chosen per variant, not per case.",
252 "tools": "Tools are chosen per variant, not per case.",
253}
254_GENERIC_REASON = "Not a case field."
257@dataclass
258class ImportReport:
259 """Parsed cases, and every field that could not be imported."""
261 cases: list[DatasetCase]
262 #: field → {"reason", "cases": [case names]}
263 ignored: dict[str, dict[str, Any]] = field(default_factory=dict)
265 def ignore(self, key: str, case_name: str, reason: str) -> None:
266 entry = self.ignored.setdefault(key, {"reason": reason, "cases": []})
267 entry["cases"].append(case_name)
269 def ignored_list(self) -> list[dict[str, Any]]:
270 return [
271 {"field": key, "reason": entry["reason"], "cases": entry["cases"]}
272 for key, entry in sorted(self.ignored.items())
273 ]
276def _pick(row: dict, keys: tuple[str, ...]) -> Optional[str]:
277 lowered = {str(k).strip().lower(): v for k, v in row.items() if k is not None}
278 for key in keys:
279 value = lowered.get(key)
280 if isinstance(value, str) and value.strip():
281 return value.strip()
282 if value not in (None, ""):
283 return str(value)
284 return None
287def _split_tags(raw: Optional[str]) -> list[str]:
288 if not raw:
289 return []
290 return [t.strip() for t in str(raw).replace(";", ",").split(",") if t.strip()]
293def _present(value: Any) -> bool:
294 return value not in (None, "", [], {})
297class _Row:
298 """One imported row, remembering which of its keys were used."""
300 def __init__(self, raw: dict) -> None:
301 self.values = {
302 str(k).strip().lower(): v for k, v in raw.items() if k is not None
303 }
304 self.used: set[str] = set()
306 def take(self, keys: tuple[str, ...]) -> tuple[Optional[str], Any]:
307 """The first present key of ``keys`` and its value; marks it used."""
308 for key in keys:
309 if key in self.values and _present(self.values[key]):
310 self.used.add(key)
311 return key, self.values[key]
312 return None, None
314 def leftovers(self) -> dict[str, Any]:
315 return {
316 k: v for k, v in self.values.items() if k not in self.used and _present(v)
317 }
320def _text(value: Any) -> Optional[str]:
321 if isinstance(value, str):
322 return value.strip() or None
323 if isinstance(value, (int, float)) and not isinstance(value, bool):
324 return str(value)
325 return None
328def _lines(value: Any) -> list[str]:
329 if isinstance(value, list):
330 return [str(v) for v in value if str(v).strip()]
331 if isinstance(value, str):
332 return [line.strip() for line in value.splitlines() if line.strip()]
333 return []
336def _checks(value: Any, report: ImportReport, name: str, prefix: str) -> dict:
337 """The recognised check keys of ``value``; the rest reported by name."""
338 out: dict[str, Any] = {}
339 for key, raw in (value or {}).items():
340 key = str(key).strip().lower()
341 if not _present(raw):
342 continue
343 if key in ("must_contain", "must_not_contain") and _lines(raw):
344 out[key] = _lines(raw)
345 elif key == "pattern" and _text(raw):
346 out[key] = _text(raw)
347 elif key == "format" and str(raw).lower() in _FORMATS:
348 out[key] = str(raw).lower()
349 elif key == "schema" and isinstance(raw, dict):
350 out[key] = raw
351 elif key in ("must_use_tools", "must_not_use_tools") and _lines(raw):
352 out[key] = _lines(raw)
353 elif key == "facts" and isinstance(raw, list):
354 kept = criteria_facts(raw)
355 if len(kept) < len(raw):
356 report.ignore(
357 f"{prefix}facts",
358 name,
359 "Each fact needs a `value`: a number, or text / a list of "
360 "accepted spellings.",
361 )
362 if kept:
363 out[key] = kept
364 else:
365 report.ignore(
366 f"{prefix}{key}",
367 name,
368 f"Checks are {', '.join(_CHECK_FIELDS)} "
369 f"(format one of {', '.join(_FORMATS)}).",
370 )
371 return out
374def _case_from_row(
375 raw: dict, index: int, report: ImportReport
376) -> Optional[DatasetCase]:
377 row = _Row(raw)
378 _, prompt = row.take(_INPUT_KEYS)
379 prompt = _text(prompt) if not isinstance(prompt, dict) else json.dumps(prompt)
380 if not prompt:
381 return None
382 _, name = row.take(_NAME_KEYS)
383 name = _text(name) or f"Case {index + 1}"
385 # The reference answer. A structured ``expected`` object is split: a
386 # scalar ``answer`` is the reference, and every number or text value —
387 # the answer included — becomes a fact, checked by code. A dict
388 # stringified into the reference answer is a label no scorer can use.
389 expected_key, expected = row.take(_EXPECTED_KEYS)
390 reference = _text(expected)
391 expected_facts: list[dict[str, Any]] = []
392 behaviour: Optional[str] = None
393 if isinstance(expected, dict):
394 reference = _text(expected.get("answer"))
395 for key, value in expected.items():
396 # The one behaviour other tools commonly encode as a flag.
397 if key == "requires_clarification" and isinstance(value, bool):
398 behaviour = "clarify" if value else None
399 continue
400 if isinstance(value, bool) or not _text(value):
401 report.ignore(
402 f"{expected_key}.{key}",
403 name,
404 "Only numbers and text become facts. Expected behaviour "
405 "(asking for clarification, using a tool) belongs in the "
406 "criteria.",
407 )
408 continue
409 expected_facts.append({"label": str(key), "value": value})
410 elif expected is not None and reference is None:
411 report.ignore(expected_key, name, "A reference answer must be text.")
413 _, criteria = row.take(_CRITERIA_KEYS)
415 behaviour_key, raw_behaviour = row.take(_BEHAVIOUR_KEYS)
416 if raw_behaviour is not None:
417 stated = _behaviour(raw_behaviour)
418 if stated is None:
419 report.ignore(
420 behaviour_key,
421 name,
422 f"Expected behaviour is one of {', '.join(BEHAVIOURS)}.",
423 )
424 behaviour = stated or behaviour
426 examples: list[dict[str, Any]] = []
427 example_key, raw_examples = row.take(_EXAMPLE_KEYS)
428 if raw_examples is not None:
429 examples = clean_examples(raw_examples)[:MAX_IMPORTED_EXAMPLES]
430 given = len(raw_examples) if isinstance(raw_examples, list) else 1
431 if len(examples) < given:
432 report.ignore(
433 example_key,
434 name,
435 "Each graded example needs an `output` and a 0–1 `score`, "
436 f"and a case holds at most {MAX_IMPORTED_EXAMPLES}.",
437 )
439 check_key, raw_checks = row.take(_CHECK_KEYS)
440 expectation = (
441 _checks(raw_checks, report, name, f"{check_key}.")
442 if isinstance(raw_checks, dict)
443 else {}
444 )
445 if raw_checks is not None and not isinstance(raw_checks, dict):
446 report.ignore(check_key, name, "Checks must be an object.")
447 top_level = {k: row.values[k] for k in _CHECK_FIELDS if _present(row.values.get(k))}
448 row.used.update(top_level)
449 expectation.update(_checks(top_level, report, name, ""))
450 if expected_facts:
451 expectation["facts"] = expectation.get("facts", []) + criteria_facts(
452 expected_facts
453 )
455 situation: dict[str, Any] = {}
456 situation_key, raw_situation = row.take(_SITUATION_KEYS)
457 spec = dict(raw_situation) if isinstance(raw_situation, dict) else {}
458 for key in ("history", "variables", "data", "tool_fixtures"):
459 if _present(row.values.get(key)):
460 spec[key] = row.values[key]
461 row.used.add(key)
462 # Other tools call a case's data its "context"; here that word means a
463 # variant's capability, so it is read as data.
464 if "data" not in spec and isinstance(row.values.get("context"), dict):
465 spec["data"] = row.values["context"]
466 row.used.add("context")
467 if spec:
468 from app.services.evaluation import context as context_service
470 try:
471 parsed = context_service.parse_situation(spec)
472 except context_service.ContextError as exc:
473 report.ignore(situation_key or "situation", name, str(exc))
474 else:
475 if parsed.history:
476 situation["history"] = list(parsed.history)
477 if parsed.variables:
478 situation["variables"] = dict(parsed.variables)
479 if parsed.data:
480 situation["data"] = dict(parsed.data)
481 if parsed.tool_fixtures:
482 situation["tool_fixtures"] = list(parsed.tool_fixtures)
484 _, raw_tags = row.take(_TAG_KEYS)
485 tags = (
486 [str(t).strip() for t in raw_tags if str(t).strip()]
487 if isinstance(raw_tags, list)
488 else _split_tags(_text(raw_tags))
489 )
490 for key in _TAGGED_FIELDS:
491 value = _text(row.values.get(key))
492 if value:
493 row.used.add(key)
494 tags.append(f"{key}:{value}")
496 for key in row.leftovers():
497 report.ignore(key, name, UNSUPPORTED_FIELDS.get(key, _GENERIC_REASON))
499 return DatasetCase(
500 input=prompt,
501 name=name,
502 expected_output=reference,
503 criteria=criteria_items(criteria),
504 examples=examples,
505 behaviour=behaviour,
506 expectation=expectation,
507 situation=situation,
508 tags=tags,
509 )
512#: Mirrors ``crud_schemas.MAX_CASE_EXAMPLES`` — the import writes rows
513#: directly, so it applies the same cap the case endpoints validate.
514MAX_IMPORTED_EXAMPLES = 8
517def parse_import(content: str, fmt: str = "auto") -> list[DatasetCase]:
518 """Parse bulk test-case content into cases — see :func:`parse_import_report`."""
519 return parse_import_report(content, fmt).cases
522def parse_import_report(content: str, fmt: str = "auto") -> ImportReport:
523 """Parse bulk test-case content into cases, reporting what did not fit.
525 Supports CSV (with a header row), JSONL (one object per line), and a JSON
526 array. ``fmt`` forces a parser; ``"auto"`` sniffs from the content.
528 Every case field is read — reference answer, criteria (a list is one item
529 each; text written as a bulleted list is split), facts (including the
530 numbers and text in a structured ``expected``), graded examples, checks, situation, tags — and every field
531 that is *not* one is reported with the reason, rather than dropped
532 silently: a file written for another tool loses information on the way
533 in, and the person importing it needs to know what.
535 Raises:
536 DatasetError: if nothing parseable is found.
537 """
538 text = (content or "").strip()
539 if not text:
540 raise DatasetError("Nothing to import.")
542 if fmt == "auto":
543 fmt = "json" if text[0] in "[{" else "csv"
545 rows: list[dict]
546 if fmt in ("json", "jsonl"):
547 rows = _parse_json_rows(text)
548 elif fmt == "csv":
549 try:
550 rows = list(csv.DictReader(io.StringIO(text)))
551 except csv.Error as exc:
552 raise DatasetError(f"Could not parse CSV: {exc}") from exc
553 else:
554 raise DatasetError(f"Unsupported import format {fmt!r}.")
556 report = ImportReport(cases=[])
557 for index, row in enumerate(rows):
558 if not isinstance(row, dict):
559 continue
560 case = _case_from_row(row, index, report)
561 if case is not None:
562 report.cases.append(case)
564 if not report.cases:
565 raise DatasetError(
566 "No rows with an input column were found. Expected a column named "
567 "one of: " + ", ".join(_INPUT_KEYS)
568 )
569 if len(report.cases) > MAX_CASES_PER_RUN:
570 raise DatasetError(
571 f"Import has {len(report.cases)} rows; the limit is {MAX_CASES_PER_RUN}."
572 )
573 return report
576def _parse_json_rows(text: str) -> list[dict]:
577 """Parse either a JSON array or newline-delimited JSON objects."""
578 try:
579 parsed = json.loads(text)
580 except ValueError:
581 rows: list[dict] = []
582 for line_no, line in enumerate(text.splitlines(), start=1):
583 line = line.strip()
584 if not line:
585 continue
586 try:
587 rows.append(json.loads(line))
588 except ValueError as exc:
589 raise DatasetError(f"Invalid JSON on line {line_no}: {exc}") from exc
590 return rows
591 if isinstance(parsed, list):
592 return [r for r in parsed if isinstance(r, dict)]
593 if isinstance(parsed, dict):
594 for key in ("cases", "data", "rows", "items"):
595 if isinstance(parsed.get(key), list):
596 return [r for r in parsed[key] if isinstance(r, dict)]
597 return [parsed]
598 raise DatasetError("JSON must be an array of objects or newline-delimited objects.")