Coverage for app / services / llm.py: 92%
258 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
1import time
3import litellm
4from langchain_core.language_models import BaseLanguageModel
5from typing import Any, AsyncIterator
7from app.models.spec import ModelConfig
8from app.services import (
9 inference_routes,
10 metering,
11 model_errors,
12 provider_usage,
13)
14from app.common.settings import get_settings
15from app.util import safe_json
16from app.util.model_output import is_strict_shaped
17from app.util.logger import get_logger
18from app.services.model_capabilities import (
19 ModelCapabilities,
20 capabilities_for,
21 temperature_for,
22)
24settings = get_settings()
25logger = get_logger(__name__)
27# Wire-level payload logging is opt-in (LITELLM_DEBUG=1), never tied to the
28# environment: in development it logged every full prompt — hundreds of KB
29# per graph node — which alone was enough to starve the event loop and flap
30# the container healthcheck under load.
31if settings.litellm_debug:
32 litellm._turn_on_debug()
34# langchain-openai drops OpenAI's cache-write count from usage metadata; the
35# meter needs it to price GPT-5.6+ cache writes (services/provider_usage.py).
36provider_usage.install_openai_cache_write_mapping()
38# Providers whose API accepts response_format={"type": "json_object"}.
39# Enabling this for other providers risks a 400 / unsupported-parameter error.
40_JSON_MODE_PROVIDERS: frozenset[str] = frozenset({"openai", "azure", "groq"})
41# Providers that decode to a strict JSON Schema sent as an OpenAI-style
42# response_format: OpenAI's Structured Outputs as sent; Anthropic's mapped by
43# LiteLLM to its structured outputs, or to a tool for a model without them.
44_SCHEMA_PROVIDERS: frozenset[str] = frozenset({"openai", "azure", "anthropic"})
47def build_format_instruction(
48 output_format: str | None, output_schema: str | None
49) -> str | None:
50 """Return a system-level instruction that enforces the requested output format.
52 Returns None for "markdown" (the default) and when output_format is unset,
53 so callers can skip inserting an instruction altogether.
54 """
55 if not output_format or output_format == "markdown":
56 return None
58 schema_clause = (
59 f" Your response must conform to this schema:\n{output_schema}"
60 if output_schema and output_schema.strip()
61 else ""
62 )
64 match output_format:
65 case "json":
66 return (
67 "Respond ONLY with valid JSON. Do not include markdown code fences, "
68 + f"commentary, or any text outside the JSON object.{schema_clause}"
69 )
70 case "yaml":
71 return (
72 "Respond ONLY with valid YAML. Do not include markdown code fences, "
73 + f"commentary, or any text outside the YAML.{schema_clause}"
74 )
75 case "csv":
76 return (
77 "Respond ONLY with valid CSV data. Include a header row. "
78 + "Do not include any explanatory text or markdown."
79 )
80 case "xml":
81 return (
82 "Respond ONLY with valid, well-formed XML. "
83 + "Do not include markdown code fences or any explanatory text."
84 )
85 case "plain":
86 return (
87 "Respond in plain text only. Do not use markdown, headers, "
88 + "bullet points, code blocks, or any special formatting."
89 )
90 case _:
91 return None
93 return None
96def _build_messages(
97 config: ModelConfig, input: str, messages: list[dict] | None
98) -> list[dict]:
99 """Construct the full message list for a model call.
101 System messages are always grouped at the front regardless of their position
102 in the supplied history. Within that group the order is:
104 1. Format instruction (derived from config.output_format / output_schema)
105 2. config.system_prompt (explicit system text set by the caller)
106 3. System messages that were already in the history (file context, etc.)
107 4. Conversation messages (user / assistant / tool) in their original order
108 5. The current user turn
110 This ensures format constraints are never "buried" after user/assistant turns,
111 which would make most providers ignore them.
113 Each distinct system message is sent once. A chat that sets a system
114 prompt sends it with every turn, and conversations stored before svc-core
115 kept only a changed one hold a copy per turn: turn N had sent it N times.
116 """
117 format_instruction = build_format_instruction(
118 config.output_format, config.output_schema
119 )
121 # Partition incoming messages into system vs conversation
122 system_msgs: list[dict] = []
123 conv_msgs: list[dict] = []
124 for msg in messages or []:
125 if msg.get("role") == "system":
126 system_msgs.append(msg)
127 else:
128 conv_msgs.append(msg)
130 result: list[dict] = []
131 sent: set[str] = set()
133 def _system(content: Any) -> None:
134 key = content if isinstance(content, str) else safe_json.dumps(content)
135 if key in sent:
136 return
137 sent.add(key)
138 result.append({"role": "system", "content": content})
140 if format_instruction:
141 _system(format_instruction)
143 if config.system_prompt:
144 _system(config.system_prompt)
146 for msg in system_msgs:
147 _system(msg.get("content", ""))
148 fitted, note = _fitted_history(config, conv_msgs, result, input)
149 result.extend(fitted)
150 result.append({"role": "user", "content": f"{note}\n\n{input}" if note else input})
152 return result
155def _fitted_history(
156 config: ModelConfig, conversation: list[dict], system: list[dict], input: str
157) -> tuple[list[dict], str]:
158 """The conversation fitted to the model (``token_budget``): inside its
159 window and below its long-context price tier, oldest turns first to go.
160 A conversation holding anything but questions and answers goes as it
161 came."""
162 from langchain_core.messages import AIMessage, HumanMessage
164 from app.services import token_budget
166 kinds = {"user": HumanMessage, "assistant": AIMessage}
167 if not conversation or any(m.get("role") not in kinds for m in conversation):
168 return conversation, ""
169 try:
170 history = [
171 kinds[m["role"]](content=m.get("content") or "") for m in conversation
172 ]
173 system_text = "\n\n".join(
174 token_budget.text_of(m.get("content")) for m in system
175 )
176 budget = token_budget.history_budget(
177 token_budget.limits_for_model(config.provider, config.model),
178 max_output=config.max_tokens,
179 fixed_tokens=token_budget.estimate_tokens(system_text)
180 + token_budget.estimate_tokens(input),
181 reserve=0,
182 )
183 fitted = token_budget.fit(history, budget)
184 except Exception: # noqa: BLE001 — a bound is worth less than the call
185 logger.warning("[llm] could not fit the conversation", exc_info=True)
186 return conversation, ""
187 if fitted.messages == history:
188 return conversation, ""
189 roles = {HumanMessage: "user", AIMessage: "assistant"}
190 return (
191 [{"role": roles[type(m)], "content": m.content} for m in fitted.messages],
192 token_budget.omitted_note(fitted),
193 )
196def _litellm_target(route: inference_routes.Route) -> dict:
197 """LiteLLM's model string for a route, and where to send it: the vendor's
198 ``provider/model``, or Bedrock's Converse API in ``BEDROCK_REGION``."""
199 if route.is_bedrock:
200 return {
201 "model": f"bedrock/converse/{route.model_id}",
202 "aws_region_name": inference_routes.region(),
203 }
204 return {"model": f"{route.provider}/{route.model_id}"}
207def _response_format(config: ModelConfig, route: inference_routes.Route) -> dict | None:
208 """The ``response_format`` a JSON reply asks a vendor's API for, or None.
210 A strict-shaped JSON Schema in ``output_schema`` is sent as one, for
211 the vendor to decode to: OpenAI's Structured Outputs, Anthropic's
212 structured outputs (LiteLLM maps it). Otherwise JSON mode
213 (``json_object``) where the API has one. Never on Bedrock: LiteLLM
214 would choose native decoding or a tool by its own model map, and the
215 route's ``outputConfig`` is sent instead (``_native_output_config``),
216 with the format instruction alone where it decodes to none."""
217 if config.output_format != "json" or route.is_bedrock:
218 return None
219 if config.provider in _SCHEMA_PROVIDERS and config.output_schema:
220 try:
221 # Configuration, read whole: a schema that does not parse is a
222 # description of a shape, which the instruction states instead.
223 schema = safe_json.loads_exact(config.output_schema)
224 except (TypeError, ValueError):
225 schema = None
226 if (
227 isinstance(schema, dict)
228 and schema.get("type") == "object"
229 and is_strict_shaped(schema)
230 ):
231 return {
232 "type": "json_schema",
233 "json_schema": {"name": "output", "schema": schema, "strict": True},
234 }
235 if config.provider in _JSON_MODE_PROVIDERS:
236 return {"type": "json_object"}
237 return None
240def _native_output_config(
241 config: ModelConfig, route: inference_routes.Route
242) -> dict | None:
243 """Bedrock's ``outputConfig`` for a JSON reply to a JSON Schema, on a
244 route that decodes to one natively (``bedrock_schema``), or None. Sent as
245 Converse's own field, which LiteLLM passes through unchanged — so the
246 schema is enforced whatever LiteLLM's model map says."""
247 if not (route.is_bedrock and route.native_structured_output):
248 return None
249 if config.output_format != "json":
250 return None
251 from app.services import bedrock_schema
253 return bedrock_schema.output_config(config.output_schema)
256def _schema_refused(kwargs: dict, exc: Exception, provider: str = "") -> bool:
257 """A provider refused the schema it was sent (a 400): drop it, so the
258 call is made again as it was before the schema was sent — never worse.
259 Bedrock's ``outputConfig`` goes; a vendor's strict ``json_schema``
260 becomes JSON mode where the API has one, else goes. Once each: the
261 second request carries no schema to refuse."""
262 from app.services import model_errors
264 if model_errors.status_of(exc) != 400:
265 return False
266 sent = kwargs.get("response_format")
267 if "outputConfig" in kwargs:
268 kwargs.pop("outputConfig")
269 what = "Bedrock's output schema"
270 elif isinstance(sent, dict) and sent.get("type") == "json_schema":
271 if provider in _JSON_MODE_PROVIDERS:
272 kwargs["response_format"] = {"type": "json_object"}
273 else:
274 kwargs.pop("response_format")
275 what = "the response schema"
276 else:
277 return False
278 logger.warning(
279 "[llm] %s was refused (%s) — retrying without it",
280 what,
281 model_errors.describe(exc),
282 )
283 return True
286async def _acompletion(config: ModelConfig, kwargs: dict):
287 """One LiteLLM request: refused before it is sent at the spending
288 ceiling or the turn's limit, metered when it fails, and made once more
289 without the native schema if Bedrock refuses that. A refusal comes before any token, so a
290 stream's retry repeats nothing the caller has seen. Returns the response
291 and when the attempt that produced it started."""
292 while True:
293 metering.check_limits()
294 started = time.monotonic()
295 try:
296 return await litellm.acompletion(**kwargs), started
297 except Exception as exc:
298 _meter_failure(config, started, exc)
299 if not _schema_refused(kwargs, exc, config.provider):
300 raise
303def _apply_sampling(kwargs: dict, config: ModelConfig) -> None:
304 """Add the steering parameters this model actually accepts.
306 ``temperature`` is omitted for models that reject it (Anthropic past
307 Opus 4.6, OpenAI's reasoning families) rather than sent and 400'd, the
308 output cap goes under whichever name the model's API uses, and
309 ``effort`` is forwarded where the model takes one. Mutates ``kwargs`` in
310 place because both LiteLLM call sites build the dict the same way and
311 the alternative is two near-identical merges.
313 LiteLLM names the reasoning control ``reasoning_effort`` for every
314 provider and translates it to Anthropic's ``output_config.effort``, so
315 one key serves both here — unlike the LangChain path below, where the
316 two clients take different parameter names.
317 """
318 caps = capabilities_for(config.provider, config.model)
320 temperature = temperature_for(config.provider, config.model, config.temperature)
321 if temperature is not None:
322 kwargs["temperature"] = temperature
324 # Named per model: OpenAI's reasoning models reject "max_tokens".
325 kwargs[caps.max_tokens_param] = config.max_tokens
327 if config.effort and caps.supports_effort:
328 kwargs["reasoning_effort"] = config.effort
331#: Retries per model call, made by the provider client itself on transient
332#: failures only: connection errors, 408, 409, 429 and 5xx. None of them
333#: retries a 400, which the same request would get again.
334MODEL_CALL_RETRIES = 2
337#: LiteLLM's own retry (``num_retries``) asks again after *any* API error,
338#: a 400 included, unless told otherwise per exception. A refused request
339#: (a 400, a context window or content policy refusal among them) or a
340#: rejected key gets the same answer every time, so neither is asked again;
341#: timeouts, rate limits, 5xx and connection errors keep their retries.
342_RETRY_POLICY = {
343 "BadRequestErrorRetries": 0,
344 "ContentPolicyViolationErrorRetries": 0,
345 "AuthenticationErrorRetries": 0,
346}
349def _apply_bounds(kwargs: dict, config: ModelConfig) -> None:
350 """Bound a LiteLLM call: a timeout per model family, transient retries."""
351 kwargs["timeout"] = capabilities_for(
352 config.provider, config.model
353 ).request_timeout_s
354 kwargs["num_retries"] = MODEL_CALL_RETRIES
355 kwargs["retry_policy"] = dict(_RETRY_POLICY)
358async def run_model(
359 config: ModelConfig,
360 input: str,
361 messages: list[dict] | None = None,
362) -> tuple[str, dict]:
363 msgs = _build_messages(config, input, messages)
365 route = inference_routes.resolve(config.provider, config.model)
366 kwargs: dict = {"messages": msgs, **_litellm_target(route)}
367 _apply_sampling(kwargs, config)
368 _apply_bounds(kwargs, config)
370 # Decoding to the schema (or to JSON) where the provider can — more
371 # reliable than the instruction alone, which is all a model is told
372 # where it cannot.
373 response_format = _response_format(config, route)
374 if response_format:
375 kwargs["response_format"] = response_format
376 output_config = _native_output_config(config, route)
377 if output_config:
378 kwargs["outputConfig"] = output_config
380 response, started = await _acompletion(config, kwargs)
382 output = response.choices[0].message.content
383 reported = provider_usage.from_litellm(response.usage)
384 metering.record(
385 config.provider,
386 config.model,
387 usage=reported,
388 latency_ms=metering.elapsed_ms(started),
389 step=_answer_step(),
390 )
391 # Cost is the meter's (merged into the response by the caller), priced
392 # on every token class — not an estimate from two totals here.
393 return output, _engine_usage(reported) if reported.reported else {}
396async def stream_model(
397 config: ModelConfig,
398 input: str,
399 messages: list[dict] | None = None,
400) -> AsyncIterator[tuple[str, dict | None]]:
401 """
402 Stream a model response token by token.
404 Yields (token, None) for each content chunk, then yields ("", usage_dict)
405 as a final sentinel once the stream is exhausted.
406 """
407 msgs = _build_messages(config, input, messages)
409 route = inference_routes.resolve(config.provider, config.model)
410 kwargs: dict = {
411 "messages": msgs,
412 "stream": True,
413 "stream_options": {"include_usage": True},
414 **_litellm_target(route),
415 }
416 _apply_sampling(kwargs, config)
417 _apply_bounds(kwargs, config)
419 response_format = _response_format(config, route)
420 if response_format:
421 kwargs["response_format"] = response_format
422 output_config = _native_output_config(config, route)
423 if output_config:
424 kwargs["outputConfig"] = output_config
426 response, started = await _acompletion(config, kwargs)
427 usage_obj = None
428 try:
429 async for chunk in response:
430 # The usage arrives on the final chunk for most providers; keep
431 # the object whole — its details carry the cache classes.
432 if getattr(chunk, "usage", None):
433 usage_obj = chunk.usage
434 if chunk.choices and chunk.choices[0].delta.content:
435 yield chunk.choices[0].delta.content, None
436 except Exception as exc:
437 _meter_failure(config, started, exc)
438 raise
440 # Recorded whether or not the provider reported usage: the call was made,
441 # and a trace that drops it has lost which model answered. Without usage
442 # it is unpriced, not free.
443 reported = provider_usage.from_litellm(usage_obj)
444 metering.record(
445 config.provider,
446 config.model,
447 usage=reported,
448 latency_ms=metering.elapsed_ms(started),
449 step=_answer_step(),
450 )
451 # Final sentinel carries usage
452 yield "", _engine_usage(reported) if reported.reported else {}
455def _engine_usage(usage: provider_usage.TokenUsage) -> dict:
456 """The token counts an engine reports for one LiteLLM call."""
457 return {
458 "prompt_tokens": usage.input_tokens,
459 "completion_tokens": usage.output_tokens,
460 "total_tokens": usage.input_tokens + usage.output_tokens,
461 }
464def _meter_failure(config: ModelConfig, started: float, exc: Exception) -> None:
465 """Put a refused LiteLLM call on the meter, against the model it went to."""
466 metering.record(
467 config.provider,
468 config.model,
469 latency_ms=metering.elapsed_ms(started),
470 status=metering.CALL_ERROR,
471 error=f"{type(exc).__name__}: {exc}",
472 step=_answer_step(),
473 )
476def _answer_step() -> str:
477 """What a direct model call is for: whatever its caller labelled it, or
478 else the answer — a model chat, a model target in an evaluation."""
479 return metering.current_step() or metering.Step.respond
482def _apply_openai_reasoning(
483 kwargs: dict, config: ModelConfig, caps: ModelCapabilities
484) -> None:
485 """Point a reasoning model at the Responses API and set its effort.
487 OpenAI's reasoning families refuse function tools on Chat Completions
488 unless reasoning is disabled outright, so an agent with tools gets a 400
489 on every turn. The Responses API accepts both, which keeps the reasoning
490 these models are chosen for — the alternative the error message offers,
491 ``reasoning_effort='none'``, buys compatibility by turning the model into
492 a worse one.
494 Applied to every call rather than only tool-bound ones: ``bind_tools()``
495 happens downstream of this function, and a model that switches endpoint
496 depending on whether tools were attached would return two different
497 response shapes for the same agent.
498 """
499 if caps.requires_responses_api:
500 kwargs["use_responses_api"] = True
501 if config.effort and caps.supports_effort:
502 kwargs["reasoning_effort"] = config.effort
505def _bedrock_chat_model(
506 config: ModelConfig, route: inference_routes.Route, caps: ModelCapabilities
507) -> BaseLanguageModel:
508 """A ``ChatBedrockConverse`` for ``route``.
510 Credentials come from botocore's default chain — on a deployed host, the
511 short-lived role credentials the host refreshes for svc-ai — never from a
512 key in this service's settings. The client retries transient failures
513 only and times out per model family, as the vendor clients do.
515 Effort goes through langchain-aws, which translates it per model family
516 and refuses a level a model's profile does not list. It is set only when
517 the profile lists it, so an unknown level degrades to the model's default
518 rather than failing the call.
519 """
520 from langchain_aws import ChatBedrockConverse
522 params: dict = {
523 "model": route.model_id,
524 "region_name": inference_routes.region(),
525 "config": inference_routes.bedrock_client_config(caps.request_timeout_s),
526 "max_tokens": config.max_tokens,
527 }
528 temperature = temperature_for(config.provider, config.model, config.temperature)
529 if temperature is not None:
530 params["temperature"] = temperature
531 llm = ChatBedrockConverse(**params)
532 if config.effort and caps.supports_effort:
533 levels = (getattr(llm, "profile", None) or {}).get("reasoning_effort_levels")
534 if config.effort in (levels or ()):
535 llm = ChatBedrockConverse(**params, reasoning_effort=config.effort)
536 return llm
539class NoDefaultModel(model_errors.ModelUnavailableError):
540 """The catalogue has no model this deployment can run by default."""
542 def __init__(self) -> None:
543 super().__init__(model_errors.FatalKind.MODEL_NOT_FOUND, None, "")
544 self.args = ("the catalogue has no available default chat model",)
546 @property
547 def user_message(self) -> str:
548 return (
549 "No model is available on this deployment to answer with. An "
550 "administrator needs to make a model available."
551 )
554def deployment_default_model(db: Any = None) -> ModelConfig:
555 """The model that answers when nothing chose one: the catalogue's default
556 chat model, which the seeder keeps runnable on this backend
557 (``providers/seeder.py`` ``_keep_default_usable``).
559 A skill node with no model of its own runs on the agent's model; this is
560 for work with no agent (a standalone skill run) and for a worker built
561 with no model at all. Nothing names a vendor model in code: one that the
562 backend cannot serve (GPT-4o on Bedrock) would refuse every such run.
563 """
564 from app.db.postgres.engine import SessionLocal
565 from app.db.postgres.models import LLMModel
567 own = db is None
568 session = SessionLocal() if own else db
569 try:
570 row = (
571 session.query(LLMModel)
572 .filter(
573 LLMModel.is_default.is_(True),
574 LLMModel.is_available.is_(True),
575 LLMModel.is_chat.is_(True),
576 LLMModel.archived_at.is_(None),
577 )
578 .first()
579 )
580 if row is None or row.provider is None:
581 raise NoDefaultModel()
582 return ModelConfig(provider=row.provider.name, model=row.model_name)
583 finally:
584 if own:
585 session.close()
588def build_langchain_llm(
589 config: ModelConfig,
590 *,
591 fallbacks: list[BaseLanguageModel] | None = None,
592) -> BaseLanguageModel:
593 """Build a LangChain ``BaseLanguageModel`` from a ``ModelConfig``.
595 Returns the base chat model directly so callers can chain methods like
596 ``bind_tools()``, ``with_structured_output()``, and ``with_retry()`` on
597 the concrete model object before invoking it. Applying ``with_retry()``
598 here would wrap the model in a ``RunnableRetry`` whose interface differs
599 from ``BaseChatModel``, breaking downstream calls to those methods.
601 Every client gets an explicit timeout for its model family and
602 ``MODEL_CALL_RETRIES``, which the provider SDK spends on transient
603 failures only. Nothing wraps it in ``with_retry()`` as well: that retried
604 every exception, a 400 included, three times over the SDK's own retries.
606 Supported providers:
607 ``anthropic`` — ``langchain-anthropic``
608 ``groq`` — ``langchain-groq``
609 ``azure`` / ``azure_openai`` — ``langchain-openai`` (AzureChatOpenAI)
610 anything else — ``langchain-openai`` (ChatOpenAI, also covers ollama)
612 Per-model request shape is resolved by ``app.services.model_capabilities``
613 rather than branched on here: ``temperature`` is dropped for models that
614 reject it, and OpenAI's reasoning families are pointed at the Responses
615 API, without which every tool-bound call they receive is refused.
616 """
617 # Refuses a catalogue model with no route on this deployment's backend.
618 route = inference_routes.resolve(config.provider, config.model)
619 caps = capabilities_for(config.provider, config.model)
621 if route.is_bedrock:
622 llm = _bedrock_chat_model(config, route, caps)
623 metering.attach(llm, config.provider, config.model)
624 return llm.with_fallbacks(fallbacks) if fallbacks else llm
626 # None rather than a value: both clients strip a None from the payload,
627 # so this omits the parameter instead of sending a null.
628 kwargs: dict = {
629 "temperature": temperature_for(
630 config.provider, config.model, config.temperature
631 ),
632 "max_tokens": config.max_tokens,
633 "max_retries": MODEL_CALL_RETRIES,
634 }
635 timeout = caps.request_timeout_s
637 llm: BaseLanguageModel
638 match config.provider:
639 case "anthropic":
640 from langchain_anthropic import ChatAnthropic
642 if config.effort and caps.supports_effort:
643 # ChatAnthropic's shorthand for output_config.effort — the
644 # control that replaced temperature on these models.
645 kwargs["effort"] = config.effort
646 llm = ChatAnthropic(
647 model=config.model, default_request_timeout=timeout, **kwargs
648 )
649 case "groq":
650 from langchain_groq import ChatGroq
652 llm = ChatGroq(model=config.model, request_timeout=timeout, **kwargs)
653 case "azure" | "azure_openai":
654 from langchain_openai import AzureChatOpenAI
656 _apply_openai_reasoning(kwargs, config, caps)
657 # Streamed calls report usage only when asked; without it a
658 # streamed call is unpriced. langchain-openai turns this on by
659 # default only for the stock endpoint, not Azure or a proxy.
660 llm = AzureChatOpenAI(
661 azure_deployment=config.model,
662 stream_usage=True,
663 request_timeout=timeout,
664 **kwargs,
665 )
666 case _:
667 from langchain_openai import ChatOpenAI
669 _apply_openai_reasoning(kwargs, config, caps)
670 llm = ChatOpenAI(
671 model=config.model,
672 stream_usage=True,
673 request_timeout=timeout,
674 **kwargs,
675 )
677 # Every call this model makes lands on the request's usage meter, priced
678 # as this model — tool loops, structured output and retries included.
679 metering.attach(llm, config.provider, config.model)
681 if fallbacks:
682 llm = llm.with_fallbacks(fallbacks)
684 return llm