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:
1 parent
3e40684112
commit
8b37976d36
16 files changed
+406
-168
No files matched your search
@@ -393,7 +393,7 @@ async def test_chat_retries_without_unsupported_server_compaction():
|
||||
assert result.content == "compaction fallback"
|
||||
assert result.provider_state is not None
|
||||
assert create.await_count == 2
|
||||
assert "context_management" in create.call_args_list[0].kwargs
|
||||
assert "context_management" in create.call_args_list[0].kwargs["extra_body"]
|
||||
assert "context_management" not in create.call_args_list[1].kwargs
|
||||
assert provider.supports_native_compaction() is False
|
||||
|
||||
|
||||
@@ -52,29 +52,6 @@ def test_custom_provider_parse_accepts_dict_response() -> None:
|
||||
assert result.usage.total_tokens == 3
|
||||
|
||||
|
||||
def test_custom_provider_parse_normalizes_text_tool_call() -> None:
|
||||
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
|
||||
provider = OpenAICompatProvider()
|
||||
|
||||
result = provider._parse({
|
||||
"choices": [{
|
||||
"message": {
|
||||
"content": (
|
||||
"I'll inspect it.\n"
|
||||
'<tool_call>{"name":"read_file","arguments":{"path":"README.md"}}'
|
||||
"</tool_call>"
|
||||
),
|
||||
},
|
||||
"finish_reason": "stop",
|
||||
}],
|
||||
})
|
||||
|
||||
assert result.content == "I'll inspect it."
|
||||
assert len(result.tool_calls) == 1
|
||||
assert result.tool_calls[0].name == "read_file"
|
||||
assert result.tool_calls[0].arguments == {"path": "README.md"}
|
||||
|
||||
|
||||
def test_custom_provider_parse_keeps_structured_tool_call_over_text_markup() -> None:
|
||||
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
|
||||
provider = OpenAICompatProvider()
|
||||
@@ -104,22 +81,6 @@ def test_custom_provider_parse_chunks_accepts_plain_text_chunks() -> None:
|
||||
assert result.content == "hello world"
|
||||
|
||||
|
||||
def test_custom_provider_parse_chunks_normalizes_split_text_tool_call() -> None:
|
||||
chunks = [
|
||||
{"choices": [{"delta": {"content": "<tool_call>"}}]},
|
||||
{"choices": [{"delta": {"content": '{"name":"list_dir",'}}]},
|
||||
{"choices": [{"delta": {"content": '"arguments":{"path":"."}}</tool_call>'}}]},
|
||||
{"choices": [{"finish_reason": "stop", "delta": {}}]},
|
||||
]
|
||||
|
||||
result = OpenAICompatProvider._parse_chunks(chunks)
|
||||
|
||||
assert result.content is None
|
||||
assert len(result.tool_calls) == 1
|
||||
assert result.tool_calls[0].name == "list_dir"
|
||||
assert result.tool_calls[0].arguments == {"path": "."}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("as_sdk", [False, True], ids=["dict", "sdk"])
|
||||
def test_custom_provider_parse_chunks_deduplicates_parallel_tool_call_ids(as_sdk: bool) -> None:
|
||||
chunks = [{
|
||||
|
||||
@@ -313,8 +313,9 @@ async def test_codex_request_non_200_populates_http_metadata(monkeypatch) -> Non
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("unsupported", [False, True])
|
||||
async def test_codex_request_marks_rejected_compaction_without_retaining_raw_body(
|
||||
monkeypatch,
|
||||
monkeypatch, unsupported,
|
||||
) -> None:
|
||||
original_client = httpx.AsyncClient
|
||||
secret = "PRIVATE PROMPT MUST NOT BE RETAINED"
|
||||
@@ -324,7 +325,10 @@ async def test_codex_request_marks_rejected_compaction_without_retaining_raw_bod
|
||||
400,
|
||||
json={
|
||||
"error": {
|
||||
"message": f"Unknown input type compaction_trigger; {secret}",
|
||||
"message": (
|
||||
f"Unknown input type compaction_trigger; {secret}" if unsupported
|
||||
else f"Invalid compaction_trigger: input exceeds context window; {secret}"
|
||||
),
|
||||
},
|
||||
},
|
||||
request=request,
|
||||
@@ -349,7 +353,7 @@ async def test_codex_request_marks_rejected_compaction_without_retaining_raw_bod
|
||||
)
|
||||
|
||||
error = caught.value
|
||||
assert error.compaction_unsupported is True
|
||||
assert error.compaction_unsupported is unsupported
|
||||
assert secret not in str(error)
|
||||
assert not hasattr(error, "body")
|
||||
|
||||
|
||||
@@ -764,6 +764,31 @@ async def test_codex_compaction_restarts_continuation_from_rewritten_history(cod
|
||||
assert any(item.get("type") == "compaction" for item in server.requests[2][1]["input"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("unsupported", [False, True])
|
||||
async def test_required_compaction_error_preserves_capability_unless_unsupported(codex_peer, unsupported):
|
||||
provider, server, _ = codex_peer
|
||||
first = await provider.chat(_messages(), provider_context=_context())
|
||||
|
||||
async def respond(peer, _body):
|
||||
await peer.socket.send_json({"type": "error", "status": 400, "error": {
|
||||
"message": (
|
||||
"Unknown input type compaction_trigger" if unsupported
|
||||
else "Invalid compaction_trigger: input exceeds context window"
|
||||
),
|
||||
}})
|
||||
|
||||
server.respond = respond
|
||||
result = await provider.chat(
|
||||
_messages("next"), max_tokens=10,
|
||||
provider_context=_context(first, context_window_tokens=4_000, compaction_input_budget=10_000),
|
||||
)
|
||||
assert result.finish_reason == "error"
|
||||
assert provider.supports_native_compaction() is (not unsupported)
|
||||
assert len(server.requests) == 2
|
||||
assert server.requests[-1][1]["input"] == [{"type": "compaction_trigger"}]
|
||||
assert not server.http_requests
|
||||
|
||||
|
||||
async def test_codex_inline_compaction_starts_next_request_with_compacted_state(codex_peer):
|
||||
provider, server, _ = codex_peer
|
||||
compaction = {"type": "compaction", "id": "cmp_1", "encrypted_content": "compacted"}
|
||||
|
||||
@@ -689,7 +689,7 @@ async def test_direct_openai_retries_without_unsupported_server_compaction() ->
|
||||
assert result.content == "compaction fallback"
|
||||
assert result.provider_state is not None
|
||||
assert mock_responses.await_count == 2
|
||||
assert "context_management" in mock_responses.call_args_list[0].kwargs
|
||||
assert "context_management" in mock_responses.call_args_list[0].kwargs["extra_body"]
|
||||
assert "context_management" not in mock_responses.call_args_list[1].kwargs
|
||||
assert provider.supports_native_compaction("gpt-5.6") is False
|
||||
mock_chat.assert_not_awaited()
|
||||
|
||||
@@ -818,9 +818,9 @@ class TestResponsesConversationState:
|
||||
):
|
||||
assert resolve_compact_threshold(context_window, max_output) == expected
|
||||
|
||||
def test_compaction_compatibility_recognizes_old_sdk_signature_error(self):
|
||||
def test_local_sdk_errors_do_not_disable_server_compaction(self):
|
||||
error = TypeError("create() got an unexpected keyword argument 'context_management'")
|
||||
assert is_compaction_compatibility_error(error) is True
|
||||
assert is_compaction_compatibility_error(error) is False
|
||||
assert is_compaction_compatibility_error(TypeError("unrelated argument")) is False
|
||||
|
||||
def test_state_observability_logs_counts_without_opaque_content(self):
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
"""Provider compatibility decisions through the SDK and local HTTP endpoints."""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from nanobot.agent.tools.exec_session import ExecSessionTool
|
||||
from nanobot.providers.azure_openai_provider import AzureOpenAIProvider
|
||||
from nanobot.providers.base import ProviderCallContext
|
||||
from nanobot.providers.model_api import ModelAPICapabilities
|
||||
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
|
||||
from nanobot.providers.registry import find_by_name
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def endpoint(monkeypatch):
|
||||
monkeypatch.setenv("NO_PROXY", "127.0.0.1")
|
||||
monkeypatch.setenv("no_proxy", "127.0.0.1")
|
||||
monkeypatch.delenv("LANGFUSE_SECRET_KEY", raising=False)
|
||||
runners = []
|
||||
|
||||
async def start(handler):
|
||||
app = web.Application()
|
||||
app.router.add_post("/{path:.*}", handler)
|
||||
runner = web.AppRunner(app)
|
||||
runners.append(runner)
|
||||
await runner.setup()
|
||||
await web.TCPSite(runner, "127.0.0.1", 0).start()
|
||||
return f"http://127.0.0.1:{runner.addresses[0][1]}"
|
||||
|
||||
yield start
|
||||
for runner in runners:
|
||||
await runner.cleanup()
|
||||
|
||||
|
||||
def _response(body):
|
||||
response = {
|
||||
"id": "resp_fixture", "object": "response", "status": "completed",
|
||||
"output": [{
|
||||
"id": "msg_fixture", "type": "message", "role": "assistant", "status": "completed",
|
||||
"content": [{"type": "output_text", "text": "ok", "annotations": []}],
|
||||
}],
|
||||
}
|
||||
if not body.get("stream"):
|
||||
return web.json_response(response)
|
||||
return _sse([
|
||||
{"type": "response.output_text.delta", "delta": "ok"},
|
||||
{"type": "response.completed", "response": response},
|
||||
])
|
||||
|
||||
|
||||
def _sse(events):
|
||||
return web.Response(
|
||||
content_type="text/event-stream",
|
||||
text="".join(f"data: {json.dumps(event)}\n\n" for event in events),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream", [False, True])
|
||||
@pytest.mark.parametrize(("content", "tool_choice"), [
|
||||
pytest.param(
|
||||
'Example only:\n```xml\n<tool_call>{"name":"read_file","arguments":{"path":"README.md"}}</tool_call>\n```',
|
||||
"none", id="quoted-json-tools-disabled",
|
||||
),
|
||||
pytest.param(
|
||||
'Example only:\n```xml\n<tool_call>{"name":"read_file","arguments":{"path":"README.md"}}</tool_call>\n```',
|
||||
"auto", id="quoted-json-tools-enabled",
|
||||
),
|
||||
pytest.param(
|
||||
'<tool_call><function=exec_session><parameter=session_id>fixture</parameter>'
|
||||
'<parameter=timeout_ms>{"session_id":"fixture","timeout_ms":{}}</parameter>'
|
||||
'</function></tool_call>',
|
||||
"auto", id="malformed-xml-in-content",
|
||||
),
|
||||
])
|
||||
async def test_plaintext_tool_examples_remain_text(endpoint, stream, content, tool_choice):
|
||||
requests = []
|
||||
deltas = []
|
||||
|
||||
async def on_content_delta(delta):
|
||||
deltas.append(delta)
|
||||
|
||||
async def handler(request):
|
||||
body = await request.json()
|
||||
requests.append(body)
|
||||
if body.get("stream"):
|
||||
return _sse([
|
||||
{"choices": [{"index": 0, "delta": {"content": part}}]}
|
||||
for part in (content[:30], content[30:35], content[35:])
|
||||
] + [{"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}])
|
||||
return web.json_response({"id": "chat_fixture", "choices": [{
|
||||
"index": 0, "message": {"role": "assistant", "content": content}, "finish_reason": "stop",
|
||||
}]})
|
||||
|
||||
url = await endpoint(handler)
|
||||
provider = OpenAICompatProvider(api_key="fixture", api_base=f"{url}/v1", spec=find_by_name("custom"))
|
||||
invoke = provider.chat_stream if stream else provider.chat
|
||||
try:
|
||||
result = await invoke(
|
||||
[{"role": "user", "content": "Show a tool call example without executing it."}],
|
||||
tools=[{"type": "function", "function": {"name": "read_file", "parameters": {"type": "object"}}}],
|
||||
tool_choice=tool_choice,
|
||||
**({"on_content_delta": on_content_delta} if stream else {}),
|
||||
)
|
||||
assert result.finish_reason == "stop"
|
||||
assert result.content == content
|
||||
assert result.tool_calls == []
|
||||
assert not result.should_execute_tools
|
||||
assert len(requests) == 1
|
||||
assert requests[0]["tool_choice"] == tool_choice
|
||||
if stream:
|
||||
assert "".join(deltas) == result.content
|
||||
finally:
|
||||
await provider.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream", [False, True])
|
||||
@pytest.mark.parametrize("timeout_ms", [1000, {"session_id": "fixture", "timeout_ms": {}}])
|
||||
async def test_structured_calls_keep_arguments_out_of_text_and_preserve_validation(endpoint, stream, timeout_ms):
|
||||
tool = ExecSessionTool()
|
||||
arguments = {"session_id": "fixture", "timeout_ms": timeout_ms}
|
||||
encoded = json.dumps(arguments)
|
||||
text = "Checking the command output."
|
||||
deltas = []
|
||||
|
||||
async def on_content_delta(delta):
|
||||
deltas.append(delta)
|
||||
|
||||
async def handler(request):
|
||||
body = await request.json()
|
||||
if body.get("stream"):
|
||||
return _sse([
|
||||
{"choices": [{"index": 0, "delta": {"content": text}}]},
|
||||
{"choices": [{"index": 0, "delta": {"tool_calls": [{
|
||||
"index": 0, "id": "call_fixture", "type": "function",
|
||||
"function": {"name": "exec_session", "arguments": encoded[:20]},
|
||||
}]}}]},
|
||||
{"choices": [{"index": 0, "delta": {"tool_calls": [{
|
||||
"index": 0, "function": {"arguments": encoded[20:]},
|
||||
}]}}]},
|
||||
{"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]},
|
||||
])
|
||||
return web.json_response({"id": "chat_fixture", "choices": [{
|
||||
"index": 0, "message": {"role": "assistant", "content": text, "tool_calls": [{
|
||||
"id": "call_fixture", "type": "function",
|
||||
"function": {"name": "exec_session", "arguments": encoded},
|
||||
}]}, "finish_reason": "tool_calls",
|
||||
}]})
|
||||
|
||||
url = await endpoint(handler)
|
||||
provider = OpenAICompatProvider(api_key="fixture", api_base=f"{url}/v1", spec=find_by_name("custom"))
|
||||
invoke = provider.chat_stream if stream else provider.chat
|
||||
try:
|
||||
result = await invoke(
|
||||
[{"role": "user", "content": "Check the running command."}],
|
||||
tools=[tool.to_schema()],
|
||||
**({"on_content_delta": on_content_delta} if stream else {}),
|
||||
)
|
||||
assert result.should_execute_tools
|
||||
assert result.content == text
|
||||
assert len(result.tool_calls) == 1
|
||||
call = result.tool_calls[0]
|
||||
assert (call.id, call.name, call.arguments) == ("call_fixture", "exec_session", arguments)
|
||||
assert tool.validate_params(call.arguments) == (
|
||||
["timeout_ms should be integer"] if isinstance(timeout_ms, dict) else []
|
||||
)
|
||||
if stream:
|
||||
assert "".join(deltas) == text
|
||||
finally:
|
||||
await provider.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream", [False, True])
|
||||
async def test_invalid_output_limit_does_not_switch_protocol_or_trip_circuit(endpoint, stream):
|
||||
paths = []
|
||||
|
||||
async def handler(request):
|
||||
paths.append(request.path)
|
||||
body = await request.json()
|
||||
if body.get("max_output_tokens", body.get("max_completion_tokens", 0)) > 64:
|
||||
return web.json_response({"error": {
|
||||
"type": "invalid_request_error", "param": "max_output_tokens",
|
||||
"message": "Invalid max_output_tokens for Responses: must be at most 64",
|
||||
}}, status=400)
|
||||
return _response(body)
|
||||
|
||||
url = await endpoint(handler)
|
||||
provider = OpenAICompatProvider(
|
||||
api_key="fixture", api_base=f"{url}/v1", default_model="gpt-5", spec=find_by_name("custom"),
|
||||
model_api=ModelAPICapabilities(("responses", "chat_completions"), "responses"),
|
||||
)
|
||||
invoke = provider.chat_stream if stream else provider.chat
|
||||
try:
|
||||
for _ in range(3):
|
||||
result = await invoke([{"role": "user", "content": "hello"}], max_tokens=100)
|
||||
assert result.finish_reason == "error"
|
||||
assert result.error_status_code == 400
|
||||
result = await invoke([{"role": "user", "content": "hello"}], max_tokens=32)
|
||||
assert result.content == "ok"
|
||||
assert paths == ["/v1/responses"] * 4
|
||||
finally:
|
||||
await provider.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream", [False, True])
|
||||
@pytest.mark.parametrize("unsupported", [False, True])
|
||||
async def test_server_compaction_distinguishes_unsupported_field_from_invalid_value(endpoint, stream, unsupported):
|
||||
bodies = []
|
||||
|
||||
async def handler(request):
|
||||
body = await request.json()
|
||||
bodies.append(body)
|
||||
if len(bodies) == 1:
|
||||
return web.json_response({"error": {
|
||||
"type": "invalid_request_error", "param": "context_management[0].compact_threshold",
|
||||
"message": (
|
||||
"Unknown parameter: context_management" if unsupported
|
||||
else "Invalid context_management compact_threshold: value exceeds the context window"
|
||||
),
|
||||
}}, status=400)
|
||||
return _response(body)
|
||||
|
||||
url = await endpoint(handler)
|
||||
provider = AzureOpenAIProvider(api_key="fixture", api_base=url, default_model="gpt-5.4")
|
||||
invoke = provider.chat_stream if stream else provider.chat
|
||||
context = ProviderCallContext(context_window_tokens=200_000)
|
||||
tools = [ExecSessionTool().to_schema()]
|
||||
messages = [
|
||||
{"role": "system", "content": "Stable instructions."},
|
||||
{"role": "user", "content": "Check the running command."},
|
||||
{"role": "assistant", "content": None, "tool_calls": [{
|
||||
"id": "call_fixture", "type": "function", "function": {
|
||||
"name": "exec_session", "arguments": '{"session_id":"fixture"}',
|
||||
},
|
||||
}]},
|
||||
{"role": "tool", "tool_call_id": "call_fixture", "content": "Command completed."},
|
||||
]
|
||||
try:
|
||||
result = await invoke(messages, tools=tools, provider_context=context)
|
||||
assert result.finish_reason == ("stop" if unsupported else "error")
|
||||
assert len(bodies) == (2 if unsupported else 1)
|
||||
assert provider.supports_native_compaction() is (not unsupported)
|
||||
if unsupported:
|
||||
without_compaction = {key: value for key, value in bodies[0].items() if key != "context_management"}
|
||||
assert json.dumps(bodies[1]) == json.dumps(without_compaction)
|
||||
result = await invoke(messages, tools=tools, provider_context=context)
|
||||
assert result.content == "ok"
|
||||
assert "context_management" in bodies[0]
|
||||
assert ("context_management" in bodies[-1]) is (not unsupported)
|
||||
assert json.dumps(bodies[-1]) == json.dumps(bodies[-2] if unsupported else bodies[0])
|
||||
assert bodies[-1]["instructions"] == "Stable instructions."
|
||||
assert bodies[-1]["input"][0]["role"] == "user"
|
||||
assert [item["type"] for item in bodies[-1]["input"][1:]] == ["function_call", "function_call_output"]
|
||||
assert bodies[-1]["tools"][0]["name"] == "exec_session"
|
||||
finally:
|
||||
await provider.aclose()
|
||||
@@ -201,11 +201,22 @@ def test_serde_deserialize_error_does_not_trigger_fallback():
|
||||
assert OpenAICompatProvider._should_fallback_from_responses_error(err) is False
|
||||
|
||||
|
||||
def test_legacy_compatibility_markers_still_trigger_fallback():
|
||||
def test_explicit_unsupported_responses_parameter_allows_fallback():
|
||||
err = _FakeAPIError(400, "parameter `instructions` is unsupported")
|
||||
assert OpenAICompatProvider._should_fallback_from_responses_error(err) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("status", "body", "expected"), [
|
||||
(400, {"code": "unsupported_parameter", "param": "instructions"}, True),
|
||||
(400, {"code": "unsupported_value", "param": "instructions", "message": "Invalid instructions"}, False),
|
||||
(404, {"message": "Previous response with id 'resp_missing' not found"}, False),
|
||||
(422, {"message": "Unsupported value for max_output_tokens: must be at most 64"}, False),
|
||||
])
|
||||
def test_responses_errors_distinguish_unsupported_parameters_from_invalid_requests(status, body, expected):
|
||||
err = _FakeAPIError(status, body)
|
||||
assert OpenAICompatProvider._should_fallback_from_responses_error(err) is expected
|
||||
|
||||
|
||||
# DeepSeek Responses wire shape (PR #5214 root cause)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user