litellm/tests/unit/test_xai_responses_auto_routing.py
Mateo Wang 897dda7920
fix(router)!: stop a chat-mode Mantle deployment from rewriting the shared Responses routing row (#46263)
* fix(router): stop a chat-mode Mantle deployment from rewriting the shared Responses routing row

A deployment with an explicit custom_llm_provider and model_info.mode: chat
used to overwrite the shared litellm.model_cost row, moving every other
deployment and plain SDK calls onto Chat Completions until restart, because
the downgrade guard read a double-prefixed key and never fired. The guard now
reads the real key, and a deployment's own mode decides its routing in
responses_api_bridge_check, except on chatgpt and github_copilot where Chat
Completions is dead for responses-mode models.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(responses): keep the bridge-check mode tests in the sharded bridge flag file

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(responses): let a deployment mode pin replace only the shared-row mode so the bridge capability rules still run

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(responses): keep Responses-only backends bridged under a deployment chat pin and satisfy the type gate

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(responses): give the bridge casts a reason and drop the bare noqa so the type discipline gate passes

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(responses): keep a responses row with no supported_endpoints bridged under a deployment chat pin

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(router): read the downgrade guard's mode from the row registration writes

A chat-mode openai/<name> deployment merged into the bare <name> row while the guard read
openai/<name>, so the guard never fired and the shared responses row turned to chat. An explicit
responses/ prefix now also outranks a deployment's chat pin.

* fix(router): let an explicit responses/ prefix outrank a registered chat row

The router now registers a chat-pinned openai/responses/<model> deployment under its own name, so the
lookup found mode chat and the request went to Chat Completions as responses/<model>.

* fix(router): keep the shared row's mode for every deployment pin and honor the pin on /v1/messages

A deployment's mode pin now never rewrites the shared cost-map row in either direction, including the responses/-stripped twin key, so siblings and SDK calls keep routing by the registered mode. The backend key formula goes back to main's, which keeps capability fields off rows that registration never wrote at base. The /v1/messages adapter and handler read the deployment's model_info, so a chat-pinned deployment gets a plain reasoning effort on chat completions.

* fix(router): keep copilot responses opt-in, make unmapped pins order-free, send Mantle auto summary as auto

A responses pin on a github_copilot model or a model missing from the cost map still marks the shared row, since that is how those models opt into the Responses API. A chat pin never marks a row, so registration order no longer matters. Mantle's OpenAI path gets summary auto in place of the auto summary detailed. The Azure o3-pro and o3-deep-research rows drop Chat Completions, which Azure does not serve for them.

* fix(router): skip a non-string model_info.mode when keeping the registered mode

* fix(router): keep chat-pinned Mantle tool calls and summaries on the Responses API

A Mantle row that also serves the Responses API now follows the GPT-5 tool and
reasoning summary bridge rules, since Mantle Chat Completions rejects function tools
on gpt-5.4+ unless reasoning is off and rejects the summary aliases. Mantle chat
gets a dict reasoning_effort as its effort level.

The opt-in auto summary asks each Responses config for its level, auto on Mantle's
OpenAI path, so a client's own detailed summary follows drop_params as at base.

No mode replaces a registered responses mode, and chatgpt and github_copilot rows
take any pin until they are responses, which restores the Copilot chat opt-out.

* fix(responses): ask the target for its auto summary level on the chat bridge and reasoning_effort

* test(integration): run the Mantle region-prefixed v1 base case again

This PR routes that deployment by its own chat pin, so the case passes and no longer needs the skip

* fix(bedrock_mantle): keep web search and reasoning summaries on the Responses API under a chat pin

A chat-pinned Mantle GPT-5 deployment now sends web_search_options and a dict reasoning_effort carrying a summary to the Responses API, which serves them. Mantle Chat Completions drops n above 1 and a reasoning summary under drop_params and answers 400 without it. The /v1/messages adapter probes the bridge with only the client's own summary, so an auto-injected one never moves the request

* fix(bedrock_mantle): check n and reasoning summaries only on the Chat Completions request

* fix(router): keep a non-string deployment mode off the shared routing row

A deployment whose model_info.mode was an int, a list, or an object still
reached the shared cost-map row, so an unpinned sibling on the same backend
stopped routing to the Responses API. The shared registration now drops a
mode that is not a string, and the deployment keeps its own raw value.

Adds integration cells for per-deployment routing across the OpenAI and
Anthropic SDKs, raw httpx, wildcard routes, malformed modes, an upstream
outage, config changes under traffic, and a worker kill plus restart.

* test(integration): find each routing cell's spend row by the response it logged

A bridged call logs its row under the wrapped Responses id, which the caller never sees on a streamed Messages answer, so look the row up by the answer's own ids and the upstream ids for its marker. Int and list modes 500 their own model group on main too, so those cells check only the sibling, and the summary cell sends the auto level Mantle's Responses path accepts

* fix(bedrock_mantle): run extra_body fields through the chat checks

A chat-pinned Mantle request that nests n or reasoning_effort in
extra_body now gets the same 400, drop, and effort-level handling as
the top-level fields. The bridge test injects a MockTransport client
instead of patching HTTPHandler.post.

* test(router): cover nested reasoning_effort routing, messages thinking summaries and per-target auto summary levels

* fix(router): probe a pinned deployment's own API on /health and keep a requested summary beside an extra_body effort

* fix(router): keep a custom-priced deployment's mode pin off the shared backend row on each request

* fix(router): run per-request custom pricing through the shared mode guard so a health probe keeps the row's mode

* fix(router): drop the debug log that wrote a request's model name from keep_registered_mode

* test(router): cover custom-priced chat pins, their health probes and summary aliases beside an extra_body effort

* fix(proxy): pass only the mode pin to a /health probe so a failing probe never cools its deployment down

* test(router): cover failing health probes leaving their deployment out of cooldown, with and without background checks

* test(router): kill the worker that holds burst calls, so the worker kill cell never depends on how the kernel spread them

* fix(router): route a fine-tune the same whichever deployment registers first

Main's register_model now seeds an unmapped fine-tune's row from its base
model's built-in row, mode included, on the first registration. The mode
guard read only the live row, so a responses pin marked the shared row only
when it registered before its siblings. The guard now reads the row the
registration merges onto, the live row or else the row it would seed.

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-17 21:39:14 +00:00

232 lines
8.6 KiB
Python

"""
Test automatic routing to xAI Responses API when tools are present
"""
import json
from collections.abc import Mapping
from typing import Final, cast
from unittest.mock import MagicMock, patch
import httpx
import pytest
import litellm
from litellm.llms.custom_httpx.http_handler import HTTPHandler
from litellm.main import responses_api_bridge_check
from litellm.types.llms.openai import OpenAIWebSearchOptions
class _RecordingResponsesHandler:
"""MockTransport handler that serves a canned /responses reply and keeps the body xAI would have received"""
def __init__(self, reply: Mapping[str, object]) -> None:
self.reply: Final = reply
self.request_body: Mapping[str, object] | None = None
def __call__(self, request: httpx.Request) -> httpx.Response:
self.request_body = json.loads(request.content)
return httpx.Response(200, json=dict(self.reply), request=request)
class TestXAIResponsesAutoRouting:
"""Test that xAI requests with tools automatically route to Responses API"""
def test_responses_api_bridge_check_without_tools(self):
"""Test that without tools, xAI uses chat mode"""
model = "grok-3"
custom_llm_provider = "xai"
tools = None
web_search_options = None
model_info, updated_model = responses_api_bridge_check(
model=model,
custom_llm_provider=custom_llm_provider,
web_search_options=web_search_options,
)
# Should not auto-route to responses mode without tools
assert model_info.get("mode") != "responses"
assert updated_model == model
def test_responses_api_bridge_check_with_empty_tools(self):
"""Test that with empty tools list, xAI does not route to Responses API"""
model = "grok-3"
custom_llm_provider = "xai"
tools = []
web_search_options = None
model_info, updated_model = responses_api_bridge_check(
model=model,
custom_llm_provider=custom_llm_provider,
web_search_options=web_search_options,
)
# Should not auto-route with empty tools list
assert model_info.get("mode") != "responses"
assert updated_model == model
def test_responses_api_bridge_check_non_xai_provider_with_tools(self):
"""Test that non-xAI providers don't get auto-routed"""
model = "gpt-4"
custom_llm_provider = "openai"
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the weather",
},
}
]
web_search_options = None
model_info, updated_model = responses_api_bridge_check(
model=model,
custom_llm_provider=custom_llm_provider,
web_search_options=web_search_options,
)
# Should not auto-route non-xAI providers
assert model_info.get("mode") != "responses"
assert updated_model == model
def test_responses_api_bridge_check_with_responses_prefix(self):
"""Test that responses/ prefix still works"""
model = "responses/grok-3"
custom_llm_provider = "xai"
tools = None
web_search_options = None
model_info, updated_model = responses_api_bridge_check(
model=model,
custom_llm_provider=custom_llm_provider,
web_search_options=web_search_options,
)
# Should route to responses mode with prefix, even without tools
assert model_info.get("mode") == "responses"
assert updated_model == "grok-3" # prefix removed
def test_responses_api_bridge_check_with_web_search_options(self):
"""Test auto-routing with web_search_options"""
model = "grok-4-1-fast"
custom_llm_provider = "xai"
tools = None
web_search_options = {} # Empty dict should trigger routing
model_info, updated_model = responses_api_bridge_check(
model=model,
custom_llm_provider=custom_llm_provider,
web_search_options=cast(OpenAIWebSearchOptions | None, web_search_options),
)
# Should auto-route with web_search_options
assert model_info.get("mode") == "responses"
assert updated_model == model
def test_responses_api_bridge_check_with_web_search_options_and_tools(self):
"""Test auto-routing with both web_search_options and tools"""
model = "grok-4"
custom_llm_provider = "xai"
tools = [{"type": "code_interpreter"}]
web_search_options = {"enabled": True}
model_info, updated_model = responses_api_bridge_check(
model=model,
custom_llm_provider=custom_llm_provider,
web_search_options=cast(OpenAIWebSearchOptions | None, web_search_options),
)
# Should auto-route with both present
assert model_info.get("mode") == "responses"
assert updated_model == model
def test_responses_api_bridge_check_with_web_search_options_on_unmapped_model(self):
"""web search must reach /responses even for a model missing from the cost map, chat returns 410"""
model_info, updated_model = responses_api_bridge_check(
model="grok-not-in-cost-map",
custom_llm_provider="xai",
web_search_options={"search_context_size": "medium"},
)
assert model_info.get("mode") == "responses"
assert updated_model == "grok-not-in-cost-map"
@patch("litellm.completion_extras.responses_api_bridge.completion")
def test_completion_with_tools_routes_to_responses_api(self, mock_responses_completion):
"""Test that completion() with tools routes to Responses API"""
# Mock the responses_api_bridge.completion to avoid actual API calls
mock_responses_completion.return_value = MagicMock()
model = "xai/grok-3"
messages = [{"role": "user", "content": "What's the weather?"}]
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather info",
"parameters": {
"type": "object",
"properties": {"location": {"type": "string"}},
},
},
}
]
try:
litellm.completion(
model=model,
messages=messages,
tools=tools,
mock_response="This is a test", # Use mock mode to avoid API calls
)
except Exception:
# It's ok if this fails, we just want to verify the routing logic
pass
# The mock should have been called, indicating responses API was used
# Note: This test may need adjustment based on actual mock_response behavior
# The key is that the responses_api_bridge_check logic routes correctly
def test_system_message_survives_web_search_bridge(self):
"""A system message becomes 'instructions' on the bridged /responses call, and xAI accepts it"""
handler: Final = _RecordingResponsesHandler(
reply={
"id": "resp_test",
"object": "response",
"created_at": 0,
"status": "completed",
"model": "grok-4.6",
"output": [
{
"type": "message",
"id": "msg_test",
"status": "completed",
"role": "assistant",
"content": [{"type": "output_text", "text": "1.0.0", "annotations": []}],
}
],
"usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2},
}
)
response: Final = litellm.completion(
model="xai/grok-4.6",
messages=[
{"role": "system", "content": "Answer briefly."},
{"role": "user", "content": "newest litellm version?"},
],
web_search_options={"search_context_size": "medium"},
api_key="fake-key",
client=HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(handler))),
)
assert response.choices[0].message.content == "1.0.0"
assert handler.request_body is not None
assert handler.request_body["instructions"] == "Answer briefly."
assert handler.request_body["tools"] == [{"type": "web_search"}]
if __name__ == "__main__":
pytest.main([__file__, "-v"])