Coverage for app / services / native_sibling.py: 93%
72 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"""
2A native sibling for an agent whose model cannot decode a schema.
4Bedrock decodes a reply to a JSON schema natively for Claude 4.5 and 4.6,
5gpt-oss and Qwen3 235B, and not for Claude 5.x (their cards). An agent on
6Claude 5.x fills each structured system step of its turns — triage, recon,
7planning, retrieval's query planning and reranking, the quality check,
8memory extraction, a router's choice, an output repair — by function
9calling, with nothing but validation afterwards to hold the reply to its
10schema. With ``NATIVE_STRUCTURED_SIBLING`` on, svc-core names a **native
11sibling** for the turn (``structured_model``) that makes those calls
12instead. svc-core chooses it, as it chooses an Economy profile's lighter
13model (``services/lighter_model.py``), because the choice is governance: it
14is the one that knows the workspace's rules.
16The sibling stands in for the model that makes the steps: the lighter model
17when an Economy profile chose one, else the agent's own. It is the available
18chat model that is, beside that model (:func:`choose`):
20* **the same maker's** (``lighter_model.maker_of``), so no prompt reaches a maker
21 the agent never named;
22* **in the same region**, so a residency the model was chosen for holds;
23* **one that decodes natively** on this deployment (svc-ai's
24 ``decodes_natively``);
25* **able to see** when that model can;
26* **named by no model-scoped rule** in force for the workspace;
28the nearest in tier, then the cheapest. There is none when the setting is
29off, the model already decodes natively, or a person chose the turn's model
30— and svc-ai checks the sibling again before it stands it
31in (``services/native_sibling.py`` there), since svc-ai is what knows the
32routes. Its calls are metered under its own model; nothing new reaches the
33ledger.
35Off by default, and unmeasured: on today's catalogue the only sibling for
36the EU's Claude 5.x models is Claude Haiku 4.5, about ten times Haiku 5.5's
37price per token, whose Bedrock end of life may now come at any time (listed
38as no sooner than 16 October 2026), and Opus 5 (EU) can drop only to it.
39"""
41from __future__ import annotations
43import logging
44from collections.abc import Iterable
45from dataclasses import dataclass
46from decimal import Decimal
47from enum import StrEnum
48from typing import Any
50from sqlalchemy.orm import Session
52from app.common.settings import get_settings
53from app.services import lighter_model, model_catalogue
55logger = logging.getLogger(__name__)
58class NoSibling(StrEnum):
59 """Why a turn has no native sibling."""
61 off = "off"
62 native = "native"
63 none_in_region = "none_in_region"
64 unknown = "unknown"
65 catalogue = "catalogue"
68@dataclass(frozen=True)
69class Sibling:
70 """The native sibling chosen, or why there is none."""
72 model: dict[str, Any] | None = None
73 reason: NoSibling | None = None
76def enabled() -> bool:
77 """Whether this deployment names native siblings at all."""
78 return bool(get_settings().NATIVE_STRUCTURED_SIBLING)
81def stands_in_for(
82 model_info: dict[str, Any] | None, lighter: Any
83) -> dict[str, Any] | None:
84 """The model whose structured steps a sibling would make: an Economy
85 profile's lighter model when one was chosen (it makes them), else the
86 turn's own."""
87 chosen = getattr(lighter, "model", None)
88 return chosen if chosen else model_info
91def choose(
92 models: Iterable[dict[str, Any]],
93 model: dict[str, Any],
94 *,
95 excluded: Iterable[str] = (),
96) -> Sibling:
97 """The native sibling for ``model`` among ``models`` (the catalogue's
98 available ones), or why there is none."""
99 maker = lighter_model.maker_of(model)
100 region = lighter_model.region_of(model)
101 if not maker or not region:
102 return Sibling(reason=NoSibling.unknown)
103 if model.get("decodes_natively"):
104 return Sibling(reason=NoSibling.native)
105 shut_out = {str(model_id) for model_id in excluded}
106 candidates = [
107 candidate
108 for candidate in models
109 if candidate.get("is_chat", True)
110 and candidate.get("decodes_natively")
111 and str(candidate.get("id")) != str(model.get("id"))
112 and lighter_model.maker_of(candidate) == maker
113 and lighter_model.region_of(candidate) == region
114 and (not model.get("is_vision") or candidate.get("is_vision"))
115 and str(candidate.get("id")) not in shut_out
116 ]
117 if not candidates:
118 return Sibling(reason=NoSibling.none_in_region)
119 tier = lighter_model.tier_of(model)
121 def rank(candidate: dict[str, Any]) -> tuple[int, bool, Decimal]:
122 own = lighter_model.tier_of(candidate)
123 distance = (
124 abs(own - tier)
125 if own is not None and tier is not None
126 else len(lighter_model.TIERS)
127 )
128 cost = model_catalogue.estimated_request_cost(
129 candidate, lighter_model.RANKING_PROMPT_TOKENS
130 )
131 return distance, cost is None, cost or Decimal(0)
133 return Sibling(model=min(candidates, key=rank))
136def pick(
137 catalogue: model_catalogue.ModelCatalogue,
138 model_info: dict[str, Any],
139 *,
140 excluded: Iterable[str] = (),
141) -> Sibling:
142 """:func:`choose` over a catalogue, or why it could not be read — for a
143 caller that reads the rules under a lock of its own (an evaluation's
144 pool)."""
145 if model_info.get("decodes_natively"):
146 return Sibling(reason=NoSibling.native)
147 if not catalogue.usable():
148 return Sibling(reason=NoSibling.catalogue)
149 return choose(catalogue.available(), model_info, excluded=excluded)
152def for_turn(
153 db: Session,
154 *,
155 model_info: dict[str, Any] | None,
156 lighter: Any = None,
157 ws: Any,
158) -> Sibling:
159 """The native sibling of a turn in ``ws`` on ``model_info`` (or on
160 ``lighter``'s model, when an Economy profile chose one), or why there is
161 none. Never raises: a choice that cannot be made leaves every step on
162 its own model."""
163 if not enabled():
164 return Sibling(reason=NoSibling.off)
165 model = stands_in_for(model_info, lighter)
166 if not model or ws is None:
167 return Sibling(reason=NoSibling.unknown)
168 if model.get("decodes_natively"):
169 return Sibling(reason=NoSibling.native)
170 try:
171 return pick(
172 model_catalogue.ModelCatalogue(),
173 model,
174 excluded=lighter_model.excluded_models(db, ws),
175 )
176 except Exception: # every step then stays on its own model
177 logger.exception("Could not choose a native sibling")
178 return Sibling(reason=NoSibling.catalogue)
181def spec(choice: Any) -> dict[str, Any] | None:
182 """svc-ai's ``structured_model`` for ``choice``: its identity, and its
183 output ceiling as ``max_tokens`` (svc-ai gives it each step's own
184 budget, held to that). Temperature is the step's own, so none is sent."""
185 model = getattr(choice, "model", None)
186 if model is None:
187 return None
188 out: dict[str, Any] = {
189 "provider": lighter_model.provider_of(model),
190 "model": model.get("model_name"),
191 }
192 ceiling = model.get("max_output_tokens")
193 if isinstance(ceiling, int):
194 out["max_tokens"] = ceiling
195 return out