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(litellm): support OpenAI chat completions custom tool calls end to end

Tin Chi Lob45c99f6c58a
diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py
index 9fd193b4eeb..75cee42dd55 100644
--- a/litellm/completion_extras/litellm_responses_transformation/transformation.py
+++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py
@@ -20,6 +20,7 @@ from typing import (
cast,
)
+from openai.types.responses.custom_tool_param import CustomToolParam
from openai.types.responses.tool_param import FunctionToolParam
from pydantic import BaseModel
@@ -894,6 +895,17 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
description=function_tool.get("description"),
)
)
+ elif tool.get("type") == "custom" and isinstance(tool.get("custom"), dict):
+ custom_payload = tool["custom"]
+ flat_custom: CustomToolParam = {
+ "type": "custom",
+ "name": custom_payload.get("name", ""),
+ }
+ if custom_payload.get("description") is not None:
+ flat_custom["description"] = custom_payload["description"]
+ if custom_payload.get("format") is not None:
+ flat_custom["format"] = custom_payload["format"]
+ responses_tools.append(flat_custom)
else:
responses_tools.append(tool) # type: ignore
diff --git a/litellm/integrations/helicone.py b/litellm/integrations/helicone.py
index 21e9479491e..4c7a606c16f 100644
--- a/litellm/integrations/helicone.py
+++ b/litellm/integrations/helicone.py
@@ -59,12 +59,15 @@ class HeliconeLogger:
content = []
if "tool_calls" in message and message["tool_calls"]:
for tool_call in message["tool_calls"]:
+ function = tool_call.get("function")
+ if not function:
+ continue
content.append(
{
"type": "tool_use",
"id": tool_call["id"],
- "name": tool_call["function"]["name"],
- "input": tool_call["function"]["arguments"],
+ "name": function["name"],
+ "input": function["arguments"],
}
)
elif "content" in message and message["content"]:
diff --git a/litellm/integrations/lunary.py b/litellm/integrations/lunary.py
index aaf5751cb79..448580f0b2d 100644
--- a/litellm/integrations/lunary.py
+++ b/litellm/integrations/lunary.py
@@ -31,7 +31,7 @@ def parse_tool_calls(tool_calls):
return serialized
- return [clean_tool_call(tool_call) for tool_call in tool_calls]
+ return [clean_tool_call(tool_call) for tool_call in tool_calls if getattr(tool_call, "function", None) is not None]
def parse_messages(input):
diff --git a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
index 47daf33824e..c5cfdea9ffe 100644
--- a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
+++ b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
@@ -19,6 +19,7 @@ from litellm.types.llms.openai import (
)
from litellm.types.utils import (
ChatCompletionDeltaToolCall,
+ ChatCompletionMessageCustomToolCall,
ChatCompletionMessageToolCall,
ChatCompletionRedactedThinkingBlock,
Choices,
@@ -43,6 +44,7 @@ from litellm.types.utils import (
TranscriptionUsageDurationObject,
TranscriptionUsageTokensObject,
Usage,
+ chat_completion_tool_call_from_dict,
)
from .get_headers import get_response_headers
@@ -369,7 +371,7 @@ from collections import defaultdict
def _handle_invalid_parallel_tool_calls(
- tool_calls: List[ChatCompletionMessageToolCall],
+ tool_calls: List[Union[ChatCompletionMessageToolCall, ChatCompletionMessageCustomToolCall]],
):
"""
Handle hallucinated parallel tool call from openai - https://community.openai.com/t/model-tries-to-call-unknown-function-multi-tool-use-parallel/490653
@@ -382,6 +384,8 @@ def _handle_invalid_parallel_tool_calls(
try:
replacements: Dict[int, List[ChatCompletionMessageToolCall]] = defaultdict(list)
for i, tool_call in enumerate(tool_calls):
+ if isinstance(tool_call, ChatCompletionMessageCustomToolCall):
+ continue
current_function = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
if current_function == "multi_tool_use.parallel":
@@ -527,19 +531,20 @@ class LiteLLMResponseObjectHandler:
def _should_convert_tool_call_to_json_mode(
- tool_calls: Optional[Union[List[ChatCompletionMessageToolCall], List[DatabricksTool]]] = None,
+ tool_calls: Optional[
+ Union[
+ List[Union[ChatCompletionMessageToolCall, ChatCompletionMessageCustomToolCall]],
+ List[DatabricksTool],
+ ]
+ ] = None,
convert_tool_call_to_json_mode: Optional[bool] = None,
) -> bool:
"""
Determine if tool calls should be converted to JSON mode
"""
- if (
- convert_tool_call_to_json_mode
- and tool_calls is not None
- and len(tool_calls) == 1
- and tool_calls[0]["function"]["name"] == RESPONSE_FORMAT_TOOL_NAME
- ):
- return True
+ if convert_tool_call_to_json_mode and tool_calls is not None and len(tool_calls) == 1:
+ function = tool_calls[0].get("function")
+ return function is not None and function["name"] == RESPONSE_FORMAT_TOOL_NAME
return False
@@ -647,7 +652,7 @@ def convert_to_model_response_object(
if tool_calls is not None:
_openai_tool_calls = []
for _tc in tool_calls:
- _openai_tc = ChatCompletionMessageToolCall(**_tc)
+ _openai_tc = chat_completion_tool_call_from_dict(_tc)
_openai_tool_calls.append(_openai_tc)
fixed_tool_calls = _handle_invalid_parallel_tool_calls(_openai_tool_calls)
diff --git a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
index d52d9849310..09bd55096e8 100644
--- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
+++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
@@ -9,6 +9,8 @@ from litellm.types.llms.openai import (
from litellm.types.utils import (
CacheCreationTokenDetails,
ChatCompletionAudioResponse,
+ ChatCompletionCustomToolCallPayload,
+ ChatCompletionMessageCustomToolCall,
ChatCompletionMessageToolCall,
Choices,
CompletionTokensDetails,
@@ -202,8 +204,10 @@ class ChunkProcessor:
response = self.update_model_response_with_hidden_params(model_response=response, chunk=chunk)
return response
- def get_combined_tool_content(self, tool_call_chunks: List[Dict[str, Any]]) -> List[ChatCompletionMessageToolCall]:
- tool_calls_list: List[ChatCompletionMessageToolCall] = []
+ def get_combined_tool_content(
+ self, tool_call_chunks: List[Dict[str, Any]]
+ ) -> List[Union[ChatCompletionMessageToolCall, ChatCompletionMessageCustomToolCall]]:
+ tool_calls_list: List[Union[ChatCompletionMessageToolCall, ChatCompletionMessageCustomToolCall]] = []
tool_call_map: Dict[int, Dict[str, Any]] = {} # Map to store tool calls by index
for chunk in tool_call_chunks:
@@ -219,12 +223,15 @@ class ChunkProcessor:
# Check if tool_call has function (either as attribute or dict key)
has_function = False
+ has_custom = False
if isinstance(tool_call, dict):
has_function = "function" in tool_call and tool_call["function"] is not None
+ has_custom = "custom" in tool_call and tool_call["custom"] is not None
else:
has_function = hasattr(tool_call, "function") and tool_call.function is not None
+ has_custom = getattr(tool_call, "custom", None) is not None
- if not has_function:
+ if not has_function and not has_custom:
continue
# Get index (handle both dict and object)
@@ -239,6 +246,8 @@ class ChunkProcessor:
"name": None,
"type": None,
"arguments": [],
+ "custom_name": None,
+ "custom_input": [],
"provider_specific_fields": None,
}
@@ -261,6 +270,13 @@ class ChunkProcessor:
tool_call_map[index]["name"] = function.name
if hasattr(function, "arguments") and function.arguments:
tool_call_map[index]["arguments"].append(function.arguments)
+
+ custom = tool_call.get("custom")
+ if isinstance(custom, dict):
+ if custom.get("name"):
+ tool_call_map[index]["custom_name"] = custom["name"]
+ if custom.get("input"):
+ tool_call_map[index]["custom_input"].append(custom["input"])
else:
# tool_call is an object
if hasattr(tool_call, "id") and tool_call.id:
@@ -273,6 +289,13 @@ class ChunkProcessor:
if hasattr(tool_call.function, "arguments") and tool_call.function.arguments:
tool_call_map[index]["arguments"].append(tool_call.function.arguments)
+ custom = getattr(tool_call, "custom", None)
+ if custom is not None:
+ if getattr(custom, "name", None):
+ tool_call_map[index]["custom_name"] = custom.name
+ if getattr(custom, "input", None):
+ tool_call_map[index]["custom_input"].append(custom.input)
+
# Preserve provider_specific_fields from streaming chunks
provider_fields = None
if isinstance(tool_call, dict):
@@ -299,7 +322,17 @@ 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["id"] and tool_call_data["name"]:
+ if tool_call_data["type"] == "custom" and tool_call_data["id"] and tool_call_data["custom_name"]:
+ tool_calls_list.append(
+ ChatCompletionMessageCustomToolCall(
+ id=tool_call_data["id"],
+ custom=ChatCompletionCustomToolCallPayload(
+ name=tool_call_data["custom_name"],
+ input="".join(tool_call_data["custom_input"]),
+ ),
+ )
+ )
+ elif tool_call_data["id"] and tool_call_data["name"]:
combined_arguments = "".join(tool_call_data["arguments"]) or "{}"
# Build function - provider_specific_fields should be on tool_call level, not function level
diff --git a/litellm/llms/openai/chat/gpt_transformation.py b/litellm/llms/openai/chat/gpt_transformation.py
index f2498c0a7e2..129a9b51d0d 100644
--- a/litellm/llms/openai/chat/gpt_transformation.py
+++ b/litellm/llms/openai/chat/gpt_transformation.py
@@ -50,12 +50,14 @@ from litellm.types.llms.openai import (
OpenAIMessageContentListBlock,
)
from litellm.types.utils import (
+ ChatCompletionMessageCustomToolCall,
ChatCompletionMessageToolCall,
Choices,
Function,
Message,
ModelResponse,
ModelResponseStream,
+ chat_completion_tool_call_from_dict,
)
from litellm.utils import convert_to_model_response_object
@@ -531,12 +533,14 @@ class OpenAIGPTConfig(BaseLLMModelInfo, BaseConfig):
for choice in choices:
## HANDLE JSON MODE - anthropic returns single function call]
tool_calls = choice["message"].get("tool_calls", None)
- new_tool_calls: Optional[List[ChatCompletionMessageToolCall]] = None
+ new_tool_calls: Optional[
+ List[Union[ChatCompletionMessageToolCall, ChatCompletionMessageCustomToolCall]]
+ ] = None
message_content = choice["message"].get("content", None)
if tool_calls is not None:
_openai_tool_calls = []
for _tc in tool_calls:
- _openai_tc = ChatCompletionMessageToolCall(**_tc) # type: ignore
+ _openai_tc = chat_completion_tool_call_from_dict(dict(_tc))
_openai_tool_calls.append(_openai_tc)
fixed_tool_calls = _handle_invalid_parallel_tool_calls(_openai_tool_calls)
diff --git a/litellm/proxy/response_api_endpoints/endpoints.py b/litellm/proxy/response_api_endpoints/endpoints.py
index 80abdab8583..f9b2cc79f73 100644
--- a/litellm/proxy/response_api_endpoints/endpoints.py
+++ b/litellm/proxy/response_api_endpoints/endpoints.py
@@ -24,6 +24,23 @@ router = APIRouter()
_user_api_key_auth_dep = Depends(user_api_key_auth)
+_FLAT_CUSTOM_TOOL_KEYS = ("name", "description", "format")
+_FLAT_FUNCTION_TOOL_KEYS = ("name", "description", "parameters", "strict")
+
+
+def _nest_flat_chat_tool(tool: object) -> object:
+ if not isinstance(tool, dict) or "name" not in tool:
+ return tool
+ if tool.get("type") == "custom" and "custom" not in tool:
+ return {"type": "custom", "custom": {k: tool[k] for k in _FLAT_CUSTOM_TOOL_KEYS if k in tool}}
+ if tool.get("type") == "function" and "function" not in tool:
+ return {"type": "function", "function": {k: tool[k] for k in _FLAT_FUNCTION_TOOL_KEYS if k in tool}}
+ return tool
+
+
+def _nest_flat_chat_tools(tools: list) -> list:
+ return [_nest_flat_chat_tool(tool) for tool in tools]
+
@router.post(
"/v1/responses",
@@ -330,7 +347,9 @@ async def cursor_chat_completions(
custom tools) to the chat/completions path while expecting chat completions responses;
those are routed through the Responses API pipeline and converted back. Genuine chat
completions bodies (`messages` present) are routed through the standard chat completions
- pipeline untouched.
+ pipeline, after nesting any flat Responses-style tool defs Cursor mixes into the chat
+ `tools` array (e.g. `{"type": "custom", "name": "ApplyPatch", ...}`) into the chat
+ completions shape OpenAI requires (`{"type": "custom", "custom": {...}}`).
```bash
curl -X POST http://localhost:4000/cursor/chat/completions \
@@ -347,6 +366,7 @@ async def cursor_chat_completions(
responses_api_bridge,
)
from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper
+ from litellm.proxy.common_utils.http_parsing_utils import _safe_set_request_parsed_body
from litellm.proxy.proxy_server import (
_read_request_body,
async_data_generator,
@@ -370,6 +390,11 @@ async def cursor_chat_completions(
if "messages" in data:
# Genuine chat completions body (Cursor sends these for models whose BYOK it
# already fixed); delegate so behavior matches /chat/completions exactly
+ tools = data.get("tools")
+ if isinstance(tools, list):
+ nested_tools = _nest_flat_chat_tools(tools)
+ if nested_tools != tools:
+ _safe_set_request_parsed_body(request=request, parsed_body={**data, "tools": nested_tools})
return await chat_completion(
request=request,
fastapi_response=fastapi_response,
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 18991f53e6f..a1e52f7584f 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -1084,6 +1084,71 @@ class ChatCompletionDeltaToolCall(OpenAIObject):
setattr(self, key, value)
+class ChatCompletionCustomToolCallPayload(OpenAIObject):
+ name: str
+ input: str
+
+ def __contains__(self, key):
+ return hasattr(self, key)
+
+ def get(self, key, default=None):
+ return getattr(self, key, default)
+
+ def __getitem__(self, key):
+ return getattr(self, key)
+
+
+class ChatCompletionDeltaCustomToolCallPayload(OpenAIObject):
+ name: str | None = None
+ input: str | None = None
+
+ def __contains__(self, key):
+ return hasattr(self, key)
+
+ def get(self, key, default=None):
+ return getattr(self, key, default)
+
+ def __getitem__(self, key):
+ return getattr(self, key)
+
+
+class ChatCompletionMessageCustomToolCall(OpenAIObject):
+ id: str
+ type: Literal["custom"] = "custom"
+ custom: ChatCompletionCustomToolCallPayload
+
+ def __contains__(self, key):
+ return hasattr(self, key)
+
+ def get(self, key, default=None):
+ return getattr(self, key, default)
+
+ def __getitem__(self, key):
+ return getattr(self, key)
+
+ def __setitem__(self, key, value):
+ setattr(self, key, value)
+
+
+class ChatCompletionDeltaCustomToolCall(OpenAIObject):
+ id: str | None = None
+ type: str | None = None
+ custom: ChatCompletionDeltaCustomToolCallPayload
+ index: int
+
+ def __contains__(self, key):
+ return hasattr(self, key)
+
+ def get(self, key, default=None):
+ return getattr(self, key, default)
+
+ def __getitem__(self, key):
+ return getattr(self, key)
+
+ def __setitem__(self, key, value):
+ setattr(self, key, value)
+
+
class ChatCompletionMessageToolCall(OpenAIObject):
def __init__(
self,
@@ -1125,6 +1190,16 @@ class ChatCompletionMessageToolCall(OpenAIObject):
setattr(self, key, value)
+def chat_completion_tool_call_from_dict(
+ tool_call: dict,
+) -> "ChatCompletionMessageToolCall | ChatCompletionMessageCustomToolCall":
+ if tool_call.get("type") == "custom":
+ return ChatCompletionMessageCustomToolCall(
+ **{k: v for k, v in tool_call.items() if not (k == "function" and v is None)}
+ )
+ return ChatCompletionMessageToolCall(**tool_call)
+
+
from openai.types.chat.chat_completion_audio import ChatCompletionAudio
@@ -1177,7 +1252,7 @@ def add_provider_specific_fields(object: BaseModel, provider_specific_fields: Op
class Message(SafeAttributeModel, OpenAIObject):
content: Optional[str]
role: Literal["assistant", "user", "system", "tool", "function"]
- tool_calls: Optional[List[ChatCompletionMessageToolCall]]
+ tool_calls: Optional[List[Union[ChatCompletionMessageToolCall, ChatCompletionMessageCustomToolCall]]]
function_call: Optional[FunctionCall]
audio: Optional[ChatCompletionAudioResponse] = None
images: Optional[List[ImageURLListItem]] = None
@@ -1208,7 +1283,7 @@ class Message(SafeAttributeModel, OpenAIObject):
"function_call": (FunctionCall(**function_call) if function_call is not None else None),
"tool_calls": (
[
- (ChatCompletionMessageToolCall(**tool_call) if isinstance(tool_call, dict) else tool_call)
+ (chat_completion_tool_call_from_dict(tool_call) if isinstance(tool_call, dict) else tool_call)
for tool_call in tool_calls
]
if tool_calls is not None and len(tool_calls) > 0
@@ -1301,7 +1376,7 @@ class Delta(SafeAttributeModel, OpenAIObject):
content: Optional[str]
role: Optional[str]
function_call: Optional[FunctionCall]
- tool_calls: Optional[List[ChatCompletionDeltaToolCall]]
+ tool_calls: Optional[List[Union[ChatCompletionDeltaToolCall, ChatCompletionDeltaCustomToolCall]]]
audio: Optional[ChatCompletionAudioResponse]
images: Optional[List[ImageURLListItem]]
annotations: Optional[List[ChatCompletionAnnotation]]
@@ -1339,17 +1414,24 @@ class Delta(SafeAttributeModel, OpenAIObject):
function_call = FunctionCall(**function_call)
if tool_calls is not None and isinstance(tool_calls, list):
- coerced_tool_calls: List[ChatCompletionDeltaToolCall] = []
+ coerced_tool_calls: List[Union[ChatCompletionDeltaToolCall, ChatCompletionDeltaCustomToolCall]] = []
current_index = 0
for tool_call in tool_calls:
if isinstance(tool_call, dict):
if tool_call.get("index", None) is None:
tool_call["index"] = current_index
current_index += 1
- if tool_call.get("type", None) is None:
- tool_call["type"] = "function"
- coerced_tool_calls.append(ChatCompletionDeltaToolCall(**tool_call))
- elif isinstance(tool_call, ChatCompletionDeltaToolCall):
+ if tool_call.get("type") == "custom" or "custom" in tool_call:
+ coerced_tool_calls.append(
+ ChatCompletionDeltaCustomToolCall(
+ **{k: v for k, v in tool_call.items() if not (k == "function" and v is None)}
+ )
+ )
+ else:
+ if tool_call.get("type", None) is None:
+ tool_call["type"] = "function"
+ coerced_tool_calls.append(ChatCompletionDeltaToolCall(**tool_call))
+ elif isinstance(tool_call, (ChatCompletionDeltaToolCall, ChatCompletionDeltaCustomToolCall)):
coerced_tool_calls.append(tool_call)
tool_calls = coerced_tool_calls
diff --git a/tests/test_litellm/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py b/tests/test_litellm/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py
index 36c32d4b3a0..767d1631649 100644
--- a/tests/test_litellm/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py
+++ b/tests/test_litellm/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py
@@ -3215,3 +3215,37 @@ def test_convert_response_output_generic_pydantic_message_item():
assert len(choices) == 1
assert choices[0].message.content == "42"
assert choices[0].finish_reason == "stop"
+
+
+def test_convert_tools_to_responses_format_flattens_nested_custom_tool():
+ from litellm.completion_extras.litellm_responses_transformation.transformation import (
+ LiteLLMResponsesTransformationHandler,
+ )
+
+ handler = LiteLLMResponsesTransformationHandler()
+ tools = [
+ {
+ "type": "custom",
+ "custom": {"name": "ApplyPatch", "description": "V4A patch", "format": {"type": "text"}},
+ },
+ {"type": "function", "function": {"name": "f", "parameters": {"type": "object"}}},
+ ]
+ converted = handler._convert_tools_to_responses_format(tools)
+ assert converted[0] == {
+ "type": "custom",
+ "name": "ApplyPatch",
+ "description": "V4A patch",
+ "format": {"type": "text"},
+ }
+ assert converted[1]["type"] == "function"
+ assert converted[1]["name"] == "f"
+
+
+def test_convert_tools_to_responses_format_flattens_custom_tool_without_optional_keys():
+ from litellm.completion_extras.litellm_responses_transformation.transformation import (
+ LiteLLMResponsesTransformationHandler,
+ )
+
+ handler = LiteLLMResponsesTransformationHandler()
+ converted = handler._convert_tools_to_responses_format([{"type": "custom", "custom": {"name": "Minimal"}}])
+ assert converted[0] == {"type": "custom", "name": "Minimal"}
diff --git a/tests/test_litellm/completion_extras/test_litellm_responses_transformation_transformation.py b/tests/test_litellm/completion_extras/test_litellm_responses_transformation_transformation.py
index 05bdc40112c..626e554d476 100644
--- a/tests/test_litellm/completion_extras/test_litellm_responses_transformation_transformation.py
+++ b/tests/test_litellm/completion_extras/test_litellm_responses_transformation_transformation.py
@@ -257,3 +257,4 @@ def test_translate_responses_chunk_passthrough_chat_completion_chunk():
assert result.choices[0].delta.content == "Hi! How can I help?"
assert result.choices[0].finish_reason is None
+
diff --git a/tests/test_litellm/litellm_core_utils/llm_response_utils/test_convert_dict_to_response.py b/tests/test_litellm/litellm_core_utils/llm_response_utils/test_convert_dict_to_response.py
new file mode 100644
index 00000000000..293e5de304f
--- /dev/null
+++ b/tests/test_litellm/litellm_core_utils/llm_response_utils/test_convert_dict_to_response.py
@@ -0,0 +1,104 @@
+import os
+import sys
+
+sys.path.insert(0, os.path.abspath("../../../.."))
+
+from litellm.constants import RESPONSE_FORMAT_TOOL_NAME
+from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
+ _handle_invalid_parallel_tool_calls,
+ _should_convert_tool_call_to_json_mode,
+ convert_to_model_response_object,
+)
+from litellm.types.utils import (
+ ChatCompletionMessageCustomToolCall,
+ ChatCompletionMessageToolCall,
+ Function,
+ ModelResponse,
+)
+
+OPENAI_CUSTOM_TOOL_CALL_RESPONSE = {
+ "id": "chatcmpl-abc",
+ "created": 1784657740,
+ "model": "gpt-5.6",
+ "object": "chat.completion",
+ "choices": [
+ {
+ "finish_reason": "tool_calls",
+ "index": 0,
+ "message": {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_njxQ",
+ "type": "custom",
+ "custom": {
+ "name": "ApplyPatch",
+ "input": "*** Begin Patch\n*** Update File: main.py\n@@\n+def hello():\n+ print(\"Hello\")\n*** End Patch\n",
+ },
+ }
+ ],
+ "refusal": None,
+ "annotations": [],
+ },
+ }
+ ],
+ "usage": {"completion_tokens": 10, "prompt_tokens": 5, "total_tokens": 15},
+}
+
+
+def test_convert_openai_custom_tool_call_response():
+ result = convert_to_model_response_object(
+ response_object=OPENAI_CUSTOM_TOOL_CALL_RESPONSE,
+ model_response_object=ModelResponse(),
+ response_type="completion",
+ )
+ tool_calls = result.choices[0].message.tool_calls
+ assert len(tool_calls) == 1
+ assert isinstance(tool_calls[0], ChatCompletionMessageCustomToolCall)
+ dumped = tool_calls[0].model_dump()
+ assert dumped == OPENAI_CUSTOM_TOOL_CALL_RESPONSE["choices"][0]["message"]["tool_calls"][0]
+ assert result.choices[0].finish_reason == "tool_calls"
+
+
+def test_should_convert_tool_call_to_json_mode_ignores_custom_tool_call():
+ custom_tool_call = ChatCompletionMessageCustomToolCall(
+ id="call_c",
+ custom={"name": "ApplyPatch", "input": "patch"},
+ )
+ assert (
+ _should_convert_tool_call_to_json_mode(
+ tool_calls=[custom_tool_call],
+ convert_tool_call_to_json_mode=True,
+ )
+ is False
+ )
+
+
+def test_should_convert_tool_call_to_json_mode_still_matches_response_format_tool():
+ response_format_call = ChatCompletionMessageToolCall(
+ id="call_f",
+ type="function",
+ function=Function(name=RESPONSE_FORMAT_TOOL_NAME, arguments='{"answer": 4}'),
+ )
+ assert (
+ _should_convert_tool_call_to_json_mode(
+ tool_calls=[response_format_call],
+ convert_tool_call_to_json_mode=True,
+ )
+ is True
+ )
+
+
+def test_handle_invalid_parallel_tool_calls_skips_custom_tool_calls():
+ custom_tool_call = ChatCompletionMessageCustomToolCall(
+ id="call_c",
+ custom={"name": "ApplyPatch", "input": "patch"},
+ )
+ function_tool_call = ChatCompletionMessageToolCall(
+ id="call_f",
+ type="function",
+ function=Function(name="get_weather", arguments='{"city": "SF"}'),
+ )
+ result = _handle_invalid_parallel_tool_calls([custom_tool_call, function_tool_call])
+ assert result == [custom_tool_call, function_tool_call]
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 be8c5a05601..197adf80f03 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
@@ -992,3 +992,38 @@ def test_cost_field_in_usage_chunks():
assert usage.cost == 0.00025
assert usage.prompt_tokens == 10
assert usage.completion_tokens == 5
+
+
+def test_get_combined_tool_content_custom_tool_call():
+ 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",
+ "type": "custom",
+ "custom": {"name": "ApplyPatch", "input": ""},
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {"choices": [{"delta": {"tool_calls": [{"index": 0, "custom": {"input": "*** Begin Patch\n"}}]}}]},
+ {"choices": [{"delta": {"tool_calls": [{"index": 0, "custom": {"input": "*** End Patch\n"}}]}}]},
+ ]
+ 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\n*** End Patch\n"},
+ }
diff --git a/tests/test_litellm/litellm_core_utils/test_streaming_handler.py b/tests/test_litellm/litellm_core_utils/test_streaming_handler.py
index 514714136fd..48bc3709517 100644
--- a/tests/test_litellm/litellm_core_utils/test_streaming_handler.py
+++ b/tests/test_litellm/litellm_core_utils/test_streaming_handler.py
@@ -3355,3 +3355,102 @@ async def test_transport_read_error_before_finish_reason_raises(logging_obj: Log
if chunk.choices and chunk.choices[0].finish_reason
]
assert fabricated_finish_reasons == []
+
+
+def test_openai_custom_tool_call_stream_deltas_survive_conversion(logging_obj: Logging):
+ """
+ Regression test: OpenAI chat completions custom tool calls stream as
+ delta.tool_calls entries with a `custom` payload and NO `function` key.
+ Delta() used to raise on those dicts and chunk_creator's except branch
+ replaced the choice with an empty Delta, silently dropping the entire
+ tool call from the client stream.
+ """
+ from openai.types.chat.chat_completion_chunk import ChatCompletionChunk
+
+ from litellm.types.utils import ChatCompletionDeltaCustomToolCall
+
+ raw_chunks = [
+ {
+ "id": "chatcmpl-custom",
+ "object": "chat.completion.chunk",
+ "created": 1784657671,
+ "model": "gpt-5.6",
+ "choices": [
+ {
+ "index": 0,
+ "delta": {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_TBs",
+ "type": "custom",
+ "custom": {"name": "ApplyPatch", "input": ""},
+ }
+ ],
+ },
+ "finish_reason": None,
+ }
+ ],
+ },
+ {
+ "id": "chatcmpl-custom",
+ "object": "chat.completion.chunk",
+ "created": 1784657671,
+ "model": "gpt-5.6",
+ "choices": [
+ {
+ "index": 0,
+ "delta": {"tool_calls": [{"index": 0, "custom": {"input": "*** Begin Patch\n"}}]},
+ "finish_reason": None,
+ }
+ ],
+ },
+ {
+ "id": "chatcmpl-custom",
+ "object": "chat.completion.chunk",
+ "created": 1784657671,
+ "model": "gpt-5.6",
+ "choices": [
+ {
+ "index": 0,
+ "delta": {"tool_calls": [{"index": 0, "custom": {"input": "*** End Patch\n"}}]},
+ "finish_reason": None,
+ }
+ ],
+ },
+ {
+ "id": "chatcmpl-custom",
+ "object": "chat.completion.chunk",
+ "created": 1784657671,
+ "model": "gpt-5.6",
+ "choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}],
+ },
+ ]
+ sdk_chunks = [ChatCompletionChunk.construct(**raw) for raw in raw_chunks]
+ first_dumped = sdk_chunks[0].choices[0].model_dump()
+ assert first_dumped["delta"]["tool_calls"][0]["custom"] == {"name": "ApplyPatch", "input": ""}
+
+ wrapper = CustomStreamWrapper(
+ completion_stream=iter(sdk_chunks),
+ model="gpt-5.6",
+ custom_llm_provider="openai",
+ logging_obj=logging_obj,
+ )
+
+ emitted = list(wrapper)
+ tool_call_deltas = [
+ chunk.choices[0].delta.tool_calls[0]
+ for chunk in emitted
+ if chunk.choices and chunk.choices[0].delta and chunk.choices[0].delta.tool_calls
+ ]
+ assert len(tool_call_deltas) == 3
+ assert isinstance(tool_call_deltas[0], ChatCompletionDeltaCustomToolCall)
+ assert tool_call_deltas[0].id == "call_TBs"
+ assert tool_call_deltas[0].type == "custom"
+ assert tool_call_deltas[0].custom.name == "ApplyPatch"
+ combined_input = "".join(tc.custom.input or "" for tc in tool_call_deltas)
+ assert combined_input == "*** Begin Patch\n*** End Patch\n"
+ finish_reasons = [chunk.choices[0].finish_reason for chunk in emitted if chunk.choices]
+ assert "tool_calls" in finish_reasons
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 c41de4a8e40..4ef338b35e4 100644
--- a/tests/test_litellm/proxy/response_api_endpoints/test_endpoints.py
+++ b/tests/test_litellm/proxy/response_api_endpoints/test_endpoints.py
@@ -907,3 +907,126 @@ def test_cursor_models_route_delegates_to_model_list():
assert mock_model_list.call_count == 2
finally:
app.dependency_overrides.pop(user_api_key_auth, None)
+
+
+class TestNestFlatChatTools:
+ def test_flat_custom_tool_is_nested(self):
+ from litellm.proxy.response_api_endpoints.endpoints import _nest_flat_chat_tools
+
+ result = _nest_flat_chat_tools(
+ [{"type": "custom", "name": "ApplyPatch", "description": "V4A patch", "format": {"type": "text"}}]
+ )
+ assert result == [
+ {
+ "type": "custom",
+ "custom": {"name": "ApplyPatch", "description": "V4A patch", "format": {"type": "text"}},
+ }
+ ]
+
+ def test_flat_function_tool_is_nested(self):
+ from litellm.proxy.response_api_endpoints.endpoints import _nest_flat_chat_tools
+
+ result = _nest_flat_chat_tools(
+ [{"type": "function", "name": "read_file", "description": "d", "parameters": {"type": "object"}}]
+ )
+ assert result == [
+ {
+ "type": "function",
+ "function": {"name": "read_file", "description": "d", "parameters": {"type": "object"}},
+ }
+ ]
+
+ def test_already_nested_and_unrecognized_tools_pass_through_unchanged(self):
+ from litellm.proxy.response_api_endpoints.endpoints import _nest_flat_chat_tools
+
+ tools = [
+ {"type": "custom", "custom": {"name": "already_nested"}},
+ {"type": "function", "function": {"name": "f", "parameters": {}}},
+ {"type": "web_search"},
+ {"type": "custom"},
+ {"name": "typeless"},
+ {},
+ "junk",
+ None,
+ 42,
+ ]
+ assert _nest_flat_chat_tools(tools) == tools
+
+
+class TestCursorMessagesArmToolNormalization:
+ @pytest.mark.asyncio
+ async def test_flat_custom_tool_nested_before_chat_completion_delegation(self):
+ from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
+ from litellm.proxy._types import UserAPIKeyAuth
+
+ seen = {}
+
+ async def fake_chat_completion(request, fastapi_response, model, user_api_key_dict):
+ from litellm.proxy.common_utils.http_parsing_utils import _read_request_body
+
+ seen["body"] = await _read_request_body(request=request)
+ return {"id": "chatcmpl-fake", "object": "chat.completion", "choices": []}
+
+ app.dependency_overrides[user_api_key_auth] = lambda: UserAPIKeyAuth(api_key="sk-1234")
+ try:
+ with patch("litellm.proxy.proxy_server.chat_completion", new=fake_chat_completion):
+ client = TestClient(app)
+ response = client.post(
+ "/cursor/chat/completions",
+ json={
+ "model": "gpt-5.6",
+ "messages": [{"role": "user", "content": "use ApplyPatch"}],
+ "tools": [
+ {
+ "type": "function",
+ "function": {"name": "read_file", "parameters": {"type": "object"}},
+ },
+ {"type": "custom", "name": "ApplyPatch", "description": "V4A patch"},
+ ],
+ "tool_choice": "required",
+ },
+ headers={"Authorization": "Bearer sk-1234"},
+ )
+ finally:
+ app.dependency_overrides.pop(user_api_key_auth, None)
+
+ assert response.status_code == 200
+ assert seen["body"]["tools"] == [
+ {"type": "function", "function": {"name": "read_file", "parameters": {"type": "object"}}},
+ {"type": "custom", "custom": {"name": "ApplyPatch", "description": "V4A patch"}},
+ ]
+ assert seen["body"]["messages"] == [{"role": "user", "content": "use ApplyPatch"}]
+
+ @pytest.mark.asyncio
+ async def test_messages_body_without_flat_tools_leaves_parsed_body_cache_untouched(self):
+ from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
+ from litellm.proxy._types import UserAPIKeyAuth
+
+ seen = {}
+
+ async def fake_chat_completion(request, fastapi_response, model, user_api_key_dict):
+ from litellm.proxy.common_utils.http_parsing_utils import _read_request_body
+
+ seen["body"] = await _read_request_body(request=request)
+ return {"id": "chatcmpl-fake", "object": "chat.completion", "choices": []}
+
+ body = {
+ "model": "gpt-5.6",
+ "messages": [{"role": "user", "content": "hi"}],
+ "tools": [{"type": "function", "function": {"name": "f", "parameters": {}}}],
+ }
+ app.dependency_overrides[user_api_key_auth] = lambda: UserAPIKeyAuth(api_key="sk-1234")
+ try:
+ with patch("litellm.proxy.proxy_server.chat_completion", new=fake_chat_completion):
+ client = TestClient(app)
+ response = client.post(
+ "/cursor/chat/completions",
+ json=body,
+ headers={"Authorization": "Bearer sk-1234"},
+ )
+ finally:
+ app.dependency_overrides.pop(user_api_key_auth, None)
+
+ assert response.status_code == 200
+ assert seen["body"]["tools"] == body["tools"]
+ assert seen["body"]["messages"] == body["messages"]
diff --git a/tests/test_litellm/types/test_types_utils.py b/tests/test_litellm/types/test_types_utils.py
index 320c46aed3b..4d08239360f 100644
--- a/tests/test_litellm/types/test_types_utils.py
+++ b/tests/test_litellm/types/test_types_utils.py
@@ -603,3 +603,92 @@ def test_delattr_fast_path_missing_attribute_is_noop():
del racy.x
del racy.x
+def test_chat_completion_tool_call_from_dict_custom():
+ from litellm.types.utils import (
+ ChatCompletionMessageCustomToolCall,
+ ChatCompletionMessageToolCall,
+ chat_completion_tool_call_from_dict,
+ )
+
+ custom_tc = {
+ "id": "call_njxQ",
+ "type": "custom",
+ "custom": {"name": "ApplyPatch", "input": "*** Begin Patch\n*** End Patch\n"},
+ }
+ parsed = chat_completion_tool_call_from_dict(custom_tc)
+ assert isinstance(parsed, ChatCompletionMessageCustomToolCall)
+ assert parsed.model_dump() == custom_tc
+
+ func_tc = {"id": "call_1", "type": "function", "function": {"name": "f", "arguments": "{}"}}
+ parsed_func = chat_completion_tool_call_from_dict(func_tc)
+ assert isinstance(parsed_func, ChatCompletionMessageToolCall)
+ assert "custom" not in parsed_func.model_dump()
+
+
+def test_chat_completion_tool_call_from_dict_custom_strips_null_function():
+ from litellm.types.utils import chat_completion_tool_call_from_dict
+
+ sdk_shaped = {
+ "id": "call_x",
+ "type": "custom",
+ "function": None,
+ "custom": {"name": "ApplyPatch", "input": ""},
+ }
+ parsed = chat_completion_tool_call_from_dict(sdk_shaped)
+ assert "function" not in parsed.model_dump()
+
+
+def test_message_with_mixed_function_and_custom_tool_calls():
+ from litellm.types.utils import (
+ ChatCompletionMessageCustomToolCall,
+ ChatCompletionMessageToolCall,
+ Message,
+ )
+
+ message = Message(
+ content=None,
+ role="assistant",
+ tool_calls=[
+ {"id": "call_c", "type": "custom", "custom": {"name": "ApplyPatch", "input": "patch"}},
+ {"id": "call_f", "type": "function", "function": {"name": "f", "arguments": "{}"}},
+ ],
+ )
+ assert isinstance(message.tool_calls[0], ChatCompletionMessageCustomToolCall)
+ assert isinstance(message.tool_calls[1], ChatCompletionMessageToolCall)
+ dumped = message.model_dump()["tool_calls"]
+ assert dumped[0] == {"id": "call_c", "type": "custom", "custom": {"name": "ApplyPatch", "input": "patch"}}
+ assert "custom" not in dumped[1]
+
+
+def test_delta_custom_tool_call_first_and_continuation_chunks():
+ from litellm.types.utils import ChatCompletionDeltaCustomToolCall, Delta
+
+ first_chunk_tc = {
+ "index": 0,
+ "id": "call_TBs",
+ "function": None,
+ "type": "custom",
+ "custom": {"name": "ApplyPatch", "input": ""},
+ }
+ continuation_tc = {"index": 0, "id": None, "function": None, "type": None, "custom": {"input": "***"}}
+
+ first_delta = Delta(role="assistant", tool_calls=[first_chunk_tc])
+ assert isinstance(first_delta.tool_calls[0], ChatCompletionDeltaCustomToolCall)
+ first_dump = first_delta.model_dump()["tool_calls"][0]
+ assert first_dump["type"] == "custom"
+ assert first_dump["custom"] == {"name": "ApplyPatch", "input": ""}
+ assert "function" not in first_dump
+
+ continuation_delta = Delta(tool_calls=[continuation_tc])
+ cont_dump = continuation_delta.model_dump()["tool_calls"][0]
+ assert cont_dump["type"] is None
+ assert cont_dump["custom"]["input"] == "***"
+ assert "function" not in cont_dump
+
+
+def test_delta_function_tool_call_unchanged_by_custom_support():
+ from litellm.types.utils import ChatCompletionDeltaToolCall, Delta
+
+ delta = Delta(tool_calls=[{"index": 0, "id": "c2", "type": "function", "function": {"name": "g", "arguments": ""}}])
+ assert isinstance(delta.tool_calls[0], ChatCompletionDeltaToolCall)
+ assert "custom" not in delta.model_dump()["tool_calls"][0]
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index 1bc8839976d..bf3cc75c796 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -2628,7 +2628,9 @@ export interface paths {
* custom tools) to the chat/completions path while expecting chat completions responses;
* those are routed through the Responses API pipeline and converted back. Genuine chat
* completions bodies (`messages` present) are routed through the standard chat completions
- * pipeline untouched.
+ * pipeline, after nesting any flat Responses-style tool defs Cursor mixes into the chat
+ * `tools` array (e.g. `{"type": "custom", "name": "ApplyPatch", ...}`) into the chat
+ * completions shape OpenAI requires (`{"type": "custom", "custom": {...}}`).
*
* ```bash
* curl -X POST http://localhost:4000/cursor/chat/completions -H "Content-Type: application/json" -H "Authorization: Bearer sk-1234" -d '{
@@ -22195,6 +22197,15 @@ export interface components {
*/
type: "ephemeral";
};
+ /** ChatCompletionCustomToolCallPayload */
+ ChatCompletionCustomToolCallPayload: {
+ /** Input */
+ input: string;
+ /** Name */
+ name: string;
+ } & {
+ [key: string]: unknown;
+ };
/** ChatCompletionDeveloperMessage */
ChatCompletionDeveloperMessage: {
cache_control?: components["schemas"]["ChatCompletionCachedContent"];
@@ -22281,6 +22292,20 @@ export interface components {
/** Url */
url: string;
};
+ /** ChatCompletionMessageCustomToolCall */
+ ChatCompletionMessageCustomToolCall: {
+ custom: components["schemas"]["ChatCompletionCustomToolCallPayload"];
+ /** Id */
+ id: string;
+ /**
+ * Type
+ * @default custom
+ * @constant
+ */
+ type: "custom";
+ } & {
+ [key: string]: unknown;
+ };
/** ChatCompletionMessageToolCall */
ChatCompletionMessageToolCall: {
[key: string]: unknown;
@@ -27909,7 +27934,7 @@ export interface components {
/** Thinking Blocks */
thinking_blocks?: (components["schemas"]["ChatCompletionThinkingBlock"] | components["schemas"]["ChatCompletionRedactedThinkingBlock"])[] | null;
/** Tool Calls */
- tool_calls: components["schemas"]["ChatCompletionMessageToolCall"][] | null;
+ tool_calls: (components["schemas"]["ChatCompletionMessageToolCall"] | components["schemas"]["ChatCompletionMessageCustomToolCall"])[] | null;
} & {
[key: string]: unknown;
};