Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(tools): classify custom tool calls by one shared rule and make envelope payload extraction total

Tin Chi Loc27f1b7b6d27
diff --git a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
index 09bd55096e8..f4f1b6fca0d 100644
--- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
+++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
@@ -322,7 +322,7 @@ class ChunkProcessor:
# Convert the map to a list of tool calls
for index in sorted(tool_call_map.keys()):
tool_call_data = tool_call_map[index]
- if tool_call_data["type"] == "custom" and tool_call_data["id"] and tool_call_data["custom_name"]:
+ if tool_call_data["id"] and tool_call_data["custom_name"]:
tool_calls_list.append(
ChatCompletionMessageCustomToolCall(
id=tool_call_data["id"],
diff --git a/litellm/proxy/response_api_endpoints/endpoints.py b/litellm/proxy/response_api_endpoints/endpoints.py
index b67352f2057..3a2c57aa2ba 100644
--- a/litellm/proxy/response_api_endpoints/endpoints.py
+++ b/litellm/proxy/response_api_endpoints/endpoints.py
@@ -43,10 +43,14 @@ def _convert_tool_envelope(obj: object, *, to_chat: bool) -> object:
if payload_keys is None:
return obj
nested = obj.get(tool_type)
- source = nested if isinstance(nested, dict) else obj
- if source is obj and "name" not in obj:
+ nested_source = nested if isinstance(nested, dict) else {}
+ payload = {
+ key: nested_source[key] if key in nested_source else obj[key]
+ for key in payload_keys
+ if key in nested_source or key in obj
+ }
+ if "name" not in payload:
return obj
- payload = {key: source[key] for key in payload_keys if key in source}
if isinstance(payload.get("format"), dict):
convert = convert_custom_tool_format_to_chat_shape if to_chat else convert_custom_tool_format_to_responses_shape
payload = {**payload, "format": convert(payload["format"])}
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 7ff12b617e3..404725ec61b 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -1162,12 +1162,16 @@ class ChatCompletionMessageToolCall(OpenAIObject):
setattr(self, key, value)
+def is_custom_tool_call_dict(tool_call: dict) -> bool:
+ return tool_call.get("type") == "custom" or tool_call.get("custom") is not None
+
+
def chat_completion_tool_call_from_dict(
tool_call: dict,
) -> "ChatCompletionMessageToolCall | ChatCompletionMessageCustomToolCall":
- if tool_call.get("type") == "custom":
+ if is_custom_tool_call_dict(tool_call):
return ChatCompletionMessageCustomToolCall(
- **{k: v for k, v in tool_call.items() if not (k == "function" and v is None)}
+ **{k: v for k, v in tool_call.items() if not (k in ("function", "type") and v is None)}
)
return ChatCompletionMessageToolCall(**tool_call)
@@ -1393,7 +1397,7 @@ class Delta(SafeAttributeModel, OpenAIObject):
if tool_call.get("index", None) is None:
tool_call["index"] = current_index
current_index += 1
- if tool_call.get("type") == "custom" or "custom" in tool_call:
+ if is_custom_tool_call_dict(tool_call):
coerced_tool_calls.append(
ChatCompletionDeltaCustomToolCall(
**{k: v for k, v in tool_call.items() if not (k == "function" and v is None)}
diff --git a/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py b/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py
index 197adf80f03..2db5461702a 100644
--- a/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py
+++ b/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py
@@ -1027,3 +1027,40 @@ def test_get_combined_tool_content_custom_tool_call():
"type": "custom",
"custom": {"name": "ApplyPatch", "input": "*** Begin Patch\n*** End Patch\n"},
}
+
+
+def test_get_combined_tool_content_custom_tool_call_without_type_field():
+ """Delta coercion classifies a tool-call chunk as custom from its ``custom`` payload
+ alone (``type`` may never arrive on any chunk). The assembler must use the same
+ evidence; requiring ``type == "custom"`` dropped the whole tool call from the
+ combined message (it matched neither the custom nor the function branch)."""
+ from litellm.litellm_core_utils.streaming_chunk_builder_utils import ChunkProcessor
+ from litellm.types.utils import ChatCompletionMessageCustomToolCall
+
+ processor = ChunkProcessor.__new__(ChunkProcessor)
+ tool_call_chunks = [
+ {
+ "choices": [
+ {
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_TBs",
+ "custom": {"name": "ApplyPatch", "input": "*** Begin"},
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {"choices": [{"delta": {"tool_calls": [{"index": 0, "custom": {"input": " Patch"}}]}}]},
+ ]
+ combined = processor.get_combined_tool_content(tool_call_chunks)
+ assert len(combined) == 1
+ assert isinstance(combined[0], ChatCompletionMessageCustomToolCall)
+ assert combined[0].model_dump() == {
+ "id": "call_TBs",
+ "type": "custom",
+ "custom": {"name": "ApplyPatch", "input": "*** Begin Patch"},
+ }
diff --git a/tests/test_litellm/proxy/response_api_endpoints/test_endpoints.py b/tests/test_litellm/proxy/response_api_endpoints/test_endpoints.py
index fa5a16a9f3b..00ac8ca386a 100644
--- a/tests/test_litellm/proxy/response_api_endpoints/test_endpoints.py
+++ b/tests/test_litellm/proxy/response_api_endpoints/test_endpoints.py
@@ -1121,6 +1121,30 @@ class TestToolEnvelopeConversionMatrix:
entries = [{"type": "web_search"}, {"type": "custom"}, "junk", None, {}, 42, {"type": "auto"}]
assert [_convert_tool_envelope(entry, to_chat=to_chat) for entry in entries] == entries
+ @pytest.mark.parametrize("to_chat", [True, False])
+ def test_empty_nested_envelope_falls_back_to_top_level_payload(self, to_chat):
+ """An empty nested envelope must not shadow payload fields that sit at the top
+ level; treating the empty dict as the sole payload source dropped the name."""
+ from litellm.proxy.response_api_endpoints.endpoints import _convert_tool_envelope
+
+ hybrid = {"type": "custom", "custom": {}, "name": "ApplyPatch", "format": self.TEXT}
+ expected_payload = {"name": "ApplyPatch", "format": self.TEXT}
+ expected = {"type": "custom", "custom": expected_payload} if to_chat else {"type": "custom", **expected_payload}
+ assert _convert_tool_envelope(hybrid, to_chat=to_chat) == expected
+
+ def test_nested_payload_wins_over_stray_top_level_fields(self):
+ from litellm.proxy.response_api_endpoints.endpoints import _convert_tool_envelope
+
+ tool = {"type": "custom", "custom": {"name": "NestedName"}, "name": "TopName"}
+ assert _convert_tool_envelope(tool, to_chat=False) == {"type": "custom", "name": "NestedName"}
+
+ @pytest.mark.parametrize("to_chat", [True, False])
+ def test_nameless_envelope_passes_through_unchanged(self, to_chat):
+ from litellm.proxy.response_api_endpoints.endpoints import _convert_tool_envelope
+
+ nameless = {"type": "custom", "custom": {}, "description": "no name anywhere"}
+ assert _convert_tool_envelope(nameless, to_chat=to_chat) == nameless
+
class TestToolChoiceSharesTheToolEnvelopeRule:
"""
diff --git a/tests/test_litellm/types/test_types_utils.py b/tests/test_litellm/types/test_types_utils.py
index 4d08239360f..a446f820870 100644
--- a/tests/test_litellm/types/test_types_utils.py
+++ b/tests/test_litellm/types/test_types_utils.py
@@ -638,6 +638,48 @@ def test_chat_completion_tool_call_from_dict_custom_strips_null_function():
assert "function" not in parsed.model_dump()
+def test_chat_completion_tool_call_from_dict_typeless_custom_payload():
+ """A tool-call dict can carry a ``custom`` payload with ``type`` absent or None
+ (e.g. rebuilt from streaming deltas, where only the first chunk has ``type``).
+ Classifying on ``type == "custom"`` alone sent these to the function branch,
+ which raised TypeError (missing ``function``) on a payload the streaming path
+ accepts as custom."""
+ from litellm.types.utils import ChatCompletionMessageCustomToolCall, chat_completion_tool_call_from_dict
+
+ typeless = {"id": "call_1", "custom": {"name": "ApplyPatch", "input": "*** Begin Patch"}}
+ parsed = chat_completion_tool_call_from_dict(typeless)
+ assert isinstance(parsed, ChatCompletionMessageCustomToolCall)
+ assert parsed.type == "custom"
+ assert parsed.custom.name == "ApplyPatch"
+
+ null_typed = {"id": "call_2", "type": None, "custom": {"name": "f", "input": "{}"}}
+ assert isinstance(chat_completion_tool_call_from_dict(null_typed), ChatCompletionMessageCustomToolCall)
+
+
+def test_custom_tool_call_classification_agrees_across_streaming_and_non_streaming():
+ """The streaming Delta coercion and the non-streaming from_dict parser must
+ classify the same tool-call dict identically, or a provider payload becomes a
+ custom tool call mid-stream and something else on the completed message."""
+ from litellm.types.utils import (
+ ChatCompletionDeltaCustomToolCall,
+ ChatCompletionMessageCustomToolCall,
+ Delta,
+ chat_completion_tool_call_from_dict,
+ )
+
+ tool_calls = [
+ {"id": "c1", "type": "custom", "custom": {"name": "ApplyPatch", "input": ""}},
+ {"id": "c2", "custom": {"name": "ApplyPatch", "input": "x"}},
+ {"id": "c3", "type": "function", "function": {"name": "g", "arguments": "{}"}},
+ ]
+ for tool_call in tool_calls:
+ message_parsed = chat_completion_tool_call_from_dict(dict(tool_call))
+ delta_parsed = Delta(tool_calls=[dict(tool_call, index=0)]).tool_calls[0]
+ assert isinstance(message_parsed, ChatCompletionMessageCustomToolCall) == isinstance(
+ delta_parsed, ChatCompletionDeltaCustomToolCall
+ )
+
+
def test_message_with_mixed_function_and_custom_tool_calls():
from litellm.types.utils import (
ChatCompletionMessageCustomToolCall,