[Bugfix] Reject empty tools array with HTTP 400 (#39780)
Signed-off-by: Jigang Zhou <zjg0907008@gmail.com> Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -681,6 +681,18 @@ class ChatCompletionRequest(OpenAIBaseModel):
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def check_tool_usage(cls, data):
|
||||
if isinstance(data, ValueError):
|
||||
raise data
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
|
||||
# Reject empty tools array, matching OpenAI API behavior
|
||||
if data.get("tools") == []:
|
||||
raise ValueError(
|
||||
"`tools` must not be an empty array. "
|
||||
"Either provide at least one tool or omit the field entirely."
|
||||
)
|
||||
|
||||
# if "tool_choice" is not specified but tools are provided,
|
||||
# default to "auto" tool_choice
|
||||
if "tool_choice" not in data and data.get("tools"):
|
||||
@@ -707,18 +719,6 @@ class ChatCompletionRequest(OpenAIBaseModel):
|
||||
"are supported."
|
||||
)
|
||||
|
||||
# if tool_choice is "required" but the "tools" list is empty,
|
||||
# override the data to behave like "none" to align with
|
||||
# OpenAI’s behavior.
|
||||
if (
|
||||
data["tool_choice"] == "required"
|
||||
and isinstance(data["tools"], list)
|
||||
and len(data["tools"]) == 0
|
||||
):
|
||||
data["tool_choice"] = "none"
|
||||
del data["tools"]
|
||||
return data
|
||||
|
||||
# ensure that if "tool_choice" is specified as an object,
|
||||
# it matches a valid tool
|
||||
correct_usage_message = (
|
||||
|
||||
Reference in New Issue
Block a user