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

+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,