Coverage for app / services / native_sibling.py: 100%
88 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""A native sibling: a model that decodes a schema, for a model that cannot.
3Bedrock decodes a reply to a JSON schema natively for Claude 4.5 and 4.6,
4gpt-oss and Qwen3 235B, and not for Claude 5.x (their cards). An agent on
5Claude 5.x fills every structured system step — triage, recon, planning,
6retrieval's query planning and reranking, the quality check, memory
7extraction, a router's choice, an output repair — by function calling, and
8holds the reply to its schema only by validating it after.
10svc-core may name a **native sibling** for a run (``structured_model``,
11``NATIVE_STRUCTURED_SIBLING``, off by default): the same maker's model, in
12the same region, that does decode natively, chosen there because the rules
13in force are svc-core's to read. Here it stands in for a structured call
14(:meth:`NativeSibling.stand_in`) only when every one of these holds, checked
15again on this side because svc-ai is what knows the routes:
17* the call is a system step's — a node's own typed output stays on the
18 node's model (``structured_call(stand_in=False)``);
19* the schema can be decoded strictly (``Shape.strict_ok``);
20* the model making the call would not decode it natively;
21* the sibling is the same maker's (``inference_routes.maker_of``: models
22 Bedrock alone serves share the ``bedrock`` provider but not a maker), in
23 the same region (``inference_routes.data_region``; an unknown region never
24 matches), and decodes natively on its route.
26It takes the caller's temperature and output budget (held to its own
27ceiling when svc-core sent one), so a step behaves as it would have on the
28caller's model. A sibling that cannot be built, or that the provider refuses
29outright (``ModelUnavailableError``), is given up for the rest of the run and
30the call goes to the caller's model, as if none had been named. Its calls are
31metered under its own model, like any other.
33**Carried in the run config** (``configurable[CONFIG_KEY]``), set by
34``AgentGraphBuilder.run_config`` for every run — batch, stream and resume —
35as the source registry is (``util/source_registry.py``): a ``ContextVar``
36set in a streaming generator would belong to whichever task advances it.
37"""
39from __future__ import annotations
41import threading
42from typing import TYPE_CHECKING, Any
44from app.services import model_errors
45from app.util.logger import get_logger
47if TYPE_CHECKING:
48 # app.models.spec imports the agents, which import structured_output,
49 # which imports this module.
50 from app.models.spec import ModelConfig
52logger = get_logger(__name__)
54#: Where a run's sibling lives in its config's ``configurable``. ``__`` so
55#: LangGraph never copies it into checkpoint metadata.
56CONFIG_KEY = "__chainr_native_sibling"
58#: Refusals that are the deployment's or svc-core's budgets, not the
59#: sibling's: the caller's model would be refused the same.
60_SPEND_REFUSALS = frozenset(
61 {model_errors.FatalKind.BUDGET, model_errors.FatalKind.TURN_LIMIT}
62)
65class NativeSibling:
66 """One run's native sibling: its model, the clients built for it, and
67 whether it has been given up."""
69 def __init__(self, config: ModelConfig) -> None:
70 self.config = config
71 self._lock = threading.Lock()
72 self._built: dict[tuple[Any, Any], Any] = {}
73 #: Why it is no longer used in this run, once it is not.
74 self.given_up: str | None = None
76 @classmethod
77 def of(cls, config: ModelConfig | dict[str, Any] | None) -> NativeSibling | None:
78 """The sibling ``config`` names, or None."""
79 if config is None:
80 return None
81 from app.models.spec import ModelConfig
83 if isinstance(config, dict):
84 config = ModelConfig(**config)
85 return cls(config)
87 # -- the decision ------------------------------------------------------
89 def applies_to(self, llm: Any, shape: Any) -> bool:
90 """Whether this sibling should make ``llm``'s structured call for
91 ``shape`` (see the module notes)."""
92 # Imported here: structured_output imports this module.
93 from app.services import inference_routes, provider_refusals
94 from app.services.model_capabilities import capabilities_for
95 from app.services.provider_refusals import Feature
96 from app.services.structured_output import NATIVE, method_for, provider_model
98 if self.given_up is not None or not shape.strict_ok:
99 return False
100 provider, model = provider_model(llm)
101 if not provider or method_for(llm, shape) == NATIVE:
102 return False
103 own_provider, own_model = self.config.provider.lower(), self.config.model
104 if own_model == model or inference_routes.maker_of(
105 own_provider, own_model
106 ) != inference_routes.maker_of(provider, model):
107 return False
108 region = inference_routes.data_region(provider, model)
109 if not region or region != inference_routes.data_region(
110 own_provider, own_model
111 ):
112 return False
113 if not capabilities_for(own_provider, own_model).native_structured_output:
114 return False
115 return not provider_refusals.refused(
116 own_provider, own_model, Feature.NATIVE_SCHEMA, shape.name
117 )
119 def stand_in(self, llm: Any, shape: Any) -> Any | None:
120 """The client to make ``llm``'s structured call for ``shape`` with,
121 or None when the caller's own should."""
122 if not self.applies_to(llm, shape):
123 return None
124 return self._client_like(llm)
126 def _client_like(self, llm: Any) -> Any | None:
127 """The sibling, with ``llm``'s temperature and output budget."""
128 temperature = getattr(llm, "temperature", None)
129 max_tokens = getattr(llm, "max_tokens", None)
130 key = (temperature, max_tokens)
131 with self._lock:
132 if key in self._built:
133 return self._built[key]
134 update: dict[str, Any] = {}
135 if isinstance(temperature, (int, float)):
136 update["temperature"] = temperature
137 budget = [max_tokens] if isinstance(max_tokens, int) else []
138 if "max_tokens" in self.config.model_fields_set:
139 budget.append(self.config.max_tokens)
140 if budget:
141 update["max_tokens"] = min(budget)
142 from app.services.llm import build_langchain_llm
144 try:
145 client = build_langchain_llm(self.config.model_copy(update=update))
146 except Exception as exc: # noqa: BLE001 — the caller's own then answers
147 self._give_up(model_errors.describe(exc))
148 return None
149 self._built[key] = client
150 return client
152 # -- giving up ---------------------------------------------------------
154 def refused(self, exc: model_errors.ModelUnavailableError) -> bool:
155 """Note that the provider refused the sibling outright. True when the
156 caller's own model should make the call instead; False for a refusal
157 that would be the caller's too (a spend limit), to be raised."""
158 if exc.kind in _SPEND_REFUSALS:
159 return False
160 self._give_up(model_errors.describe(exc))
161 return True
163 def _give_up(self, why: str) -> None:
164 if self.given_up is None:
165 self.given_up = why
166 logger.warning(
167 "[sibling] %s/%s given up for this run (%s) — structured steps "
168 "go to their own models",
169 self.config.provider,
170 self.config.model,
171 why,
172 )
175def of_config(config: Any) -> NativeSibling | None:
176 """The sibling a run config carries, or None."""
177 if not isinstance(config, dict):
178 return None
179 found = (config.get("configurable") or {}).get(CONFIG_KEY)
180 return found if isinstance(found, NativeSibling) else None
183def current(config: Any = None) -> NativeSibling | None:
184 """The sibling of the run this code is part of: ``config``'s, else the
185 run config LangChain hands every node and tool; None outside a run."""
186 found = of_config(config)
187 if found is not None:
188 return found
189 from langchain_core.runnables.config import var_child_runnable_config
191 return of_config(var_child_runnable_config.get())