litellm/tests/unit/test_tool_loop.py
Mateo Wang 9fb29c7e38
fix(tool_choice): accept the Responses API's flat allowed_tools layout on chat completions (#50467)
* fix(tool_choice): accept the Responses API's flat allowed_tools layout on chat completions

An allowed_tools tool_choice in the flat Responses layout ({"type": "allowed_tools", "mode": ..., "tools": [...]})
answered 400 on litellm.completion, acompletion, Router and the proxy's chat and /v1/responses-to-chat routes. One
parser now reads both layouts into the nested Chat layout, and the existing Responses bridge flattens it back for
/v1/responses, so either layout reaches OpenAI in the shape each endpoint expects

* fix(tool_choice): drop an allowed_tools choice under drop_params and refuse conflicting flat entries

An allowed_tools tool_choice a provider can't enforce, or a malformed one, now drops under drop_params and answers 400 without it, the same rule LiteLLM uses for other unsupported values. That covers providers outside OpenAI and Azure, malformed choices on every provider, and Azure api versions older than 2023-12-01

A flat allowed_tools entry that carries both name and a nested function or custom key answers 400, since the two names can disagree, matching what flattening already refuses

* fix(tool-choice): keep the 400 when LiteLLM runs the tools, report auto after a drop

Under drop_params an allowed_tools choice a provider can't enforce was dropped, so on MCP gateway tools and in
run_tool_loop and arun_tool_loop LiteLLM could run a tool the allow list excluded. Those paths now keep the 400 they
answered before the flat layout was accepted, and a malformed choice stays a 400 on MCP gateway tools.

/v1/responses served through chat echoed a choice it had dropped, on sync, async and streamed responses. It now
reports auto, and a choice the provider received is still echoed as sent.

* fix(tool-choice): refuse an excluded tool right before LiteLLM runs it

Checking the provider up front missed a model alias, an old Azure api_version,
a litellm_proxy hop, and SDK fallbacks. The tool loop and the MCP gateway now
check the allowed_tools list right before they run a tool call, so an excluded
call answers 400 and never runs.

Under drop_params the choice now drops only when the caller runs every tool,
so a provider-run MCP server or built-in keeps the 400. The Azure checks read
the request's api_version, which also fixes the /v1/responses echo there.

* fix(tool-choice): drop the choice under drop_params and hand an excluded MCP call back unrun

The drop now applies to every provider that cannot take an allowed_tools
tool_choice, whatever the request's tools hold. LiteLLM never runs a call the
choice excludes: on MCP paths the whole round goes back to the caller in a 200,
the same shape as require_approval, and the tool loop keeps its 400 because it
only returns final content. A malformed choice stays a 400 before any request
on the tool loop and on chat with MCP gateway tools.

* fix(tool-choice): refuse an allowed_tools entry whose name is not a string

An mcp or other non-function entry with a list or dict name passed the
parser and crashed when the allow list was hashed. The parser now treats
it as malformed on both layouts, so it answers the same 400 as an empty
allow list, or drops under drop_params.

* fix(tool-choice): honor server-level and null-name mcp entries and stop hooks running excluded calls

* fix(tool-choice): match named mcp entries by server label and let built-in entries allow their interception call

* fix(tool-choice): leave a malformed allowed_tools choice unrewritten in the interception hooks

* fix(tool-choice): resolve mcp entries like the gateway and keep the choice on every hook path

Under drop_params a malformed allowed_tools choice now acts as if it was never sent, and only a choice that parses is stored and enforced. Without drop_params it answers 400 before any provider request, on /v1/responses with gateway tools before MCP listing

An mcp entry resolves its label the way the gateway picks servers to list (server name in any case, alias, access group, toolset), and a named entry matches the tool's own name or the gateway's prefixed name. The gateway rewrites mcp entries into function entries in the caller's layout and sends "none" when nothing is left

The web search follow-up keeps an allowed_tools choice, compression's litellm_content_retrieve is never excluded and joins the provider-facing choice, and the native /v1/responses hook loop applies the exclusion check and stores the choice

* fix(allowed_tools): stop web search and code interpreter follow-ups forcing another call

A kept allowed_tools choice now goes to the follow-up in mode auto, so a
required choice no longer loops to the agentic loop limit. The MCP label
scope dataclass uses a default_factory so the module imports on Python 3.11

* fix(allowed_tools): stop the Responses web search follow-up forcing another call

The Responses-shaped follow-up after a web search left tool_choice out of its patch, so the caller's required choice went out again through the chat to Responses bridge and looped to the loop limit. It now carries a kept allowed_tools choice in mode auto, like the chat follow-up

* fix(mcp): scope each MCP entry to its own allowed_tools and keep the allowlist on follow-ups

A label now covers only the tools its own allowed_tools lists, so a second label on the same server no longer widens it. Responses MCP follow-ups, streamed or not, keep an allowed_tools choice in auto mode instead of dropping it. The new Responses tests fake only the upstream MCP listing, so LiteLLM's own discovery runs

* fix(mcp): match an entry's allowed_tools against the tool name the gateway lists

A server with a display name override lists the display name, and the listing
filter matches allowed_tools against it, but the label scope only checked the
original name, so no spelling worked. The scope now also accepts the listed
name and its unprefixed part, like the listing filter. Tests now cover the
whole gateway and toolset entries and a display-named tool.

* fix(mcp): match an entry's allowed_tools only against a server's own prefix, not the first hyphen

* fix(mcp): match a tool no server resolves only by its exact listed name in an entry's allowed_tools

* fix(mcp): refuse a tool whose display name only looks like an allowed name, and let the chat follow-up answer

An MCP entry's allowed_tools now matches a tool only by its exact listed name or a spelling routing
accepts for its real name, so a display name that carries the server's own prefix no longer passes for
another tool. The chat MCP follow-up keeps an allowed_tools choice in auto mode, so the model can answer
with text after the tool ran.

* fix(mcp): match a toolset label's tools by exact native name

A toolset label served any tool whose name a routing spelling of a granted name matched, so a toolset granting the literal name "server-tool" also served the real tool "tool" that only another toolset grants. It now serves a tool only when the toolset grants its exact native name, the same check tool_is_granted uses when the gateway lists tools
2026-11-10 13:04:06 -08:00

887 lines
31 KiB
Python

import json
from typing import Final
import httpx
import pytest
import respx
import litellm
from litellm.tool_loop import ToolLoopMaxRoundsExceeded
from litellm.types.llms.openai import ChatCompletionToolMessage
from litellm.types.utils import ChatCompletionMessageToolCall
OPENAI_CHAT_COMPLETIONS_URL: Final = "https://api.openai.com/v1/chat/completions"
ANTHROPIC_MESSAGES_URL: Final = "https://api.anthropic.com/v1/messages"
WEATHER_TOOLS: Final = (
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
},
)
def _openai_response(content: str | None, tool_calls: list | None = None, **message_fields: object) -> dict:
return {
"id": "chatcmpl-tool-loop",
"object": "chat.completion",
"created": 1739462947,
"model": "gpt-5-mini",
"choices": [
{
"index": 0,
"finish_reason": "tool_calls" if tool_calls else "stop",
"message": {
"role": "assistant",
"content": content,
"tool_calls": tool_calls,
**message_fields,
},
}
],
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
}
def _tool_call(call_id: str, name: str, arguments: dict) -> dict:
return {
"id": call_id,
"type": "function",
"function": {"name": name, "arguments": json.dumps(arguments)},
}
def _tool_result(tool_call: ChatCompletionMessageToolCall) -> ChatCompletionToolMessage:
return ChatCompletionToolMessage(role="tool", content='{"temp": "72F"}', tool_call_id=tool_call.id or "")
def _request_bodies(respx_mock: respx.MockRouter) -> list[dict]:
return [json.loads(call.request.content) for call in respx_mock.calls]
def test_final_answer_without_tool_calls_returns_content(respx_mock: respx.MockRouter) -> None:
route: Final = respx_mock.post(OPENAI_CHAT_COMPLETIONS_URL).mock(
return_value=httpx.Response(200, json=_openai_response("done"))
)
executor_called: Final = []
def executor(tc: ChatCompletionMessageToolCall) -> ChatCompletionToolMessage:
executor_called.append(tc)
return _tool_result(tc)
answer: Final = litellm.run_tool_loop(
model="openai/gpt-5-mini",
messages=[{"role": "user", "content": "hi"}],
tools=WEATHER_TOOLS,
execute_tool=executor,
api_key="sk-test",
)
assert answer == "done"
assert executor_called == []
assert route.call_count == 1
def test_two_rounds_appends_assistant_and_tool_messages_in_order(respx_mock: respx.MockRouter) -> None:
tool_calls: Final = [
_tool_call("call_1", "get_weather", {"city": "Paris"}),
_tool_call("call_2", "get_weather", {"city": "Tokyo"}),
]
route: Final = respx_mock.post(OPENAI_CHAT_COMPLETIONS_URL).mock(
side_effect=[
httpx.Response(200, json=_openai_response(None, tool_calls)),
httpx.Response(200, json=_openai_response("Paris 72F, Tokyo 60F")),
]
)
executed: Final = []
def executor(tc: ChatCompletionMessageToolCall) -> ChatCompletionToolMessage:
executed.append(tc)
return _tool_result(tc)
messages: Final = [{"role": "user", "content": "weather in Paris and Tokyo?"}]
messages_snapshot: Final = [dict(message) for message in messages]
answer: Final = litellm.run_tool_loop(
model="openai/gpt-5-mini",
messages=messages,
tools=WEATHER_TOOLS,
execute_tool=executor,
api_key="sk-test",
)
assert answer == "Paris 72F, Tokyo 60F"
assert route.call_count == 2
assert [tc.id for tc in executed] == ["call_1", "call_2"]
assert [tc.function.name for tc in executed] == ["get_weather", "get_weather"]
assert [tc.function.arguments for tc in executed] == [
'{"city": "Paris"}',
'{"city": "Tokyo"}',
]
second_body: Final = _request_bodies(respx_mock)[1]
assert second_body["messages"] == [
{"role": "user", "content": "weather in Paris and Tokyo?"},
{
"role": "assistant",
"tool_calls": [
{
"id": "call_1",
"type": "function",
"function": {"name": "get_weather", "arguments": '{"city": "Paris"}'},
},
{
"id": "call_2",
"type": "function",
"function": {"name": "get_weather", "arguments": '{"city": "Tokyo"}'},
},
],
},
{"role": "tool", "content": '{"temp": "72F"}', "tool_call_id": "call_1"},
{"role": "tool", "content": '{"temp": "72F"}', "tool_call_id": "call_2"},
]
assert len(messages) == len(messages_snapshot)
assert messages == messages_snapshot
def test_response_format_and_tools_forwarded_every_round(respx_mock: respx.MockRouter) -> None:
respx_mock.post(OPENAI_CHAT_COMPLETIONS_URL).mock(
side_effect=[
httpx.Response(200, json=_openai_response(None, [_tool_call("call_1", "get_weather", {"city": "Paris"})])),
httpx.Response(200, json=_openai_response('{"summary": "sunny"}')),
]
)
response_format: Final = {
"type": "json_schema",
"json_schema": {
"name": "weather_report",
"schema": {
"type": "object",
"properties": {"summary": {"type": "string"}},
"required": ["summary"],
},
},
}
litellm.run_tool_loop(
model="openai/gpt-5-mini",
messages=[{"role": "user", "content": "weather?"}],
tools=WEATHER_TOOLS,
execute_tool=_tool_result,
response_format=response_format,
api_key="sk-test",
)
bodies: Final = _request_bodies(respx_mock)
assert len(bodies) == 2
for body in bodies:
assert body["response_format"] == response_format
assert body["tools"] == list(WEATHER_TOOLS)
def test_max_rounds_exceeded_raises_without_executing_last_round(respx_mock: respx.MockRouter) -> None:
tool_call: Final = _tool_call("call_1", "get_weather", {"city": "Paris"})
route: Final = respx_mock.post(OPENAI_CHAT_COMPLETIONS_URL).mock(
return_value=httpx.Response(200, json=_openai_response(None, [tool_call]))
)
executed: Final = []
def executor(tc: ChatCompletionMessageToolCall) -> ChatCompletionToolMessage:
executed.append(tc)
return _tool_result(tc)
with pytest.raises(ToolLoopMaxRoundsExceeded) as exc_info:
litellm.run_tool_loop(
model="openai/gpt-5-mini",
messages=[{"role": "user", "content": "weather?"}],
tools=WEATHER_TOOLS,
execute_tool=executor,
max_rounds=2,
api_key="sk-test",
)
assert exc_info.value.max_rounds == 2
assert route.call_count == 2
assert [tc.id for tc in executed] == ["call_1"]
def test_max_rounds_below_one_rejected_before_any_request(respx_mock: respx.MockRouter) -> None:
route: Final = respx_mock.post(OPENAI_CHAT_COMPLETIONS_URL).mock(
return_value=httpx.Response(200, json=_openai_response("done"))
)
with pytest.raises(ValueError, match="max_rounds must be >= 1"):
litellm.run_tool_loop(
model="openai/gpt-5-mini",
messages=[{"role": "user", "content": "hi"}],
tools=WEATHER_TOOLS,
execute_tool=_tool_result,
max_rounds=0,
api_key="sk-test",
)
assert route.call_count == 0
def test_stream_rejected_before_any_request(respx_mock: respx.MockRouter) -> None:
route: Final = respx_mock.post(OPENAI_CHAT_COMPLETIONS_URL).mock(
return_value=httpx.Response(200, json=_openai_response("done"))
)
with pytest.raises(ValueError, match="stream=True is not supported"):
litellm.run_tool_loop(
model="openai/gpt-5-mini",
messages=[{"role": "user", "content": "hi"}],
tools=WEATHER_TOOLS,
execute_tool=_tool_result,
stream=True,
api_key="sk-test",
)
assert route.call_count == 0
_ALLOWED_WEATHER_ONLY: Final = {
"type": "allowed_tools",
"mode": "auto",
"tools": [{"type": "function", "name": "get_weather"}],
}
_EMPTY_ALLOWED_TOOLS: Final = {"type": "allowed_tools", "mode": "auto", "tools": []}
_TIME_CALL: Final = _tool_call("call_1", "get_time", {})
def _anthropic_message(*content: dict[str, object]) -> httpx.Response:
return httpx.Response(
200,
json={
"id": "msg_tool_loop",
"type": "message",
"role": "assistant",
"model": "claude-haiku-4-5",
"content": list(content),
"stop_reason": "tool_use" if content[0]["type"] == "tool_use" else "end_turn",
"usage": {"input_tokens": 10, "output_tokens": 5},
},
)
def _anthropic_tool_use(name: str) -> httpx.Response:
return _anthropic_message({"type": "tool_use", "id": "toolu_1", "name": name, "input": {}})
def _tools_run_before_the_refusal(
tool_choice: dict[str, object], **completion_kwargs: object
) -> list[ChatCompletionMessageToolCall]:
executed: Final[list[ChatCompletionMessageToolCall]] = []
def execute(tool_call: ChatCompletionMessageToolCall) -> ChatCompletionToolMessage:
executed.append(tool_call)
return _tool_result(tool_call)
with pytest.raises(litellm.BadRequestError, match="LiteLLM did not run the call"):
litellm.run_tool_loop(
messages=[{"role": "user", "content": "hi"}],
tools=WEATHER_TOOLS,
execute_tool=execute,
tool_choice=tool_choice,
api_key="sk-test",
**completion_kwargs,
)
return executed
def test_a_tool_the_dropped_choice_excludes_never_runs(respx_mock: respx.MockRouter) -> None:
respx_mock.post(ANTHROPIC_MESSAGES_URL).mock(return_value=_anthropic_tool_use("get_time"))
assert not _tools_run_before_the_refusal(
_ALLOWED_WEATHER_ONLY, model="anthropic/claude-haiku-4-5", drop_params=True
)
assert "tool_choice" not in _request_bodies(respx_mock)[0]
def test_a_tool_the_dropped_choice_lists_still_runs(respx_mock: respx.MockRouter) -> None:
respx_mock.post(ANTHROPIC_MESSAGES_URL).mock(
side_effect=[_anthropic_tool_use("get_weather"), _anthropic_message({"type": "text", "text": "done"})]
)
assert (
litellm.run_tool_loop(
model="anthropic/claude-haiku-4-5",
messages=[{"role": "user", "content": "hi"}],
tools=WEATHER_TOOLS,
execute_tool=_tool_result,
tool_choice=_ALLOWED_WEATHER_ONLY,
drop_params=True,
api_key="sk-test",
)
== "done"
)
def test_a_tool_the_choice_excludes_never_runs_when_the_model_ignored_the_choice(
respx_mock: respx.MockRouter,
) -> None:
respx_mock.post(OPENAI_CHAT_COMPLETIONS_URL).mock(
return_value=httpx.Response(200, json=_openai_response(None, [_TIME_CALL]))
)
assert not _tools_run_before_the_refusal(_ALLOWED_WEATHER_ONLY, model="openai/gpt-5-mini")
@pytest.mark.parametrize(
"tool_choice",
[_EMPTY_ALLOWED_TOOLS, {"type": "allowed_tools", "mode": "auto", "tools": [{"type": "mcp", "name": ["get_time"]}]}],
)
def test_a_malformed_choice_is_refused_before_any_request(
tool_choice: dict[str, object], respx_mock: respx.MockRouter
) -> None:
with pytest.raises(litellm.BadRequestError, match="Invalid tool choice"):
litellm.run_tool_loop(
model="openai/gpt-5-mini",
messages=[{"role": "user", "content": "hi"}],
tools=WEATHER_TOOLS,
execute_tool=_tool_result,
tool_choice=tool_choice,
api_key="sk-test",
)
assert not respx_mock.calls
@pytest.mark.parametrize(
"tool_choice",
[_EMPTY_ALLOWED_TOOLS, {"type": "allowed_tools", "mode": "auto", "tools": [{"type": "mcp", "name": ["get_time"]}]}],
)
def test_a_malformed_choice_under_drop_params_runs_the_loop_as_if_never_sent(
tool_choice: dict[str, object], respx_mock: respx.MockRouter
) -> None:
respx_mock.post(OPENAI_CHAT_COMPLETIONS_URL).mock(
side_effect=[
httpx.Response(200, json=_openai_response(None, [_TIME_CALL])),
httpx.Response(200, json=_openai_response("done")),
]
)
executed: Final[list[str | None]] = []
def execute(tool_call: ChatCompletionMessageToolCall) -> ChatCompletionToolMessage:
executed.append(tool_call.function.name)
return _tool_result(tool_call)
answer: Final = litellm.run_tool_loop(
model="openai/gpt-5-mini",
messages=[{"role": "user", "content": "hi"}],
tools=WEATHER_TOOLS,
execute_tool=execute,
tool_choice=tool_choice,
drop_params=True,
api_key="sk-test",
)
assert (answer, executed) == ("done", ["get_time"])
assert all("tool_choice" not in body for body in _request_bodies(respx_mock))
def test_a_choice_on_a_model_alias_reaches_the_loop(
respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(litellm, "model_alias_map", {"the-alias": "openai/gpt-5-mini"})
respx_mock.post(OPENAI_CHAT_COMPLETIONS_URL).mock(
return_value=httpx.Response(200, json=_openai_response("done"))
)
assert (
litellm.run_tool_loop(
model="the-alias",
messages=[{"role": "user", "content": "hi"}],
tools=WEATHER_TOOLS,
execute_tool=_tool_result,
tool_choice=_ALLOWED_WEATHER_ONLY,
api_key="sk-test",
)
== "done"
)
@pytest.mark.asyncio
async def test_async_loop_never_runs_a_tool_the_choice_excludes(
respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
) -> None:
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
monkeypatch.setattr(litellm, "module_level_aclient", AsyncHTTPHandler())
respx_mock.post(OPENAI_CHAT_COMPLETIONS_URL).mock(
return_value=httpx.Response(200, json=_openai_response(None, [_TIME_CALL]))
)
executed: Final[list[ChatCompletionMessageToolCall]] = []
async def execute(tool_call: ChatCompletionMessageToolCall) -> ChatCompletionToolMessage:
executed.append(tool_call)
return _tool_result(tool_call)
with pytest.raises(litellm.BadRequestError, match="LiteLLM did not run the call"):
await litellm.arun_tool_loop(
model="openai/gpt-5-mini",
messages=[{"role": "user", "content": "hi"}],
tools=WEATHER_TOOLS,
execute_tool=execute,
tool_choice=_ALLOWED_WEATHER_ONLY,
drop_params=True,
api_key="sk-test",
)
assert not executed
def test_allowed_tools_choice_the_provider_enforces_reaches_it_every_round(respx_mock: respx.MockRouter) -> None:
respx_mock.post(OPENAI_CHAT_COMPLETIONS_URL).mock(
side_effect=[
httpx.Response(200, json=_openai_response(None, [_tool_call("call_1", "get_weather", {"city": "Paris"})])),
httpx.Response(200, json=_openai_response("done")),
]
)
answer: Final = litellm.run_tool_loop(
model="openai/gpt-5-mini",
messages=[{"role": "user", "content": "hi"}],
tools=WEATHER_TOOLS,
execute_tool=_tool_result,
tool_choice={"type": "allowed_tools", "mode": "auto", "tools": [{"type": "function", "name": "get_weather"}]},
api_key="sk-test",
)
assert answer == "done"
assert [body["tool_choice"]["type"] for body in _request_bodies(respx_mock)] == ["allowed_tools", "allowed_tools"]
def test_custom_tool_call_raises_type_error_without_executing(respx_mock: respx.MockRouter) -> None:
custom_response: Final = _openai_response(
None,
[{"id": "call_custom", "type": "custom", "custom": {"name": "apply_patch", "input": "*** patch"}}],
)
route: Final = respx_mock.post(OPENAI_CHAT_COMPLETIONS_URL).mock(
return_value=httpx.Response(200, json=custom_response)
)
executor_called: Final = []
def executor(tc: ChatCompletionMessageToolCall) -> ChatCompletionToolMessage:
executor_called.append(tc)
return _tool_result(tc)
with pytest.raises(TypeError, match="custom tool call call_custom"):
litellm.run_tool_loop(
model="openai/gpt-5-mini",
messages=[{"role": "user", "content": "hi"}],
tools=WEATHER_TOOLS,
execute_tool=executor,
api_key="sk-test",
)
assert executor_called == []
assert route.call_count == 1
def _responses_payload(response_id: str, output: list) -> dict:
return {
"id": response_id,
"object": "response",
"created_at": 1734366691,
"status": "completed",
"model": "gpt-5.5",
"output": output,
"parallel_tool_calls": True,
"usage": {"input_tokens": 10, "output_tokens": 5, "total_tokens": 15},
"error": None,
"incomplete_details": None,
"instructions": None,
"metadata": None,
"temperature": None,
"tool_choice": "auto",
"tools": [],
"top_p": None,
"max_output_tokens": None,
"previous_response_id": None,
"reasoning": None,
"truncation": None,
"user": None,
}
def test_responses_bridge_replays_reasoning_items_across_rounds(respx_mock: respx.MockRouter) -> None:
round_one: Final = _responses_payload(
"resp_1",
[
{"type": "reasoning", "id": "rs_abc123", "summary": [], "encrypted_content": "enc_xyz"},
{
"type": "function_call",
"id": "fc_1",
"call_id": "call_1",
"name": "get_weather",
"arguments": '{"city": "Paris"}',
"status": "completed",
},
],
)
round_two: Final = _responses_payload(
"resp_2",
[
{
"type": "message",
"id": "msg_1",
"status": "completed",
"role": "assistant",
"content": [{"type": "output_text", "text": "Paris is 72F", "annotations": []}],
}
],
)
route: Final = respx_mock.post("https://api.openai.com/v1/responses").mock(
side_effect=[httpx.Response(200, json=round_one), httpx.Response(200, json=round_two)]
)
executed: Final = []
def executor(tc: ChatCompletionMessageToolCall) -> ChatCompletionToolMessage:
executed.append(tc)
return _tool_result(tc)
answer: Final = litellm.run_tool_loop(
model="openai/responses/gpt-5.5",
messages=[{"role": "user", "content": "weather in Paris?"}],
tools=WEATHER_TOOLS,
execute_tool=executor,
api_key="sk-test",
)
assert answer == "Paris is 72F"
assert route.call_count == 2
assert [tc.id for tc in executed] == ["fc_1"]
second_input: Final = _request_bodies(respx_mock)[1]["input"]
item_types: Final = [item.get("type") for item in second_input]
reasoning_index: Final = next(i for i, item in enumerate(second_input) if item.get("type") == "reasoning")
function_call_index: Final = next(
i for i, item in enumerate(second_input) if item.get("type") == "function_call"
)
reasoning_item: Final = second_input[reasoning_index]
assert reasoning_item["id"] == "rs_abc123"
assert reasoning_item["encrypted_content"] == "enc_xyz"
assert reasoning_index < function_call_index, f"reasoning item must precede function_call: {item_types}"
def test_responses_bridge_replays_tool_search_items_across_rounds(respx_mock: respx.MockRouter) -> None:
round_one: Final = _responses_payload(
"resp_1",
[
{"type": "reasoning", "id": "rs_1", "summary": [], "encrypted_content": "enc_1"},
{"type": "tool_search_call", "id": "tsc_1", "execution": "server", "arguments": {"paths": ["weather"]}},
{
"type": "tool_search_output",
"id": "tso_1",
"execution": "server",
"tools": [{"type": "namespace", "name": "weather", "tools": [{"type": "function", "name": "get_weather"}]}],
},
{
"type": "function_call",
"id": "fc_1",
"call_id": "call_1",
"name": "get_weather",
"namespace": "weather",
"arguments": '{"city": "Paris"}',
"status": "completed",
},
],
)
round_two: Final = _responses_payload(
"resp_2",
[
{
"type": "message",
"id": "msg_1",
"status": "completed",
"role": "assistant",
"content": [{"type": "output_text", "text": "Paris is 72F", "annotations": []}],
}
],
)
respx_mock.post("https://api.openai.com/v1/responses").mock(
side_effect=[httpx.Response(200, json=round_one), httpx.Response(200, json=round_two)]
)
litellm.run_tool_loop(
model="openai/responses/gpt-5.5",
messages=[{"role": "user", "content": "weather in Paris?"}],
tools=({"type": "tool_search"}, *WEATHER_TOOLS),
execute_tool=_tool_result,
api_key="sk-test",
)
second_input: Final = _request_bodies(respx_mock)[1]["input"]
replayed: Final = [
(item["type"], item.get("id"), item.get("namespace")) for item in second_input if item["type"] != "message"
]
assert replayed == [
("reasoning", "rs_1", None),
("tool_search_call", "tsc_1", None),
("tool_search_output", "tso_1", None),
("function_call", None, "weather"),
("function_call_output", None, None),
]
async def test_arun_tool_loop_two_rounds(respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch) -> None:
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
monkeypatch.setattr(litellm, "module_level_aclient", AsyncHTTPHandler())
tool_calls: Final = [
_tool_call("call_1", "get_weather", {"city": "Paris"}),
_tool_call("call_2", "get_weather", {"city": "Tokyo"}),
]
route: Final = respx_mock.post(OPENAI_CHAT_COMPLETIONS_URL).mock(
side_effect=[
httpx.Response(200, json=_openai_response(None, tool_calls)),
httpx.Response(200, json=_openai_response("Paris 72F, Tokyo 60F")),
]
)
executed: Final = []
async def executor(tc: ChatCompletionMessageToolCall) -> ChatCompletionToolMessage:
executed.append(tc)
return _tool_result(tc)
messages: Final = [{"role": "user", "content": "weather in Paris and Tokyo?"}]
messages_snapshot: Final = [dict(message) for message in messages]
answer: Final = await litellm.arun_tool_loop(
model="openai/gpt-5-mini",
messages=messages,
tools=WEATHER_TOOLS,
execute_tool=executor,
api_key="sk-test",
)
assert answer == "Paris 72F, Tokyo 60F"
assert route.call_count == 2
assert [tc.id for tc in executed] == ["call_1", "call_2"]
second_body: Final = _request_bodies(respx_mock)[1]
assert second_body["messages"] == [
{"role": "user", "content": "weather in Paris and Tokyo?"},
{
"role": "assistant",
"tool_calls": [
{
"id": "call_1",
"type": "function",
"function": {"name": "get_weather", "arguments": '{"city": "Paris"}'},
},
{
"id": "call_2",
"type": "function",
"function": {"name": "get_weather", "arguments": '{"city": "Tokyo"}'},
},
],
},
{"role": "tool", "content": '{"temp": "72F"}', "tool_call_id": "call_1"},
{"role": "tool", "content": '{"temp": "72F"}', "tool_call_id": "call_2"},
]
assert messages == messages_snapshot
TOOL_SEARCH_CALL: Final = {
"type": "server_tool_use",
"id": "srvtoolu_01Search",
"name": "tool_search_tool_bm25",
"input": {"query": "weather"},
}
WEATHER_CALL: Final = {"type": "tool_use", "id": "toolu_01Weather", "name": "get_weather", "input": {"city": "Paris"}}
def _tool_search_result(tool_names: list[str]) -> dict:
return {
"type": "tool_search_tool_result",
"tool_use_id": "srvtoolu_01Search",
"content": {
"type": "tool_search_tool_search_result",
"tool_references": [{"type": "tool_reference", "tool_name": name} for name in tool_names],
},
}
def _anthropic_response(content: list[dict], stop_reason: str) -> dict:
return {
"id": "msg_tool_loop",
"type": "message",
"role": "assistant",
"model": "claude-opus-5-5",
"content": content,
"stop_reason": stop_reason,
"stop_sequence": None,
"usage": {"input_tokens": 10, "output_tokens": 5},
}
def test_tool_search_call_is_replayed_with_its_result_instead_of_executed(respx_mock: respx.MockRouter) -> None:
search_turn: Final = [TOOL_SEARCH_CALL, _tool_search_result(["get_weather"]), WEATHER_CALL]
respx_mock.post(ANTHROPIC_MESSAGES_URL).mock(
side_effect=[
httpx.Response(200, json=_anthropic_response(search_turn, "tool_use")),
httpx.Response(200, json=_anthropic_response([{"type": "text", "text": "Paris is 72F"}], "end_turn")),
]
)
executed: Final = []
def executor(tc: ChatCompletionMessageToolCall) -> ChatCompletionToolMessage:
executed.append(tc.function.name)
return _tool_result(tc)
answer: Final = litellm.run_tool_loop(
model="anthropic/claude-opus-5-5",
messages=[{"role": "user", "content": "weather in Paris?"}],
tools=WEATHER_TOOLS,
execute_tool=executor,
api_key="sk-ant-test",
)
assert answer == "Paris is 72F"
assert executed == ["get_weather"]
second_messages: Final = _request_bodies(respx_mock)[1]["messages"]
assert second_messages[1]["content"] == search_turn
assert [block["tool_use_id"] for block in second_messages[2]["content"]] == ["toolu_01Weather"]
async def test_arun_tool_loop_answers_after_a_search_that_found_nothing(
respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
) -> None:
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
monkeypatch.setattr(litellm, "module_level_aclient", AsyncHTTPHandler())
route: Final = respx_mock.post(ANTHROPIC_MESSAGES_URL).mock(
return_value=httpx.Response(
200,
json=_anthropic_response(
[TOOL_SEARCH_CALL, _tool_search_result([]), {"type": "text", "text": "I have no flight tool."}],
"end_turn",
),
)
)
executed: Final = []
async def executor(tc: ChatCompletionMessageToolCall) -> ChatCompletionToolMessage:
executed.append(tc.function.name)
return _tool_result(tc)
answer: Final = await litellm.arun_tool_loop(
model="anthropic/claude-opus-5-5",
messages=[{"role": "user", "content": "book me a flight"}],
tools=WEATHER_TOOLS,
execute_tool=executor,
api_key="sk-ant-test",
)
assert answer == "I have no flight tool."
assert executed == []
assert route.call_count == 1
def test_client_tool_turn_is_replayed_without_its_provider_specific_fields(respx_mock: respx.MockRouter) -> None:
respx_mock.post(OPENAI_CHAT_COMPLETIONS_URL).mock(
side_effect=[
httpx.Response(
200,
json=_openai_response(
None,
[_tool_call("call_1", "get_weather", {"city": "Paris"})],
reasoning_details=[{"type": "reasoning.text", "text": "Check the weather tool"}],
),
),
httpx.Response(200, json=_openai_response("Paris is 72F")),
]
)
answer: Final = litellm.run_tool_loop(
model="openai/gpt-5-mini",
messages=[{"role": "user", "content": "weather in Paris?"}],
tools=WEATHER_TOOLS,
execute_tool=_tool_result,
api_key="sk-test",
)
assert answer == "Paris is 72F"
replayed_assistant: Final = _request_bodies(respx_mock)[1]["messages"][1]
assert replayed_assistant["tool_calls"][0]["id"] == "call_1"
assert "provider_specific_fields" not in replayed_assistant
def test_responses_bridge_replays_commentary_reasoning_and_tool_call_in_order(respx_mock: respx.MockRouter) -> None:
round_one: Final = _responses_payload(
"resp_1",
[
{
"type": "message",
"id": "msg_commentary",
"status": "completed",
"role": "assistant",
"phase": "commentary",
"content": [{"type": "output_text", "text": "Checking Paris.", "annotations": []}],
},
{"type": "reasoning", "id": "rs_abc123", "summary": [], "encrypted_content": "enc_xyz"},
{
"type": "function_call",
"id": "fc_1",
"call_id": "call_weather_paris",
"name": "get_weather",
"arguments": '{"city": "Paris"}',
"status": "completed",
},
],
)
round_two: Final = _responses_payload(
"resp_2",
[
{
"type": "message",
"id": "msg_1",
"status": "completed",
"role": "assistant",
"phase": "final_answer",
"content": [{"type": "output_text", "text": "Paris is 72F", "annotations": []}],
}
],
)
respx_mock.post("https://api.openai.com/v1/responses").mock(
side_effect=[httpx.Response(200, json=round_one), httpx.Response(200, json=round_two)]
)
answer: Final = litellm.run_tool_loop(
model="openai/responses/gpt-5.6",
messages=[{"role": "user", "content": "weather in Paris?"}],
tools=WEATHER_TOOLS,
execute_tool=_tool_result,
api_key="sk-test",
)
assert answer == "Paris is 72F"
assert _request_bodies(respx_mock)[1]["input"][1:] == [
{
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "Checking Paris."}],
"phase": "commentary",
},
{"type": "reasoning", "id": "rs_abc123", "summary": [], "encrypted_content": "enc_xyz"},
{"type": "function_call", "call_id": "call_weather_paris", "name": "get_weather", "arguments": '{"city": "Paris"}'},
{
"type": "function_call_output",
"call_id": "call_weather_paris",
"output": [{"type": "input_text", "text": '{"temp": "72F"}'}],
},
]