Coverage for app / services / model_errors.py: 99%
130 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"""Which model-call failures end a turn, and what a person is told about them.
3Most failures of a single model call are local to the step that made it: a
4system node that cannot classify, plan or evaluate degrades to a safe
5default, and the run continues. Some cannot be degraded around, because the
6next call — to the same provider, with the same credentials — fails the same
7way: the key is wrong (401), the account may not use the model (403), the
8model does not exist (404), or the account has no quota left. Before, each
9node swallowed these in turn: with a bad key, gate, recon and planning each
10failed, wrote the provider's response body into the run, and carried on to
11the answering node, which failed too.
13``raise_if_fatal(exc)`` turns those into one ``ModelUnavailableError``, which
14every graph node re-raises instead of degrading, and which the engines report
15once, with ``user_message`` — never the provider's response body.
17Deliberately not fatal: a 400. One node's request can be refused (a schema a
18strict mode rejects, an over-long prompt) while the next node's is accepted,
19so a 400 degrades the step that caused it. Transient failures (connection,
20408, 409, 429 rate limits, 5xx) are retried by the provider client
21(``llm.MODEL_CALL_RETRIES``) before they reach here.
22"""
24from __future__ import annotations
26from enum import StrEnum
29class FatalKind(StrEnum):
30 AUTH = "auth"
31 PERMISSION = "permission"
32 MODEL_NOT_FOUND = "model_not_found"
33 QUOTA = "quota"
34 #: The deployment's own spending ceiling, not the provider's
35 #: (``spend_guard``): raised before the call, so nothing was spent.
36 BUDGET = "budget_reached"
37 #: The turn has spent what svc-core said was left of a budget governing
38 #: it (``X-Spend-Limit``, ``metering.check_limits``): raised before the
39 #: next call, so the turn keeps what it already spent and stops there.
40 TURN_LIMIT = "spend_limit"
43#: What a person is told, per kind. No provider text: a response body can
44#: carry a masked key, an account id or an organisation name.
45_USER_MESSAGES: dict[FatalKind, str] = {
46 FatalKind.AUTH: (
47 "The AI provider rejected this service's credentials. An administrator "
48 "needs to check the provider API key."
49 ),
50 FatalKind.PERMISSION: (
51 "The AI provider account is not permitted to use this model. An "
52 "administrator needs to check the account's model access."
53 ),
54 FatalKind.MODEL_NOT_FOUND: (
55 "The AI provider does not recognise the configured model. It may have "
56 "been retired or misspelt; choose another model for this agent."
57 ),
58 FatalKind.QUOTA: (
59 "The AI provider account has run out of quota. An administrator needs "
60 "to check the account's billing or limits."
61 ),
62 FatalKind.BUDGET: (
63 "This deployment has reached its AI spending limit. An administrator "
64 "can raise it."
65 ),
66 FatalKind.TURN_LIMIT: (
67 "This answer was stopped: it reached what was left of a budget that governs it."
68 ),
69}
71#: Shown for any failure that is not classified above.
72GENERIC_MESSAGE = "The model call failed. Please try again."
75class ModelUnavailableError(Exception):
76 """A model call failed in a way no later step can work around."""
78 def __init__(self, kind: FatalKind, status: int | None, provider: str) -> None:
79 super().__init__(f"{provider or 'provider'} {kind.value} (HTTP {status})")
80 self.kind = kind
81 self.status = status
82 self.provider = provider
84 @property
85 def user_message(self) -> str:
86 return _USER_MESSAGES[self.kind]
88 def payload(self) -> dict[str, object]:
89 """The error frame / response body for this failure."""
90 return {"message": self.user_message, "code": self.kind.value}
93#: Amazon Bedrock's error codes that no later call with the same credentials
94#: and model could get past (botocore ``ClientError``). Throttling and 5xx are
95#: absent on purpose: botocore retries them, and they pass. A
96#: ``ValidationException`` is a 400 — one request refused — unless it says
97#: the model id itself is unknown.
98_BEDROCK_FATAL: dict[str, FatalKind] = {
99 "AccessDeniedException": FatalKind.PERMISSION,
100 "UnrecognizedClientException": FatalKind.AUTH,
101 "InvalidSignatureException": FatalKind.AUTH,
102 "ExpiredTokenException": FatalKind.AUTH,
103 "MissingAuthenticationTokenException": FatalKind.AUTH,
104 "ResourceNotFoundException": FatalKind.MODEL_NOT_FOUND,
105 "ServiceQuotaExceededException": FatalKind.QUOTA,
106}
108#: How Bedrock words a ``ValidationException`` for a model id it does not
109#: know, as opposed to a parameter it does not accept.
110_BEDROCK_UNKNOWN_MODEL = ("model identifier is invalid", "model id is invalid")
113def _bedrock_error(exc: BaseException) -> tuple[int | None, str, str] | None:
114 """``(status, code, message)`` when ``exc`` is a Bedrock ``ClientError``."""
115 from botocore.exceptions import ClientError
117 if not isinstance(exc, ClientError):
118 return None
119 response = getattr(exc, "response", None) or {}
120 error = response.get("Error") or {}
121 status = (response.get("ResponseMetadata") or {}).get("HTTPStatusCode")
122 return (
123 status if isinstance(status, int) else None,
124 str(error.get("Code") or ""),
125 str(error.get("Message") or ""),
126 )
129def _no_aws_credentials(exc: BaseException) -> bool:
130 """botocore could not obtain credentials at all — no request was made."""
131 from botocore.exceptions import NoCredentialsError, PartialCredentialsError
133 try:
134 from botocore.exceptions import CredentialRetrievalError
135 except ImportError: # pragma: no cover — older botocore
136 CredentialRetrievalError = NoCredentialsError # type: ignore[misc]
137 return isinstance(
138 exc, (NoCredentialsError, PartialCredentialsError, CredentialRetrievalError)
139 )
142def status_of(exc: BaseException) -> int | None:
143 """The HTTP status a provider answered ``exc`` with, whatever the SDK."""
144 status = getattr(exc, "status_code", None)
145 if isinstance(status, int):
146 return status
147 bedrock = _bedrock_error(exc)
148 return bedrock[0] if bedrock else None
151#: What a provider's 400 names when it refused the shape a reply was asked
152#: to take rather than the request's content: Bedrock's ``outputConfig`` /
153#: ``textFormat`` or a tool's ``inputSchema``, OpenAI's ``response_format``,
154#: Anthropic's ``output_config`` / ``output_format`` — and nearly always the
155#: word "schema". A prompt too long for the window names none of them.
156_SCHEMA_REFUSAL_MARKERS = (
157 "schema",
158 "outputconfig",
159 "textformat",
160 "output_config",
161 "output_format",
162 "response_format",
163 "structured output",
164)
166#: What a 400 names when the model would not be forced to call a tool —
167#: Anthropic's "Thinking may not be enabled when tool_choice forces tool
168#: use", as the vendor and Bedrock word it.
169_TOOL_CHOICE_REFUSAL_MARKERS = ("tool_choice", "toolchoice")
172def _refusal_text(exc: BaseException) -> str:
173 """The provider's own words for ``exc``, lower-cased, to classify it by.
174 Read, never logged or shown: Bedrock's can name the account and role."""
175 bedrock = _bedrock_error(exc)
176 if bedrock is not None:
177 return bedrock[2].lower()
178 return str(exc).lower()
181def refused_schema(exc: BaseException) -> bool:
182 """Whether ``exc`` is a provider refusing the schema a reply was asked to
183 decode to (or a strict tool's input schema) — a refusal it will repeat
184 for that schema, so the caller may remember it
185 (``provider_refusals``). Any other 400 is about one request."""
186 return status_of(exc) == 400 and any(
187 marker in _refusal_text(exc) for marker in _SCHEMA_REFUSAL_MARKERS
188 )
191def refused_tool_choice(exc: BaseException) -> bool:
192 """Whether ``exc`` is a provider refusing to force a tool call — which a
193 thinking model does on every such request."""
194 return status_of(exc) == 400 and any(
195 marker in _refusal_text(exc) for marker in _TOOL_CHOICE_REFUSAL_MARKERS
196 )
199def _provider_status_error(exc: BaseException) -> tuple[int, str] | None:
200 """``(status, provider)`` when ``exc`` is a provider SDK's HTTP error.
202 Only the provider SDKs' own status errors count (LiteLLM's subclass
203 OpenAI's): a 404 from anything else — a webhook, a fetched page — says
204 nothing about the model.
205 """
206 import anthropic
207 import openai
209 if isinstance(exc, openai.APIStatusError):
210 return exc.status_code, "openai"
211 if isinstance(exc, anthropic.APIStatusError):
212 return exc.status_code, "anthropic"
213 bedrock = _bedrock_error(exc)
214 if bedrock is not None and bedrock[0] is not None:
215 return bedrock[0], "bedrock"
216 return None
219def _classify_bedrock(exc: BaseException) -> FatalKind | None:
220 if _no_aws_credentials(exc):
221 return FatalKind.AUTH
222 bedrock = _bedrock_error(exc)
223 if bedrock is None:
224 return None
225 _, code, message = bedrock
226 if code == "ValidationException":
227 lowered = message.lower()
228 return (
229 FatalKind.MODEL_NOT_FOUND
230 if any(phrase in lowered for phrase in _BEDROCK_UNKNOWN_MODEL)
231 else None
232 )
233 return _BEDROCK_FATAL.get(code)
236def classify(exc: BaseException) -> FatalKind | None:
237 """The fatal kind of ``exc``, or None when a step may degrade around it."""
238 if isinstance(exc, ModelUnavailableError):
239 return exc.kind
240 bedrock_kind = _classify_bedrock(exc)
241 if bedrock_kind is not None or _bedrock_error(exc) is not None:
242 return bedrock_kind
243 found = _provider_status_error(exc)
244 if found is None:
245 return None
246 status, _ = found
247 if status == 401:
248 return FatalKind.AUTH
249 if status == 403:
250 return FatalKind.PERMISSION
251 if status == 404:
252 return FatalKind.MODEL_NOT_FOUND
253 if status == 429 and getattr(exc, "code", None) == "insufficient_quota":
254 return FatalKind.QUOTA
255 return None
258def raise_if_fatal(exc: BaseException) -> None:
259 """Re-raise ``exc`` as ``ModelUnavailableError`` when no step can work
260 around it. Call first in every ``except`` that would otherwise degrade."""
261 if isinstance(exc, ModelUnavailableError):
262 raise exc
263 kind = classify(exc)
264 if kind is None:
265 return
266 found = _provider_status_error(exc)
267 status, provider = (
268 found if found else (None, "bedrock" if _no_aws_credentials(exc) else "")
269 )
270 raise ModelUnavailableError(kind, status, provider) from exc
273def user_message(exc: BaseException) -> str:
274 """What a person may be told about ``exc``: a classified message, or the
275 generic one. Never the exception's own text."""
276 if isinstance(exc, ModelUnavailableError):
277 return exc.user_message
278 kind = classify(exc)
279 return _USER_MESSAGES[kind] if kind is not None else GENERIC_MESSAGE
282class StepFailed(Exception):
283 """A step's own failure, already described in one line (``describe``
284 returns it as it stands)."""
287def describe(exc: BaseException) -> str:
288 """One line describing a failure, for a trace or a log line.
290 Never the exception's full text: a pydantic error dumps the model's whole
291 input, and a provider error carries its response body. Neither belongs in
292 a trace a person reads, and neither may reach a model.
293 """
294 from pydantic import ValidationError
296 if isinstance(exc, StepFailed):
297 return str(exc)
298 if isinstance(exc, ValidationError):
299 fields = sorted(
300 {
301 f"{'.'.join(str(p) for p in err.get('loc', ())) or '(root)'} "
302 f"({err.get('type', 'invalid')})"
303 for err in exc.errors()
304 }
305 )
306 return f"{exc.title} did not validate: {', '.join(fields)}"[:300]
307 if isinstance(exc, ModelUnavailableError):
308 return f"{type(exc).__name__}: {exc.kind.value}"
309 bedrock = _bedrock_error(exc)
310 if bedrock is not None:
311 # The code, never the message: it can name the account and role.
312 # Traces are read in the product, so the service is not named.
313 status, code, _ = bedrock
314 return f"Model service {code or 'error'} (HTTP {status})"
315 status = getattr(exc, "status_code", None)
316 if isinstance(status, int):
317 return f"{type(exc).__name__} (HTTP {status})"
318 first_line = (str(exc).strip().splitlines() or [""])[0]
319 if not first_line:
320 return type(exc).__name__
321 return f"{type(exc).__name__}: {first_line}"[:300]