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]

add better err handling for antropic (#18955)

Harshit Jain5ce3a56ac331
diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.py
index 2f8568db704..a8b8b207de4 100644
--- a/litellm/litellm_core_utils/prompt_templates/common_utils.py
+++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py
@@ -95,7 +95,9 @@ def handle_messages_with_content_list_to_str_conversion(
return messages
-def strip_name_from_message(message: AllMessageValues, allowed_name_roles: List[str] = ["user"]) -> AllMessageValues:
+def strip_name_from_message(
+ message: AllMessageValues, allowed_name_roles: List[str] = ["user"]
+) -> AllMessageValues:
"""
Removes 'name' from message
"""
@@ -104,6 +106,7 @@ def strip_name_from_message(message: AllMessageValues, allowed_name_roles: List[
msg_copy.pop("name", None) # type: ignore
return msg_copy
+
def strip_name_from_messages(
messages: List[AllMessageValues], allowed_name_roles: List[str] = ["user"]
) -> List[AllMessageValues]:
@@ -444,7 +447,7 @@ def update_responses_input_with_model_file_ids(
"""
Updates responses API input with provider-specific file IDs.
File IDs are always inside the content array, not as direct input_file items.
-
+
For managed files (unified file IDs), decodes the base64-encoded unified file ID
and extracts the llm_output_file_id directly.
"""
@@ -452,25 +455,28 @@ def update_responses_input_with_model_file_ids(
_is_base64_encoded_unified_file_id,
convert_b64_uid_to_unified_uid,
)
-
+
if isinstance(input, str):
return input
-
+
if not isinstance(input, list):
return input
-
+
updated_input = []
for item in input:
if not isinstance(item, dict):
updated_input.append(item)
continue
-
+
updated_item = item.copy()
content = item.get("content")
if isinstance(content, list):
updated_content = []
for content_item in content:
- if isinstance(content_item, dict) and content_item.get("type") == "input_file":
+ if (
+ isinstance(content_item, dict)
+ and content_item.get("type") == "input_file"
+ ):
file_id = content_item.get("file_id")
if file_id:
# Check if this is a managed file ID (base64-encoded unified file ID)
@@ -478,7 +484,9 @@ def update_responses_input_with_model_file_ids(
if is_unified_file_id:
unified_file_id = convert_b64_uid_to_unified_uid(file_id)
if "llm_output_file_id," in unified_file_id:
- provider_file_id = unified_file_id.split("llm_output_file_id,")[1].split(";")[0]
+ provider_file_id = unified_file_id.split(
+ "llm_output_file_id,"
+ )[1].split(";")[0]
else:
# Fallback: keep original if we can't extract
provider_file_id = file_id
@@ -492,9 +500,9 @@ def update_responses_input_with_model_file_ids(
else:
updated_content.append(content_item)
updated_item["content"] = updated_content
-
+
updated_input.append(updated_item)
-
+
return updated_input
@@ -697,9 +705,9 @@ def _get_image_mime_type_from_url(url: str) -> Optional[str]:
video/flv
"""
from urllib.parse import urlparse
-
+
url = url.lower()
-
+
# Parse URL to extract path without query parameters
# This handles URLs like: https://example.com/image.jpg?signature=...
parsed = urlparse(url)
@@ -744,28 +752,28 @@ def infer_content_type_from_url_and_content(
) -> str:
"""
Infer content type from URL extension and binary content when content-type header is missing or generic.
-
+
This helper implements a fallback strategy for determining MIME types when HTTP headers
are missing or provide generic values (like binary/octet-stream). It's commonly used
when processing images and documents from various sources (S3, URLs, etc.).
-
+
Fallback Strategy:
1. If current_content_type is valid (not None and not generic octet-stream), return it
2. Try to infer from URL extension (handles query parameters)
3. Try to detect from binary content signature (magic bytes)
4. Raise ValueError if all methods fail
-
+
Args:
url: The URL of the content (used to extract file extension)
content: The binary content (first ~100 bytes are sufficient for detection)
current_content_type: The current content-type from headers (may be None or generic)
-
+
Returns:
str: The inferred MIME type (e.g., "image/png", "application/pdf")
-
+
Raises:
ValueError: If content type cannot be determined by any method
-
+
Example:
>>> content_type = infer_content_type_from_url_and_content(
... url="https://s3.amazonaws.com/bucket/image.png?AWSAccessKeyId=123",
@@ -776,14 +784,14 @@ def infer_content_type_from_url_and_content(
"image/png"
"""
from litellm.litellm_core_utils.token_counter import get_image_type
-
+
# If we have a valid content type that's not generic, use it
if current_content_type and current_content_type not in [
"binary/octet-stream",
"application/octet-stream",
]:
return current_content_type
-
+
# Extension to MIME type mapping
# Supports images, documents, and other common file types
extension_to_mime = {
@@ -804,14 +812,14 @@ def infer_content_type_from_url_and_content(
"txt": "text/plain",
"md": "text/markdown",
}
-
+
# Try to infer from URL extension
if url:
extension = url.split(".")[-1].lower().split("?")[0] # Remove query params
inferred_type = extension_to_mime.get(extension)
if inferred_type:
return inferred_type
-
+
# Try to detect from binary content signature (magic bytes)
if content:
detected_type = get_image_type(content[:100])
@@ -825,7 +833,7 @@ def infer_content_type_from_url_and_content(
}
if detected_type in type_to_mime:
return type_to_mime[detected_type]
-
+
# If all fallbacks failed, raise error
raise ValueError(
f"Unable to determine content type from URL: {url}. "
@@ -1085,7 +1093,9 @@ def _parse_content_for_reasoning(
return None, message_text
reasoning_match = re.match(
- r"<(?:think|thinking|budget:thinking)>(.*?)</(?:think|thinking|budget:thinking)>(.*)", message_text, re.DOTALL
+ r"<(?:think|thinking|budget:thinking)>(.*?)</(?:think|thinking|budget:thinking)>(.*)",
+ message_text,
+ re.DOTALL,
)
if reasoning_match:
@@ -1135,3 +1145,47 @@ def extract_images_from_message(message: AllMessageValues) -> List[str]:
elif isinstance(image_url, dict) and "url" in image_url:
images.append(_extract_base64_data(image_url["url"]))
return images
+
+
+def parse_tool_call_arguments(
+ arguments: Optional[str],
+ tool_name: Optional[str] = None,
+ context: Optional[str] = None,
+) -> Dict[str, Any]:
+ """
+ Parse tool call arguments from a JSON string.
+
+ This function handles malformed JSON gracefully by raising a ValueError
+ with context about what failed and what the problematic input was.
+
+ Args:
+ arguments: The JSON string containing tool arguments, or None.
+ tool_name: Optional name of the tool (for error messages).
+ context: Optional context string (e.g., "Anthropic Messages API").
+
+ Returns:
+ Parsed arguments as a dictionary. Returns empty dict if arguments is None or empty.
+
+ Raises:
+ ValueError: If the arguments string is not valid JSON.
+ """
+ import json
+
+ if not arguments:
+ return {}
+
+ try:
+ return json.loads(arguments)
+ except json.JSONDecodeError as e:
+ error_parts = ["Failed to parse tool call arguments"]
+
+ if tool_name:
+ error_parts.append(f"for tool '{tool_name}'")
+ if context:
+ error_parts.append(f"({context})")
+
+ error_message = (
+ " ".join(error_parts) + f". Error: {str(e)}. Arguments: {arguments}"
+ )
+
+ raise ValueError(error_message) from e
diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.py
index d8e82199272..4320f756454 100644
--- a/litellm/litellm_core_utils/prompt_templates/factory.py
+++ b/litellm/litellm_core_utils/prompt_templates/factory.py
@@ -44,6 +44,7 @@ from .common_utils import (
convert_content_list_to_str,
infer_content_type_from_url_and_content,
is_non_content_values_set,
+ parse_tool_call_arguments,
)
from .image_handling import convert_url_to_base64
@@ -911,13 +912,13 @@ def convert_to_anthropic_image_obj(
def create_anthropic_image_param(
- image_url_input: Union[str, dict],
+ image_url_input: Union[str, dict],
format: Optional[str] = None,
- is_bedrock_invoke: bool = False
+ is_bedrock_invoke: bool = False,
) -> AnthropicMessagesImageParam:
"""
Create an AnthropicMessagesImageParam from an image URL input.
-
+
Supports both URL references (for HTTP/HTTPS URLs) and base64 encoding.
"""
# Extract URL and format from input
@@ -927,7 +928,7 @@ def create_anthropic_image_param(
image_url = image_url_input.get("url", "")
if format is None:
format = image_url_input.get("format")
-
+
# Check if the image URL is an HTTP/HTTPS URL
if image_url.startswith("http://") or image_url.startswith("https://"):
# For Bedrock invoke and Vertex AI Anthropic, always convert URLs to base64
@@ -1031,9 +1032,11 @@ def convert_to_anthropic_tool_invoke_xml(tool_calls: list) -> str:
tool_function = get_attribute_or_key(tool, "function")
tool_name = get_attribute_or_key(tool_function, "name")
tool_arguments = get_attribute_or_key(tool_function, "arguments")
+ parsed_args = parse_tool_call_arguments(
+ tool_arguments, tool_name=tool_name, context="Anthropic XML tool invoke"
+ )
parameters = "".join(
- f"<{param}>{val}</{param}>\n"
- for param, val in json.loads(tool_arguments).items()
+ f"<{param}>{val}</{param}>\n" for param, val in parsed_args.items()
)
invokes += (
"<invoke>\n"
@@ -1071,8 +1074,14 @@ def anthropic_messages_pt_xml(messages: list):
if isinstance(messages[msg_i]["content"], list):
for m in messages[msg_i]["content"]:
if m.get("type", "") == "image_url":
- format = m["image_url"].get("format") if isinstance(m["image_url"], dict) else None
- image_param = create_anthropic_image_param(m["image_url"], format=format)
+ format = (
+ m["image_url"].get("format")
+ if isinstance(m["image_url"], dict)
+ else None
+ )
+ image_param = create_anthropic_image_param(
+ m["image_url"], format=format
+ )
# Convert to dict format for XML version
source = image_param["source"]
if isinstance(source, dict) and source.get("type") == "url":
@@ -1381,10 +1390,10 @@ def convert_to_gemini_tool_call_invoke(
if tool_calls is not None:
for idx, tool in enumerate(tool_calls):
if "function" in tool:
- gemini_function_call: Optional[
- VertexFunctionCall
- ] = _gemini_tool_call_invoke_helper(
- function_call_params=tool["function"]
+ gemini_function_call: Optional[VertexFunctionCall] = (
+ _gemini_tool_call_invoke_helper(
+ function_call_params=tool["function"]
+ )
)
if gemini_function_call is not None:
part_dict: VertexPartType = {
@@ -1484,10 +1493,10 @@ def convert_to_gemini_tool_call_result(
}
"""
from litellm.types.llms.vertex_ai import BlobType
-
+
content_str: str = ""
inline_data: Optional[BlobType] = None
-
+
if "content" in message:
if isinstance(message["content"], str):
content_str = message["content"]
@@ -1500,15 +1509,21 @@ def convert_to_gemini_tool_call_result(
elif content_type in ("input_image", "image_url"):
# Extract image for inline_data (for Computer Use screenshots and tool results)
image_url_data = content.get("image_url", "")
- image_url = image_url_data.get("url", "") if isinstance(image_url_data, dict) else image_url_data
-
+ image_url = (
+ image_url_data.get("url", "")
+ if isinstance(image_url_data, dict)
+ else image_url_data
+ )
+
if image_url:
# Convert image to base64 blob format for Gemini
try:
- image_obj = convert_to_anthropic_image_obj(image_url, format=None)
+ image_obj = convert_to_anthropic_image_obj(
+ image_url, format=None
+ )
inline_data = BlobType(
data=image_obj["data"],
- mime_type=image_obj["media_type"]
+ mime_type=image_obj["media_type"],
)
except Exception as e:
verbose_logger.warning(
@@ -1541,6 +1556,7 @@ def convert_to_gemini_tool_call_result(
response_data: dict
try:
import json
+
if content_str.strip().startswith("{") or content_str.strip().startswith("["):
# Try to parse as JSON (for Computer Use structured responses)
parsed = json.loads(content_str)
@@ -1553,7 +1569,7 @@ def convert_to_gemini_tool_call_result(
except (json.JSONDecodeError, ValueError):
# Not valid JSON, wrap in content field
response_data = {"content": content_str}
-
+
# We can't determine from openai message format whether it's a successful or
# error call result so default to the successful result template
_function_response = VertexFunctionResponse(
@@ -1562,7 +1578,7 @@ def convert_to_gemini_tool_call_result(
# Create part with function_response, and optionally inline_data for images (Computer Use)
_part: VertexPartType = {"function_response": _function_response}
-
+
# For Computer Use, if we have an image, we need separate parts:
# - One part with function_response
# - One part with inline_data
@@ -1570,19 +1586,19 @@ def convert_to_gemini_tool_call_result(
if inline_data:
image_part: VertexPartType = {"inline_data": inline_data}
return [_part, image_part]
-
+
return _part
def _sanitize_anthropic_tool_use_id(tool_use_id: str) -> str:
"""
Sanitize tool_use_id to match Anthropic's required pattern: ^[a-zA-Z0-9_-]+$
-
+
Anthropic requires tool_use_id to only contain alphanumeric characters, underscores, and hyphens.
This function replaces any invalid characters with underscores.
"""
# Replace any character that's not alphanumeric, underscore, or hyphen with underscore
- sanitized = re.sub(r'[^a-zA-Z0-9_-]', '_', tool_use_id)
+ sanitized = re.sub(r"[^a-zA-Z0-9_-]", "_", tool_use_id)
# Ensure it's not empty (fallback to a default if needed)
if not sanitized:
sanitized = "tool_use_id"
@@ -1644,8 +1660,14 @@ def convert_to_anthropic_tool_result(
)
)
elif content["type"] == "image_url":
- format = content["image_url"].get("format") if isinstance(content["image_url"], dict) else None
- _anthropic_image_param = create_anthropic_image_param(content["image_url"], format=format)
+ format = (
+ content["image_url"].get("format")
+ if isinstance(content["image_url"], dict)
+ else None
+ )
+ _anthropic_image_param = create_anthropic_image_param(
+ content["image_url"], format=format
+ )
_anthropic_image_param = add_cache_control_to_content(
anthropic_content_element=_anthropic_image_param,
original_content_element=content,
@@ -1665,7 +1687,9 @@ def convert_to_anthropic_tool_result(
# We can't determine from openai message format whether it's a successful or
# error call result so default to the successful result template
anthropic_tool_result = AnthropicMessagesToolResultParam(
- type="tool_result", tool_use_id=sanitized_tool_use_id, content=anthropic_content
+ type="tool_result",
+ tool_use_id=sanitized_tool_use_id,
+ content=anthropic_content,
)
if message["role"] == "function":
@@ -1674,7 +1698,9 @@ def convert_to_anthropic_tool_result(
# Sanitize tool_use_id to match Anthropic's pattern requirement: ^[a-zA-Z0-9_-]+$
sanitized_tool_use_id = _sanitize_anthropic_tool_use_id(tool_call_id)
anthropic_tool_result = AnthropicMessagesToolResultParam(
- type="tool_result", tool_use_id=sanitized_tool_use_id, content=anthropic_content
+ type="tool_result",
+ tool_use_id=sanitized_tool_use_id,
+ content=anthropic_content,
)
if anthropic_tool_result is None:
@@ -1690,12 +1716,17 @@ def convert_function_to_anthropic_tool_invoke(
try:
_name = get_attribute_or_key(function_call, "name") or ""
_arguments = get_attribute_or_key(function_call, "arguments")
+
+ tool_input = parse_tool_call_arguments(
+ _arguments, tool_name=_name, context="Anthropic function to tool invoke"
+ )
+
anthropic_tool_invoke = [
AnthropicMessagesToolUseParam(
type="tool_use",
id=str(uuid.uuid4()),
name=_name,
- input=json.loads(_arguments) if _arguments else {},
+ input=tool_input,
)
]
return anthropic_tool_invoke
@@ -1749,7 +1780,9 @@ def convert_to_anthropic_tool_invoke(
Fixes: https://github.com/BerriAI/litellm/issues/17737
"""
- anthropic_tool_invoke: List[Union[AnthropicMessagesToolUseParam, Dict[str, Any]]] = []
+ anthropic_tool_invoke: List[
+ Union[AnthropicMessagesToolUseParam, Dict[str, Any]]
+ ] = []
for tool in tool_calls:
if not get_attribute_or_key(tool, "type") == "function":
@@ -1760,10 +1793,10 @@ def convert_to_anthropic_tool_invoke(
str,
get_attribute_or_key(get_attribute_or_key(tool, "function"), "name"),
)
- tool_input = json.loads(
- get_attribute_or_key(
- get_attribute_or_key(tool, "function"), "arguments"
- )
+ tool_input = parse_tool_call_arguments(
+ get_attribute_or_key(get_attribute_or_key(tool, "function"), "arguments"),
+ tool_name=tool_name,
+ context="Anthropic tool invoke",
)
# Check if this is a server-side tool (web_search, tool_search, etc.)
@@ -2015,11 +2048,17 @@ def anthropic_messages_pt( # noqa: PLR0915
for m in user_message_types_block["content"]:
if m.get("type", "") == "image_url":
m = cast(ChatCompletionImageObject, m)
- format = m["image_url"].get("format") if isinstance(m["image_url"], dict) else None
+ format = (
+ m["image_url"].get("format")
+ if isinstance(m["image_url"], dict)
+ else None
+ )
# Convert ChatCompletionImageUrlObject to dict if needed
image_url_value = m["image_url"]
if isinstance(image_url_value, str):
- image_url_input: Union[str, dict[str, Any]] = image_url_value
+ image_url_input: Union[str, dict[str, Any]] = (
+ image_url_value
+ )
else:
# ChatCompletionImageUrlObject or dict case - convert to dict
image_url_input = {
@@ -2029,20 +2068,26 @@ def anthropic_messages_pt( # noqa: PLR0915
# Bedrock invoke models have format: invoke/...
# Vertex AI Anthropic also doesn't support URL sources for images
is_bedrock_invoke = model.lower().startswith("invoke/")
- is_vertex_ai = llm_provider.startswith("vertex_ai") if llm_provider else False
+ is_vertex_ai = (
+ llm_provider.startswith("vertex_ai")
+ if llm_provider
+ else False
+ )
force_base64 = is_bedrock_invoke or is_vertex_ai
_anthropic_content_element = create_anthropic_image_param(
- image_url_input, format=format, is_bedrock_invoke=force_base64
- )
+ image_url_input,
+ format=format,
+ is_bedrock_invoke=force_base64,
+ )
_content_element = add_cache_control_to_content(
anthropic_content_element=_anthropic_content_element,
original_content_element=dict(m),
)
if "cache_control" in _content_element:
- _anthropic_content_element[
- "cache_control"
- ] = _content_element["cache_control"]
+ _anthropic_content_element["cache_control"] = (
+ _content_element["cache_control"]
+ )
user_content.append(_anthropic_content_element)
elif m.get("type", "") == "text":
m = cast(ChatCompletionTextObject, m)
@@ -2080,9 +2125,9 @@ def anthropic_messages_pt( # noqa: PLR0915
)
if "cache_control" in _content_element:
- _anthropic_content_text_element[
- "cache_control"
- ] = _content_element["cache_control"]
+ _anthropic_content_text_element["cache_control"] = (
+ _content_element["cache_control"]
+ )
user_content.append(_anthropic_content_text_element)
@@ -2178,18 +2223,27 @@ def anthropic_messages_pt( # noqa: PLR0915
): # support assistant tool invoke conversion
# Get web_search_results from provider_specific_fields for server_tool_use reconstruction
# Fixes: https://github.com/BerriAI/litellm/issues/17737
- _provider_specific_fields_raw = assistant_content_block.get("provider_specific_fields")
+ _provider_specific_fields_raw = assistant_content_block.get(
+ "provider_specific_fields"
+ )
_provider_specific_fields: Dict[str, Any] = {}
if isinstance(_provider_specific_fields_raw, dict):
- _provider_specific_fields = cast(Dict[str, Any], _provider_specific_fields_raw)
- _web_search_results = _provider_specific_fields.get("web_search_results")
+ _provider_specific_fields = cast(
+ Dict[str, Any], _provider_specific_fields_raw
+ )
+ _web_search_results = _provider_specific_fields.get(
+ "web_search_results"
+ )
tool_invoke_results = convert_to_anthropic_tool_invoke(
assistant_tool_calls,
web_search_results=_web_search_results,
)
# AnthropicMessagesAssistantMessageValues includes AnthropicMessagesToolUseParam
assistant_content.extend(
- cast(List[AnthropicMessagesAssistantMessageValues], tool_invoke_results)
+ cast(
+ List[AnthropicMessagesAssistantMessageValues],
+ tool_invoke_results,
+ )
)
assistant_function_call = assistant_content_block.get("function_call")
@@ -3252,14 +3306,18 @@ def _convert_to_bedrock_tool_call_result(
"""
-
"""
- tool_result_content_blocks:List[BedrockToolResultContentBlock] = []
+ tool_result_content_blocks: List[BedrockToolResultContentBlock] = []
if isinstance(message["content"], str):
- tool_result_content_blocks.append(BedrockToolResultContentBlock(text=message["content"]))
+ tool_result_content_blocks.append(
+ BedrockToolResultContentBlock(text=message["content"])
+ )
elif isinstance(message["content"], List):
content_list = message["content"]
for content in content_list:
if content["type"] == "text":
- tool_result_content_blocks.append(BedrockToolResultContentBlock(text=content["text"]))
+ tool_result_content_blocks.append(
+ BedrockToolResultContentBlock(text=content["text"])
+ )
elif content["type"] == "image_url":
format: Optional[str] = None
if isinstance(content["image_url"], dict):
@@ -3267,12 +3325,14 @@ def _convert_to_bedrock_tool_call_result(
format = content["image_url"].get("format")
else:
image_url = content["image_url"]
- _block:BedrockContentBlock = BedrockImageProcessor.process_image_sync(
+ _block: BedrockContentBlock = BedrockImageProcessor.process_image_sync(
image_url=image_url,
format=format,
)
if "image" in _block:
- tool_result_content_blocks.append(BedrockToolResultContentBlock(image=_block["image"]))
+ tool_result_content_blocks.append(
+ BedrockToolResultContentBlock(image=_block["image"])
+ )
message.get("name", "")
id = str(message.get("tool_call_id", str(uuid.uuid4())))
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
index 8868fabdcef..06092755b17 100644
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
@@ -14,6 +14,10 @@ from typing import (
from openai.types.chat.chat_completion_chunk import Choice as OpenAIStreamingChoice
+from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ parse_tool_call_arguments,
+)
+
from litellm.types.llms.anthropic import (
AllAnthropicToolsValues,
AnthopicMessagesAssistantMessageParam,
@@ -425,15 +429,15 @@ class LiteLLMAnthropicMessagesAdapter:
) -> Optional[str]:
"""
Translate Anthropic's thinking parameter to OpenAI's reasoning_effort.
-
+
Anthropic thinking format: {'type': 'enabled'|'disabled', 'budget_tokens': int}
OpenAI reasoning_effort: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'default'
"""
if not isinstance(thinking, dict):
return None
-
+
thinking_type = thinking.get("type", "disabled")
-
+
if thinking_type == "disabled":
return None
elif thinking_type == "enabled":
@@ -446,7 +450,7 @@ class LiteLLMAnthropicMessagesAdapter:
return "low"
else:
return "minimal"
-
+
return None
def translate_anthropic_tool_choice_to_openai(
@@ -676,10 +680,10 @@ class LiteLLMAnthropicMessagesAdapter:
type="tool_use",
id=tool_call.id,
name=tool_call.function.name or "",
- input=(
- json.loads(tool_call.function.arguments)
- if tool_call.function.arguments
- else {}
+ input=parse_tool_call_arguments(
+ tool_call.function.arguments,
+ tool_name=tool_call.function.name,
+ context="Anthropic pass-through adapter",
),
)
# Add provider_specific_fields if signature is present
diff --git a/tests/llm_translation/test_prompt_factory.py b/tests/llm_translation/test_prompt_factory.py
index d0c0c12ba7c..8974632631d 100644
--- a/tests/llm_translation/test_prompt_factory.py
+++ b/tests/llm_translation/test_prompt_factory.py
@@ -7,11 +7,10 @@ import pytest
sys.path.insert(0, os.path.abspath("../.."))
-from typing import Union, List
+from typing import List
# from litellm.litellm_core_utils.prompt_templates.factory import prompt_factory
import litellm
-from litellm import completion
from litellm.litellm_core_utils.prompt_templates.factory import (
_bedrock_tools_pt,
anthropic_messages_pt,
@@ -31,7 +30,7 @@ from litellm.llms.vertex_ai.gemini.transformation import (
_gemini_convert_messages_with_history,
)
from litellm.types.llms.openai import AllMessageValues
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import MagicMock, patch
def test_llama_3_prompt():
@@ -129,10 +128,6 @@ def test_anthropic_pt_formatting():
def test_anthropic_messages_nested_pt():
- from litellm.types.llms.anthropic import (
- AnthopicMessagesAssistantMessageParam,
- AnthropicMessagesUserMessageParam,
- )
messages = [
{"content": [{"text": "here is a task", "type": "text"}], "role": "user"},
@@ -214,7 +209,7 @@ def test_create_anthropic_image_param_with_http_url():
image_param = create_anthropic_image_param(
"https://example.com/image.jpg", format=None
)
-
+
assert image_param["type"] == "image"
assert image_param["source"]["type"] == "url"
assert image_param["source"]["url"] == "https://example.com/image.jpg"
@@ -225,7 +220,7 @@ def test_create_anthropic_image_param_with_https_url():
image_param = create_anthropic_image_param(
"https://example.com/image.png", format=None
)
-
+
assert image_param["type"] == "image"
assert image_param["source"]["type"] == "url"
assert image_param["source"]["url"] == "https://example.com/image.png"
@@ -236,7 +231,7 @@ def test_create_anthropic_image_param_with_dict_input():
image_param = create_anthropic_image_param(
{"url": "https://example.com/image.jpg", "format": "image/jpeg"}, format=None
)
-
+
assert image_param["type"] == "image"
assert image_param["source"]["type"] == "url"
assert image_param["source"]["url"] == "https://example.com/image.jpg"
@@ -247,7 +242,7 @@ def test_create_anthropic_image_param_with_base64_data_uri():
image_param = create_anthropic_image_param(
"data:image/jpeg;base64,/9j/4AAQSkZJRg==", format=None
)
-
+
assert image_param["type"] == "image"
assert image_param["source"]["type"] == "base64"
assert image_param["source"]["media_type"] == "image/jpeg"
@@ -259,7 +254,7 @@ def test_create_anthropic_image_param_with_format_override():
image_param = create_anthropic_image_param(
"data:image/jpeg;base64,1234", format="image/png"
)
-
+
assert image_param["type"] == "image"
assert image_param["source"]["type"] == "base64"
assert image_param["source"]["media_type"] == "image/png"
@@ -279,19 +274,19 @@ def test_anthropic_messages_pt_with_url_image():
],
}
]
-
+
result = anthropic_messages_pt(
messages=messages, model="claude-3-5-sonnet", llm_provider="anthropic"
)
-
+
assert len(result) == 1
assert result[0]["role"] == "user"
assert isinstance(result[0]["content"], list)
assert len(result[0]["content"]) == 2
-
+
# Check text content
assert result[0]["content"][0]["type"] == "text"
-
+
# Check image content - should be URL reference, not base64
assert result[0]["content"][1]["type"] == "image"
assert result[0]["content"][1]["source"]["type"] == "url"
@@ -312,16 +307,16 @@ def test_anthropic_messages_pt_with_base64_image():
],
}
]
-
+
result = anthropic_messages_pt(
messages=messages, model="claude-3-5-sonnet", llm_provider="anthropic"
)
-
+
assert len(result) == 1
assert result[0]["role"] == "user"
assert isinstance(result[0]["content"], list)
assert len(result[0]["content"]) == 2
-
+
# Check image content - should be base64, not URL
assert result[0]["content"][1]["type"] == "image"
assert result[0]["content"][1]["source"]["type"] == "base64"
@@ -568,7 +563,9 @@ def test_vertex_only_image_user_message():
},
]
- response = _gemini_convert_messages_with_history(messages=messages, model="gemini-1.5-pro")
+ response = _gemini_convert_messages_with_history(
+ messages=messages, model="gemini-1.5-pro"
+ )
expected_response = [
{
@@ -962,8 +959,8 @@ def test_convert_to_anthropic_tool_invoke_regular_tool():
"type": "function",
"function": {
"name": "get_weather",
- "arguments": '{"location": "San Francisco"}'
- }
+ "arguments": '{"location": "San Francisco"}',
+ },
}
]
@@ -979,7 +976,7 @@ def test_convert_to_anthropic_tool_invoke_regular_tool():
def test_convert_to_anthropic_tool_invoke_server_tool():
"""
Test that server_tool_use (srvtoolu_) is reconstructed as server_tool_use.
-
+
Fixes: https://github.com/BerriAI/litellm/issues/17737
"""
tool_calls = [
@@ -988,8 +985,8 @@ def test_convert_to_anthropic_tool_invoke_server_tool():
"type": "function",
"function": {
"name": "web_search",
- "arguments": '{"query": "elephant weight"}'
- }
+ "arguments": '{"query": "elephant weight"}',
+ },
}
]
@@ -1005,7 +1002,7 @@ def test_convert_to_anthropic_tool_invoke_server_tool():
def test_convert_to_anthropic_tool_invoke_with_web_search_results():
"""
Test that web_search_tool_result is included after server_tool_use.
-
+
Fixes: https://github.com/BerriAI/litellm/issues/17737
"""
tool_calls = [
@@ -1014,8 +1011,8 @@ def test_convert_to_anthropic_tool_invoke_with_web_search_results():
"type": "function",
"function": {
"name": "web_search",
- "arguments": '{"query": "elephant weight"}'
- }
+ "arguments": '{"query": "elephant weight"}',
+ },
}
]
@@ -1028,13 +1025,15 @@ def test_convert_to_anthropic_tool_invoke_with_web_search_results():
"type": "web_search_result",
"url": "https://example.com",
"title": "Elephant Facts",
- "snippet": "Elephants weigh 5000 kg"
+ "snippet": "Elephants weigh 5000 kg",
}
- ]
+ ],
}
]
- result = convert_to_anthropic_tool_invoke(tool_calls, web_search_results=web_search_results)
+ result = convert_to_anthropic_tool_invoke(
+ tool_calls, web_search_results=web_search_results
+ )
assert len(result) == 2
# First: server_tool_use
@@ -1048,7 +1047,7 @@ def test_convert_to_anthropic_tool_invoke_with_web_search_results():
def test_convert_to_anthropic_tool_invoke_mixed_tools():
"""
Test that mixed server and regular tools are reconstructed correctly.
-
+
Fixes: https://github.com/BerriAI/litellm/issues/17737
"""
tool_calls = [
@@ -1057,28 +1056,27 @@ def test_convert_to_anthropic_tool_invoke_mixed_tools():
"type": "function",
"function": {
"name": "web_search",
- "arguments": '{"query": "elephant weight"}'
- }
+ "arguments": '{"query": "elephant weight"}',
+ },
},
{
"id": "toolu_01XYZ789",
"type": "function",
- "function": {
- "name": "add_numbers",
- "arguments": '{"a": 5000, "b": 100}'
- }
- }
+ "function": {"name": "add_numbers", "arguments": '{"a": 5000, "b": 100}'},
+ },
]
web_search_results = [
{
"type": "web_search_tool_result",
"tool_use_id": "srvtoolu_01ABC123",
- "content": [{"url": "https://example.com", "title": "Test"}]
+ "content": [{"url": "https://example.com", "title": "Test"}],
}
]
- result = convert_to_anthropic_tool_invoke(tool_calls, web_search_results=web_search_results)
+ result = convert_to_anthropic_tool_invoke(
+ tool_calls, web_search_results=web_search_results
+ )
assert len(result) == 3
# First: server_tool_use
@@ -1094,7 +1092,7 @@ def test_convert_to_anthropic_tool_invoke_mixed_tools():
def test_anthropic_messages_pt_with_server_tool_use():
"""
Test that anthropic_messages_pt correctly reconstructs server_tool_use from provider_specific_fields.
-
+
Fixes: https://github.com/BerriAI/litellm/issues/17737
"""
messages = [
@@ -1108,36 +1106,40 @@ def test_anthropic_messages_pt_with_server_tool_use():
"type": "function",
"function": {
"name": "web_search",
- "arguments": '{"query": "elephant weight"}'
- }
+ "arguments": '{"query": "elephant weight"}',
+ },
},
{
"id": "toolu_01XYZ789",
"type": "function",
"function": {
"name": "add_numbers",
- "arguments": '{"a": 5000, "b": 100}'
- }
- }
+ "arguments": '{"a": 5000, "b": 100}',
+ },
+ },
],
"provider_specific_fields": {
"web_search_results": [
{
"type": "web_search_tool_result",
"tool_use_id": "srvtoolu_01ABC123",
- "content": [{"url": "https://example.com", "title": "Test", "snippet": "5000 kg"}]
+ "content": [
+ {
+ "url": "https://example.com",
+ "title": "Test",
+ "snippet": "5000 kg",
+ }
+ ],
}
]
- }
+ },
},
- {
- "role": "tool",
- "tool_call_id": "toolu_01XYZ789",
- "content": "5100"
- }
+ {"role": "tool", "tool_call_id": "toolu_01XYZ789", "content": "5100"},
]
- result = anthropic_messages_pt(messages, model="claude-sonnet-4-5", llm_provider="anthropic")
+ result = anthropic_messages_pt(
+ messages, model="claude-sonnet-4-5", llm_provider="anthropic"
+ )
# Find the assistant message
assistant_msg = next(m for m in result if m["role"] == "assistant")
@@ -1162,3 +1164,73 @@ def test_anthropic_messages_pt_with_server_tool_use():
# Verify regular tool_use
tool_use = next(c for c in content if c.get("type") == "tool_use")
assert tool_use["id"] == "toolu_01XYZ789"
+
+
+# ============ parse_tool_call_arguments Tests ============
+# Tests for the shared utility that parses tool call JSON arguments
+
+
+def test_parse_tool_call_arguments_valid_json():
+ """Test that valid JSON is parsed correctly."""
+ from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ parse_tool_call_arguments,
+ )
+
+ result = parse_tool_call_arguments('{"city": "Paris", "units": "celsius"}')
+ assert result == {"city": "Paris", "units": "celsius"}
+
+
+def test_parse_tool_call_arguments_empty_input():
+ """Test that None/empty input returns empty dict."""
+ from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ parse_tool_call_arguments,
+ )
+
+ assert parse_tool_call_arguments(None) == {}
+ assert parse_tool_call_arguments("") == {}
+
+
+def test_parse_tool_call_arguments_malformed_json():
+ """Test that malformed JSON raises ValueError with context."""
+ from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ parse_tool_call_arguments,
+ )
+
+ with pytest.raises(ValueError) as exc_info:
+ parse_tool_call_arguments(
+ '{"skill_name": "pptx',
+ tool_name="load_skill",
+ context="Anthropic tool invoke",
+ )
+
+ error_msg = str(exc_info.value)
+ assert "load_skill" in error_msg
+ assert "Anthropic tool invoke" in error_msg
+ assert '{"skill_name": "pptx' in error_msg
+ assert "Unterminated string" in error_msg
+
+
+def test_convert_to_anthropic_tool_invoke_malformed_json():
+ """
+ Test that convert_to_anthropic_tool_invoke raises ValueError with context
+ when tool arguments contain malformed JSON.
+
+ Fixes: https://github.com/BerriAI/litellm/issues/18920
+ """
+ tool_calls = [
+ {
+ "id": "toolu_01_invalid",
+ "type": "function",
+ "function": {
+ "name": "bad_tool",
+ "arguments": '{"truncated', # Malformed JSON
+ },
+ }
+ ]
+
+ with pytest.raises(ValueError) as exc_info:
+ convert_to_anthropic_tool_invoke(tool_calls)
+
+ error_msg = str(exc_info.value)
+ assert "bad_tool" in error_msg
+ assert '{"truncated' in error_msg