Coverage for app / services / model_capabilities.py: 100%
109 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"""
2What a given model will accept on the wire.
4Providers do not keep one request shape across generations, and the penalty
5for sending a parameter a model has since dropped is a hard 400 rather than
6a warning — the invocation fails outright. Two such breaks are live today:
8 * Anthropic models released after Claude Opus 4.6 reject ``temperature``
9 ("`temperature` is deprecated for this model"). ``output_config.effort``
10 replaces it as the steering control.
11 * OpenAI's reasoning families reject *function tools* on
12 ``/v1/chat/completions`` unless reasoning is switched off entirely
13 ("Function tools with reasoning_effort are not supported … use
14 /v1/responses or set reasoning_effort to 'none'"). They also reject any
15 ``temperature`` other than the default, and take the output cap as
16 ``max_completion_tokens`` rather than ``max_tokens``. The fix for the
17 first is the Responses API, which keeps the reasoning the model exists
18 for; the alternative the error suggests, ``reasoning_effort='none'``,
19 buys compatibility by making the model a worse one.
21Both rules are about the *model*, not the provider, so they cannot live in
22the provider branch of ``build_langchain_llm`` — and they apply equally to
23the LiteLLM path, which does not go through that branch at all. Hence one
24table, consulted by every call path.
26Adding a model generation means adding or adjusting one rule here, and the
27seeded catalogue is checked against this table by
28``tests/services/test_model_capabilities.py`` so a newly seeded model cannot
29quietly arrive without one.
30"""
32from __future__ import annotations
34import re
35from dataclasses import dataclass
36from functools import lru_cache
37from typing import Any, Literal
40#: How a model's reply carries its answer (``app/services/reply_formats``,
41#: one registered class each): ``typed`` reasoning and commentary in blocks of
42#: their own (Anthropic, OpenAI, Claude on Bedrock); ``inline_tags`` reasoning
43#: between ``<think>``-style tags (open-weight models on Bedrock, Groq, local
44#: servers); ``gpt_oss`` the analysis channel as answer text, answered in an
45#: envelope.
46ReplyFormatKey = Literal["typed", "inline_tags", "gpt_oss", "dsml"]
49@dataclass(frozen=True)
50class ModelCapabilities:
51 """What one model accepts. Defaults are the permissive, pre-existing
52 behaviour, so a provider or model this module knows nothing about is
53 called exactly as it was before."""
55 # False when the model rejects an explicit ``temperature``. Omitting it
56 # is always safe — the provider applies its own default — which is why
57 # an uncertain case resolves this way round: a dropped temperature is a
58 # mild behaviour change, a rejected one is a failed invocation.
59 supports_temperature: bool = True
61 # True when function tools require OpenAI's Responses API. Chat
62 # Completions still answers these models for plain text, but any request
63 # carrying tools is refused, and an agent without tools is not the
64 # agent the user configured.
65 requires_responses_api: bool = False
67 # The name this model's API gives the output-token cap. OpenAI's
68 # reasoning models reject ``max_tokens`` outright and require
69 # ``max_completion_tokens``; LiteLLM translates it for the models it
70 # recognises, but a model newer than the pinned LiteLLM (gpt-6-astra
71 # today) is passed through unchanged and 400s.
72 max_tokens_param: str = "max_tokens"
74 # True when the model takes a reasoning-effort control — the replacement
75 # for temperature on models that dropped it. Anthropic spells it
76 # ``output_config.effort``, OpenAI ``reasoning_effort``; both take the
77 # same level names, which is why one flag covers both.
78 supports_effort: bool = False
80 # How long one request may run before it is abandoned, in seconds. Every
81 # provider SDK defaults to ten minutes, so with retries one call could hold
82 # a turn for half an hour. A model that deliberates before answering gets
83 # longer. For a streamed call this bounds each wait between chunks, not
84 # the whole answer.
85 request_timeout_s: float = 120.0
87 # True when the model takes a JSON schema it is *constrained* to follow
88 # (OpenAI Structured Outputs with ``strict``; Anthropic structured outputs,
89 # ``output_config.format``). Constrained decoding cannot omit a required
90 # field or invent an enum value, which forced function calling can — a
91 # planner that left out an empty list once failed every simple question.
92 # False keeps forced function calling, which every tool-capable model
93 # takes. An unknown model resolves to False: the old path is safe.
94 native_structured_output: bool = False
96 # True when function calling may force the model to call the schema tool
97 # (``tool_choice`` naming it), as the vendors' clients do. False where
98 # the model refuses that — Claude 5.x on Bedrock, which thinks by
99 # default — or the route offers no tool choice (Bedrock's open-weight
100 # models): ``structured_output`` offers the tool and asks for the call.
101 forced_tool_choice: bool = True
103 # True when a tool's arguments may be held to its schema (Bedrock's
104 # ``toolSpec.strict``): the route decodes them as it decodes a reply.
105 # Only Bedrock routes say so; strict tools on the vendors' APIs require
106 # every argument, which would change what an optional one means. Used
107 # for platform-written tool schemas only (``app/tools/wire.py``).
108 strict_tools: bool = False
110 # True when text the model writes in a turn that also calls tools is
111 # part of its answer. Claude writes a long answer incrementally — a
112 # section, a render call, the next section — so its last, tool-free
113 # message holds only the tail, and the earlier text belongs before it.
114 # Other models write what they are about to do there ("Let me search…";
115 # gpt-oss its analysis), which is narration. False keeps only the last
116 # message, falling back to the tool-turn text when that is empty, so an
117 # unknown model never delivers its working to the person.
118 answer_prose_in_tool_turns: bool = False
120 # How the model's reply carries its answer on this route, so every read
121 # of it leaves the reasoning out (``reply_formats``). gpt-oss's analysis
122 # channel arrives on Bedrock as answer text, run straight into the answer
123 # ("…Now produce final answer.Here’s a quick roundup…"); Claude's thinking
124 # and OpenAI's commentary arrive typed. A client that reports no model
125 # gets ``typed``, which removes nothing but a leading think block.
126 reply_format: ReplyFormatKey = "typed"
128 # True when the model reasons before it answers and that reasoning counts
129 # against its output cap (OpenAI's reasoning families, gpt-oss, Claude
130 # with thinking, open-weight "thinking" models). A small step's cap must
131 # leave it room: a healthy gpt-oss triage writes about 1,850 tokens, where
132 # Qwen3 235B Instruct's largest was 991.
133 reasons_before_answering: bool = False
136_DEFAULT = ModelCapabilities()
138# OpenAI's open-weight reasoning models (gpt-oss-120b, gpt-oss-20b), served
139# by Bedrock rather than OpenAI's API.
140_OPEN_WEIGHT_REASONING_PREFIXES = ("gpt-oss",)
142# Models that reason before they answer take longer to send their first token.
143_DELIBERATE_TIMEOUT_S = 300.0
145# Open-weight models elsewhere (Groq, a local server) that reason before they
146# answer, by the names their families give them.
147_OPEN_WEIGHT_THINKING = re.compile(
148 r"thinking|qwq|reasoner|(?:^|[-_/.:])r1(?:$|[-_/.:])"
149)
151# Anthropic: the first number after the family name is the generation
152# ("claude-sonnet-5" → 5, "claude-haiku-4-5-20251001" → 4). The older scheme
153# puts the number first ("claude-3-5-sonnet-20240620" → 3), so the family
154# segment is optional.
155_ANTHROPIC_GENERATION = re.compile(r"^claude-(?:[a-z]+-)?(\d+)")
157# The generation at which Anthropic dropped `temperature`. Claude Opus 4.6
158# and everything before it still accept it; Opus 5, Sonnet 5, Fable and
159# Mythos do not.
160_ANTHROPIC_NO_TEMPERATURE_FROM = 5
162# Anthropic models that take `output_config.effort`. Irregular enough to be
163# worth listing: it reaches back to Opus 4.5 but skips Haiku 4.5, so it
164# cannot be derived from the generation number.
165_ANTHROPIC_EFFORT_PREFIXES = (
166 "claude-fable-",
167 "claude-mythos-",
168 "claude-haiku-5",
169 "claude-opus-5",
170 "claude-opus-4-8",
171 "claude-opus-4-7",
172 "claude-opus-4-6",
173 "claude-opus-4-5",
174 "claude-sonnet-5",
175 "claude-sonnet-4-6",
176)
178# OpenAI reasoning families. `gpt-5-chat` is deliberately excluded: it is the
179# non-reasoning chat variant and behaves like GPT-4o.
180_OPENAI_REASONING_PREFIXES = ("gpt-5", "gpt-6", "o1", "o3", "o4")
182# OpenAI models that take a strict JSON schema (Structured Outputs): GPT-4o
183# from its 2024-08-06 snapshot on, GPT-4.1, and the reasoning families.
184# `o1-mini` and `o1-preview` predate it.
185_OPENAI_STRUCTURED_PREFIXES = ("gpt-4o", "gpt-4.1", "gpt-5", "gpt-6", "o1", "o3", "o4")
186_OPENAI_STRUCTURED_EXCLUDED = ("o1-mini", "o1-preview", "gpt-4o-2024-05-13")
188# Anthropic structured outputs (``output_config.format``) start at the 4.5
189# models: Haiku 4.5, Sonnet 4.5 and Opus 4.5, then every later generation and
190# Fable / Mythos. "claude-opus-4-1" and earlier do not take it.
191_ANTHROPIC_STRUCTURED_FAMILIES = ("claude-fable-", "claude-mythos-")
192_ANTHROPIC_VERSION = re.compile(r"^claude-[a-z]+-(\d+)(?:-(\d{1,2})(?!\d))?")
195def _anthropic_generation(model: str) -> int | None:
196 match = _ANTHROPIC_GENERATION.match(model)
197 return int(match.group(1)) if match else None
200def _is_openai_reasoning_model(model: str) -> bool:
201 return model.startswith(_OPENAI_REASONING_PREFIXES) and "chat" not in model
204def _openai_native_structured(model: str) -> bool:
205 return model.startswith(_OPENAI_STRUCTURED_PREFIXES) and not model.startswith(
206 _OPENAI_STRUCTURED_EXCLUDED
207 )
210def _anthropic_native_structured(model: str) -> bool:
211 if model.startswith(_ANTHROPIC_STRUCTURED_FAMILIES):
212 return True
213 match = _ANTHROPIC_VERSION.match(model)
214 if not match:
215 return False
216 major, minor = int(match.group(1)), int(match.group(2) or 0)
217 return major > 4 or (major == 4 and minor >= 5)
220def capabilities_for(provider: str, model: str) -> ModelCapabilities:
221 """Resolve what ``model`` accepts on the route this deployment serves it
222 by (``inference_routes``).
224 An unrecognised provider or model gets the permissive default, so this
225 never turns an unknown model into a broken one. A model with no route
226 here is described as its vendor serves it; building a client for it is
227 what refuses.
228 """
229 from app.services import inference_routes
231 try:
232 route = inference_routes.resolve(provider, model)
233 except inference_routes.RouteUnavailable:
234 route = None
235 if route is None or not route.is_bedrock:
236 return _vendor_capabilities(provider, model)
237 return _bedrock_capabilities(
238 route.vendor,
239 route.model_id,
240 route.native_structured_output,
241 route.forced_tool_choice,
242 route.strict_tools,
243 route.reasons_before_answering,
244 )
247#: Bedrock model ids carry an inference-profile prefix, the vendor and a
248#: version suffix around the vendor's own name:
249#: ``eu.anthropic.claude-haiku-4-5-20251001-v1:0`` is ``claude-haiku-4-5…``.
250_BEDROCK_ID = re.compile(r"^(?:[a-z]{2,6}\.)?(?:anthropic|openai)\.(?P<name>.+)$")
252#: Vendors whose models Bedrock serves in a format of their own: typed
253#: reasoning (Anthropic), or DeepSeek's tool-call markup left in its text.
254#: Every other vendor's open-weight model is read for inline tags.
255_BEDROCK_VENDOR_FORMATS: dict[str, ReplyFormatKey] = {
256 "anthropic": "typed",
257 "deepseek": "dsml",
258}
261def _reply_format_on_bedrock(vendor: str, name: str) -> ReplyFormatKey:
262 own = _BEDROCK_VENDOR_FORMATS.get((vendor or "").lower())
263 if own:
264 return own
265 if name.startswith(_OPEN_WEIGHT_REASONING_PREFIXES):
266 return "gpt_oss"
267 return "inline_tags"
270@lru_cache(maxsize=512)
271def _bedrock_capabilities(
272 vendor: str,
273 model_id: str,
274 native_structured_output: bool | None,
275 forced_tool_choice: bool | None = None,
276 strict_tools: bool | None = None,
277 reasons_before_answering: bool | None = None,
278) -> ModelCapabilities:
279 """What a model accepts through Bedrock's Converse API.
281 The vendor's rules for temperature and effort still hold — it is the same
282 model — but the request is Bedrock's: no Responses API, one output-cap
283 name (``maxTokens``, which langchain-aws and LiteLLM both fill from
284 ``max_tokens``), and constrained decoding only where Bedrock offers it,
285 which is narrower than the vendors' (Claude 4.5 and 4.6, gpt-oss, Qwen3
286 235B; no Claude 5.x). The catalogue states that per route, and whether a
287 tool call may be forced; a model it does not know gets function calling
288 with the tool offered, not forced. Whether it reasons first is the
289 vendor's rule, a reasoning name, or what the reply probe measured on the
290 route (``BedrockRoute.reasons_before_answering``) for a model whose name
291 says nothing.
292 """
293 match = _BEDROCK_ID.match((model_id or "").lower())
294 name = match.group("name") if match else (model_id or "").lower()
295 vendor_caps = _vendor_capabilities(vendor, name)
296 return ModelCapabilities(
297 supports_temperature=vendor_caps.supports_temperature,
298 requires_responses_api=False,
299 max_tokens_param="max_tokens",
300 supports_effort=vendor_caps.supports_effort,
301 # Bedrock compiles a schema it has not seen into a grammar on first
302 # use, which "may take up to a few minutes" (then cached 24 hours):
303 # a route that decodes natively waits as long as a reasoning model.
304 request_timeout_s=(
305 max(vendor_caps.request_timeout_s, _DELIBERATE_TIMEOUT_S)
306 if native_structured_output
307 else vendor_caps.request_timeout_s
308 ),
309 native_structured_output=bool(native_structured_output),
310 forced_tool_choice=bool(forced_tool_choice),
311 strict_tools=bool(strict_tools),
312 answer_prose_in_tool_turns=vendor_caps.answer_prose_in_tool_turns,
313 reply_format=_reply_format_on_bedrock(vendor, name),
314 reasons_before_answering=vendor_caps.reasons_before_answering
315 or bool(_OPEN_WEIGHT_THINKING.search(name))
316 or bool(reasons_before_answering),
317 )
320@lru_cache(maxsize=512)
321def _vendor_capabilities(provider: str, model: str) -> ModelCapabilities:
322 """What ``model`` accepts on its vendor's own API."""
323 provider = (provider or "").lower()
324 model = (model or "").lower()
326 if provider == "anthropic":
327 generation = _anthropic_generation(model)
328 effort = model.startswith(_ANTHROPIC_EFFORT_PREFIXES)
329 return ModelCapabilities(
330 # An unparseable name keeps temperature: every Anthropic naming
331 # scheme this fails to read predates the deprecation.
332 supports_temperature=(
333 generation is None or generation < _ANTHROPIC_NO_TEMPERATURE_FROM
334 ),
335 requires_responses_api=False,
336 supports_effort=effort,
337 request_timeout_s=(
338 _DELIBERATE_TIMEOUT_S if effort else _DEFAULT.request_timeout_s
339 ),
340 native_structured_output=_anthropic_native_structured(model),
341 answer_prose_in_tool_turns=True,
342 reasons_before_answering=effort,
343 )
345 if provider in ("openai", "azure", "azure_openai"):
346 if _is_openai_reasoning_model(model):
347 return ModelCapabilities(
348 supports_temperature=False,
349 requires_responses_api=True,
350 max_tokens_param="max_completion_tokens",
351 supports_effort=True,
352 request_timeout_s=_DELIBERATE_TIMEOUT_S,
353 native_structured_output=_openai_native_structured(model),
354 reasons_before_answering=True,
355 )
356 open_weight = model.startswith(_OPEN_WEIGHT_REASONING_PREFIXES)
357 return ModelCapabilities(
358 native_structured_output=_openai_native_structured(model),
359 reply_format="gpt_oss" if open_weight else "typed",
360 reasons_before_answering=open_weight,
361 )
363 if provider:
364 # Groq, a local server, any other provider: open-weight models whose
365 # reasoning, if any, comes between tags.
366 open_weight = model.startswith(_OPEN_WEIGHT_REASONING_PREFIXES)
367 return ModelCapabilities(
368 reply_format="gpt_oss" if open_weight else "inline_tags",
369 reasons_before_answering=open_weight
370 or bool(_OPEN_WEIGHT_THINKING.search(model)),
371 )
372 return _DEFAULT
375#: LangSmith's name for a client that calls Bedrock (``ChatBedrockConverse``,
376#: ``ChatBedrock``).
377_LS_BEDROCK = "amazon_bedrock"
380def of_client(llm: Any) -> ModelCapabilities:
381 """What the model behind a built client accepts and how it replies.
383 Read from the client's own identity, LangSmith's ``ls_provider`` and
384 ``ls_model_name``, which every chat model reports and every wrapper this
385 service puts round one forwards (bound tools, ``with_config``,
386 ``with_fallbacks``: the primary's). So code that holds only a client —
387 the tool loop, a stream event — reads the same table as code that holds
388 the catalogue identity. Anything that reports no identity (a test
389 double, a custom model) gets the permissive default.
390 """
391 try:
392 params = llm._get_ls_params()
393 except Exception: # noqa: BLE001 — any client, double or custom model
394 return _DEFAULT
395 if not isinstance(params, dict):
396 return _DEFAULT
397 return of_traced(params.get("ls_provider"), params.get("ls_model_name"))
400def of_traced(provider: Any, model: Any) -> ModelCapabilities:
401 """``of_client`` from the identity a client stamped on its trace — what
402 a LangChain stream event's metadata carries as ``ls_provider`` and
403 ``ls_model_name``."""
404 if not isinstance(provider, str) or not isinstance(model, str):
405 return _DEFAULT
406 provider, model = provider.strip().lower(), model.strip()
407 if provider != _LS_BEDROCK:
408 return _vendor_capabilities(provider, model.lower())
409 from app.services import inference_routes
411 seeded = inference_routes.seeded_route_of(model)
412 return _bedrock_capabilities(
413 inference_routes.bedrock_vendor(model),
414 model,
415 bool(seeded.get("native_structured_output")) if seeded else None,
416 bool(seeded.get("forced_tool_choice")) if seeded else None,
417 bool(seeded.get("strict_tools")) if seeded else None,
418 bool(seeded.get("reasons_before_answering")) if seeded else None,
419 )
422def temperature_for(
423 provider: str, model: str, temperature: float | None
424) -> float | None:
425 """The temperature to send, or ``None`` to omit the parameter.
427 Both LangChain's ``ChatAnthropic``/``ChatOpenAI`` and LiteLLM drop a
428 ``None`` rather than forwarding a null, so callers can pass the result
429 straight through.
430 """
431 if temperature is None:
432 return None
433 return (
434 temperature if capabilities_for(provider, model).supports_temperature else None
435 )