Coverage for app / router / app / evaluations / schemas.py: 100%
108 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"""Request bodies for the evaluation execution endpoints.
3These sit alongside the generic CRUD schemas in ``crud_schemas`` because they
4describe *actions* (run this, compare those, optimise that) rather than the
5shape of a stored row.
6"""
8from typing import Any, Literal, Optional
9from uuid import UUID
11from pydantic import BaseModel, Field
13from app.db.postgres.crud_schemas import (
14 MAX_CASE_EXAMPLES,
15 CaseExample,
16 CriteriaField,
17 ExpectationField,
18 ExpectedBehaviour,
19 Schema,
20)
21from app.services.evaluation.context import (
22 MAX_HISTORY_MESSAGES,
23 MAX_MESSAGE_CHARS,
24)
25from app.services.evaluation.optimiser import (
26 DEFAULT_CANDIDATES,
27 DEFAULT_ROUNDS,
28 MAX_CANDIDATES_PER_ROUND,
29 MAX_ROUNDS,
30)
31from app.services.evaluation.promotion import MAX_NOTE_LENGTH
32from app.services.evaluation.runner import MAX_CONCURRENCY
33from app.services.evaluation.spread import MAX_REPEATS
34from app.util.cost_profiles import CostProfile
37class ContextMessage(BaseModel):
38 """One prior turn in a case's conversation."""
40 role: str
41 content: str = Field(min_length=1, max_length=MAX_MESSAGE_CHARS)
44class ContextSpec(BaseModel):
45 """What surrounds the prompt when this is evaluated.
47 Every field is optional, and **omitted is not the same as empty**: leaving
48 ``tools`` out keeps the agent's own, while sending ``[]`` takes them all
49 away. That distinction is the point — it is what makes a with/without
50 comparison expressible.
52 Rules are deliberately absent. Governance rules apply at inference, and an
53 evaluation that could switch them off would measure a system nobody runs.
54 """
56 #: Repositories to attach, replacing the agent's own grants.
57 knowledge_repository_ids: Optional[list[UUID]] = None
58 #: Individual knowledge bases, for the cases a repository is too coarse.
59 knowledge_ids: Optional[list[UUID]] = None
60 #: Tool names the agent may call, replacing its toolkits.
61 tools: Optional[list[str]] = None
62 #: Prior turns, oldest first.
63 history: Optional[list[ContextMessage]] = Field(
64 default=None, max_length=MAX_HISTORY_MESSAGES
65 )
66 #: Substituted into the system prompt and the case input as ``{{name}}``.
67 variables: Optional[dict[str, str]] = None
70class TargetSpec(BaseModel):
71 """What an evaluation invokes.
73 Either a model (``provider`` + ``model``, or a svc-ai ``model_id``) or one
74 of the user's agents (``agent_id``).
75 """
77 type: Optional[str] = None
78 provider: Optional[str] = None
79 model: Optional[str] = None
80 model_id: Optional[str] = None
81 agent_id: Optional[str] = None
82 label: Optional[str] = None
83 system_prompt: Optional[str] = None
84 temperature: Optional[float] = Field(default=None, ge=0.0, le=2.0)
85 max_tokens: Optional[int] = Field(default=None, ge=1, le=32000)
86 #: Reasoning effort, for models that take it instead of temperature.
87 effort: Optional[Literal["low", "medium", "high", "xhigh", "max"]] = None
88 #: An agent's cost profile (``app/util/cost_profiles.py``) in place of
89 #: its own — how much pipeline work each answer does. Agents only.
90 cost_profile: Optional[CostProfile] = None
91 context: Optional[ContextSpec] = None
94class RunExperimentRequest(BaseModel):
95 """Kick off a run of an evaluation: its variants over its dataset.
97 What is asked and how it is graded are the evaluation's own and are not
98 overridable per run — a run that could swap either would not be a run of
99 that evaluation, and its verdict against the previous run would compare
100 two different things.
101 """
103 variant_ids: Optional[list[UUID]] = None
104 label: Optional[str] = None
105 concurrency: Optional[int] = Field(default=None, ge=1, le=MAX_CONCURRENCY)
106 #: Ask every case this many times, to measure how much the score moves
107 #: run to run (``services/evaluation/spread.py``). Costs that many runs.
108 repeats: int = Field(default=1, ge=1, le=MAX_REPEATS)
111class EvaluateAgentRequest(BaseModel):
112 """Evaluate one agent, as it is configured, on chosen datasets.
114 One experiment per dataset — found again on the next request, so its runs
115 accumulate and each is compared with the last — owned where the agent's
116 evidence is read (``evidence.evidence_owner``), so the result counts on
117 Assurance and for the evidence gate.
118 """
120 dataset_ids: list[UUID] = Field(min_length=1, max_length=20)
121 repeats: int = Field(default=1, ge=1, le=MAX_REPEATS)
124class EvaluateAgentStarted(BaseModel):
125 dataset_id: UUID
126 experiment_id: UUID
127 #: None when the experiment already had a run in progress.
128 batch_id: Optional[UUID] = None
129 #: ``started``, or ``running`` when a run of it was already in progress.
130 status: Literal["started", "running"]
131 created: bool
134class CompareRequest(BaseModel):
135 """Run one prompt against several targets without persisting anything."""
137 prompt: str = Field(min_length=1)
138 targets: list[TargetSpec] = Field(min_length=1, max_length=6)
139 system_prompt: str = ""
140 expected_output: Optional[str] = None
141 #: The question's label, as a dataset case would carry it — saving the
142 #: comparison puts it on the new dataset's case.
143 criteria: CriteriaField = None
144 examples: Optional[list[CaseExample]] = Field(
145 default=None, max_length=MAX_CASE_EXAMPLES
146 )
147 expectation: ExpectationField = None
148 expected_behaviour: Optional[ExpectedBehaviour] = None
149 scorer: Optional[str] = None
150 #: How to judge — never what is correct; criteria and checks are refused.
151 scorer_config: Optional[dict[str, Any]] = None
152 #: The model that grades, for the ``llm`` scorer. svc-ai's default model
153 #: when omitted. Stored on the comparison, so saving it as an evaluation
154 #: carries the judge that actually graded these results.
155 judge: Optional[dict[str, Any]] = None
158class OptimiseRequest(BaseModel):
159 """Start an automatic prompt-optimisation run."""
161 base_variant_id: UUID
162 rounds: int = Field(default=DEFAULT_ROUNDS, ge=1, le=MAX_ROUNDS)
163 candidates_per_round: int = Field(
164 default=DEFAULT_CANDIDATES, ge=1, le=MAX_CANDIDATES_PER_ROUND
165 )
166 instructions: str = ""
169class ImportCasesRequest(BaseModel):
170 """Bulk-create test cases from CSV, JSONL, or a JSON array."""
172 content: str = Field(min_length=1)
173 format: str = "auto"
174 replace: bool = False
177class ImportIgnoredField(BaseModel):
178 """A field the import could not use, and the cases that carried it."""
180 field: str
181 reason: str
182 cases: list[str]
185class ImportCasesResult(BaseModel):
186 created: list[Schema.TestCase.Read]
187 ignored: list[ImportIgnoredField] = []
190class PresetRequest(BaseModel):
191 """Apply a variant preset to an experiment — or preview it."""
193 params: dict[str, Any] = Field(default_factory=dict)
194 #: True (the default) answers what would be made and what a run would
195 #: cost without writing anything.
196 dry_run: bool = True
199class PromoteRequest(BaseModel):
200 """Write a winning variant's prompt back onto the agent it targets."""
202 agent_id: Optional[UUID] = None
203 #: Promote past a closed gate. The override is recorded on the experiment
204 #: with the reason the gate gave, so a promotion made against the evidence
205 #: is on the record rather than indistinguishable from a clean one.
206 force: bool = False
207 #: Why — stored alongside a forced promotion.
208 note: Optional[str] = Field(default=None, max_length=MAX_NOTE_LENGTH)
211# ── Scorer catalogue ──────────────────────────────────────────────────────────
214class ScorerConfigField(BaseModel):
215 """One setting a scorer takes, described for the control that renders it."""
217 key: str
218 label: str
219 #: ``text`` | ``lines`` | ``textarea`` | ``boolean``
220 type: str
221 hint: str = ""
222 placeholder: str = ""
223 default: Optional[Any] = None
226class ScorerInfo(BaseModel):
227 """One scorer, described well enough for a picker to explain it.
229 Everything the user reads about a scorer comes from here: the label, when
230 to reach for it, how the number is arrived at, what it needs from the
231 dataset, and which settings to render. A scorer carrying a
232 ``superseded_by`` is still described — an evaluation that already selected
233 one must be able to say what it is — but is not offered for new ones.
234 """
236 kind: str
237 label: str
238 summary: str = ""
239 description: str = ""
240 how_it_scores: str = ""
241 needs: str = ""
242 group: str
243 requires_expected: bool = False
244 uses_threshold: bool = True
245 superseded_by: Optional[str] = None
246 config_fields: list[ScorerConfigField] = Field(default_factory=list)
249class ScorerGroupInfo(BaseModel):
250 """A picker heading: what does the grading."""
252 key: str
253 label: str
254 summary: str = ""
257class ScorerCatalogue(BaseModel):
258 """The scorer vocabulary, served as the rule catalogue is.
260 Two registries rather than a flat list, because the first question a user
261 answers is *who grades this* — a model, a rule, or me.
262 """
264 scorers: list[ScorerInfo]
265 groups: list[ScorerGroupInfo]
266 #: The score at or above which a case passes when nothing is configured.
267 default_pass_threshold: float