Coverage for app / services / evaluation / presets.py: 94%
324 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"""
2Variant presets — add a whole comparison to an experiment in one step.
4"Which model is best on this dataset?", "which temperature?", "does the
5compliance repository help?" are each one question with several answers to
6try. Building them a variant at a time is the work a preset removes: pick the
7models, or the temperatures, and the preset writes one variant per value.
9The variants it writes are **ordinary variants** — editable, deletable,
10promotable — each tagged in ``config["preset"]`` with the dimension it varies
11and its value there, so results can be read along that dimension. A preset
12never creates a kind of thing only it understands; like the optimiser's
13candidates, what it makes is inspectable afterwards.
15Presets are a **registry**: one class per preset, served as a catalogue with
16the parameters each takes, so the form holds no list and a new preset is one
17class. Every id a preset is given — model, agent, repository — is checked
18before anything is written: a model must exist, an agent must be one the
19caller may use, and a setting the model drops (``temperature`` on a model that
20rejects it, effort on one without it) is refused with the reason rather than
21written as a variant that measures nothing.
22"""
24from __future__ import annotations
26import logging
27from abc import ABC, abstractmethod
28from dataclasses import dataclass, field
29from typing import Any, ClassVar
30from uuid import UUID
32from sqlalchemy.orm import Session
34from app.db.postgres.models import Agent
35from app.services import ai_client
36from app.services.ai_client import AIServiceError, ModelNotAvailableError
37from app.services.evaluation import context as context_service
38from app.services.evaluation.targets import EFFORT_LEVELS
40logger = logging.getLogger(__name__)
42#: Variants one preset may add at a time. A sweep wider than this is several
43#: experiments' worth of calls in one click.
44MAX_PRESET_VARIANTS = 12
46#: Temperatures a sweep may try — svc-ai's accepted range.
47MIN_TEMPERATURE, MAX_TEMPERATURE = 0.0, 2.0
50class PresetError(ValueError):
51 """A preset's parameters cannot be turned into variants; the message says why."""
54@dataclass(frozen=True)
55class PresetParam:
56 """One parameter a preset takes, described for the form that renders it.
58 ``type`` is one of: ``models`` / ``agents`` (several), ``agent`` (one),
59 ``base`` (a model or an agent, optionally on another model),
60 ``temperatures`` (numbers), ``effort_levels``, ``repositories``,
61 ``tools``, ``prompt`` (a system prompt for every variant).
62 """
64 key: str
65 label: str
66 type: str
67 hint: str = ""
68 required: bool = True
69 min_items: int | None = None
70 max_items: int | None = None
72 def as_json(self) -> dict[str, Any]:
73 out: dict[str, Any] = {
74 "key": self.key,
75 "label": self.label,
76 "type": self.type,
77 "hint": self.hint,
78 "required": self.required,
79 }
80 if self.min_items is not None:
81 out["min_items"] = self.min_items
82 if self.max_items is not None:
83 out["max_items"] = self.max_items
84 return out
87@dataclass
88class DraftVariant:
89 """A variant a preset would write."""
91 name: str
92 config: dict[str, Any]
93 prompt: str | None = None
95 def as_json(self) -> dict[str, Any]:
96 return {"name": self.name, "prompt": self.prompt, "config": self.config}
99@dataclass
100class PresetContext:
101 """What a preset may look up: models, the caller's agents, contexts.
103 Model records are cached for the request — a sweep names the same model
104 once per value.
105 """
107 db: Session
108 owner: Any
109 can_use_agent: Any
110 #: Whether the caller may use a swarm; None refuses every one.
111 can_use_swarm: Any = None
112 _models: dict[str, dict[str, Any]] = field(default_factory=dict)
114 def model(self, model_id: Any) -> dict[str, Any]:
115 key = str(model_id)
116 if key not in self._models:
117 try:
118 self._models[key] = ai_client.get_model(UUID(key))
119 except (ValueError, AttributeError) as exc:
120 raise PresetError(f"Invalid model id {model_id!r}.") from exc
121 except ModelNotAvailableError as exc:
122 raise PresetError(f"Model {model_id} is not available.") from exc
123 except AIServiceError as exc:
124 raise PresetError(f"Models could not be looked up: {exc}") from exc
125 return self._models[key]
127 def agent(self, agent_id: Any) -> Agent:
128 try:
129 agent = self.db.get(Agent, UUID(str(agent_id)))
130 except (ValueError, AttributeError) as exc:
131 raise PresetError(f"Invalid agent id {agent_id!r}.") from exc
132 # Not found and not yours read the same, so neither confirms the other.
133 if agent is None or not self.can_use_agent(agent):
134 raise PresetError(f"Agent {agent_id} was not found.")
135 return agent
137 def swarm(self, swarm_id: Any) -> Any:
138 from app.db.postgres.models import Swarm
140 try:
141 swarm = self.db.get(Swarm, UUID(str(swarm_id)))
142 except (ValueError, AttributeError) as exc:
143 raise PresetError(f"Invalid swarm id {swarm_id!r}.") from exc
144 if swarm is None or self.can_use_swarm is None or not self.can_use_swarm(swarm):
145 raise PresetError(f"Swarm {swarm_id} was not found.")
146 return swarm
148 def check_context(self, spec: dict[str, Any]) -> None:
149 """Refuse a context the run would refuse — unknown tools, unreachable
150 knowledge — now, rather than as a failed batch later."""
151 try:
152 context_service.resolve(self.db, spec, owner=self.owner)
153 except context_service.ContextError as exc:
154 raise PresetError(str(exc)) from exc
157# ── Parameter readers ─────────────────────────────────────────────────────────
160def _ids(params: dict, key: str, lo: int, hi: int, noun: str) -> list[str]:
161 raw = params.get(key)
162 if not isinstance(raw, list):
163 raise PresetError(f"Choose the {noun} to compare.")
164 ids = list(dict.fromkeys(str(v) for v in raw if str(v).strip()))
165 if len(ids) < lo:
166 raise PresetError(f"Choose at least {lo} {noun}.")
167 if len(ids) > hi:
168 raise PresetError(f"Choose at most {hi} {noun}.")
169 return ids
172def _prompt(params: dict) -> str | None:
173 text = str(params.get("prompt") or "").strip()
174 return text or None
177def _model_name(record: dict[str, Any]) -> str:
178 return str(record.get("display_name") or record.get("model_name") or "model")
181@dataclass
182class _Base:
183 """What a sweep varies around: a target spec, its label, and the model it
184 will actually run on (None when that cannot be told)."""
186 spec: dict[str, Any]
187 label: str
188 model: dict[str, Any] | None
189 is_agent: bool
192def _base(ctx: PresetContext, params: dict) -> _Base:
193 raw = params.get("base")
194 if not isinstance(raw, dict):
195 raise PresetError("Choose the model or agent to vary.")
196 if raw.get("agent_id"):
197 agent = ctx.agent(raw["agent_id"])
198 spec: dict[str, Any] = {"type": "agent", "agent_id": str(agent.id)}
199 model = None
200 if raw.get("model_id"):
201 model = ctx.model(raw["model_id"])
202 spec["model_id"] = str(raw["model_id"])
203 label = f"{agent.name} · {_model_name(model)}"
204 else:
205 label = str(agent.name)
206 if agent.ai_model_id:
207 model = ctx.model(agent.ai_model_id)
208 return _Base(spec=spec, label=label, model=model, is_agent=True)
209 if raw.get("model_id"):
210 model = ctx.model(raw["model_id"])
211 return _Base(
212 spec={"type": "model", "model_id": str(raw["model_id"])},
213 label=_model_name(model),
214 model=model,
215 is_agent=False,
216 )
217 raise PresetError("Choose the model or agent to vary.")
220def _refuse_unsupported(base: _Base, capability: str, what: str) -> None:
221 """A sweep over a control the model drops would measure nothing."""
222 if base.model is not None and base.model.get(capability) is False:
223 raise PresetError(
224 f"{_model_name(base.model)} does not take {what}, so varying it "
225 "would change nothing. Choose another model"
226 + (", or run the agent on one" if base.is_agent else "")
227 + "."
228 )
231def _tag(key: str, dimension: str, value: Any, label: str) -> dict[str, Any]:
232 return {"key": key, "dimension": dimension, "value": value, "label": label}
235# ── Registry ──────────────────────────────────────────────────────────────────
238class Preset(ABC):
239 """One way of turning a question into several variants."""
241 key: ClassVar[str]
242 label: ClassVar[str]
243 summary: ClassVar[str]
244 #: What the variants differ in — what results are read along.
245 dimension: ClassVar[str]
246 params: ClassVar[tuple[PresetParam, ...]]
248 @abstractmethod
249 def expand(self, params: dict[str, Any], ctx: PresetContext) -> list[DraftVariant]:
250 """The variants these parameters make, every id checked."""
252 @classmethod
253 def describe(cls) -> dict[str, Any]:
254 return {
255 "key": cls.key,
256 "label": cls.label,
257 "summary": cls.summary,
258 "dimension": cls.dimension,
259 "params": [p.as_json() for p in cls.params],
260 }
263_REGISTRY: dict[str, type[Preset]] = {}
266def register_preset(cls: type[Preset]) -> type[Preset]:
267 _REGISTRY[cls.key] = cls
268 return cls
271def preset_catalogue() -> list[dict[str, Any]]:
272 """Every preset, in the order they are registered."""
273 return [cls.describe() for cls in _REGISTRY.values()]
276def expand_preset(
277 key: str, params: dict[str, Any] | None, ctx: PresetContext
278) -> list[DraftVariant]:
279 cls = _REGISTRY.get(key)
280 if cls is None:
281 raise PresetError(f"Unknown preset {key!r}.")
282 drafts = cls().expand(dict(params or {}), ctx)
283 if len(drafts) > MAX_PRESET_VARIANTS:
284 raise PresetError(
285 f"This would add {len(drafts)} variants; a preset adds at most "
286 f"{MAX_PRESET_VARIANTS} at a time."
287 )
288 return drafts
291_PROMPT = PresetParam(
292 key="prompt",
293 label="System prompt",
294 type="prompt",
295 hint="optional — used by every variant; blank keeps each one's own",
296 required=False,
297)
300@register_preset
301class ModelsPreset(Preset):
302 key = "models"
303 label = "Models"
304 summary = (
305 "The same prompt on several models — which answers best, and at what cost."
306 )
307 dimension = "model"
308 params = (
309 PresetParam(
310 key="model_ids",
311 label="Models",
312 type="models",
313 min_items=2,
314 max_items=MAX_PRESET_VARIANTS,
315 ),
316 _PROMPT,
317 )
319 def expand(self, params, ctx):
320 prompt = _prompt(params)
321 drafts = []
322 for model_id in _ids(params, "model_ids", 2, MAX_PRESET_VARIANTS, "models"):
323 name = _model_name(ctx.model(model_id))
324 drafts.append(
325 DraftVariant(
326 name=name,
327 prompt=prompt,
328 config={
329 "target": {"type": "model", "model_id": model_id},
330 "preset": _tag(self.key, self.dimension, model_id, name),
331 },
332 )
333 )
334 return drafts
337@register_preset
338class AgentsPreset(Preset):
339 key = "agents"
340 label = "Agents"
341 summary = "Several agents as they are — each with its own model, prompt, knowledge and tools."
342 dimension = "agent"
343 params = (
344 PresetParam(
345 key="agent_ids",
346 label="Agents",
347 type="agents",
348 min_items=2,
349 max_items=MAX_PRESET_VARIANTS,
350 ),
351 )
353 def expand(self, params, ctx):
354 drafts = []
355 for agent_id in _ids(params, "agent_ids", 2, MAX_PRESET_VARIANTS, "agents"):
356 agent = ctx.agent(agent_id)
357 drafts.append(
358 DraftVariant(
359 name=str(agent.name),
360 config={
361 "target": {"type": "agent", "agent_id": str(agent.id)},
362 "preset": _tag(
363 self.key, self.dimension, str(agent.id), str(agent.name)
364 ),
365 },
366 )
367 )
368 return drafts
371@register_preset
372class AgentModelsPreset(Preset):
373 key = "agent_models"
374 label = "Agent × models"
375 summary = "One agent — its prompt, knowledge and tools — run on several models."
376 dimension = "model"
377 params = (
378 PresetParam(key="agent_id", label="Agent", type="agent"),
379 PresetParam(
380 key="model_ids",
381 label="Models",
382 type="models",
383 min_items=2,
384 max_items=MAX_PRESET_VARIANTS,
385 ),
386 )
388 def expand(self, params, ctx):
389 agent = ctx.agent(params.get("agent_id"))
390 drafts = []
391 for model_id in _ids(params, "model_ids", 2, MAX_PRESET_VARIANTS, "models"):
392 model_name = _model_name(ctx.model(model_id))
393 drafts.append(
394 DraftVariant(
395 name=f"{agent.name} · {model_name}",
396 config={
397 "target": {
398 "type": "agent",
399 "agent_id": str(agent.id),
400 "model_id": model_id,
401 },
402 "preset": _tag(self.key, self.dimension, model_id, model_name),
403 },
404 )
405 )
406 return drafts
409@register_preset
410class TemperaturePreset(Preset):
411 key = "temperature"
412 label = "Temperature"
413 summary = "One model or agent at several temperatures — how much randomness helps or hurts."
414 dimension = "temperature"
415 params = (
416 PresetParam(key="base", label="Runs on", type="base"),
417 PresetParam(
418 key="temperatures",
419 label="Temperatures",
420 type="temperatures",
421 hint=f"{MIN_TEMPERATURE:g} to {MAX_TEMPERATURE:g}",
422 min_items=2,
423 max_items=8,
424 ),
425 _PROMPT,
426 )
428 def expand(self, params, ctx):
429 base = _base(ctx, params)
430 _refuse_unsupported(base, "supports_temperature", "a temperature")
431 raw = params.get("temperatures")
432 values: list[float] = []
433 for value in raw if isinstance(raw, list) else []:
434 try:
435 number = round(float(value), 2)
436 except (TypeError, ValueError) as exc:
437 raise PresetError(f"{value!r} is not a temperature.") from exc
438 if not MIN_TEMPERATURE <= number <= MAX_TEMPERATURE:
439 raise PresetError(
440 f"Temperatures run from {MIN_TEMPERATURE:g} to {MAX_TEMPERATURE:g}; "
441 f"{number:g} is outside that."
442 )
443 if number not in values:
444 values.append(number)
445 if not 2 <= len(values) <= 8:
446 raise PresetError("Choose between 2 and 8 temperatures.")
447 prompt = _prompt(params)
448 return [
449 DraftVariant(
450 name=f"{base.label} · temp {value:g}",
451 prompt=prompt,
452 config={
453 "target": {**base.spec, "temperature": value},
454 "preset": _tag(self.key, self.dimension, value, f"{value:g}"),
455 },
456 )
457 for value in sorted(values)
458 ]
461@register_preset
462class EffortPreset(Preset):
463 key = "effort"
464 label = "Effort"
465 summary = "One model or agent at several reasoning-effort levels — the control newer models use instead of temperature."
466 dimension = "effort"
467 params = (
468 PresetParam(key="base", label="Runs on", type="base"),
469 PresetParam(
470 key="levels",
471 label="Effort levels",
472 type="effort_levels",
473 min_items=2,
474 max_items=len(EFFORT_LEVELS),
475 ),
476 _PROMPT,
477 )
479 def expand(self, params, ctx):
480 base = _base(ctx, params)
481 _refuse_unsupported(base, "supports_effort", "an effort level")
482 raw = params.get("levels")
483 chosen = [lvl for lvl in EFFORT_LEVELS if isinstance(raw, list) and lvl in raw]
484 unknown = [lvl for lvl in raw or [] if lvl not in EFFORT_LEVELS]
485 if unknown:
486 raise PresetError(
487 f"Effort levels are {', '.join(EFFORT_LEVELS)}; not {', '.join(map(str, unknown))}."
488 )
489 if len(chosen) < 2:
490 raise PresetError("Choose at least 2 effort levels.")
491 prompt = _prompt(params)
492 return [
493 DraftVariant(
494 name=f"{base.label} · effort {level}",
495 prompt=prompt,
496 config={
497 "target": {**base.spec, "effort": level},
498 "preset": _tag(self.key, self.dimension, level, level),
499 },
500 )
501 for level in chosen
502 ]
505class _WithWithout(Preset):
506 """Two variants of one base: with something, and without it.
508 "Without" is *explicitly none* — not "whatever the base has" — so the
509 comparison is between having the thing and not having it at all. A model
510 has none of its own, so its "without" is simply the plain model.
511 """
513 #: The context key the "with" half sets, and how a value is named.
514 context_key: ClassVar[str]
515 noun: ClassVar[str]
517 @abstractmethod
518 def chosen(self, params: dict, ctx: PresetContext) -> tuple[list[Any], str]:
519 """The values for the "with" half, and how to name them."""
521 def expand(self, params, ctx):
522 base = _base(ctx, params)
523 values, names = self.chosen(params, ctx)
524 with_spec = {self.context_key: values}
525 ctx.check_context(with_spec)
526 without_config: dict[str, Any] = {
527 "target": dict(base.spec),
528 "preset": _tag(self.key, self.dimension, "without", f"without {self.noun}"),
529 }
530 if base.is_agent:
531 without_config["context"] = {self.context_key: []}
532 prompt = _prompt(params)
533 return [
534 DraftVariant(
535 name=f"{base.label} · with {names}",
536 prompt=prompt,
537 config={
538 "target": dict(base.spec),
539 "context": with_spec,
540 "preset": _tag(self.key, self.dimension, "with", f"with {names}"),
541 },
542 ),
543 DraftVariant(
544 name=f"{base.label} · without {self.noun}",
545 prompt=prompt,
546 config=without_config,
547 ),
548 ]
551@register_preset
552class KnowledgePreset(_WithWithout):
553 key = "knowledge"
554 label = "With / without knowledge"
555 summary = "The same model or agent with and without a knowledge repository — does it actually help?"
556 dimension = "knowledge"
557 context_key = "knowledge_repository_ids"
558 noun = "knowledge"
559 params = (
560 PresetParam(key="base", label="Runs on", type="base"),
561 PresetParam(
562 key="repository_ids",
563 label="Repositories",
564 type="repositories",
565 min_items=1,
566 max_items=10,
567 ),
568 _PROMPT,
569 )
571 def chosen(self, params, ctx):
572 ids = _ids(params, "repository_ids", 1, 10, "repositories")
573 return ids, "knowledge" if len(ids) > 1 else "the repository"
576@register_preset
577class ToolsPreset(_WithWithout):
578 key = "tools"
579 label = "With / without tools"
580 summary = "The same model or agent with and without tools — does it reach for them, and do they help?"
581 dimension = "tools"
582 context_key = "tools"
583 noun = "tools"
584 params = (
585 PresetParam(key="base", label="Runs on", type="base"),
586 PresetParam(
587 key="tools", label="Tools", type="tools", min_items=1, max_items=20
588 ),
589 _PROMPT,
590 )
592 def chosen(self, params, ctx):
593 names = _ids(params, "tools", 1, 20, "tools")
594 return names, ", ".join(names)
597@register_preset
598class CostProfilesPreset(Preset):
599 """One agent under every cost profile (``app/util/cost_profiles.py``):
600 how much its answers lose, if anything, for what a cheaper pipeline
601 saves. The variant for the profile the agent already runs under is the
602 agent as configured, so it counts as the agent's evidence; the others
603 test an alternative. Read the leaderboard's cost per answer beside the
604 score."""
606 key = "cost_profiles"
607 label = "Cost profiles"
608 summary = "One agent under each cost profile — how much a cheaper pipeline saves, and whether its answers hold."
609 dimension = "cost_profile"
610 params = (
611 PresetParam(key="agent_id", label="Agent", type="agent"),
612 _PROMPT,
613 )
615 def expand(self, params, ctx):
616 from app.util import cost_profiles
618 if not params.get("agent_id"):
619 raise PresetError("Choose the agent to compare.")
620 agent = ctx.agent(params["agent_id"])
621 own = cost_profiles.parse(getattr(agent, "cost_profile", None)) or (
622 cost_profiles.DEFAULT
623 )
624 prompt = _prompt(params)
625 drafts = []
626 for profile in cost_profiles.CostProfile:
627 label = cost_profiles.LABELS[profile]
628 target: dict[str, Any] = {"type": "agent", "agent_id": str(agent.id)}
629 if profile is not own:
630 target["cost_profile"] = profile.value
631 drafts.append(
632 DraftVariant(
633 name=f"{agent.name} · {label}"
634 + (" (its own)" if profile is own else ""),
635 prompt=prompt,
636 config={
637 "target": target,
638 "preset": _tag(self.key, self.dimension, profile.value, label),
639 },
640 )
641 )
642 return drafts
645def lead_of(swarm: Any) -> str | None:
646 """The agent that leads ``swarm``: the first member of its shape's first
647 role (a lead, a router, a chair, a pipeline's first stage)."""
648 from app.services.swarms import topologies
650 topology = topologies.get(str(swarm.topology))
651 entries = [e for e in swarm.roster or [] if isinstance(e, dict)]
652 if topology is None or not entries:
653 return None
654 first_role = topology.roles[0].key
655 lead = next((e for e in entries if e.get("role") == first_role), None)
656 return str(lead["agent_id"]) if lead and lead.get("agent_id") else None
659@register_preset
660class SwarmsPreset(Preset):
661 """Swarms beside single agents on the same dataset — what a shape gains
662 over one agent, and at what cost per answer. With no agents chosen, each
663 swarm is compared with its own lead working alone: the question a swarm
664 has to answer is whether its team beats the agent that would otherwise
665 do the work. Each swarm runs once a case, unattended (``SwarmTarget``)."""
667 key = "swarms"
668 label = "Swarms against single agents"
669 summary = "Each swarm beside single agents — by default its own lead alone — so a shape's gain is measured at its cost per answer."
670 dimension = "target"
671 params = (
672 PresetParam(
673 key="swarm_ids",
674 label="Swarms",
675 type="swarms",
676 min_items=1,
677 max_items=MAX_PRESET_VARIANTS // 2,
678 ),
679 PresetParam(
680 key="agent_ids",
681 label="Single agents",
682 type="agents",
683 hint="optional — blank compares each swarm with its own lead alone",
684 required=False,
685 max_items=MAX_PRESET_VARIANTS // 2,
686 ),
687 )
689 def expand(self, params, ctx):
690 swarms = [
691 ctx.swarm(swarm_id)
692 for swarm_id in _ids(
693 params, "swarm_ids", 1, MAX_PRESET_VARIANTS // 2, "swarms"
694 )
695 ]
696 chosen = params.get("agent_ids") or []
697 agent_ids = (
698 _ids(params, "agent_ids", 1, MAX_PRESET_VARIANTS // 2, "agents")
699 if chosen
700 else list(dict.fromkeys(a for a in map(lead_of, swarms) if a))
701 )
702 drafts = [
703 DraftVariant(
704 name=str(swarm.name),
705 config={
706 "target": {"type": "swarm", "swarm_id": str(swarm.id)},
707 "preset": _tag(
708 self.key, self.dimension, f"swarm:{swarm.id}", str(swarm.name)
709 ),
710 },
711 )
712 for swarm in swarms
713 ]
714 for agent_id in agent_ids:
715 agent = ctx.agent(agent_id)
716 name = f"{agent.name} alone"
717 drafts.append(
718 DraftVariant(
719 name=name,
720 config={
721 "target": {"type": "agent", "agent_id": str(agent.id)},
722 "preset": _tag(
723 self.key, self.dimension, f"agent:{agent.id}", name
724 ),
725 },
726 )
727 )
728 return drafts