Coverage for app / services / lighter_model.py: 89%
100 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"""
2An Economy profile's lighter model (cost-control plan B3).
4The Economy cost profile (``app/util/cost_profiles.py``) has a lighter model
5do the lighter work of a turn: in svc-ai it runs the steps nobody reads
6(triage, planning, retrieval's query planning and reranking, the quality
7check, memory summaries) and answers a request triage calls simple
8(``app/agents/effort.py`` there). svc-core chooses that model, because the
9choice is governance: it is the one that knows the workspace's rules.
11The lighter model is the cheapest available chat model that is, beside the
12agent's own (:func:`choose`):
14* **the same maker's** (:func:`maker_of`, svc-ai's catalogue ``maker``), so
15 no prompt reaches a maker the agent never named — models Bedrock alone
16 serves share its ``bedrock`` provider, so the provider cannot tell them
17 apart;
18* **in the same region** — so a residency the agent's model was chosen for
19 holds (a model that declares no region never qualifies);
20* **in a lighter tier** (svc-ai's ``effort``: light < balanced < deep <
21 frontier) and **cheaper** by the estimated cost of a request;
22* **able to see** when the agent's model can;
23* **named by no model-scoped rule** in force for the workspace — a rule
24 written for a model is never sidestepped by moving the work to it.
26None qualifies — the agent is already on its maker's lightest model in its
27region, say — and svc-ai does all the work on the agent's own model, as it
28would without the profile. Each reason is said in words for the agent's page
29(``GET /app/agents/cost-profiles?agent_id=``).
30"""
32from __future__ import annotations
34import logging
35from dataclasses import dataclass
36from enum import StrEnum
37from typing import Any, Iterable
39from sqlalchemy.orm import Session
41from app.services import model_catalogue
42from app.util import cost_profiles
44logger = logging.getLogger(__name__)
46#: svc-ai's model tiers (``ModelEnum.Effort``), lightest first.
47TIERS: tuple[str, ...] = ("light", "balanced", "deep", "frontier")
48#: The prompt a request's cost is estimated at, to rank two models: a turn's
49#: system prompt and a few earlier turns.
50RANKING_PROMPT_TOKENS = 2_000
53class NoLighter(StrEnum):
54 """Why an agent has no lighter model."""
56 not_used = "not_used"
57 lightest = "lightest"
58 none_in_region = "none_in_region"
59 unknown = "unknown"
60 catalogue = "catalogue"
63#: What each reason reads as on the agent's page.
64NO_LIGHTER_TEXT: dict[str, str] = {
65 NoLighter.not_used: "This profile uses the agent's own model throughout.",
66 NoLighter.lightest: (
67 "The agent is already on its maker's lightest model in this region, "
68 "so it uses its own model throughout."
69 ),
70 NoLighter.none_in_region: (
71 "No lighter model of the same maker is available in this region, so "
72 "the agent uses its own model throughout."
73 ),
74 NoLighter.unknown: (
75 "The agent's model does not say its tier or region, so no lighter "
76 "model is chosen for it."
77 ),
78 NoLighter.catalogue: (
79 "The model catalogue could not be read just now, so the agent uses "
80 "its own model."
81 ),
82}
83if set(NO_LIGHTER_TEXT) != set(NoLighter):
84 raise RuntimeError("Every reason for no lighter model needs its words")
87@dataclass(frozen=True)
88class Choice:
89 """The lighter model chosen, or why there is none."""
91 model: dict[str, Any] | None = None
92 reason: NoLighter | None = None
94 @property
95 def text(self) -> str | None:
96 return NO_LIGHTER_TEXT[self.reason] if self.reason is not None else None
99def tier_of(model: dict[str, Any]) -> int | None:
100 effort = str(model.get("effort") or "").lower()
101 return TIERS.index(effort) if effort in TIERS else None
104def provider_of(model: dict[str, Any]) -> str:
105 provider = model.get("provider")
106 if isinstance(provider, dict):
107 provider = provider.get("name")
108 return str(provider or "").lower()
111def maker_of(model: dict[str, Any]) -> str:
112 """Who made ``model``: svc-ai's catalogue ``maker`` (the provider, or the
113 vendor a ``bedrock`` model's id names), else its provider."""
114 return str(model.get("maker") or "").lower() or provider_of(model)
117def region_of(model: dict[str, Any]) -> str:
118 return str(model.get("data_region") or "").lower()
121def choose(
122 models: Iterable[dict[str, Any]],
123 model: dict[str, Any],
124 *,
125 excluded: Iterable[str] = (),
126) -> Choice:
127 """The lighter model for an agent on ``model`` among ``models`` (the
128 catalogue's available ones), or why there is none."""
129 maker, region, tier = maker_of(model), region_of(model), tier_of(model)
130 if not maker or not region or tier is None:
131 return Choice(reason=NoLighter.unknown)
132 if tier == 0:
133 return Choice(reason=NoLighter.lightest)
134 own_cost = model_catalogue.estimated_request_cost(model, RANKING_PROMPT_TOKENS)
135 if own_cost is None:
136 return Choice(reason=NoLighter.unknown)
137 shut_out = {str(model_id) for model_id in excluded}
138 candidates = [
139 candidate
140 for candidate in models
141 if candidate.get("is_chat", True)
142 and str(candidate.get("id")) != str(model.get("id"))
143 and maker_of(candidate) == maker
144 and region_of(candidate) == region
145 and (candidate_tier := tier_of(candidate)) is not None
146 and candidate_tier < tier
147 and (not model.get("is_vision") or candidate.get("is_vision"))
148 and str(candidate.get("id")) not in shut_out
149 ]
150 for candidate in model_catalogue.cheapest_first(candidates, RANKING_PROMPT_TOKENS):
151 cost = model_catalogue.estimated_request_cost(candidate, RANKING_PROMPT_TOKENS)
152 if cost is not None and cost < own_cost:
153 return Choice(model=candidate)
154 return Choice(reason=NoLighter.none_in_region)
157def excluded_models(db: Session, ws: Any) -> set[str]:
158 """The models a rule in force for ``ws`` names — never a lighter model."""
159 from app.db.postgres.enums import RuleEnum
160 from app.db.postgres.models import Rule
161 from app.services import workspace as workspace_service
163 rows = (
164 db.query(Rule.scope_id)
165 .filter(
166 Rule.is_active.is_(True),
167 Rule.is_system.is_(False),
168 Rule.scope_type == RuleEnum.Scope.model,
169 workspace_service.governing_rules(ws),
170 )
171 .all()
172 )
173 return {str(row[0]) for row in rows if row[0] is not None}
176def for_turn(
177 db: Session,
178 *,
179 profile: Any,
180 model_info: dict[str, Any] | None,
181 ws: Any,
182) -> Choice:
183 """The lighter model a turn in ``ws`` on ``model_info`` does its lighter
184 work on, under ``profile`` — or why there is none. Never raises: a
185 choice that cannot be made leaves the agent's own model doing it all."""
186 if not uses_one(profile):
187 return Choice(reason=NoLighter.not_used)
188 if not model_info or ws is None:
189 return Choice(reason=NoLighter.unknown)
190 try:
191 return pick(
192 model_catalogue.ModelCatalogue(),
193 model_info,
194 excluded=excluded_models(db, ws),
195 )
196 except Exception: # noqa: BLE001 — the agent's own model does it all
197 logger.exception("Could not choose a lighter model")
198 return Choice(reason=NoLighter.catalogue)
201def uses_one(profile: Any) -> bool:
202 """Whether ``profile`` (a key, or None for the default) has a lighter
203 model do some of the work."""
204 found = cost_profiles.parse(profile) or cost_profiles.DEFAULT
205 return cost_profiles.LIGHTER_MODEL[found]
208def pick(
209 catalogue: model_catalogue.ModelCatalogue,
210 model_info: dict[str, Any],
211 *,
212 excluded: Iterable[str] = (),
213) -> Choice:
214 """:func:`choose` over a catalogue, or why it could not be read — for a
215 caller that reads the rules (``excluded_models``) under a lock of its
216 own and the catalogue outside it (an evaluation's pool)."""
217 if not catalogue.usable():
218 return Choice(reason=NoLighter.catalogue)
219 return choose(catalogue.available(), model_info, excluded=excluded)
222def spec(choice: Choice, config: dict[str, Any] | None = None) -> dict[str, Any] | None:
223 """svc-ai's ``lighter_model`` for ``choice``: its identity, with the
224 agent's sampling settings (an answer it writes is the agent's answer),
225 its output held to what the lighter model can write."""
226 model = choice.model
227 if model is None:
228 return None
229 config = config or {}
230 out: dict[str, Any] = {
231 "provider": provider_of(model),
232 "model": model.get("model_name"),
233 }
234 if config.get("temperature") is not None:
235 out["temperature"] = config["temperature"]
236 max_tokens = config.get("max_tokens")
237 ceiling = model.get("max_output_tokens")
238 if isinstance(max_tokens, int):
239 out["max_tokens"] = (
240 min(max_tokens, ceiling) if isinstance(ceiling, int) else max_tokens
241 )
242 return out
245def answered(
246 choice_model: dict[str, Any] | None, answered_by: Any
247) -> dict[str, Any] | None:
248 """The lighter model's catalogue row when svc-ai says it wrote the
249 answer (the ``answered_by`` it reports), else None."""
250 if not choice_model or not isinstance(answered_by, dict):
251 return None
252 if str(answered_by.get("model") or "") == str(
253 choice_model.get("model_name") or ""
254 ) and str(answered_by.get("provider") or "").lower() == provider_of(choice_model):
255 return choice_model
256 return None
259def answer_meta(answered_by: Any) -> dict[str, Any]:
260 """What a stored answer the lighter model wrote says of it
261 (``meta.lighter_model``)."""
262 reason = answered_by.get("reason") if isinstance(answered_by, dict) else None
263 return {"answered": True, "reason": str(reason or "simple")}