fix(providers): tighten tool calls and compatibility fallbacks

Require structured tool calls and explicit unsupported-feature errors.
Preserve supported SDK compaction requests and add compatibility coverage.

Co-authored-by: Xubin Ren <52506698+Re-bin@users.noreply.github.com>
This commit is contained in:
chengyongruandXubin Ren authored and Xubin Ren committed 2026-10-31 11:55:13 +08:00
1 parent 3e40684112
commit 8b37976d36
16 files changed
+406 -168

No files matched your search

+5 -4
View File
@@ -41,6 +41,10 @@ from nanobot.providers.openai_responses import (
ResponsesWebSocketOptions,
responses_state_matches,
)
from nanobot.providers.openai_responses.errors import (
COMPACTION_FEATURES,
is_unsupported_feature_error,
)
from nanobot.providers.openai_responses.state import (
responses_compaction_items,
without_response_item_ids,
@@ -620,10 +624,7 @@ def _build_codex_http_error(status_code: int, headers: httpx.Headers, raw: str)
retry_after = LLMProvider._extract_retry_after_from_headers(headers)
error_type, error_code = LLMProvider._extract_error_type_code(raw)
error_param, error_message = _codex_error_details(raw)
compaction_unsupported = status_code in {400, 404, 422} and any(
marker in raw.lower()
for marker in ("context_management", "compact_threshold", "compaction_trigger")
)
compaction_unsupported = is_unsupported_feature_error(status_code, raw, COMPACTION_FEATURES)
return _CodexHTTPError(
_friendly_error(status_code), status_code=status_code,
retry_after=retry_after, error_type=error_type, error_code=error_code,
+8 -94
View File
@@ -7,7 +7,6 @@ import hashlib
import importlib.util
import json
import os
import re
import secrets
import string
import time
@@ -40,6 +39,11 @@ from nanobot.providers.model_api import (
is_hosted_web_search_tool,
)
from nanobot.providers.openai_responses import ResponsesBackend, responses_state_matches
from nanobot.providers.openai_responses.errors import (
RESPONSES_FEATURES,
is_unsupported_feature_error,
response_error_details,
)
from nanobot.providers.registry import KIMI_K3_MODELS
if TYPE_CHECKING:
@@ -95,7 +99,6 @@ _KIMI_SERVER_MANAGED_TEMPERATURE_MODELS: frozenset[str] = frozenset({
"kimi-k2.5",
"kimi-k2.6",
})
_TEXT_TOOL_CALL_RE = re.compile(r"<tool_call>\s*(.*?)\s*</tool_call>", re.DOTALL)
# Thinking-capable MiMo models per Xiaomi docs (see
# tests/providers/test_xiaomi_mimo_thinking.py). mimo-v2-flash is omitted
# because it does not support thinking.
@@ -207,68 +210,6 @@ def _short_tool_id() -> str:
return "".join(secrets.choice(_ALNUM) for _ in range(9))
def _strip_json_fence(text: str) -> str:
stripped = text.strip()
if not stripped.startswith("```") or not stripped.endswith("```"):
return stripped
lines = stripped.splitlines()
if len(lines) < 2:
return stripped
return "\n".join(lines[1:-1]).strip()
def _extract_text_tool_calls(content: str | None) -> tuple[str | None, list[ToolCallRequest]]:
if not content or "<tool_call>" not in content:
return content, []
tool_calls: list[ToolCallRequest] = []
spans: list[tuple[int, int]] = []
for match in _TEXT_TOOL_CALL_RE.finditer(content):
try:
raw_payload: object = json.loads(
_strip_json_fence(match.group(1))
)
except Exception:
continue
if not isinstance(raw_payload, dict):
continue
payload = cast(dict[str, Any], raw_payload)
nested = cast(object, payload.get("tool_call"))
if isinstance(nested, dict):
payload = cast(dict[str, Any], nested)
function = cast(object, payload.get("function"))
if not isinstance(function, dict):
function = payload
function_data = cast(dict[str, Any], function)
name = cast(object, function_data.get("name"))
if not isinstance(name, str) or not name:
continue
arguments = function_data.get(
"arguments",
payload.get("arguments", {}),
)
tool_calls.append(ToolCallRequest(
id=str(payload.get("id") or _short_tool_id()),
name=name,
arguments=parse_tool_arguments(arguments),
))
spans.append(match.span())
if not tool_calls:
return content, []
visible_parts: list[str] = []
last = 0
for start, end in spans:
visible_parts.append(content[last:start])
last = end
visible_parts.append(content[last:])
visible_content = "".join(visible_parts).strip() or None
return visible_content, tool_calls
def _get(obj: object, key: str) -> Any:
if isinstance(obj, dict):
return cast(dict[str, Any], obj).get(key)
@@ -1146,32 +1087,9 @@ class OpenAICompatProvider(LLMProvider):
@staticmethod
def _should_fallback_from_responses_error(e: Exception) -> bool:
"""Fallback only for likely Responses API compatibility errors."""
response = getattr(e, "response", None)
status_code = getattr(e, "status_code", None)
if status_code is None and response is not None:
status_code = getattr(response, "status_code", None)
if status_code not in {400, 404, 422}:
return False
body = (
getattr(e, "body", None)
or getattr(e, "doc", None)
or getattr(response, "text", None)
)
body_text = str(body).lower() if body is not None else ""
compatibility_markers = (
"responses",
"response api",
"max_output_tokens",
"instructions",
"previous_response",
"unsupported",
"not supported",
"unknown parameter",
"unrecognized request argument",
)
return any(marker in body_text for marker in compatibility_markers)
"""Fallback only when the endpoint rejects a Responses API feature."""
status, body = response_error_details(e)
return is_unsupported_feature_error(status, body, RESPONSES_FEATURES)
def _build_responses_body(
self,
@@ -1494,8 +1412,6 @@ class OpenAICompatProvider(LLMProvider):
provider_specific_fields=prov,
function_provider_specific_fields=fn_prov,
))
if not parsed_tool_calls:
content, parsed_tool_calls = _extract_text_tool_calls(content)
return LLMResponse(
content=content,
@@ -1620,8 +1536,6 @@ class OpenAICompatProvider(LLMProvider):
)
for b in tc_bufs.values()
]
if not tool_calls:
content, tool_calls = _extract_text_tool_calls(content)
return LLMResponse(
content=content,
@@ -271,13 +271,18 @@ class ResponsesBackend:
idle_timeout = resolve_stream_idle_timeout_s()
if body.get("stream"):
options["timeout"] = idle_timeout
# Older supported SDKs accept server compaction through extra_body.
sdk_body = dict(body)
if "context_management" in sdk_body:
options["extra_body"] = {"context_management": sdk_body.pop("context_management")}
try:
response = await client.responses.create(**body, **options)
response = await client.responses.create(**sdk_body, **options)
except Exception as exc:
if "context_management" not in body or not is_compaction_compatibility_error(exc):
raise
self.native_compaction_available = False
body.pop("context_management")
options.pop("extra_body")
logger.warning(
"Responses server compaction unsupported; disabled for {} (status={})",
provider, getattr(exc, "status_code", None),
@@ -0,0 +1,62 @@
"""Explicit unsupported-feature errors at the Responses transport boundary."""
from __future__ import annotations
import json
import re
from typing import cast
COMPACTION_FEATURES = ("context_management", "compact_threshold", "compaction_trigger")
RESPONSES_FEATURES = (
"responses", "responses api", "responses endpoint", "response api",
"max_output_tokens", "instructions", "previous_response_id", "input_image",
)
def response_error_details(exc: Exception) -> tuple[object, object]:
"""Read SDK error metadata without treating local exceptions as API errors."""
response = getattr(exc, "response", None)
status = getattr(exc, "status_code", None) or getattr(response, "status_code", None)
body = (
getattr(exc, "body", None)
or getattr(exc, "doc", None)
or getattr(response, "text", None)
)
return status, body
def is_unsupported_feature_error(
status: object, body: object, features: tuple[str, ...],
) -> bool:
"""Require rejection of a named feature, not an invalid value or incidental mention."""
if status not in (400, 404, 422):
return False
if isinstance(body, str):
try:
body = json.loads(body)
except ValueError:
pass
if isinstance(body, dict):
fields = cast(dict[str, object], body)
error = fields.get("error")
if isinstance(error, dict):
fields = cast(dict[str, object], error)
code = fields.get("code")
param = fields.get("param")
if code in ("unknown_parameter", "unsupported_parameter", "unrecognized_parameter"):
if isinstance(param, str) and re.split(r"[.\[]", param)[0] in features:
return True
if code in ("invalid_value", "unsupported_value"):
return False
body = fields.get("message")
if not isinstance(body, str):
return False
target = "(?:" + "|".join(re.escape(feature) for feature in features) + ")"
return bool(re.search(
rf"(?:unknown|unrecognized|unsupported)\s+"
rf"(?:parameter|field|request argument(?: supplied)?|input type|endpoint|api)"
rf"\s*[:=]?\s*[`'\"]?{target}(?!\w)"
rf"|(?<!\w){target}[`'\"]?\s+(?:is\s+)?(?:not supported|unsupported|not implemented)\b"
rf"|does not support\s+(?:the\s+)?{target}(?!\w)",
body, re.IGNORECASE,
))
+7 -18
View File
@@ -7,6 +7,11 @@ from loguru import logger
from nanobot.providers.base import LLMResponse, LLMUsage, ProviderConversationState
from nanobot.providers.openai_responses.converters import convert_messages
from nanobot.providers.openai_responses.errors import (
COMPACTION_FEATURES,
is_unsupported_feature_error,
response_error_details,
)
RESPONSES_STATE_KIND = "openai_responses"
RESPONSES_STATE_VERSION = 1
@@ -193,24 +198,8 @@ def is_compaction_compatibility_error(exc: Exception) -> bool:
"""Recognize endpoints that reject native Responses compaction fields."""
if getattr(exc, "compaction_unsupported", False) is True:
return True
response = getattr(exc, "response", None)
status_code = getattr(exc, "status_code", None)
if status_code is None and response is not None:
status_code = getattr(response, "status_code", None)
body = (
getattr(exc, "body", None)
or getattr(exc, "doc", None)
or getattr(response, "text", None)
or str(exc)
)
text = str(body).lower()
has_compaction_marker = any(
marker in text
for marker in ("context_management", "compact_threshold", "compaction_trigger")
)
if not has_compaction_marker:
return False
return isinstance(exc, TypeError) or status_code in {400, 404, 422}
status, body = response_error_details(exc)
return is_unsupported_feature_error(status, body, COMPACTION_FEATURES)
def _prune_before_latest_output_compaction(
@@ -18,6 +18,10 @@ from websockets.protocol import State
from nanobot.providers.base import LLMProvider, LLMResponse, resolve_stream_idle_timeout_s
from nanobot.providers.openai_responses.backend import ResponsesBackend
from nanobot.providers.openai_responses.errors import (
COMPACTION_FEATURES,
is_unsupported_feature_error,
)
from nanobot.providers.openai_responses.parsing import ResponsesStreamCapture
_TRANSPORT_FAILURE_LIMIT = 3
@@ -88,9 +92,8 @@ class ResponsesWebSocketError(RuntimeError):
_error_token(cast(dict[str, Any], raw_headers).get("x-request-id"))
if isinstance(raw_headers, dict) else None
)
self.compaction_unsupported = self.status_code in {400, 404, 422} and any(
marker in str(message).lower()
for marker in ("context_management", "compact_threshold", "compaction_trigger")
self.compaction_unsupported = is_unsupported_feature_error(
self.status_code, fields, COMPACTION_FEATURES,
)
super().__init__(
f"HTTP {self.status_code}: Responses WebSocket request failed"