Files
DeepTutor/deeptutor/services/llm/request_compat.py
OrdoAbChao7 d7240fd377 fix(llm,web): address PR #2938 review findings
- Check value-constraint markers before parameter-unknown markers in
  classify_reasoning_param_error so mixed phrasings like
  'Unsupported parameter: ... Supported values are ...' retry once
  without disabling reasoning params for the whole endpoint.
- Align MiniMax-M3 Thinking toggle (none/high) across backend
  resolve_reasoning_control and frontend validation so turning
  Thinking on survives effectiveReasoningEffort/dropUnvalidatedReasoningEffort.
- Filter non-chat model IDs (e.g. text-embedding-3-small) when /models
  probe entries omit services metadata.
- Cancel and discard stale in-flight Quick Setup probe/apply responses
  when switching vendors/regions or closing the form so old responses
  cannot save the prior vendor or clear the newly entered API key.
- Sync THINKING_OFF_EFFORTS symbol rename from upstream/dev.
2026-12-02 10:29:30 +08:00

476 lines
16 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Provider-error classifiers used by retry and graceful-degradation paths."""
from __future__ import annotations
import re
from typing import Any, Literal
import httpx
from .exceptions import LLMProviderTransportError, LLMTimeoutError
def _exception_chain(exc: Exception):
"""Yield an exception and its wrapped causes without looping forever."""
pending = [exc]
seen: set[int] = set()
while pending:
current = pending.pop()
if id(current) in seen:
continue
seen.add(id(current))
yield current
nested = getattr(current, "exceptions", ())
if isinstance(nested, tuple):
pending.extend(item for item in nested if isinstance(item, Exception))
cause = current.__cause__ or current.__context__
if isinstance(cause, Exception):
pending.append(cause)
_MAX_LOGGED_ERROR_CHARS = 2000
def logged_error_text(exc: Exception) -> str:
"""``error_text`` bounded for a log line.
The compat predicates only scan this text, but a log line is different:
``data/user/logs/deeptutor.jsonl`` is what a user is asked to attach to a
bug report, and some providers echo the rejected request back — the tool
schemas, occasionally the messages themselves. The parameter a provider
objects to is always near the front, so cap it rather than ship an
unbounded copy of the request into a file destined for a public issue.
"""
text = error_text(exc)
if len(text) <= _MAX_LOGGED_ERROR_CHARS:
return text
dropped = len(text) - _MAX_LOGGED_ERROR_CHARS
return f"{text[:_MAX_LOGGED_ERROR_CHARS]}… (+{dropped} chars)"
def error_text(exc: Exception) -> str:
"""Return the best available lowercase provider error body."""
response = getattr(exc, "response", None)
body = (
getattr(exc, "body", None)
or getattr(exc, "doc", None)
or getattr(response, "text", None)
or getattr(exc, "message", None)
or str(exc)
)
return str(body).lower()
def is_stream_options_unsupported(exc: Exception) -> bool:
"""Whether a provider rejected OpenAI's ``stream_options`` parameter."""
text = error_text(exc)
return any(
marker in text
for marker in (
"stream_options",
"stream options",
"unknown parameter",
"unrecognized request argument",
"unsupported parameter",
"extra inputs are not permitted",
"unexpected keyword",
)
)
def is_response_format_unsupported(exc: Exception) -> bool:
"""Whether a provider rejected OpenAI's ``response_format`` parameter.
Seen from LM Studio + Gemma (``'response_format.type' must be 'json_schema'
or 'text'``) and DashScope (``'json_object' is not supported by this
model``). One predicate for every execution path, so the graceful
drop-and-retry behaves the same wherever the request was made.
"""
text = error_text(exc)
# Value-specific markers name a response_format value directly, so they
# stand on their own — DashScope's rejection ("'json_object' is not
# supported by this model") never mentions ``response_format`` itself.
if any(
marker in text
for marker in (
"json_object",
"json_schema",
"must be 'json_schema' or 'text'",
"specified for 'response_format.type' is not valid",
)
):
return True
# Generic markers ("unsupported", "not valid") are gated behind an explicit
# response_format mention so an unrelated unsupported-parameter error (e.g.
# stream_options) does not spuriously drop response_format.
if "response_format" not in text and "response format" not in text:
return False
return any(
marker in text
for marker in (
"not supported",
"unsupported",
"not valid",
)
)
_REASONING_FIELD_MARKERS = (
"reasoning_effort",
"reasoning effort",
"reasoning.effort",
"enable_thinking",
"reasoning_split",
"extra_body.thinking",
"extra_body.reasoning",
"thinking.type",
"'thinking'",
'"thinking"',
"'reasoning'",
'"reasoning"',
"parameter: reasoning",
"parameter reasoning",
"argument: reasoning",
"argument reasoning",
"field: reasoning",
"field reasoning",
"parameter: thinking",
"parameter thinking",
"argument: thinking",
"argument thinking",
"field: thinking",
"field thinking",
"reasoning is not supported",
"reasoning is unsupported",
"does not support reasoning",
"thinking is not supported",
"thinking is unsupported",
"does not support thinking",
)
_REASONING_PARAM_UNKNOWN_MARKERS = (
"unknown parameter",
"unknown_parameter",
"unrecognized request argument",
"unsupported parameter",
"unsupported_parameter",
"extra inputs are not permitted",
"extra_forbidden",
"unexpected keyword",
)
_REASONING_VALUE_MARKERS = (
"unsupported parameter value",
"unsupported_parameter_value",
"invalid value",
"invalid_value",
"unsupported value",
"unsupported_value",
"invalid_enum_value",
"literal_error",
"not a valid",
"is not valid",
"not valid",
"invalid choice",
"invalid option",
"supported values",
"allowed values",
"valid values",
"must be one of",
"expected one of",
"should be one of",
"input should be",
"only supports",
"only accepts",
"invalid reasoning_effort",
"invalid reasoning effort",
"unsupported reasoning_effort value",
"unsupported reasoning effort value",
)
_REASONING_VALUE_CONSTRAINT_RE = re.compile(
r"(?:reasoning[_ .]effort|thinking(?:\.type)?)\s+must\s+be\b"
)
_EFFORT_VALUE_TOKEN = (
r"(?:none|minimal|minimum|low|medium|high|xhigh|max|adaptive|enabled|disabled)"
)
_REASONING_VALUE_IN_UNSUPPORTED_RE = re.compile(
rf"(?:"
rf"(?:['\"]?(?:reasoning[_ .]effort|thinking(?:\.type)?)['\"]?\s+does\s+not\s+support)"
rf"|(?:['\"]?reasoning[_ .]effort['\"]?\s*(?:=|:|\s+)\s*['\"]?{_EFFORT_VALUE_TOKEN}['\"]?(?:$|[^a-z0-9_]))"
rf"|(?:(?:['\"]{_EFFORT_VALUE_TOKEN}['\"]|\b{_EFFORT_VALUE_TOKEN}\b)\s+(?:is\s+)?(?:not\s+(?:a\s+)?supported|unsupported|not\s+allowed|invalid))"
rf"|(?:does\s+not\s+support\s+(?:the\s+)?(?:value\s+|level\s+|effort\s+)?['\"]?{_EFFORT_VALUE_TOKEN}['\"]?(?:$|[^a-z0-9_]))"
rf"|(?:(?:invalid|unsupported)\s+(?:value|level|effort|mode))"
rf")"
)
def classify_reasoning_param_error(exc: Exception) -> Literal["param", "value"] | None:
"""Classify an HTTP 400/422 reasoning-parameter rejection.
Returns:
- ``"param"`` when the upstream explicitly rejected the reasoning
parameter itself (safe to cache disablement for this endpoint/model).
- ``"value"`` when the upstream rejected a specific effort/mode value
(safe for a one-off retry without reasoning params, must NOT disable
other valid levels such as ``"low"`` on subsequent requests).
- ``None`` for auth, quota, transport, or unrelated validation errors.
"""
status = getattr(exc, "status_code", None)
if status is None:
response = getattr(exc, "response", None)
status = getattr(response, "status_code", None)
if status is not None and status not in {400, 422}:
return None
text = error_text(exc)
if not any(field in text for field in _REASONING_FIELD_MARKERS):
return None
# Value constraints must win over parameter-unknown markers: providers
# often phrase a bad *value* as "Unsupported parameter: 'reasoning_effort'.
# Supported values are 'low' and 'medium'." Treating that as a
# parameter-level rejection would cache a disablement and silently drop
# every other valid level for the endpoint. A value classification only
# triggers a one-off retry, so it is the conservative choice whenever a
# value constraint is present.
if any(
marker in text for marker in _REASONING_VALUE_MARKERS
) or _REASONING_VALUE_CONSTRAINT_RE.search(text):
return "value"
if any(marker in text for marker in _REASONING_PARAM_UNKNOWN_MARKERS):
if _REASONING_VALUE_IN_UNSUPPORTED_RE.search(text):
return "value"
return "param"
if any(marker in text for marker in ("not supported", "unsupported", "does not support")):
if _REASONING_VALUE_IN_UNSUPPORTED_RE.search(text):
return "value"
return "param"
return None
def is_reasoning_param_error(exc: Exception) -> bool:
"""Whether a provider rejected a reasoning parameter or its value (HTTP 400/422)."""
return classify_reasoning_param_error(exc) is not None
def is_reasoning_param_unsupported(exc: Exception) -> bool:
"""Whether a provider rejected the reasoning/thinking parameter itself (HTTP 400/422).
Returns ``False`` for value-specific rejections (e.g. ``invalid value`` for
``reasoning_effort``) so callers can still do a one-off retry without
caching a permanent disablement across other valid effort levels.
"""
return classify_reasoning_param_error(exc) == "param"
def is_forced_tool_choice_unsupported(exc: Exception) -> bool:
"""Whether a provider rejected *naming* the tool it must call.
Distinct from :func:`is_tool_schema_unsupported`: the provider is happy to
receive tools, it just will not be told which one to use. DeepSeek V4 with
thinking enabled answers ``"Thinking mode does not support this
tool_choice"`` — so Ask Questions, whose whole first round is a forced
``ask_user``, failed the turn outright. Downgrading to ``"required"``
keeps "you must call a tool" and lets the loop's own fallback wrap the
model's question into a local card if it still writes prose.
A malformed choice is deliberately not matched: a shape the endpoint
cannot deserialize is a bug on our side to fix, not a capability to
degrade around.
"""
text = error_text(exc)
if "tool_choice" not in text and "tool choice" not in text:
return False
if "missing field" in text or "failed to deserialize" in text:
return False
return any(
marker in text
for marker in (
"does not support",
"not supported",
"unsupported",
"not allowed",
"cannot be used",
)
)
def is_tool_schema_unsupported(exc: Exception) -> bool:
"""Whether a provider rejected native tool/function-calling schemas.
Deliberately avoids matching the bare substring ``\"tool\"``. Any 400 that
merely mentions tools — or echoes the outbound request body — used to trip
the chat loop's silent strip-and-retry path and leave the model answering
in prose with no tools (#708). Keep markers tied to schema/parameter
rejections; ``logged_error_text`` already captures unknowns for follow-up.
"""
text = error_text(exc)
rejected_schema = any(
marker in text
for marker in (
"function_declaration",
"function declaration",
"function_declarations",
"tool_choice",
"parameters.properties",
"unsupported parameter: tools",
"unknown parameter: tools",
"unknown parameter 'tools'",
'unknown parameter "tools"',
"unexpected keyword argument 'tools'",
"tools is not supported",
"tools are not supported",
"does not support tools",
"does not support function calling",
"function calling is not supported",
"tool use is not supported",
"tool calling is not supported",
)
)
if rejected_schema:
return True
not_found = "404_not_found" in text or "404 not_found" in text
return not_found and any(
marker in text
for marker in (
"tool schema",
"function schema",
"function declaration",
"function_declaration",
"function calling",
"tool calling",
"tool_choice",
)
)
def is_reasoning_effort_tools_incompatible(exc: Exception) -> bool:
"""Whether a provider rejected combining ``reasoning_effort`` with tools.
Some models/endpoints (e.g. ``gpt-6-luna`` on ``/v1/chat/completions``)
reject requests that send both ``tools`` and ``reasoning_effort`` even
though native tool calling works without ``reasoning_effort``. Callers
should drop ``reasoning_effort`` and keep ``tools`` intact rather than
degrading the turn to plain prose (#2439).
"""
text = error_text(exc)
return "reasoning_effort" in text and any(
marker in text
for marker in (
"function tools with reasoning_effort are not supported",
"tools with reasoning_effort are not supported",
"tools with reasoning_effort is not supported",
"reasoning_effort with tools is not supported",
"reasoning_effort with function tools is not supported",
"reasoning_effort cannot be used with tools",
"reasoning_effort is not supported with tools",
)
)
def without_reasoning_effort(kwargs: dict[str, Any]) -> dict[str, Any] | None:
"""Return a copy of ``kwargs`` with ``reasoning_effort`` removed, or ``None``."""
has_top = "reasoning_effort" in kwargs
extra = kwargs.get("extra_body")
has_extra = isinstance(extra, dict) and "reasoning_effort" in extra
if not has_top and not has_extra:
return None
retry_kwargs = dict(kwargs)
retry_kwargs.pop("reasoning_effort", None)
if has_extra:
trimmed_extra = {key: value for key, value in extra.items() if key != "reasoning_effort"}
if trimmed_extra:
retry_kwargs["extra_body"] = trimmed_extra
else:
retry_kwargs.pop("extra_body", None)
return retry_kwargs
def is_image_input_unsupported(exc: Exception) -> bool:
"""Whether a provider or model rejected multimodal message content."""
text = error_text(exc)
# GLM's dotted-path validation only indicates unsupported image content
# when the message content type explicitly permits text and nothing else.
text_only_content = re.search(
r"messages(?:\[\d+\])?\.content(?:\[\d+\])?\.type"
r"[^\n]*取值范围\s*[::]?\s*\[\s*['\"]text['\"]\s*\]",
text,
)
return bool(text_only_content) or any(
marker in text
for marker in (
"image",
"vision",
"multimodal",
"image_url",
"content type",
"must be a string",
"expected a string",
"expected string",
"invalid type for 'messages",
)
)
def is_transient_transport_error(exc: Exception) -> bool:
"""Return whether retrying can recover a provider transport failure.
Authentication, rate-limit, HTTP-status and response-shape errors are
intentionally excluded. OpenAI-compatible clients wrap httpx/httpcore
failures, so the complete exception chain is inspected.
"""
if getattr(exc, "retryable", None) is False:
return False
for current in _exception_chain(exc):
if isinstance(
current,
(
httpx.TransportError,
LLMProviderTransportError,
LLMTimeoutError,
TimeoutError,
ConnectionError,
),
):
return True
error_type = type(current)
module = error_type.__module__
name = error_type.__name__
if module.startswith("openai") and name in {
"APIConnectionError",
"APITimeoutError",
}:
return True
if module.startswith("httpcore") and name in {
"ConnectError",
"ConnectTimeout",
"ReadError",
"ReadTimeout",
"RemoteProtocolError",
"WriteError",
"WriteTimeout",
}:
return True
return False
__all__ = [
"classify_reasoning_param_error",
"error_text",
"is_image_input_unsupported",
"is_reasoning_effort_tools_incompatible",
"is_reasoning_param_error",
"is_reasoning_param_unsupported",
"is_response_format_unsupported",
"is_stream_options_unsupported",
"is_transient_transport_error",
"is_forced_tool_choice_unsupported",
"is_tool_schema_unsupported",
"without_reasoning_effort",
]