From 76488beaf8d1a44e0f07b6a4a66c06b9b4390222 Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Tue, 15 Sep 2026 05:55:25 -0700 Subject: [PATCH 1/2] fix(utils): reject an untranslatable tool_choice with a 400 instead of a 500 --- litellm/main.py | 2 +- litellm/utils.py | 16 +++- tests/litellm_utils_tests/test_utils.py | 6 +- .../test_validate_tool_choice.py | 74 ++++++++++--------- .../test_litellm_completion_responses.py | 15 ++++ tests/test_litellm/test_main.py | 14 ++++ 6 files changed, 85 insertions(+), 42 deletions(-) diff --git a/litellm/main.py b/litellm/main.py index f6f4ec1bf63..9eea6779abf 100644 --- a/litellm/main.py +++ b/litellm/main.py @@ -5102,7 +5102,7 @@ def completion( messages = validate_and_fix_openai_messages(messages=messages) tools = validate_and_fix_openai_tools(tools=tools) # validate tool_choice - tool_choice = validate_chat_completion_tool_choice(tool_choice=tool_choice) + tool_choice = validate_chat_completion_tool_choice(tool_choice=tool_choice, model=model) # validate optional params stop = validate_openai_optional_params(stop=stop) thinking = validate_and_fix_thinking_param(thinking=thinking) diff --git a/litellm/utils.py b/litellm/utils.py index 18df5e2abf7..17088f0475b 100644 --- a/litellm/utils.py +++ b/litellm/utils.py @@ -8038,6 +8038,7 @@ def validate_chat_completion_user_messages(messages: list[AllMessageValues]): def validate_chat_completion_tool_choice( tool_choice: dict | str | None, + model: str, ) -> dict | str | None: """ Confirm the tool choice is passed in the OpenAI format. @@ -8053,12 +8054,19 @@ def validate_chat_completion_tool_choice( # Standard OpenAI format: {"type": "function", "function": {...}} if tool_choice.get("type") is None or tool_choice.get("function") is None: - raise Exception( - f"Invalid tool choice, tool_choice={tool_choice}. Please ensure tool_choice follows the OpenAI spec" + raise BadRequestError( + message=f"Invalid tool choice, tool_choice={tool_choice}. Please ensure tool_choice follows the OpenAI spec", + model=model, + llm_provider="", ) return tool_choice - raise Exception( - f"Invalid tool choice, tool_choice={tool_choice}. Got={type(tool_choice)}. Expecting str, or dict. Please ensure tool_choice follows the OpenAI tool_choice spec" + raise BadRequestError( + message=( + f"Invalid tool choice, tool_choice={tool_choice}. Got={type(tool_choice)}. Expecting str, or dict. " + "Please ensure tool_choice follows the OpenAI tool_choice spec" + ), + model=model, + llm_provider="", ) diff --git a/tests/litellm_utils_tests/test_utils.py b/tests/litellm_utils_tests/test_utils.py index 0ccfae55290..11d089719c6 100644 --- a/tests/litellm_utils_tests/test_utils.py +++ b/tests/litellm_utils_tests/test_utils.py @@ -1334,10 +1334,10 @@ def test_validate_chat_completion_tool_choice(tool_choice, expected_bool): from litellm.utils import validate_chat_completion_tool_choice if expected_bool: - validate_chat_completion_tool_choice(tool_choice=tool_choice) + validate_chat_completion_tool_choice(tool_choice=tool_choice, model="gpt-5.6-sol") else: - with pytest.raises(Exception, match="Invalid tool choice"): - validate_chat_completion_tool_choice(tool_choice=tool_choice) + with pytest.raises(litellm.BadRequestError, match="Invalid tool choice"): + validate_chat_completion_tool_choice(tool_choice=tool_choice, model="gpt-5.6-sol") def test_models_by_provider(): diff --git a/tests/litellm_utils_tests/test_validate_tool_choice.py b/tests/litellm_utils_tests/test_validate_tool_choice.py index b8246fe0deb..b4272af7b90 100644 --- a/tests/litellm_utils_tests/test_validate_tool_choice.py +++ b/tests/litellm_utils_tests/test_validate_tool_choice.py @@ -1,60 +1,66 @@ +import re +from typing import Final + import pytest - +import litellm from litellm.utils import validate_chat_completion_tool_choice +MODEL: Final = "anthropic/claude-haiku-4-5" + def test_validate_tool_choice_none(): """Test that None is returned as-is.""" - result = validate_chat_completion_tool_choice(None) + result = validate_chat_completion_tool_choice(None, model=MODEL) assert result is None def test_validate_tool_choice_string(): """Test that string values are returned as-is.""" - assert validate_chat_completion_tool_choice("auto") == "auto" - assert validate_chat_completion_tool_choice("none") == "none" - assert validate_chat_completion_tool_choice("required") == "required" + assert validate_chat_completion_tool_choice("auto", model=MODEL) == "auto" + assert validate_chat_completion_tool_choice("none", model=MODEL) == "none" + assert validate_chat_completion_tool_choice("required", model=MODEL) == "required" def test_validate_tool_choice_standard_dict(): """Test standard OpenAI format with function.""" tool_choice = {"type": "function", "function": {"name": "my_function"}} - result = validate_chat_completion_tool_choice(tool_choice) + result = validate_chat_completion_tool_choice(tool_choice, model=MODEL) assert result == tool_choice def test_validate_tool_choice_cursor_format(): """Cursor IDE format {"type": "auto"} is unwrapped to the bare string.""" - assert validate_chat_completion_tool_choice({"type": "auto"}) == "auto" - assert validate_chat_completion_tool_choice({"type": "none"}) == "none" - assert validate_chat_completion_tool_choice({"type": "required"}) == "required" + assert validate_chat_completion_tool_choice({"type": "auto"}, model=MODEL) == "auto" + assert validate_chat_completion_tool_choice({"type": "none"}, model=MODEL) == "none" + assert validate_chat_completion_tool_choice({"type": "required"}, model=MODEL) == "required" -def test_validate_tool_choice_invalid_dict(): - """Test that invalid dict formats raise exceptions.""" - # Missing both type and function - with pytest.raises(Exception, match='Invalid tool choice, tool_choice=\\{\\}\\. Please ensure') as exc_info: - validate_chat_completion_tool_choice({}) - assert "Invalid tool choice" in str(exc_info.value) - - # Invalid type value - with pytest.raises(Exception, match="Invalid tool choice, tool_choice=\\{'type': 'invalid'\\}\\.") as exc_info: - validate_chat_completion_tool_choice({"type": "invalid"}) - assert "Invalid tool choice" in str(exc_info.value) - - # Has type but missing function when type is "function" - with pytest.raises(Exception, match="Invalid tool choice, tool_choice=\\{'type': 'function'\\}\\.") as exc_info: - validate_chat_completion_tool_choice({"type": "function"}) - assert "Invalid tool choice" in str(exc_info.value) +@pytest.mark.parametrize( + "tool_choice", + [ + {}, + {"type": "invalid"}, + {"type": "function"}, + {"name": "lookup_fruit"}, + {"type": "file_search"}, + ], +) +def test_validate_tool_choice_invalid_dict_is_a_400(tool_choice): + """A dict shape chat completions cannot carry is the caller's mistake: a 400 that names the field, never a 500.""" + with pytest.raises( + litellm.BadRequestError, match=f"Invalid tool choice, tool_choice={re.escape(str(tool_choice))}\\. Please ensure" + ) as exc_info: + validate_chat_completion_tool_choice(tool_choice, model=MODEL) + assert exc_info.value.status_code == 400 + assert exc_info.value.model == MODEL -def test_validate_tool_choice_invalid_type(): - """Test that invalid types raise exceptions.""" - with pytest.raises(Exception, match="\\. Expecting str, or dict\\. Please ensure") as exc_info: - validate_chat_completion_tool_choice(123) - assert "Got=" in str(exc_info.value) - - with pytest.raises(Exception, match="Invalid tool choice, tool_choice=\\[\\]\\. Got=\\.") as exc_info: - validate_chat_completion_tool_choice([]) - assert "Got=" in str(exc_info.value) +@pytest.mark.parametrize("tool_choice", [123, []]) +def test_validate_tool_choice_invalid_type_is_a_400(tool_choice): + """A non-str, non-dict tool_choice is rejected as a 400 that names the type it got.""" + with pytest.raises( + litellm.BadRequestError, match=f"Got={re.escape(str(type(tool_choice)))}\\. Expecting str, or dict\\." + ) as exc_info: + validate_chat_completion_tool_choice(tool_choice, model=MODEL) + assert exc_info.value.status_code == 400 diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py index 0ed101952be..3950fd549ef 100644 --- a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py +++ b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py @@ -4906,3 +4906,18 @@ class TestStreamingSnapshotItemIds: reasoning_items = _bridged_output_items(completed_event.response, "reasoning") assert len(reasoning_items) == 1 assert reasoning_items[0].id == streamed_event.item_id + + +@pytest.mark.parametrize("stream", [True, False]) +async def test_bridge_rejects_untranslatable_tool_choice_with_a_400(stream: bool): + with pytest.raises(litellm.BadRequestError) as exc_info: + await litellm.aresponses( + model="anthropic/claude-haiku-4-5", + input="Which fruit is red?", + tools=[{"type": "function", "name": "lookup_fruit", "parameters": {"type": "object"}}], + tool_choice={"type": "file_search"}, + stream=stream, + api_key="sk-unused", + ) + assert exc_info.value.status_code == 400 + assert "tool_choice={'type': 'file_search'}" in str(exc_info.value) diff --git a/tests/test_litellm/test_main.py b/tests/test_litellm/test_main.py index 3dccb2b35bf..81ad161772e 100644 --- a/tests/test_litellm/test_main.py +++ b/tests/test_litellm/test_main.py @@ -3850,3 +3850,17 @@ def test_bridged_responses_with_openai_http_handler_keeps_forwarded_headers_out_ assert "extra_headers" not in body assert body["model"] == "gpt-5.4" assert {k: request.headers[k] for k in FORWARDED_CLIENT_HEADERS} == FORWARDED_CLIENT_HEADERS + + +@pytest.mark.parametrize("tool_choice", [{"type": "bogus"}, {"name": "lookup_fruit"}, {"type": "file_search"}]) +def test_completion_rejects_untranslatable_tool_choice_with_a_400(tool_choice): + with pytest.raises(litellm.BadRequestError) as exc_info: + litellm.completion( + model="anthropic/claude-haiku-4-5", + messages=[{"role": "user", "content": "Which fruit is red?"}], + tools=[{"type": "function", "function": {"name": "lookup_fruit", "parameters": {"type": "object"}}}], + tool_choice=tool_choice, + api_key="sk-unused", + ) + assert exc_info.value.status_code == 400 + assert f"tool_choice={tool_choice}" in str(exc_info.value) From 2bbf34c6520ef3266a62121510470868f73e499e Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Tue, 15 Sep 2026 07:00:33 -0700 Subject: [PATCH 2/2] fix(utils): keep the tool_choice validator's model argument optional --- litellm/utils.py | 2 +- tests/litellm_utils_tests/test_validate_tool_choice.py | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/litellm/utils.py b/litellm/utils.py index 17088f0475b..c2dbbda2b68 100644 --- a/litellm/utils.py +++ b/litellm/utils.py @@ -8038,7 +8038,7 @@ def validate_chat_completion_user_messages(messages: list[AllMessageValues]): def validate_chat_completion_tool_choice( tool_choice: dict | str | None, - model: str, + model: str = "", ) -> dict | str | None: """ Confirm the tool choice is passed in the OpenAI format. diff --git a/tests/litellm_utils_tests/test_validate_tool_choice.py b/tests/litellm_utils_tests/test_validate_tool_choice.py index b4272af7b90..a9dacf9fa15 100644 --- a/tests/litellm_utils_tests/test_validate_tool_choice.py +++ b/tests/litellm_utils_tests/test_validate_tool_choice.py @@ -64,3 +64,11 @@ def test_validate_tool_choice_invalid_type_is_a_400(tool_choice): ) as exc_info: validate_chat_completion_tool_choice(tool_choice, model=MODEL) assert exc_info.value.status_code == 400 + + +def test_validate_tool_choice_without_model_is_still_a_400(): + """Callers that predate the model argument keep getting a 400, with an empty model on the error.""" + with pytest.raises(litellm.BadRequestError, match="Invalid tool choice") as exc_info: + validate_chat_completion_tool_choice({"type": "bogus"}) + assert exc_info.value.status_code == 400 + assert exc_info.value.model == ""