Coverage for app / services / evaluation / targets.py: 89%
777 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"""
2Execution targets for evaluation runs.
4A *target* is whatever an evaluation invokes to produce an output: a bare
5model with a system prompt, or one of the user's configured agents (with its
6tools, knowledge bases and rules). Both are normalised behind
7:class:`ExecutionTarget` so the runner invokes them identically and every
8result carries a comparable label, latency and token count.
9"""
11from __future__ import annotations
13import dataclasses
14import logging
15import threading
16import time
17import weakref
18from abc import ABC, abstractmethod
19from contextvars import ContextVar
20from dataclasses import dataclass, field
21from decimal import Decimal
22from typing import TYPE_CHECKING, Any, Callable, Optional
23from uuid import UUID
25from pydantic import BaseModel
26from sqlalchemy.orm import Session
28from app.db.postgres.models import Agent
29from app.services import agent_spec, ai_client, rule_engine
30from app.services import governance_activity as activity_service
31from app.services import spend_limits, structured_reply
32from app.services import usage as usage_service
33from app.services import withholding
34from app.services.model_catalogue import ModelCatalogue
35from app.services.ai_client import (
36 AIServiceError,
37 ModelNotAvailableError,
38 RuleBlockedError,
39)
40from app.services.rule_engine import RuleBlock
41from app.services.rules import scopes as rule_scopes
43if TYPE_CHECKING: # pragma: no cover - import cycle: context builds no targets
44 from app.services.evaluation.context import EvaluationContext
46logger = logging.getLogger(__name__)
48# Evaluations are batch workloads, so a conservative default keeps a single
49# runaway case from stalling a whole suite.
50DEFAULT_MAX_TOKENS = 1024
52#: The ``purpose`` svc-ai records on an evaluation cell's invocation trace,
53#: and on the judge call that grades one. fe-core's Activity feed keys its
54#: label and its link back to the run on these.
55TRACE_PURPOSE = "evaluation"
56JUDGE_TRACE_PURPOSE = "evaluation_judge"
58#: What a person is told when a call failed for a reason that is not theirs
59#: to fix (``Invocation.shown_error``).
60UNAVAILABLE_MESSAGE = "The agent or model could not answer. Try again shortly."
63def _cited_sources(cited: Any, output_rules: Any) -> list[dict[str, Any]] | None:
64 """What an answer cites, as a chat answer stores it
65 (``agents.transformers.stored_cited_sources``)."""
66 from app.router.app.agents.transformers import stored_cited_sources
68 return stored_cited_sources(cited, output_rules)
71#: Not read yet, as distinct from read as None.
72_UNREAD = object()
75@dataclass
76class Invocation:
77 """One completed (or failed) call to a target."""
79 output: str
80 input_tokens: int = 0
81 output_tokens: int = 0
82 latency_ms: int = 0
83 error: Optional[str] = None
84 rule_events: list[dict] = field(default_factory=list)
85 # The questions the agent paused to ask (``ask_user``) instead of
86 # answering. ``output`` then reads them back, so every scorer grades what
87 # the agent actually said; this is the certain signal that it asked.
88 clarification: Optional[list[dict]] = None
89 # Every tool the agent called — name, arguments, result — in order. What
90 # "used the market-data tool" and "quoted the price it returned" are
91 # checked against.
92 tool_calls: list[dict] = field(default_factory=list)
93 # True when a policy rule refused the call before it reached the provider.
94 # Scored as a failure like any other, but *not* written to the usage
95 # ledger: a blocked invocation is already on record — one
96 # ``governance_events`` row per rule that refused it — and the ledger
97 # records what reached the provider (see ``UsageEnum.Outcome``).
98 blocked: bool = False
99 #: What svc-ai measured for this call (``ai_client.UsageCapture``): every
100 #: model call it made, priced per model. What the ledger records.
101 usage: Any = None
102 #: The cell's id (``rule_engine.new_invocation_id``): its governance
103 #: activity, ledger row and svc-ai's traces carry it.
104 invocation_id: Optional[str] = None
105 #: True once the call is on the usage ledger — a run ledgers each call as
106 #: it finishes (``runner.ledger_as_it_goes``), and the sweep at the end of
107 #: the run writes only the calls still without a row.
108 ledgered: bool = False
109 #: The lighter model the cell's Economy profile gave svc-ai, if any — its
110 #: ledger row names it when svc-ai says it wrote the answer.
111 lighter_model: Optional[dict[str, Any]] = None
112 #: The exception a failed call raised, for a caller that answers a person
113 #: rather than grading a cell: a spend stop or a refusal is told apart
114 #: from svc-ai being unreachable (``shown_error``).
115 raised: Optional[BaseException] = field(default=None, repr=False, compare=False)
116 #: An Output rule withheld the answer: ``output`` is its message — what
117 #: people would have received, so what is graded — and the answer is kept
118 #: nowhere (an evaluation has no review queue). Its tool calls keep only
119 #: which tools ran (``withholding.strip_tool_calls``).
120 withheld: bool = False
121 #: For a swarm's cell, the run that answered (``SwarmTarget``): its id,
122 #: status and shape of work — where the cell's page links to.
123 swarm_run: Optional[dict[str, Any]] = None
124 #: The sources the answer cites, each with the ``marker`` its text cites
125 #: it by (svc-ai's ``cited_citations``), redacted as the answer was.
126 #: None when svc-ai sent none — a model call, an older svc-ai.
127 citations: Optional[list[dict[str, Any]]] = None
129 @property
130 def shown_error(self) -> Optional[str]:
131 """``error`` as a person may read it. A rule's block and a refusal's
132 message are written to be shown; any other failure's text is an
133 exception's — svc-ai's response body, say — and is replaced."""
134 if self.error is None:
135 return None
136 if self.blocked or self.raised is None:
137 return self.error
138 if isinstance(
139 self.raised, (ai_client.ModelRefusedError, ai_client.AIServiceTimeout)
140 ):
141 return self.raised.user_message
142 return UNAVAILABLE_MESSAGE
144 @property
145 def cost_usd(self) -> Any:
146 """Measured cost, or None when nothing could be priced."""
147 return getattr(self.usage, "cost_usd", None)
149 @property
150 def ok(self) -> bool:
151 return self.error is None
153 def as_metadata(self) -> dict[str, Any]:
154 meta: dict[str, Any] = {
155 "latency_ms": self.latency_ms,
156 "input_tokens": self.input_tokens,
157 "output_tokens": self.output_tokens,
158 "total_tokens": self.input_tokens + self.output_tokens,
159 }
160 if self.error:
161 meta["error"] = self.error
162 if self.rule_events:
163 meta["rule_events"] = self.rule_events
164 if self.clarification is not None:
165 meta["clarification"] = self.clarification
166 if self.tool_calls:
167 meta["tool_calls"] = self.tool_calls
168 if self.swarm_run:
169 meta["swarm_run"] = self.swarm_run
170 usage = self.usage
171 if getattr(usage, "measured", False):
172 # What this answer cost as svc-ai measured it — None, never 0,
173 # when nothing in it could be priced.
174 meta["cost_usd"] = (
175 float(usage.cost_usd) if usage.cost_usd is not None else None
176 )
177 meta["llm_calls"] = usage.calls
178 if usage.unpriced_calls:
179 meta["unpriced_calls"] = usage.unpriced_calls
180 return meta
183@dataclass
184class TargetGovernance:
185 """The rules and ledger identity an evaluation target runs under.
187 Evaluation runs used to reach the provider ungoverned: ``invoke_agent``
188 accepts ``rules`` and was never handed any, and nothing on this path wrote
189 the usage ledger. So a cost cap did not count an evaluation, a block rule
190 did not stop one, and the platform's own guide gave the reason contexts may
191 not switch rules off — "an evaluation that could would measure a system
192 nobody runs" — while every evaluation did exactly that.
194 One of these is attached per target by ``build_target(..., owner=...)``:
196 * ``rule_specs`` — the forwardable policy/audit rules, resolved once per
197 target (they do not change mid-batch) and sent to svc-ai on every call.
198 * ``check_input`` / ``check_output`` — svc-core's own pass over every
199 rule, the ``core_only`` actions (rate limits, cost caps, the evidence
200 gate) included, which are never forwarded and so have to run here.
202 Guarded by a lock **per session**, not per target: ``_execute_matrix``
203 invokes cells from a thread pool, every target of a batch shares the one
204 session, and the rule engine commits on it. A lock per target let two
205 targets' cells commit on the same session at once — SQLAlchemy refuses
206 with ``IllegalStateChangeError`` ("commit() is already in progress").
207 """
209 db: Session
210 owner_user_id: str
211 scope_chain: list[dict]
212 rule_specs: list[dict]
213 scope_type: str
214 scope_id: str | None
215 execution_type: str = "evaluation"
216 extra_context: dict[str, Any] = field(default_factory=dict)
217 #: The model catalogue a cell's lighter model and native sibling are
218 #: chosen from, read once for the target's whole run, so every cell
219 #: chooses from the same list.
220 catalogue: ModelCatalogue = field(default_factory=ModelCatalogue)
222 @property
223 def _lock(self) -> threading.Lock:
224 return _session_lock(self.db)
226 def _context(
227 self, invocation_id: str, *, cell: "_Cell | None" = None, **phase: Any
228 ) -> dict[str, Any]:
229 """One cell's rule context. With the ``cell``, the model it runs on
230 joins it (``model_name``, ``provider``)."""
231 context: dict[str, Any] = {
232 "execution_type": self.execution_type,
233 "user_id": self.owner_user_id,
234 "scope_type": self.scope_type,
235 "scope_id": self.scope_id,
236 rule_engine.SCOPES_CONTEXT_KEY: self.scope_chain,
237 rule_engine.INVOCATION_CONTEXT_KEY: invocation_id,
238 **self.extra_context,
239 }
240 if cell is not None:
241 context.update(
242 {
243 key: value
244 for key, value in rule_engine.model_fields(cell.model_info).items()
245 if value
246 }
247 )
248 context.update(phase)
249 return context
251 def check_input(
252 self, prompt: str, invocation_id: str, *, cell: "_Cell | None" = None
253 ) -> rule_engine.RulePass:
254 """Policy rules on the prompt. Raises ``RuleBlock`` when one refuses.
256 Unpacks as ``(prompt, events)``; the pass also carries the PII
257 redaction that ran, for the case's history sent beside the prompt."""
258 with self._lock:
259 result = rule_engine.evaluate_input(
260 self.db,
261 prompt,
262 self._context(invocation_id, cell=cell, prompt=prompt),
263 self.owner_user_id,
264 )
265 activity_service.commit(self.db)
266 return result
268 def check_output(
269 self,
270 response: str,
271 invocation_id: str,
272 figures: dict[str, Any] | None = None,
273 *,
274 cell: "_Cell | None" = None,
275 ) -> rule_engine.RulePass:
276 """Audit rules on the response — redactions apply to what is stored,
277 and a withhold rule's message replaces an answer it withheld.
279 Unpacks as ``(response, events)``. ``figures`` are the cell's latency
280 and cost (``audit_figures``), for a rule that asks about either."""
281 with self._lock:
282 result = rule_engine.evaluate_output(
283 self.db,
284 response,
285 self._context(
286 invocation_id, cell=cell, response=response, **(figures or {})
287 ),
288 self.owner_user_id,
289 )
290 activity_service.commit(self.db)
291 return result
293 def record_stop(
294 self, exc: BaseException, invocation_id: str, *, cell: "_Cell | None" = None
295 ) -> None:
296 """Record that a budget stopped this cell part-way
297 (``ai_client.SpendLimitReached``); nothing for another error."""
298 if not isinstance(exc, ai_client.SpendLimitReached):
299 return
300 if getattr(exc.limit, "kind", None) == rule_engine.SWARM_LIMIT:
301 # A swarm task's own share of its run's budget, not a rule's:
302 # the run records the stop on the task (``swarms.engine``).
303 return
304 with self._lock:
305 spend_limits.record_stop(
306 exc,
307 self._context(invocation_id, cell=cell),
308 self.owner_user_id,
309 db=self.db,
310 )
311 activity_service.commit(self.db)
314@dataclass
315class _Cell:
316 """What one cell runs on, decided before its policy rules: its model
317 (for the rules' context) and an Economy profile's lighter model.
319 Per call, never on the target: one target serves the whole thread pool
320 for its variant, so a cell's choices kept on ``self`` would be applied to
321 its neighbours'. ``_invoke`` reads it through :data:`_CELL`, set on the
322 thread making the call for the call's length.
323 """
325 #: svc-ai's record of the model the cell runs on.
326 model_info: dict[str, Any] | None = None
327 lighter: Any = None
328 #: The native sibling for its structured system steps
329 #: (``native_sibling.Sibling``), chosen beside the lighter model.
330 sibling: Any = None
331 #: The lighter model the request carried (``AgentRequest.lighter_model``).
332 lighter_row: dict[str, Any] | None = None
333 #: The ``ModelOutput`` class the reply is asked to fill (``invoke(output=)``,
334 #: ``structured_reply``), or None for a prose reply.
335 output: Any = None
336 #: Documents sent beside the prompt (``invoke(attachments=)``).
337 attachments: list[dict[str, Any]] | None = None
340#: The cell the current thread is invoking (:class:`_Cell`).
341_CELL: ContextVar[_Cell | None] = ContextVar("evaluation_cell", default=None)
344_SESSION_LOCKS: "weakref.WeakKeyDictionary[Any, threading.Lock]" = (
345 weakref.WeakKeyDictionary()
346)
347_SESSION_LOCKS_GUARD = threading.Lock()
350def _session_lock(db: Session) -> threading.Lock:
351 """The one lock every governed target on ``db`` serialises its commits on.
353 Keyed weakly by the session so a finished batch leaves nothing behind.
354 """
355 with _SESSION_LOCKS_GUARD:
356 lock = _SESSION_LOCKS.get(db)
357 if lock is None:
358 lock = threading.Lock()
359 _SESSION_LOCKS[db] = lock
360 return lock
363class ExecutionTarget(ABC):
364 """Something an evaluation can send a prompt to."""
366 #: Discriminator persisted in run metadata.
367 type: str
369 #: The variant's own context, when it declared one. Subclasses that accept a
370 #: context set it; the base class declares it so ``invoke`` can swap it.
371 context: Optional["EvaluationContext"] = None
373 #: Set by ``build_target(..., owner=...)``. None leaves the target
374 #: ungoverned, which is only right for a target that never runs — the
375 #: pre-flight validation the run endpoints do to 422 early.
376 governance: TargetGovernance | None = None
378 #: What svc-ai records the call as. Without it the trace says "model" or
379 #: "agent" — the execution type — and an evaluation cell is
380 #: indistinguishable from a chat in the activity feed. The judge that
381 #: grades a cell overrides it (see ``resolve_default_judge_target``).
382 purpose: str = TRACE_PURPOSE
384 #: Ids svc-ai stores on the invocation's request snapshot: the
385 #: evaluation or dataset, the batch and the variant this target answers
386 #: for. Set by the runner once it knows the batch; empty for a target
387 #: built only to validate.
388 reference: dict[str, str]
390 #: Who the trace is attributed to when the target is not governed — a
391 #: caller outside evaluation that knows the user but has no owner row to
392 #: govern as (dashboard generation). Governance, when present, wins.
393 attributed_user_id: str | None = None
395 #: Called with every finished call, from the thread that made it — how a
396 #: run puts each call on the usage ledger as it happens
397 #: (``runner.ledger_as_it_goes``), so a cost cap judging the next cell
398 #: counts the ones before it. None for a target outside a run.
399 on_call: Callable[["ExecutionTarget", Invocation], None] | None = None
401 #: How long one call may take before svc-core gives up on it; None for
402 #: the call's own default. A dashboard tile allows longer than a cell: a
403 #: refresh may search the web, run a skill graph and render a document.
404 timeout: float | None = None
406 #: The most one call may spend, whatever the rules leave it — a swarm
407 #: task's share of its run's budget (``swarms.budget``). Called as each
408 #: call starts and tightened with the rules' own limit; None for every
409 #: other target.
410 spend_ceiling: Callable[[], Any] | None = None
412 #: Whether a person can answer a pause, when the caller says so rather
413 #: than the purpose deciding (``attended``): a swarm's workers may ask.
414 attended_override: bool | None = None
416 def __init__(self, *, label: str, config: Optional[dict] = None) -> None:
417 self.label = label
418 self.config = config or {}
419 self.reference = {}
420 self._model_info: dict[str, Any] | None = None
421 self._model_info_lock = threading.Lock()
423 @property
424 def attended(self) -> bool:
425 """Whether a person can answer a pause in this call. An evaluation
426 asks what the agent does in chat, where an agent may ask first — its
427 questions are then the answer graded. A reused target (a dashboard
428 tile) runs unattended: it refreshes with nobody to answer. A caller
429 may say otherwise (``attribute(attended=)``)."""
430 if self.attended_override is not None:
431 return self.attended_override
432 return self.purpose == TRACE_PURPOSE
434 @property
435 def trace_user_id(self) -> str:
436 """Who svc-ai attributes the call to.
438 The owner the target is governed as, so the call lands in *their*
439 invocation trace — svc-ai's list is read per user, and a call sent as
440 ``"system"`` (what evaluations used to send) appears in nobody's.
441 """
442 if self.governance is not None:
443 return self.governance.owner_user_id
444 return self.attributed_user_id or "system"
446 def attribute(
447 self,
448 *,
449 purpose: str,
450 execution_type: str | None = None,
451 reference: dict[str, str] | None = None,
452 user_id: str | None = None,
453 attended: bool | None = None,
454 ) -> "ExecutionTarget":
455 """Say what this call is for, when it is not an evaluation.
457 The targets are reused outside evaluation — dashboard tiles and board
458 generation run through them for the same governed path — and every
459 default here says "evaluation". Left alone, a dashboard refresh reads
460 as an evaluation cell in the activity feed, is ledgered as one, and
461 matches a rule conditioned on ``execution_type``. A reused target must
462 call this.
463 """
464 self.purpose = purpose
465 if reference:
466 self.reference = {k: str(v) for k, v in reference.items() if v}
467 if user_id:
468 self.attributed_user_id = str(user_id)
469 if execution_type and self.governance is not None:
470 self.governance.execution_type = execution_type
471 if attended is not None:
472 self.attended_override = attended
473 return self
475 def _resolve_model_info(self) -> dict[str, Any]:
476 """svc-ai's record for the model this target answers with.
478 Empty by default: a target that cannot say which model answered is
479 still ledgered — for its tokens and latency — it simply cannot be
480 costed. Real targets override this.
481 """
482 return {}
484 @property
485 def model_info(self) -> dict[str, Any]:
486 """The model record, resolved once and cached for the target's life.
488 Resolved lazily because it costs a call to svc-ai, and cached because a
489 target is invoked once per case — resolving per cell made every batch
490 pay N lookups for one answer. Empty when svc-ai cannot say, so the
491 ledger still records the tokens; the cost is what it cannot estimate,
492 and ``estimate_cost`` treats an unpriced model as *unknown*, never as
493 free.
494 """
495 if self._model_info is None:
496 with self._model_info_lock:
497 if self._model_info is None:
498 try:
499 self._model_info = dict(self._resolve_model_info() or {})
500 except (
501 AIServiceError,
502 ModelNotAvailableError,
503 RuntimeError,
504 ) as exc:
505 logger.warning(
506 "Could not resolve model for target %s: %s", self.label, exc
507 )
508 self._model_info = {}
509 return self._model_info
511 @property
512 def ledger_scope(self) -> tuple[str, str | None]:
513 """``(scope_type, scope_id)`` the usage ledger records this target as."""
514 if self.governance is not None:
515 return self.governance.scope_type, self.governance.scope_id
516 return self.type, None
518 def _cell_model(self) -> dict[str, Any]:
519 """svc-ai's record of the model a cell runs on, for the cell's rule
520 context."""
521 return self.model_info
523 def _lighter_for(self) -> Any:
524 """The lighter model a cell's cost profile does its lighter work on
525 (``lighter_model.Choice``), or None — only an agent has one."""
526 return None
528 def _sibling_for(self, lighter: Any) -> Any:
529 """The native sibling for a cell's structured system steps
530 (``native_sibling.Sibling``), or None — only an agent has one."""
531 return None
533 @staticmethod
534 def _cell() -> "_Cell | None":
535 """The cell this thread is invoking, inside ``_invoke``."""
536 return _CELL.get()
538 def _rule_specs(self) -> list[dict] | None:
539 """The rules svc-ai enforces on the call."""
540 return self.governance.rule_specs if self.governance else None
542 @abstractmethod
543 def _invoke(
544 self,
545 prompt: str,
546 system_prompt: str,
547 context: Optional["EvaluationContext"],
548 ) -> tuple[str, int, int, list]:
549 """Perform the call, returning (output, in_tokens, out_tokens, rule_events)
550 — plus, optionally, ``{"interrupt", "tool_calls"}`` for the run."""
552 def invoke(
553 self,
554 prompt: str,
555 system_prompt: str = "",
556 context: Optional["EvaluationContext"] = None,
557 output: type[BaseModel] | None = None,
558 attachments: list[dict[str, Any]] | None = None,
559 invocation_id: str | None = None,
560 ) -> Invocation:
561 """Call the target, converting any failure into a failed ``Invocation``.
563 Evaluation is a batch workload: one unreachable provider or one rule
564 block must be recorded against that case and scored as a failure, not
565 raised so it aborts the remaining cases.
567 ``context`` is the *effective* context for this one cell — the variant's
568 capability merged with the case's situation. It arrives per call rather
569 than on the target because history and variables vary case by case,
570 while a target is built once per variant.
572 ``output`` is the ``ModelOutput`` class the reply is asked to fill:
573 svc-ai is sent its schema (``structured_reply``) and decodes to it
574 natively where the route can. Reading the reply is the caller's —
575 ``invoke_structured`` reads it and corrects it once.
577 ``attachments`` are documents sent beside the prompt
578 (``attachments.wire``): an agent reads them as a chat's documents.
579 A swarm hands a reviewer its team's work this way.
581 ``invocation_id`` is the call's id when the caller minted it first —
582 a swarm records it on the task before the call, so a call cut off by
583 a restart can still be found in svc-ai's traces and ledgered.
584 """
585 started = time.monotonic()
586 # Passed down rather than stashed on the target: one target object is
587 # shared across the whole thread pool for its variant, so per-cell state
588 # on ``self`` would be two threads overwriting each other's context.
589 effective = context if context is not None else self.context
590 governance = self.governance
591 # One id for both phases of this cell, so the activity log groups the
592 # policy rules that ran on the prompt with the audit rules that ran on
593 # the answer — the same grouping an agent turn gets.
594 invocation_id = invocation_id or rule_engine.new_invocation_id()
595 # Everything svc-ai metered for this cell rides on the invocation, so
596 # whoever ledgers it records measured cost rather than an estimate;
597 # svc-ai is told the cell's id for its traces.
598 with ai_client.usage_capture() as used, ai_client.in_invocation(invocation_id):
599 invocation = self._invoke_governed(
600 prompt,
601 system_prompt,
602 effective,
603 governance,
604 invocation_id,
605 started,
606 used,
607 output,
608 attachments,
609 )
610 invocation.usage = used
611 invocation.invocation_id = invocation_id
612 if self.on_call is not None:
613 try:
614 self.on_call(self, invocation)
615 except Exception: # noqa: BLE001 — a record must not fail the cell
616 logger.exception("Could not record a finished call of %s", self.label)
617 return invocation
619 def _invoke_governed(
620 self,
621 prompt: str,
622 system_prompt: str,
623 effective: Optional["EvaluationContext"],
624 governance: "TargetGovernance | None",
625 invocation_id: str,
626 started: float,
627 used: Any = None,
628 output: type[BaseModel] | None = None,
629 attachments: list[dict[str, Any]] | None = None,
630 ) -> Invocation:
631 """``invoke``'s body: governance, the call, and every failure mode."""
632 input_events: list[dict] = []
633 # What this cell's rules hand svc-ai: the most it may spend — what
634 # is left of the tightest budget governing it, where svc-ai stops it
635 # (``spend_limits``) — and the web sources its Tools rules set. The
636 # judge's calls are made outside it: grading is not the cell's turn.
637 # An ungoverned target keeps whatever its caller set — a generative
638 # flow's limit (``generation.metered``), which this used to reset to
639 # none, so svc-ai was never told it.
640 turn_rules: Any = (
641 None
642 if governance is not None
643 else ai_client.TurnGovernance(
644 ai_client.current_spend_limit(), ai_client.current_web_policy()
645 )
646 )
647 cell = _Cell(output=output, attachments=attachments)
648 try:
649 if governance is not None:
650 cell.model_info = self._cell_model()
651 input_rules = governance.check_input(prompt, invocation_id, cell=cell)
652 prompt, input_events = input_rules
653 turn_rules = input_rules
654 if (
655 effective is not None
656 and effective.history
657 and isinstance(input_rules, rule_engine.RulePass)
658 ):
659 # The case's conversation goes to the model beside the
660 # prompt, so it meets the prompt's PII redaction.
661 effective = dataclasses.replace(
662 effective,
663 history=input_rules.redact_history(list(effective.history)),
664 )
665 cell.lighter = self._lighter_for()
666 cell.sibling = self._sibling_for(cell.lighter)
667 turn_rules = self._within_ceiling(turn_rules)
668 token = _CELL.set(cell)
669 try:
670 with ai_client.in_turn_governance(turn_rules):
671 output, in_tokens, out_tokens, rule_events, *more = self._invoke(
672 prompt, system_prompt, effective
673 )
674 finally:
675 _CELL.reset(token)
676 extras = more[0] if more and isinstance(more[0], dict) else {}
677 interrupt = extras.get("interrupt")
678 tool_calls = list(extras.get("tool_calls") or [])
679 clarification = None
680 if interrupt:
681 # Nothing resumes an evaluation's pause, and svc-ai keeps its
682 # checkpoint in memory until something does: drop it now.
683 _discard_pause(interrupt)
684 if interrupt.get("interrupt_type") != CLARIFICATION_INTERRUPT:
685 # An approval gate: nobody in a batch run can approve, and
686 # an empty answer graded as a failure would blame the agent.
687 raise AIServiceError(
688 "The agent paused for a person's approval, which an "
689 "unattended run cannot give."
690 )
691 clarification = [
692 q for q in interrupt.get("questions") or [] if isinstance(q, dict)
693 ]
694 output = clarification_text(interrupt)
695 output_events: list[dict] = []
696 withheld = False
697 output_rules: rule_engine.RulePass | None = None
698 if governance is not None:
699 output_rules = governance.check_output(
700 output or "",
701 invocation_id,
702 usage_service.audit_figures(
703 latency_ms=(time.monotonic() - started) * 1000,
704 measured=used,
705 input_tokens=in_tokens or 0,
706 output_tokens=out_tokens or 0,
707 ),
708 cell=cell,
709 )
710 output, output_events = output_rules
711 if getattr(output_rules, "withheld", None) is not None:
712 withheld = True
713 tool_calls = withholding.strip_tool_calls(tool_calls)
714 clarification = None
715 except RuleBlock as exc:
716 return Invocation(
717 output="",
718 latency_ms=int((time.monotonic() - started) * 1000),
719 error=f"Blocked by rule '{exc.rule_name}': {exc.message}",
720 rule_events=input_events,
721 blocked=True,
722 )
723 except RuleBlockedError as exc:
724 return Invocation(
725 output="",
726 latency_ms=int((time.monotonic() - started) * 1000),
727 error=f"Blocked by rule '{exc.rule}': {exc.message}",
728 rule_events=input_events,
729 blocked=True,
730 )
731 except (AIServiceError, ModelNotAvailableError, RuntimeError) as exc:
732 logger.warning("%s call to %s failed: %s", self.purpose, self.label, exc)
733 if governance is not None:
734 governance.record_stop(exc, invocation_id, cell=cell)
735 return Invocation(
736 output="",
737 latency_ms=int((time.monotonic() - started) * 1000),
738 # A refusal's message says what to fix — or which budget
739 # stopped the cell — and is written to be shown.
740 error=exc.user_message
741 if isinstance(exc, ai_client.ModelRefusedError)
742 else f"{type(exc).__name__}: {exc}",
743 rule_events=input_events,
744 lighter_model=cell.lighter_row,
745 raised=exc,
746 )
747 # Rules svc-ai enforced sit between the two svc-core phases, so the
748 # persisted trace reads in enforcement order.
749 return Invocation(
750 output=output or "",
751 input_tokens=in_tokens,
752 output_tokens=out_tokens,
753 latency_ms=int((time.monotonic() - started) * 1000),
754 rule_events=[*input_events, *(rule_events or []), *output_events],
755 clarification=clarification,
756 tool_calls=tool_calls,
757 lighter_model=cell.lighter_row,
758 withheld=withheld,
759 # What the answer cites, as a chat answer keeps it: redacted as
760 # its text was; none for an answer withheld.
761 citations=None
762 if withheld or clarification is not None
763 else _cited_sources(extras.get("cited_citations"), output_rules),
764 )
766 def _within_ceiling(self, turn_rules: Any) -> Any:
767 """The call's governance with the caller's ceiling
768 (``spend_ceiling``) applied: the tighter of it and the rules' own
769 limit, the rules' web policy unchanged."""
770 if self.spend_ceiling is None:
771 return turn_rules
772 return ai_client.TurnGovernance(
773 rule_engine.tighter(
774 getattr(turn_rules, "spend_limit", None), self.spend_ceiling()
775 ),
776 getattr(turn_rules, "web_policy", None),
777 )
779 def describe(self) -> dict[str, Any]:
780 """The serialisable identity of this target, stored on every run."""
781 return {"type": self.type, "label": self.label, **self.config}
784class ModelTarget(ExecutionTarget):
785 """A raw model invocation — provider, model name, and inference config.
787 Given tools, knowledge or scripted tools by its context, it runs through
788 svc-ai's agent path instead, as a model with exactly those and nothing
789 else: a plain model call has no tools to bind. So "gpt-4o with and without
790 the calculator" is two model variants, with no agent built to hold them.
791 """
793 type = "model"
795 def __init__(
796 self,
797 *,
798 provider: str,
799 model_name: str,
800 label: Optional[str] = None,
801 model_id: Optional[str] = None,
802 temperature: Optional[float] = None,
803 max_tokens: Optional[int] = None,
804 effort: Optional[str] = None,
805 context: Optional["EvaluationContext"] = None,
806 ) -> None:
807 self.provider = provider
808 self.model_name = model_name
809 self.model_id = model_id
810 self.context = context
811 self.temperature = 0.0 if temperature is None else float(temperature)
812 self.max_tokens = int(max_tokens or DEFAULT_MAX_TOKENS)
813 self.effort = effort
814 super().__init__(
815 label=label or f"{provider}/{model_name}",
816 config={
817 "provider": provider,
818 "model": model_name,
819 "model_id": model_id,
820 "temperature": self.temperature,
821 "max_tokens": self.max_tokens,
822 **({"effort": effort} if effort else {}),
823 **(
824 {"context": context.describe()}
825 if context and not context.is_empty
826 else {}
827 ),
828 },
829 )
831 @staticmethod
832 def _needs_agent_path(context: Optional["EvaluationContext"]) -> bool:
833 """Whether this cell asks for anything a plain model call cannot do."""
834 return context is not None and (
835 context.tools is not None
836 or bool(context.knowledge_bases)
837 or bool(context.tool_fixtures)
838 )
840 def _resolve_model_info(self) -> dict[str, Any]:
841 if self.model_id:
842 return ai_client.get_model(UUID(str(self.model_id)))
843 return ai_client.fetch_model_info(self.provider, self.model_name)
845 def _cell_model(self) -> dict[str, Any]:
846 """The variant's model as the target names it, with svc-ai's record
847 once read: the rules need its identity, not a lookup per target."""
848 return {
849 "id": self.model_id,
850 "provider": {"name": self.provider},
851 "model_name": self.model_name,
852 **(self._model_info or {}),
853 }
855 def _answering(self) -> tuple[str, str]:
856 """``(provider, model_name)`` the call goes to."""
857 return self.provider, self.model_name
859 def _invoke(self, prompt, system_prompt, context=None):
860 config = {
861 "temperature": self.temperature,
862 "max_tokens": self.max_tokens,
863 **({"effort": self.effort} if self.effort else {}),
864 }
865 provider, model_name = self._answering()
866 cell = self._cell()
867 shape = cell.output if cell is not None else None
868 structured = (
869 {
870 "output_format": structured_reply.OUTPUT_FORMAT,
871 "output_schema": structured_reply.output_schema(shape),
872 }
873 if shape is not None
874 else {}
875 )
876 if self._needs_agent_path(context):
877 # The tools a model variant has are exactly the ones it names —
878 # none of the general set a stored agent gets by default.
879 return ai_client.invoke_agent_detailed(
880 provider=provider,
881 model_name=model_name,
882 config=config,
883 prompt=prompt,
884 messages=list(context.history),
885 system_prompt=system_prompt or "You are a helpful AI assistant.",
886 tools=list(context.tools or []),
887 tools_enabled=False,
888 knowledge_bases=list(context.knowledge_bases or []),
889 mcp_servers=[],
890 user_id=self.trace_user_id,
891 agent_name=self.label,
892 rules=self._rule_specs(),
893 purpose=self.purpose,
894 reference=self.reference or None,
895 tool_fixtures=list(context.tool_fixtures) or None,
896 # A model has no memory of anyone; svc-ai keeps none for a run
897 # that names no agent, and this says so too.
898 memory=False,
899 **structured,
900 )
901 return ai_client.invoke_model(
902 provider=provider,
903 model_name=model_name,
904 config={**config, "system_prompt": system_prompt},
905 prompt=prompt,
906 # A conversation is a property of the situation, not of the agent,
907 # so a raw model gets the same history a case declares.
908 messages=list(context.history) if context else [],
909 rules=self._rule_specs(),
910 user_id=self.trace_user_id,
911 purpose=self.purpose,
912 reference=self.reference or None,
913 # A new schema can wait for its grammar to compile on svc-ai's
914 # side; a prose call keeps the target's bound.
915 **structured,
916 timeout=max(
917 self.timeout or ai_client.MODEL_TIMEOUT_S,
918 ai_client.STRUCTURED_TIMEOUT_S if structured else 0.0,
919 ),
920 )
923class AgentTarget(ExecutionTarget):
924 """One of the user's agents, invoked as it answers in chat — through its
925 skill graph when it has one (``app/services/agent_spec.py``, the request
926 every path that runs an agent builds). It used to run every agent as
927 itself, so an agent with a skill graph was evaluated as an agent nobody
928 talks to.
930 A variant may override the agent's system prompt (that is the point of a
931 prompt experiment) and its *context* — the knowledge it can reach, the
932 tools it may call, and the conversation it is already in — without mutating
933 the stored agent. That is what makes "the same agent, with and without the
934 compliance repository" one run rather than two agents kept in sync by hand.
935 A skill graph's tools are its nodes', so a variant naming its own tools
936 runs the agent as itself; the target's description says which ran
937 (``skill_id``), so a comparison across the two reads as a changed target.
938 """
940 type = "agent"
942 def __init__(
943 self,
944 *,
945 agent: Agent,
946 db: Session,
947 temperature: Optional[float] = None,
948 max_tokens: Optional[int] = None,
949 effort: Optional[str] = None,
950 model: Optional[dict[str, Any]] = None,
951 context: Optional["EvaluationContext"] = None,
952 cost_profile: Optional[str] = None,
953 ) -> None:
954 self.agent = agent
955 self.db = db
956 # A cost profile in place of the agent's own (``cost_profiles``):
957 # "this agent, thorough and balanced" is two variants of one agent.
958 self.cost_profile = cost_profile
959 self.temperature = temperature
960 self.max_tokens = max_tokens
961 self.effort = effort
962 # A model to run the agent on instead of its own — svc-ai's model
963 # record, resolved when the target was built. "The same agent on
964 # three models" is three variants of one agent, not three agents.
965 self.model_override = model
966 self.context = context
967 self._agent_setup: tuple["agent_spec.AgentSetup", Any, dict | None] | None = (
968 None
969 )
970 self._setup_lock = threading.Lock()
971 # What an Economy profile's lighter model is chosen from
972 # (``services/lighter_model.py``), read once per target as the
973 # agent's setup is: the models the workspace's rules name (None when
974 # the workspace cannot be read), and — ungoverned — a catalogue.
975 self._excluded: Any = _UNREAD
976 self._lighter_lock = threading.Lock()
977 self._own_catalogue = ModelCatalogue()
978 # Read once, on the thread that built the target. ``agent`` is a live
979 # ORM instance on the shared session, and every rule evaluation
980 # commits that session, which *expires* the instance: the next
981 # attribute read anywhere refreshes it with a query. Reading
982 # ``agent.name`` from a pool thread while another cell held the
983 # session lock was a second way to hit "concurrent operations are not
984 # permitted" — intermittent, because it needed the expiry and the
985 # overlap to coincide. Scalars are copied here; anything that needs
986 # the session goes through ``_setup`` under the lock.
987 self._agent_id = str(agent.id)
988 self._agent_name = str(agent.name)
989 # What ``agent_spec.load`` reads, copied for the same reason.
990 self._agent_snapshot = agent_spec.snapshot(agent)
991 override_name = (model or {}).get("model_name")
992 super().__init__(
993 label=f"{agent.name} · {override_name}" if override_name else agent.name,
994 config={
995 "agent_id": str(agent.id),
996 "agent_name": agent.name,
997 **(
998 {"model_id": str(model.get("id")), "model": override_name}
999 if model
1000 else {}
1001 ),
1002 **({"temperature": temperature} if temperature is not None else {}),
1003 **({"max_tokens": max_tokens} if max_tokens is not None else {}),
1004 **({"effort": effort} if effort else {}),
1005 **({"cost_profile": cost_profile} if cost_profile else {}),
1006 # Recorded on every result: a score is not interpretable without
1007 # knowing what the agent could reach when it produced it.
1008 **({"context": context.describe()} if context else {}),
1009 },
1010 )
1012 def _resolve_model_info(self) -> dict[str, Any]:
1013 if self.model_override:
1014 return self.model_override
1015 # Imported lazily: the transformers module pulls in the conversation
1016 # stack, and importing it at module scope would make the evaluation
1017 # service a dependency of it in reverse.
1018 from app.router.app.agents.transformers import _resolve_model
1020 # Reads the agent's model off the session, so it takes the session
1021 # lock like every other read a pool thread makes — see ``_setup``.
1022 with _session_lock(self.db):
1023 return _resolve_model(self.db, self.agent)
1025 @property
1026 def _setup(self) -> tuple["agent_spec.AgentSetup", Any, dict | None]:
1027 """What the agent brings with it (``agent_spec.load``), the skill it
1028 answers through, and that skill's graph as this deployment runs it.
1030 Loaded once per target, and under the **session lock**. ``_invoke``
1031 runs on a pool thread, and these reads used to happen there
1032 unguarded, while another cell's rule evaluation held the lock and
1033 used the same session: SQLAlchemy refused with "concurrent
1034 operations are not permitted" and the whole batch failed — every
1035 agent-versus-model comparison, every time. A target's agent does not
1036 change mid-batch, so once is also the right number of times.
1037 """
1038 if self._agent_setup is None:
1039 with self._setup_lock:
1040 if self._agent_setup is None:
1041 with _session_lock(self.db):
1042 setup = agent_spec.load(self.db, self._agent_snapshot)
1043 skill = setup.skills[0] if setup.skills else None
1044 graph = (
1045 agent_spec.resolve_skill(self.db, setup, skill)[0]
1046 if skill is not None
1047 else None
1048 )
1049 self._agent_setup = (setup, skill, graph)
1050 return self._agent_setup
1052 def _request(
1053 self,
1054 config: dict[str, Any],
1055 system_prompt: str,
1056 context: Optional["EvaluationContext"],
1057 ) -> "agent_spec.AgentRequest":
1058 """The cell as svc-ai runs it: the agent as configured, with the
1059 variant's and the case's context on top."""
1060 setup, skill, graph = self._profiled_setup()
1061 cell = self._cell()
1062 shape = cell.output if cell is not None else None
1063 lighter = cell.lighter if cell is not None else self._lighter_for()
1064 return agent_spec.build(
1065 setup,
1066 model_info=self._cell_model_info(),
1067 config=config,
1068 skill=skill,
1069 graph_definition=graph,
1070 # A reply to a schema: svc-ai states it in the agent's
1071 # instructions (``structured_reply``).
1072 output_format=structured_reply.OUTPUT_FORMAT if shape else None,
1073 output_schema=structured_reply.output_schema(shape) if shape else None,
1074 # As chat chooses them: the cell runs the agent as chat does.
1075 lighter=lighter,
1076 structured=(
1077 cell.sibling if cell is not None else self._sibling_for(lighter)
1078 ),
1079 # An evaluation asks what the agent does in chat, and in chat an
1080 # agent that checks scope may ask first — its questions are then
1081 # the answer graded (expected behaviour "clarify"). A reused
1082 # target (a dashboard tile) has nobody to answer, so never asks.
1083 interactive=self.attended,
1084 overrides=agent_spec.Overrides(
1085 # None means "whatever the agent already has"; an empty list
1086 # means "explicitly nothing". Collapsing the two would make
1087 # the without half of a with/without comparison impossible.
1088 knowledge_bases=None if context is None else context.knowledge_bases,
1089 # Built-in tools are bound by svc-ai, not granted here: an
1090 # agent that says nothing gets the general set, and a context
1091 # that names tools gets exactly those.
1092 tools=None if context is None else context.tools,
1093 # The case's scripted tools: part of the situation it sets up.
1094 tool_fixtures=list(context.tool_fixtures) if context else [],
1095 system_prompt=system_prompt or None,
1096 ),
1097 )
1099 def _profiled_setup(self) -> tuple["agent_spec.AgentSetup", Any, dict | None]:
1100 """``_setup``, under the variant's cost profile when it names one."""
1101 setup, skill, graph = self._setup
1102 if self.cost_profile:
1103 setup = dataclasses.replace(setup, cost_profile=self.cost_profile)
1104 return setup, skill, graph
1106 def _cell_model_info(self) -> dict[str, Any]:
1107 """svc-ai's record of the model the cell runs on: the agent's (or the
1108 variant's override)."""
1109 return self.model_info
1111 def _lighter_for(self) -> Any:
1112 """The lighter model the cell's profile does its lighter work on, or
1113 why there is none — as chat chooses it, from the target's catalogue,
1114 less what the workspace's rules name (read once, under the session
1115 lock)."""
1116 from app.services import lighter_model as lighter_service
1118 setup = self._profiled_setup()[0]
1119 if not lighter_service.uses_one(setup.cost_profile):
1120 return lighter_service.Choice(reason=lighter_service.NoLighter.not_used)
1121 return self.lighter_model_choice()
1123 def lighter_model_choice(self) -> Any:
1124 """The lighter model this agent would do lighter work on, chosen as
1125 an Economy profile chooses one, whatever the agent's own profile —
1126 for a caller that runs it on one outright (a swarm level's lighter
1127 tier). A ``lighter_model.Choice``: the model, or why there is none."""
1128 from app.services import lighter_model as lighter_service
1130 setup = self._profiled_setup()[0]
1131 model_info = self.model_info
1132 excluded = self._lighter_excluded(setup)
1133 if excluded is None or not model_info:
1134 return lighter_service.Choice(reason=lighter_service.NoLighter.unknown)
1135 catalogue = (
1136 self.governance.catalogue
1137 if self.governance is not None
1138 else self._own_catalogue
1139 )
1140 return lighter_service.pick(catalogue, model_info, excluded=excluded)
1142 def _sibling_for(self, lighter: Any) -> Any:
1143 """The native sibling for the cell's structured system steps, as chat
1144 chooses it (``native_sibling``): for the lighter model when the
1145 profile chose one, else the cell's model, and never a model the
1146 workspace's rules name."""
1147 from app.services import native_sibling
1149 if not native_sibling.enabled():
1150 return native_sibling.Sibling(reason=native_sibling.NoSibling.off)
1151 model_info = native_sibling.stands_in_for(self.model_info, lighter)
1152 excluded = self._lighter_excluded(self._profiled_setup()[0])
1153 if excluded is None or not model_info:
1154 return native_sibling.Sibling(reason=native_sibling.NoSibling.unknown)
1155 catalogue = (
1156 self.governance.catalogue
1157 if self.governance is not None
1158 else self._own_catalogue
1159 )
1160 return native_sibling.pick(catalogue, model_info, excluded=excluded)
1162 def _lighter_excluded(self, setup: "agent_spec.AgentSetup") -> set[str] | None:
1163 """The models a rule in force for the agent's workspace names — never
1164 a lighter model nor a native sibling — or None when the workspace
1165 cannot be read."""
1166 from app.services import lighter_model as lighter_service
1167 from app.services import workspace as workspace_service
1169 if self._excluded is _UNREAD:
1170 with self._lighter_lock:
1171 if self._excluded is _UNREAD:
1172 try:
1173 with _session_lock(self.db):
1174 ws = workspace_service.home_of(self.db, setup.owner)
1175 self._excluded = (
1176 lighter_service.excluded_models(self.db, ws)
1177 if ws is not None
1178 else None
1179 )
1180 except Exception: # noqa: BLE001 — the agent's own does it
1181 logger.exception(
1182 "Could not read the rules a lighter model meets"
1183 )
1184 self._excluded = None
1185 return self._excluded
1187 def describe(self) -> dict[str, Any]:
1188 """As every target, plus the skill the agent answered through, when
1189 it did: a run through the graph and one without are different
1190 targets to compare (``regression._target_identity``)."""
1191 described = super().describe()
1192 try:
1193 _, skill, _ = self._setup
1194 except Exception: # noqa: BLE001 — a description never fails a run
1195 logger.warning("Could not read %s's skill to describe it", self.label)
1196 return described
1197 if skill is not None and (self.context is None or self.context.tools is None):
1198 described["skill_id"] = str(skill.id)
1199 return described
1201 def _invoke(self, prompt, system_prompt, context=None):
1202 model_info = self._cell_model_info()
1203 if not model_info:
1204 raise RuntimeError(
1205 f"No model could be resolved for agent {self._agent_name!r}"
1206 )
1207 config = dict(model_info.get("config") or {})
1208 if self.temperature is not None:
1209 config["temperature"] = self.temperature
1210 if self.max_tokens is not None:
1211 config["max_tokens"] = self.max_tokens
1212 if self.effort:
1213 config["effort"] = self.effort
1215 request = self._request(config, system_prompt, context)
1216 if (cell := self._cell()) is not None:
1217 # The ledger names it when svc-ai says it wrote the answer.
1218 cell.lighter_row = request.lighter_model
1219 return ai_client.execute_agent_request(
1220 request.payload(
1221 prompt=prompt,
1222 messages=list(context.history) if context else [],
1223 user_id=self.trace_user_id,
1224 rules=self._rule_specs(),
1225 external_agent_id=self._agent_id,
1226 # Neither an evaluation's cases nor a dashboard tile is
1227 # anyone's conversation. Remembered, one case's data and
1228 # answers were recalled into the next (the platform benchmark
1229 # ran every case as one "system" user) and a person's
1230 # Evaluate filed its cases into their own chats' memory; a
1231 # tile ran as its board's creator, so on an organisation's
1232 # board the creator's memories were recalled into what every
1233 # member saw, and each scheduled refresh wrote one more
1234 # memory of a prompt nobody typed.
1235 memory=False,
1236 # Nor is either attended by anyone a tile could ask: svc-ai
1237 # offers an unattended run no ``ask_user`` (a tile's question
1238 # was cached as its answer).
1239 may_ask=self.attended,
1240 purpose=self.purpose,
1241 reference=self.reference or None,
1242 attachments=cell.attachments if cell is not None else None,
1243 ),
1244 detail=True,
1245 timeout=self.timeout or ai_client.AGENT_TIMEOUT_S,
1246 )
1249class SwarmTarget(ExecutionTarget):
1250 """A swarm, as an evaluation answers with it: each cell is one whole run
1251 of the swarm on the case, and the run's answer is what is graded — so a
1252 shape is measured against a single agent on the same dataset, at what it
1253 cost per answer.
1255 The run is the swarm's own (``swarms.engine``), started unattended — no
1256 plan to approve, no questions — with the case as its task and the
1257 variant's budget and time cap per case (else the swarm's defaults).
1258 Every task in it is its agent's governed turn under its own rules, and
1259 ledgered as it finishes as the evaluation's spend
1260 (``engine.Origin.evaluation``), so the cell is not governed or ledgered
1261 again here: its ``Invocation`` carries the run's measured figures, marked
1262 ledgered, and the run's id for the cell's page. The run is left out of
1263 the Swarms lists. A case's conversation and data go into the task; a
1264 variant's knowledge or tools, and a case's scripted tools, have nowhere
1265 to go — a swarm's agents use their own — and are refused.
1266 """
1268 type = "swarm"
1270 def __init__(
1271 self,
1272 *,
1273 swarm: Any,
1274 budget_usd: Any = None,
1275 time_cap_s: Any = None,
1276 context: Optional["EvaluationContext"] = None,
1277 session_factory: Callable[[], Session] | None = None,
1278 execute: Callable[[Any], None] | None = None,
1279 ) -> None:
1280 config: dict[str, Any] = {"swarm_id": str(swarm.id)}
1281 if budget_usd is not None:
1282 config["budget_usd"] = float(budget_usd)
1283 if time_cap_s is not None:
1284 config["time_cap_s"] = int(time_cap_s)
1285 super().__init__(label=str(swarm.name), config=config)
1286 self.swarm_id = swarm.id
1287 self.topology = str(getattr(swarm, "topology", "") or "")
1288 self.budget_usd = budget_usd
1289 self.time_cap_s = time_cap_s
1290 self.context = context
1291 #: Who the run runs as — the person an evaluation runs as
1292 #: (``govern``); None for a target built only to validate.
1293 self.owner_user_id: str | None = None
1294 #: The evaluation whose spend the run is.
1295 self.experiment_id: str | None = None
1296 self._session_factory = session_factory
1297 self._execute = execute
1299 def _invoke(self, prompt, system_prompt, context=None): # pragma: no cover
1300 raise NotImplementedError("A swarm's cell is a whole run: see invoke.")
1302 def describe(self) -> dict[str, Any]:
1303 return {**super().describe(), "topology": self.topology}
1305 def _task(self, prompt: str, context: Optional["EvaluationContext"]) -> str:
1306 """The run's task: the case, with its conversation before it and its
1307 data after it."""
1308 if context is None:
1309 return prompt
1310 text = context.present(context.render(prompt))
1311 if context.history:
1312 earlier = "\n\n".join(
1313 f"{m['role'].capitalize()}: {m['content']}" for m in context.history
1314 )
1315 text = f"Earlier in the conversation:\n\n{earlier}\n\nNow:\n\n{text}"
1316 return text
1318 def invoke(
1319 self,
1320 prompt: str,
1321 system_prompt: str = "",
1322 context: Optional["EvaluationContext"] = None,
1323 output: type[BaseModel] | None = None,
1324 attachments: list[dict[str, Any]] | None = None,
1325 invocation_id: str | None = None,
1326 ) -> Invocation:
1327 """Run the swarm on the case, start to finish, and grade its answer."""
1328 started = time.monotonic()
1329 effective = context if context is not None else self.context
1330 invocation = self._run(prompt, effective, output)
1331 invocation.latency_ms = int((time.monotonic() - started) * 1000)
1332 if self.on_call is not None:
1333 try:
1334 self.on_call(self, invocation)
1335 except Exception: # noqa: BLE001 — a record must not fail the cell
1336 logger.exception("Could not record a finished call of %s", self.label)
1337 return invocation
1339 def _run(
1340 self,
1341 prompt: str,
1342 context: Optional["EvaluationContext"],
1343 output: type[BaseModel] | None,
1344 ) -> Invocation:
1345 from app.db.postgres.engine import SessionLocal
1346 from app.db.postgres.models import Swarm, SwarmRun, User
1347 from app.services.budgets.gate import BudgetReached
1348 from app.services.swarms import engine
1350 if output is not None:
1351 return Invocation(output="", error="A swarm cannot fill a schema.")
1352 if context is not None and context.tool_fixtures:
1353 return Invocation(
1354 output="",
1355 error="This case scripts tools, which a swarm's agents cannot "
1356 "use: they call their own.",
1357 )
1358 if self.owner_user_id is None:
1359 return Invocation(output="", error="This run has no one to run it as.")
1360 factory = self._session_factory or SessionLocal
1361 overrides: dict[str, Any] = {}
1362 if self.budget_usd is not None:
1363 overrides["budget_usd"] = self.budget_usd
1364 if self.time_cap_s is not None:
1365 overrides["time_cap_s"] = self.time_cap_s
1366 origin = {
1367 "kind": engine.Origin.evaluation.value,
1368 "experiment_id": self.experiment_id or self.reference.get("experiment_id"),
1369 **{
1370 key: self.reference[key]
1371 for key in ("batch_id", "variant_id")
1372 if self.reference.get(key)
1373 },
1374 }
1375 db = factory()
1376 try:
1377 swarm = db.get(Swarm, self.swarm_id)
1378 if swarm is None:
1379 return Invocation(output="", error="The swarm was deleted.")
1380 user = db.get(User, UUID(self.owner_user_id))
1381 if user is None:
1382 return Invocation(output="", error="The person it runs as is gone.")
1383 run = engine.start(
1384 db,
1385 swarm,
1386 user,
1387 task=self._task(prompt, context),
1388 overrides=overrides,
1389 submit=lambda _run_id: None,
1390 origin=origin,
1391 )
1392 run_id = run.id
1393 except engine.RunRefused as exc:
1394 problems = "; ".join(f"{k}: {v}" for k, v in exc.fields.items())
1395 return Invocation(
1396 output="",
1397 error=f"{exc}" + (f" ({problems})" if problems else ""),
1398 )
1399 except BudgetReached as exc:
1400 return Invocation(output="", error=str(exc), blocked=True, raised=exc)
1401 finally:
1402 db.close()
1403 (self._execute or engine.execute)(run_id)
1404 db = factory()
1405 try:
1406 run = db.get(SwarmRun, run_id)
1407 return _swarm_invocation(run)
1408 finally:
1409 db.close()
1412def _swarm_invocation(run: Any) -> Invocation:
1413 """What a swarm's run came to, as a cell reads it: its answer (or why it
1414 has none), its measured figures — on the ledger already, as each task
1415 finished — and where its page is."""
1416 from app.services.swarms import engine
1418 status = str(run.status)
1419 answered = status in (
1420 engine.RunStatus.completed.value,
1421 engine.RunStatus.partial.value,
1422 )
1423 calls = int(run.llm_calls or 0)
1424 unpriced = int(run.unpriced_calls or 0)
1425 spent = Decimal(str(run.spent_usd or 0))
1426 cost = Decimal(str(run.cost_usd or 0)) if calls > unpriced else None
1427 usage = ai_client.UsageCapture(
1428 calls=calls,
1429 input_tokens=int(run.input_tokens or 0),
1430 output_tokens=int(run.output_tokens or 0),
1431 cost_usd=cost,
1432 unpriced_calls=unpriced,
1433 unpriced_estimate_usd=(
1434 max(spent - (cost or 0), Decimal(0)) if unpriced else None
1435 ),
1436 )
1437 final = next(
1438 (
1439 t
1440 for t in sorted(run.tasks or [], key=lambda t: -int(t.seq or 0))
1441 if t.status == engine.TaskStatus.done
1442 and (t.output or "") == (run.output or "")
1443 ),
1444 None,
1445 )
1446 plan = run.plan if isinstance(run.plan, dict) else {}
1447 return Invocation(
1448 output=(run.output or "") if answered else "",
1449 input_tokens=usage.input_tokens,
1450 output_tokens=usage.output_tokens,
1451 error=None if answered else (run.error or f"The swarm's run {status}."),
1452 usage=usage,
1453 # Its tasks put every call on the ledger as they finished.
1454 ledgered=True,
1455 invocation_id=str(final.invocation_id)
1456 if final and final.invocation_id
1457 else None,
1458 swarm_run={
1459 "id": str(run.id),
1460 "status": status,
1461 "wrap_up_reason": run.wrap_up_reason,
1462 "tasks": len(
1463 [t for t in run.tasks or [] if t.status != engine.TaskStatus.cancelled]
1464 ),
1465 "approach": plan.get("approach"),
1466 },
1467 )
1470def ledger_identity(
1471 target: Any, invocation: Any
1472) -> tuple[str, str | None, dict[str, Any]]:
1473 """``(scope_type, scope_id, model_info)`` a call's usage-ledger row
1474 records: the target's scope, and the model that wrote the answer — an
1475 Economy profile's lighter model when svc-ai says it did, else the
1476 target's own. What an evaluation's rows (``runner._ledger_call``) and a
1477 dashboard tile's (``dashboards.widgets``) both write."""
1478 from app.services import lighter_model as lighter_service
1480 scope_type, scope_id = target.ledger_scope
1481 answered = lighter_service.answered(
1482 getattr(invocation, "lighter_model", None),
1483 getattr(getattr(invocation, "usage", None), "answered_by", None),
1484 )
1485 return scope_type, scope_id, answered or target.model_info or {}
1488#: svc-ai's discriminator for an ``ask_user`` pause (``tools/clarify.py``).
1489CLARIFICATION_INTERRUPT = "clarification_request"
1491#: How a clarification reads as an answer — the marker a scorer (and a person
1492#: reading the result) can recognise.
1493CLARIFICATION_HEADER = "[Asked for clarification instead of answering]"
1496def _discard_pause(interrupt: dict) -> None:
1497 """Drop the checkpoint svc-ai holds for a paused evaluation cell.
1499 A paused run's state stays in svc-ai's memory until it is resumed, and an
1500 evaluation never resumes one: every clarifying question a case drew (the
1501 Clarification gold dataset draws one on purpose, on every benchmark run)
1502 would otherwise stay there until svc-ai restarts. Best-effort — the
1503 cell's result does not depend on it.
1504 """
1505 thread_id = interrupt.get("thread_id")
1506 if not thread_id:
1507 return
1508 try:
1509 ai_client.discard_paused_run(str(thread_id))
1510 except AIServiceError:
1511 logger.warning("Could not discard paused evaluation run %s", thread_id)
1514def clarification_text(interrupt: dict) -> str:
1515 """The questions an agent paused to ask, written out as its answer."""
1516 lines = [CLARIFICATION_HEADER]
1517 if interrupt.get("intro"):
1518 lines.append(str(interrupt["intro"]))
1519 for question in interrupt.get("questions") or []:
1520 if not isinstance(question, dict):
1521 continue
1522 text = f"- {question.get('question', '')}"
1523 options = [
1524 str(o.get("label") or o.get("value"))
1525 for o in question.get("options") or []
1526 if isinstance(o, dict)
1527 ]
1528 if options:
1529 text += f" (options: {', '.join(options)})"
1530 lines.append(text)
1531 return "\n".join(lines)
1534class TargetResolutionError(ValueError):
1535 """Raised when a target spec cannot be turned into an ExecutionTarget."""
1538def govern(target: ExecutionTarget, db: Session, owner: Any) -> ExecutionTarget:
1539 """Attach the rules and ledger identity a target runs under.
1541 ``owner`` is the experiment or dataset the run belongs to — or, for the
1542 Compare scratchpad, the user — and contributes the project or organisation
1543 an ownership-scoped rule lives on. The chain is what an agent turn builds
1544 for itself: the agent (or model) plus what owns it, so a rule written at
1545 any of those levels governs the evaluation exactly as it governs a chat.
1546 """
1547 owner_user_id = getattr(owner, "owner_user_id", None)
1548 shared = getattr(owner, "owner_organisation_id", None) or getattr(
1549 owner, "owner_project_id", None
1550 )
1551 if not owner_user_id and shared:
1552 # An organisation's or project's evaluation or board runs as a
1553 # person — it used to run ungoverned and unledgered here.
1554 owner_user_id = _actor_of(db, owner)
1555 if not owner_user_id:
1556 raise TargetResolutionError(
1557 "This run has no one to run it as. Start it again from its page."
1558 )
1559 if not owner_user_id:
1560 return target
1561 if isinstance(target, AgentTarget):
1562 chain = rule_scopes.invocation_chain(
1563 agent=target.agent,
1564 # Read off the row rather than resolved, so composing the chain
1565 # costs no call to svc-ai — the same choice the agent router makes.
1566 # The model the cell actually runs on, so a model-scoped rule
1567 # governs an agent variant switched onto that model.
1568 model_id=(target.model_override or {}).get("id")
1569 or target.agent.ai_model_id,
1570 owner=owner,
1571 )
1572 scope_type, scope_id = "agent", str(target.agent.id)
1573 extra = {"agent_id": str(target.agent.id), "agent_name": target.agent.name}
1574 else:
1575 model_id = getattr(target, "model_id", None)
1576 chain = rule_scopes.invocation_chain(model_id=model_id, owner=owner)
1577 scope_type, scope_id = "model", (str(model_id) if model_id else None)
1578 extra = {
1579 "provider": getattr(target, "provider", None),
1580 "model_name": getattr(target, "model_name", None),
1581 }
1582 scope_chain = rule_scopes.serialize(chain)
1583 target.governance = TargetGovernance(
1584 db=db,
1585 owner_user_id=str(owner_user_id),
1586 scope_chain=scope_chain,
1587 rule_specs=rule_engine.serialize_rules(
1588 db, str(owner_user_id), scopes=scope_chain
1589 ),
1590 scope_type=scope_type,
1591 scope_id=scope_id,
1592 extra_context={k: v for k, v in extra.items() if v is not None},
1593 )
1594 return target
1597def _actor_of(db: Session, owner: Any) -> Any:
1598 """Who an organisation's or project's evaluation or board runs as: the
1599 person who started the run (``run_by_user_id``, set by the runner), else
1600 whoever created it — a board's tiles always, since a refresh has no
1601 viewer to run as when the scheduler starts it — so its calls are
1602 governed and ledgered like a person's, never skipped."""
1603 actor = getattr(owner, "run_by_user_id", None)
1604 if actor:
1605 return actor
1606 from app.dependency.resource_access import creator_of
1607 from app.services import access
1609 kind = access.kind_of(owner)
1610 if kind is None or getattr(owner, "id", None) is None:
1611 return None
1612 try:
1613 return creator_of(db, kind, owner)
1614 except Exception:
1615 logger.exception("Could not read who created %s %s", kind.key, owner.id)
1616 return None
1619def _reachable_by(resource: Any, owner: Any) -> bool:
1620 """Whether ``resource`` sits in the same owner scope as ``owner``.
1622 An agent target runs that agent over its knowledge and tools and hands
1623 back the answer, so an agent id in a variant, a Quick try or a dashboard
1624 tile is a read of that agent. It is scoped by the owning evaluation or
1625 board — not the request user — for the reason
1626 ``context._owner_filter`` gives: targets are rebuilt inside background
1627 batches and scheduled refreshes, where there is no request to check. No
1628 owner fails closed; this is access control.
1629 """
1630 if owner is None:
1631 return False
1632 # CHAINR Bot belongs to nobody and is readable by everybody, so any
1633 # owning evaluation or board may target it. Still behind the check above:
1634 # no owner is no access, system row or not.
1635 if getattr(resource, "is_system", False) is True:
1636 return True
1637 for column in ("owner_user_id", "owner_organisation_id", "owner_project_id"):
1638 value = getattr(owner, column, None)
1639 if value is not None:
1640 return str(getattr(resource, column, None)) == str(value)
1641 return False
1644def build_target(
1645 spec: dict,
1646 db: Session,
1647 context: Optional["EvaluationContext"] = None,
1648 *,
1649 owner: Any = None,
1650) -> ExecutionTarget:
1651 """Build an :class:`ExecutionTarget` from a stored/posted target spec.
1653 Accepted shapes::
1655 {"type": "model", "provider": "openai", "model": "gpt-4o", ...}
1656 {"type": "model", "model_id": "<svc-ai model uuid>", ...}
1657 {"type": "model", "default": true, ...}
1658 {"type": "agent", "agent_id": "<uuid>", ...}
1660 ``default`` is the deployment's default model, resolved now — what a
1661 built-in dashboard tile runs on, since no model id is the same on every
1662 deployment.
1664 ``model_id`` is resolved through svc-ai so the UI can pass the same model
1665 identifier it lists everywhere else rather than provider/name pairs.
1667 ``context`` is the resolved knowledge / tools / history the target should
1668 run with. It is already validated by the time it arrives here — resolving
1669 it is the caller's job, because an unusable context should be a 422 at
1670 request time rather than a failure inside a background batch.
1671 """
1672 if not isinstance(spec, dict):
1673 raise TargetResolutionError("Target must be an object.")
1675 kind = str(spec.get("type") or ("agent" if spec.get("agent_id") else "model"))
1677 if kind == "agent":
1678 raw_id = spec.get("agent_id")
1679 if not raw_id:
1680 raise TargetResolutionError("An agent target requires 'agent_id'.")
1681 try:
1682 agent = db.get(Agent, UUID(str(raw_id)))
1683 except (ValueError, AttributeError) as exc:
1684 raise TargetResolutionError(f"Invalid agent_id {raw_id!r}.") from exc
1685 # Somebody else's agent reports as not found, never forbidden, for
1686 # the reason ``context._resolve_knowledge`` gives: the two answers
1687 # together are an existence oracle.
1688 if agent is None or not _reachable_by(agent, owner):
1689 raise TargetResolutionError(f"Agent {raw_id} not found.")
1690 override = None
1691 if spec.get("model_id"):
1692 override = _resolve_model_record(spec["model_id"])
1693 return govern(
1694 AgentTarget(
1695 agent=agent,
1696 db=db,
1697 temperature=spec.get("temperature"),
1698 max_tokens=spec.get("max_tokens"),
1699 effort=_effort(spec),
1700 model=override,
1701 context=context,
1702 cost_profile=_cost_profile(spec),
1703 ),
1704 db,
1705 owner,
1706 )
1708 if kind == "swarm":
1709 return _swarm_target(spec, db, context, owner)
1711 if kind != "model":
1712 raise TargetResolutionError(f"Unsupported target type {kind!r}.")
1713 if spec.get("cost_profile"):
1714 raise TargetResolutionError(
1715 "A cost profile is how much work an agent's pipeline does; a model "
1716 "has none."
1717 )
1719 provider = spec.get("provider")
1720 model_name = spec.get("model") or spec.get("model_name")
1721 model_id = spec.get("model_id")
1722 if not (provider and model_name) and not model_id and spec.get("default") is True:
1723 default = _default_model_record()
1724 model_id = default.get("id")
1725 provider = (default.get("provider") or {}).get("name")
1726 model_name = default.get("model_name")
1728 if not (provider and model_name):
1729 if not model_id:
1730 raise TargetResolutionError(
1731 "A model target requires 'model_id', both 'provider' and "
1732 "'model', or 'default': true."
1733 )
1734 info = _resolve_model_record(model_id)
1735 provider = (info.get("provider") or {}).get("name")
1736 model_name = info.get("model_name")
1737 if not (provider and model_name):
1738 raise TargetResolutionError(
1739 f"Model {model_id} is missing provider details."
1740 )
1742 return govern(
1743 ModelTarget(
1744 provider=str(provider),
1745 model_name=str(model_name),
1746 label=spec.get("label"),
1747 model_id=str(model_id) if model_id else None,
1748 temperature=spec.get("temperature"),
1749 max_tokens=spec.get("max_tokens"),
1750 effort=_effort(spec),
1751 context=context,
1752 ),
1753 db,
1754 owner,
1755 )
1758def _swarm_target(
1759 spec: dict, db: Session, context: Optional["EvaluationContext"], owner: Any
1760) -> "SwarmTarget":
1761 """A swarm variant: the swarm, reachable from the evaluation's owner,
1762 with an optional budget and time cap per case — and no knowledge or
1763 tools of its own, which a swarm's agents would have nowhere to use."""
1764 from app.db.postgres.models import Swarm
1765 from app.services.swarms import engine
1767 raw_id = spec.get("swarm_id")
1768 if not raw_id:
1769 raise TargetResolutionError("A swarm target requires 'swarm_id'.")
1770 try:
1771 swarm = db.get(Swarm, UUID(str(raw_id)))
1772 except (ValueError, AttributeError) as exc:
1773 raise TargetResolutionError(f"Invalid swarm_id {raw_id!r}.") from exc
1774 if swarm is None or not _reachable_by(swarm, owner):
1775 raise TargetResolutionError(f"Swarm {raw_id} not found.")
1776 if context is not None and (
1777 context.knowledge_bases is not None or context.tools is not None
1778 ):
1779 raise TargetResolutionError(
1780 "A swarm variant takes no knowledge or tools of its own: its agents "
1781 "use theirs."
1782 )
1783 for key in ("temperature", "max_tokens", "effort", "model_id", "cost_profile"):
1784 if spec.get(key) not in (None, ""):
1785 raise TargetResolutionError(
1786 f"A swarm variant has no '{key}': its agents run as they are."
1787 )
1788 overrides = {
1789 k: spec[k] for k in ("budget_usd", "time_cap_s") if spec.get(k) is not None
1790 }
1791 _, problems = engine.read_defaults(overrides)
1792 if problems:
1793 raise TargetResolutionError(
1794 "; ".join(f"{field}: {why}" for field, why in problems.items())
1795 )
1796 target = SwarmTarget(
1797 swarm=swarm,
1798 budget_usd=overrides.get("budget_usd"),
1799 time_cap_s=overrides.get("time_cap_s"),
1800 context=context,
1801 )
1802 if owner is not None:
1803 owner_user_id = getattr(owner, "owner_user_id", None) or _actor_of(db, owner)
1804 if not owner_user_id:
1805 raise TargetResolutionError(
1806 "This run has no one to run it as. Start it again from its page."
1807 )
1808 target.owner_user_id = str(owner_user_id)
1809 from app.db.postgres.models import Experiment
1811 # An evaluation's id; a Quick try has none yet.
1812 target.experiment_id = str(owner.id) if isinstance(owner, Experiment) else None
1813 return target
1816#: svc-ai's reasoning-effort levels (``ModelConfig.effort``). Dropped by
1817#: svc-ai for a model that does not take the control.
1818EFFORT_LEVELS = ("low", "medium", "high", "xhigh", "max")
1821def _effort(spec: dict) -> Optional[str]:
1822 """A spec's effort, refused at build time when it is not a level."""
1823 raw = spec.get("effort")
1824 if raw in (None, ""):
1825 return None
1826 if raw not in EFFORT_LEVELS:
1827 raise TargetResolutionError(
1828 f"Effort must be one of {', '.join(EFFORT_LEVELS)}; got {raw!r}."
1829 )
1830 return str(raw)
1833def _cost_profile(spec: dict) -> Optional[str]:
1834 """A spec's cost profile, refused at build time when it names none."""
1835 from app.util import cost_profiles
1837 raw = spec.get("cost_profile")
1838 if raw in (None, ""):
1839 return None
1840 found = cost_profiles.parse(raw)
1841 if found is None:
1842 raise TargetResolutionError(
1843 f"Cost profile must be one of {', '.join(cost_profiles.keys())}; "
1844 f"got {raw!r}."
1845 )
1846 return found.value
1849def _default_model_record() -> dict[str, Any]:
1850 """The deployment's default model — the one an agent with no model of its
1851 own answers with (``agents.transformers._resolve_model``)."""
1852 try:
1853 available = ai_client.list_models(is_available=True, is_default=True)
1854 except AIServiceError as exc:
1855 raise TargetResolutionError(
1856 f"The default model could not be resolved: {exc}"
1857 ) from exc
1858 if not available or not available[0].get("id"):
1859 raise TargetResolutionError("No default model is available.")
1860 return available[0]
1863def _resolve_model_record(model_id: Any) -> dict[str, Any]:
1864 """svc-ai's record for ``model_id``, or a resolution error to report."""
1865 try:
1866 return ai_client.get_model(UUID(str(model_id)))
1867 except (ValueError, AttributeError) as exc:
1868 raise TargetResolutionError(f"Invalid model_id {model_id!r}.") from exc
1869 except (AIServiceError, ModelNotAvailableError) as exc:
1870 raise TargetResolutionError(
1871 f"Model {model_id} is not available: {exc}"
1872 ) from exc
1875#: Judging must be deterministic whichever model does it: the same output has
1876#: to grade the same way on a re-run, or regression detection reports provider
1877#: noise as a regression. Applied to a nominated judge as well as the default
1878#: one — a picked judge that graded at the provider's default temperature
1879#: would quietly make every verdict unreliable.
1880JUDGE_TEMPERATURE = 0.0
1881#: A checklist verdict is a sentence per criterion, a few hundred tokens. The
1882#: cap is higher because a model that reasons first counts its reasoning
1883#: against it: at 512 the default model (a reasoning one) could spend the
1884#: budget thinking and return a verdict cut short — unscored, and so left out
1885#: of the mean. Only what the judge writes is paid for.
1886JUDGE_MAX_TOKENS = 4096
1889def judge_spec(spec: Optional[dict]) -> dict:
1890 """A nominated judge's spec, with deterministic grading defaults filled in.
1892 Only the model identity comes from the user. The UI offers no temperature
1893 control for a judge deliberately, and an explicit value in a stored spec
1894 still wins so a spec written before these defaults keeps its behaviour.
1895 """
1896 base = {k: v for k, v in (spec or {}).items() if v is not None}
1897 base.setdefault("temperature", JUDGE_TEMPERATURE)
1898 base.setdefault("max_tokens", JUDGE_MAX_TOKENS)
1899 base["type"] = "model"
1900 return base
1903def resolve_default_judge_target(
1904 db: Session, spec: Optional[dict], *, owner: Any = None
1905) -> Optional[ModelTarget]:
1906 """Resolve the model that grades LLM-judged runs.
1908 Falls back to svc-ai's default model so a suite configured with the ``llm``
1909 scorer works without the user also having to nominate a judge.
1911 ``owner`` is the evaluation or dataset the grading belongs to. The judge
1912 is governed and attributed like the cells it grades: its calls are the
1913 same user's spend, and a trace that showed the answers but not the
1914 grading would account for half of what the run cost.
1915 """
1916 target: Optional[ModelTarget] = None
1917 if spec:
1918 try:
1919 built = build_target(judge_spec(spec), db, owner=owner)
1920 except TargetResolutionError as exc:
1921 logger.warning("Judge target unusable (%s) — falling back to default", exc)
1922 else:
1923 target = built if isinstance(built, ModelTarget) else None
1924 if target is None:
1925 target = _default_judge_target(db, owner)
1926 if target is not None:
1927 target.purpose = JUDGE_TRACE_PURPOSE
1928 return target
1931def _default_judge_target(db: Session, owner: Any) -> Optional[ModelTarget]:
1932 """svc-ai's default model, as a deterministic judge."""
1934 try:
1935 available = ai_client.list_models(is_available=True, is_default=True)
1936 except (AIServiceError, ModelNotAvailableError) as exc:
1937 logger.warning("Could not resolve a default judge model: %s", exc)
1938 return None
1939 if not available:
1940 return None
1941 info = available[0]
1942 provider = (info.get("provider") or {}).get("name")
1943 model_name = info.get("model_name")
1944 if not (provider and model_name):
1945 return None
1946 judge = ModelTarget(
1947 provider=provider,
1948 model_name=model_name,
1949 model_id=str(info.get("id")) if info.get("id") else None,
1950 temperature=JUDGE_TEMPERATURE,
1951 max_tokens=JUDGE_MAX_TOKENS,
1952 )
1953 return govern(judge, db, owner) if owner is not None else judge
1956@dataclass
1957class StructuredInvocation[T: BaseModel]:
1958 """What :func:`invoke_structured` got: the value, when a reply matched
1959 its schema, and every call it made — each one is the caller's to ledger
1960 — with what went wrong in one line when none did."""
1962 value: T | None
1963 invocations: list[Invocation]
1964 failure: str = ""
1966 @property
1967 def last(self) -> Invocation:
1968 return self.invocations[-1]
1970 @property
1971 def failed_call(self) -> bool:
1972 """True when the last call failed or was blocked, rather than
1973 answering with a reply that did not match."""
1974 return not self.last.ok
1977def invoke_structured[T: BaseModel](
1978 target: ExecutionTarget,
1979 prompt: str,
1980 system_prompt: str,
1981 schema: type[T],
1982 context: EvaluationContext | None = None,
1983 attachments: list[dict[str, Any]] | None = None,
1984 invocation_id: str | None = None,
1985) -> StructuredInvocation[T]:
1986 """Ask ``target`` for a reply filled to ``schema``, governed and metered
1987 like any call to it.
1989 svc-ai is sent the schema (``structured_reply``) and decodes to it
1990 natively where the route can. The reply is read by
1991 ``structured_reply.read``; one that does not match is answered once with
1992 what was wrong (``structured_reply.correction``), the exchange so far as
1993 the conversation before it. Never after a call that failed or was
1994 blocked: asking again would meet the same refusal. ``attachments`` go
1995 with both calls, and so does ``invocation_id``: a correction is part of
1996 the same step.
1997 """
1998 # Passed only when given: every other caller's call is as it was.
1999 documents: dict[str, Any] = {"attachments": attachments} if attachments else {}
2000 if invocation_id:
2001 documents["invocation_id"] = invocation_id
2002 first = target.invoke(prompt, system_prompt, context, output=schema, **documents)
2003 invocations = [first]
2004 if not first.ok:
2005 return StructuredInvocation(None, invocations, first.error or "the call failed")
2006 if getattr(first, "withheld", False):
2007 # A rule withheld the reply: asking again would only be withheld again.
2008 return StructuredInvocation(
2009 None, invocations, "the reply was withheld by an Output rule"
2010 )
2011 value, problem = structured_reply.read(first.output, schema)
2012 if value is not None:
2013 return StructuredInvocation(value, invocations)
2015 from app.services.evaluation.context import EvaluationContext
2017 history = [
2018 *(context.history if context is not None else []),
2019 {"role": "user", "content": prompt},
2020 {"role": "assistant", "content": first.output},
2021 ]
2022 retry_context = (
2023 dataclasses.replace(context, history=history)
2024 if context is not None
2025 else EvaluationContext(history=history)
2026 )
2027 second = target.invoke(
2028 structured_reply.correction(schema, problem),
2029 system_prompt,
2030 retry_context,
2031 output=schema,
2032 **documents,
2033 )
2034 invocations.append(second)
2035 if not second.ok:
2036 return StructuredInvocation(
2037 None, invocations, second.error or "the call failed"
2038 )
2039 value, problem = structured_reply.read(second.output, schema)
2040 return StructuredInvocation(value, invocations, problem)
2043def make_judge_fn(target: Optional[ModelTarget]):
2044 """Adapt a judge target into the callable :class:`LLMJudgeScorer` expects:
2045 ``judge(system, user, output)``, where ``output`` is the verdict's
2046 ``ModelOutput`` class. It returns the text of the reply that matched it
2047 — or, when none did, of the last reply, which the scorer reports.
2049 The callable keeps every invocation it made on ``judge.invocations`` (with
2050 the target on ``judge.target``), so the runner can put the judge's calls
2051 — a correction included — on the usage ledger beside the cells they
2052 graded. Grading used to be the one part of an evaluation nothing counted.
2053 """
2054 if target is None:
2055 return None
2057 invocations: list[Invocation] = []
2059 def judge(system_prompt: str, user_prompt: str, output: type[BaseModel]) -> str:
2060 result = invoke_structured(target, user_prompt, system_prompt, output)
2061 # list.extend of a fresh list is atomic across pool threads
2062 invocations.extend(result.invocations)
2063 if result.failed_call:
2064 raise AIServiceError(result.last.error or "judge invocation failed")
2065 return result.last.output
2067 judge.invocations = invocations # type: ignore[attr-defined]
2068 judge.target = target # type: ignore[attr-defined]
2069 return judge