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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
[Fix] CI/CD - Add missing documentation for ENVs & Clean Functionality (#18211)
Alexsander Hamir5230e97448db
diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.mdindex 998311b922b..4ee091e2e85 100644--- a/docs/my-website/docs/proxy/config_settings.md+++ b/docs/my-website/docs/proxy/config_settings.md@@ -346,6 +346,7 @@ router_settings:| optional_pre_call_checks | List[str] | List of pre-call checks to add to the router. Currently supported: 'router_budget_limiting', 'prompt_caching' || ignore_invalid_deployments | boolean | If true, ignores invalid deployments. Default for proxy is True - to prevent invalid models from blocking other models from being loaded. || search_tools | List[SearchToolTypedDict] | List of search tool configurations for Search API integration. Each tool specifies a search_tool_name and litellm_params with search_provider, api_key, api_base, etc. [Further Docs](../search.md) |+| guardrail_list | List[GuardrailTypedDict] | List of guardrail configurations for guardrail load balancing. Enables load balancing across multiple guardrail deployments with the same guardrail_name. [Further Docs](./guardrails/guardrail_load_balancing.md) |### environment variables - Referencediff --git a/litellm/__init__.py b/litellm/__init__.pyindex c85441e26c1..a1a12fc9313 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -558,6 +558,8 @@ ovhcloud_embedding_models: Set = set()lemonade_models: Set = set()docker_model_runner_models: Set = set()amazon_nova_models: Set = set()+stability_models: Set = set()+github_copilot_models: Set = set()def is_bedrock_pricing_only_model(key: str) -> bool:@@ -802,6 +804,10 @@ def add_known_models():docker_model_runner_models.add(key)elif value.get("litellm_provider") == "amazon_nova":amazon_nova_models.add(key)+ elif value.get("litellm_provider") == "stability":+ stability_models.add(key)+ elif value.get("litellm_provider") == "github_copilot":+ github_copilot_models.add(key)add_known_models()@@ -1004,6 +1010,8 @@ models_by_provider: dict = {"lemonade": lemonade_models,"clarifai": clarifai_models,"amazon_nova": amazon_nova_models,+ "stability": stability_models,+ "github_copilot": github_copilot_models,}# mapping for those models which have larger equivalentsdiff --git a/litellm/proxy/db/db_spend_update_writer.py b/litellm/proxy/db/db_spend_update_writer.pyindex da91790b941..5c5cd7c19f7 100644--- a/litellm/proxy/db/db_spend_update_writer.py+++ b/litellm/proxy/db/db_spend_update_writer.py@@ -13,7 +13,7 @@ import randomimport timeimport tracebackfrom datetime import datetime, timedelta-from typing import TYPE_CHECKING, Any, Dict, Literal, Optional, Union, cast, overload+from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Union, cast, overloadimport litellmfrom litellm._logging import verbose_proxy_logger@@ -869,6 +869,14 @@ class DBSpendUpdateWriter:team_member_list_transactions is not Noneand len(team_member_list_transactions.keys()) > 0):+ # Track which team memberships will be updated for cache invalidation+ team_memberships_to_invalidate: List[tuple[str, str]] = []+ for key in team_member_list_transactions.keys():+ # key is "team_id::<value>::user_id::<value>"+ team_id = key.split("::")[1]+ user_id = key.split("::")[3]+ team_memberships_to_invalidate.append((user_id, team_id))+for i in range(n_retry_times + 1):start_time = time.time()try:@@ -888,6 +896,7 @@ class DBSpendUpdateWriter:where={"team_id": team_id, "user_id": user_id},data={"spend": {"increment": response_cost}},)+ # Transaction succeeded, break out of retry loopbreakexcept DB_CONNECTION_ERROR_TYPES as e:if (@@ -904,6 +913,18 @@ class DBSpendUpdateWriter:_raise_failed_update_spend_exception(e=e, start_time=start_time, proxy_logging_obj=proxy_logging_obj)++ # Invalidate cache for updated team memberships+ # This ensures budget checks read fresh spend data from the database+ if team_memberships_to_invalidate and proxy_logging_obj is not None:+ user_api_key_cache = proxy_logging_obj.call_details.get("user_api_key_cache")+ if user_api_key_cache is not None:+ for user_id, team_id in team_memberships_to_invalidate:+ cache_key = "team_membership:{}:{}".format(user_id, team_id)+ await user_api_key_cache.async_delete_cache(key=cache_key)+ verbose_proxy_logger.debug(+ f"Invalidated team membership cache for user_id={user_id}, team_id={team_id}"+ )### UPDATE ORG TABLE ###org_list_transactions = db_spend_update_transactions["org_list_transactions"]diff --git a/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py b/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.pyindex 06e90763a03..83eb57158d7 100644--- a/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py+++ b/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py@@ -11,6 +11,7 @@ import refrom typing import (TYPE_CHECKING,Any,+ AsyncGenerator,Dict,List,Literal,@@ -27,6 +28,8 @@ from fastapi import HTTPExceptionfrom litellm import Routerfrom litellm._logging import verbose_proxy_loggerfrom litellm.integrations.custom_guardrail import CustomGuardrail+from litellm.proxy._types import UserAPIKeyAuth+from litellm.types.utils import ModelResponseStreamif TYPE_CHECKING:from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj@@ -737,6 +740,101 @@ class ContentFilterGuardrail(CustomGuardrail):inputs["texts"] = processed_textsreturn inputs+ async def async_post_call_streaming_iterator_hook(+ self,+ user_api_key_dict: UserAPIKeyAuth,+ response: Any,+ request_data: dict,+ ) -> AsyncGenerator[ModelResponseStream, None]:+ """+ Process streaming response chunks and check for blocked content.++ For BLOCK action: Raises HTTPException immediately when blocked content is detected.+ For MASK action: Content passes through (masking streaming responses is not supported).+ """++ # Accumulate content as we iterate through chunks+ accumulated_content = ""++ async for item in response:+ # Accumulate content from this chunk before checking+ if isinstance(item, ModelResponseStream) and item.choices:+ for choice in item.choices:+ if hasattr(choice, "delta") and choice.delta:+ content = getattr(choice.delta, "content", None)+ if content and isinstance(content, str):+ accumulated_content += content++ # Check accumulated content for blocked patterns/keywords after processing all choices+ # Only check for BLOCK actions, not MASK (masking streaming is not supported)+ if accumulated_content:+ try:+ # Check patterns+ pattern_match = self._check_patterns(accumulated_content)+ if pattern_match:+ matched_text, pattern_name, action = pattern_match+ if action == ContentFilterAction.BLOCK:+ error_msg = f"Content blocked: {pattern_name} pattern detected"+ verbose_proxy_logger.warning(error_msg)+ raise HTTPException(+ status_code=403,+ detail={"error": error_msg, "pattern": pattern_name},+ )++ # Check blocked words+ blocked_word_match = self._check_blocked_words(accumulated_content)+ if blocked_word_match:+ keyword, action, description = blocked_word_match+ if action == ContentFilterAction.BLOCK:+ error_msg = f"Content blocked: keyword '{keyword}' detected"+ if description:+ error_msg += f" ({description})"+ verbose_proxy_logger.warning(error_msg)+ raise HTTPException(+ status_code=403,+ detail={+ "error": error_msg,+ "keyword": keyword,+ "description": description,+ },+ )++ # Check category keywords+ all_exceptions = []+ for category in self.loaded_categories.values():+ all_exceptions.extend(category.exceptions)+ category_match = self._check_category_keywords(+ accumulated_content, all_exceptions+ )+ if category_match:+ keyword, category_name, severity, action = category_match+ if action == ContentFilterAction.BLOCK:+ error_msg = (+ f"Content blocked: {category_name} category keyword '{keyword}' detected "+ f"(severity: {severity})"+ )+ verbose_proxy_logger.warning(error_msg)+ raise HTTPException(+ status_code=403,+ detail={+ "error": error_msg,+ "category": category_name,+ "keyword": keyword,+ "severity": severity,+ },+ )+ except HTTPException:+ # Re-raise HTTPException (blocked content detected)+ raise+ except Exception as e:+ # Log other exceptions but don't block the stream+ verbose_proxy_logger.warning(+ f"Error checking content filter in streaming: {e}"+ )++ # Yield the chunk (only if no exception was raised above)+ yield item+@staticmethoddef get_config_model():from litellm.types.proxy.guardrails.guardrail_hooks.litellm_content_filter import (diff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.pyindex 49eacb32a0b..af0847e3e24 100644--- a/litellm/responses/litellm_completion_transformation/transformation.py+++ b/litellm/responses/litellm_completion_transformation/transformation.py@@ -291,7 +291,39 @@ class LiteLLMCompletionResponsesConfig:)_messages = litellm_completion_request.get("messages") or []session_messages = chat_completion_session.get("messages") or []- litellm_completion_request["messages"] = session_messages + _messages++ # If session messages are empty (e.g., no database in test environment),+ # we still need to process the new input messages+ # Store original _messages before combining for safety check+ original_new_messages = _messages.copy() if _messages else []++ combined_messages = session_messages + _messages++ # Fix: Ensure tool_results have corresponding tool_calls in previous assistant message+ # Pass tools parameter to help reconstruct tool_calls if not in cache+ tools = litellm_completion_request.get("tools") or []+ combined_messages = LiteLLMCompletionResponsesConfig._ensure_tool_results_have_corresponding_tool_calls(+ messages=combined_messages,+ tools=tools+ )++ # Safety check: Ensure we don't end up with empty messages+ # This can happen when using previous_response_id without a database (e.g., in tests)+ # and session messages are empty but new input messages exist+ if not combined_messages:+ # If we end up with empty messages, try to restore from original inputs+ if original_new_messages:+ # If we had new input messages but they got filtered out,+ # restore them (better to have messages than empty list)+ # This can happen when tool_call_id is empty and can't be recovered+ combined_messages = original_new_messages+ elif session_messages:+ # If we had session messages but they got filtered out,+ # restore them+ combined_messages = session_messages+ # If both are empty, we'll let it fail with a proper error message++ litellm_completion_request["messages"] = combined_messageslitellm_completion_request["litellm_trace_id"] = chat_completion_session.get("litellm_session_id")@@ -361,6 +393,244 @@ class LiteLLMCompletionResponsesConfig:return Truereturn False+ @staticmethod+ def _find_previous_assistant_idx(+ messages: List[Any], current_idx: int+ ) -> Optional[int]:+ """Find the index of the previous assistant message."""+ for j in range(current_idx - 1, -1, -1):+ if messages[j].get("role") == "assistant":+ return j+ return None++ @staticmethod+ def _recover_tool_call_id_from_assistant(+ assistant_message: Any, message: Any+ ) -> str:+ """Try to recover empty tool_call_id from assistant message's tool_calls."""+ tool_calls_raw = (+ assistant_message.get("tool_calls")+ if isinstance(assistant_message, dict)+ else getattr(assistant_message, "tool_calls", None)+ )+ if tool_calls_raw and isinstance(tool_calls_raw, list) and len(tool_calls_raw) > 0:+ first_tool_call = tool_calls_raw[0]+ if isinstance(first_tool_call, dict):+ tool_call_id_raw = first_tool_call.get("id", "")+ return str(tool_call_id_raw) if tool_call_id_raw is not None else ""+ elif hasattr(first_tool_call, "id"):+ tool_call_id_raw = getattr(first_tool_call, "id", None)+ return str(tool_call_id_raw) if tool_call_id_raw is not None else ""+ return ""++ @staticmethod+ def _get_tool_calls_list(assistant_message: Any) -> List[Any]:+ """Extract tool_calls as a list from assistant message."""+ tool_calls_raw = (+ assistant_message.get("tool_calls")+ if isinstance(assistant_message, dict)+ else getattr(assistant_message, "tool_calls", None)+ )+ if tool_calls_raw is None:+ return []+ if isinstance(tool_calls_raw, list):+ return tool_calls_raw+ if hasattr(tool_calls_raw, "__iter__") and not isinstance(+ tool_calls_raw, (str, bytes)+ ):+ return list(tool_calls_raw)+ return []++ @staticmethod+ def _check_tool_call_exists(tool_calls: List[Any], tool_call_id: str) -> bool:+ """Check if a tool_call with the given ID exists in the list."""+ for tool_call in tool_calls:+ tool_call_id_to_check: Optional[str] = None+ if isinstance(tool_call, dict):+ tool_call_id_to_check = tool_call.get("id")+ elif hasattr(tool_call, "id"):+ tool_call_id_to_check = getattr(tool_call, "id", None)+ if tool_call_id_to_check == tool_call_id:+ return True+ return False++ @staticmethod+ def _reconstruct_tool_call_from_tools(+ tool_call_id: str, tools: List[Any]+ ) -> Optional[Dict[str, Any]]:+ """Reconstruct a minimal tool_call definition from tools list."""+ for tool in tools:+ if isinstance(tool, dict):+ tool_function = tool.get("function") or {}+ tool_name = tool_function.get("name") or tool.get("name") or ""+ if tool_name:+ return {+ "id": tool_call_id,+ "type": "function",+ "function": {+ "name": tool_name,+ "arguments": "{}", # We don't know the arguments, use empty+ },+ }+ return None++ @staticmethod+ def _create_tool_call_chunk(+ tool_use_definition: Dict[str, Any], tool_call_id: str, index: int+ ) -> ChatCompletionToolCallChunk:+ """Create a ChatCompletionToolCallChunk from tool_use_definition."""+ function_raw = tool_use_definition.get("function")+ function: Dict[str, Any] = function_raw if isinstance(function_raw, dict) else {}+ tool_use_id_raw = tool_use_definition.get("id")+ tool_use_id: str = (+ str(tool_use_id_raw) if tool_use_id_raw is not None else str(tool_call_id)+ )+ tool_use_type_raw = tool_use_definition.get("type")+ tool_use_type: str = (+ str(tool_use_type_raw) if tool_use_type_raw is not None else "function"+ )+ return ChatCompletionToolCallChunk(+ id=tool_use_id,+ type=cast(Literal["function"], tool_use_type),+ function=ChatCompletionToolCallFunctionChunk(+ name=str(function.get("name", "")),+ arguments=str(function.get("arguments", "{}")),+ ),+ index=index,+ )++ @staticmethod+ def _add_tool_call_to_assistant(+ assistant_message: Any, tool_call_chunk: ChatCompletionToolCallChunk+ ) -> None:+ """Add a tool_call to an assistant message."""+ if isinstance(assistant_message, dict):+ prev_assistant_dict = cast(Dict[str, Any], assistant_message)+ if "tool_calls" not in prev_assistant_dict:+ prev_assistant_dict["tool_calls"] = []+ tool_calls_list = prev_assistant_dict["tool_calls"]+ if isinstance(tool_calls_list, list):+ tool_calls_list.append(tool_call_chunk)+ elif hasattr(assistant_message, "tool_calls"):+ if assistant_message.tool_calls is None:+ assistant_message.tool_calls = []+ if isinstance(assistant_message.tool_calls, list):+ assistant_message.tool_calls.append(tool_call_chunk)++ @staticmethod+ def _ensure_tool_results_have_corresponding_tool_calls(+ messages: List[Union[AllMessageValues, GenericChatCompletionMessage, ChatCompletionResponseMessage]],+ tools: Optional[List[Any]] = None,+ ) -> List[Union[AllMessageValues, GenericChatCompletionMessage, ChatCompletionResponseMessage]]:+ """+ Ensure that tool_result messages have corresponding tool_calls in the previous assistant message.++ This is critical for Anthropic API which requires that each tool_result block has a+ corresponding tool_use block in the previous assistant message.++ Args:+ messages: List of messages that may include tool_result messages+ tools: Optional list of tools that can be used to reconstruct tool_calls if not in cache++ Returns:+ List of messages with tool_calls added to assistant messages when needed+ """+ if not messages:+ return messages++ # Create a deep copy to avoid modifying the original+ import copy+ fixed_messages = copy.deepcopy(messages)+ messages_to_remove = []++ # Count non-tool messages to avoid removing all messages+ # This prevents empty messages list when using previous_response_id without a database+ non_tool_messages_count = sum(+ 1 for msg in fixed_messages if msg.get("role") != "tool"+ )++ for i, message in enumerate(fixed_messages):+ # Only process tool messages - check role first to narrow the type+ if message.get("role") != "tool":+ continue++ # At this point, we know it's a tool message, so it should have tool_call_id+ # Use get() with default to safely access tool_call_id+ tool_call_id_raw = message.get("tool_call_id") if isinstance(message, dict) else getattr(message, "tool_call_id", None)+ tool_call_id: str = (+ str(tool_call_id_raw) if tool_call_id_raw is not None else ""+ )++ prev_assistant_idx = LiteLLMCompletionResponsesConfig._find_previous_assistant_idx(+ fixed_messages, i+ )++ # Try to recover empty tool_call_id from previous assistant message+ if not tool_call_id and prev_assistant_idx is not None:+ prev_assistant = fixed_messages[prev_assistant_idx]+ tool_call_id = LiteLLMCompletionResponsesConfig._recover_tool_call_id_from_assistant(+ prev_assistant, message+ )+ if tool_call_id:+ # Type-safe way to set tool_call_id on tool message+ if isinstance(message, dict):+ # Cast to dict to allow setting tool_call_id+ message_dict = cast(Dict[str, Any], message)+ message_dict["tool_call_id"] = tool_call_id+ elif hasattr(message, "tool_call_id"):+ setattr(message, "tool_call_id", tool_call_id)++ # Only remove messages with empty tool_call_id if we have other non-tool messages+ # This prevents ending up with an empty messages list when using previous_response_id+ # without a database (e.g., in tests where session messages are empty)+ if not tool_call_id:+ # If we have non-tool messages, we can safely remove this tool message+ # But if removing it would leave us with no messages, keep it to avoid empty list+ if non_tool_messages_count > 0:+ messages_to_remove.append(i)+ # If no non-tool messages, keep the tool message even with empty call_id+ # The API will return a proper error message about the missing tool_use block+ continue++ # Check if the previous assistant message has the corresponding tool_call+ # This needs to run for ALL tool messages with a valid tool_call_id,+ # not just those that had an empty tool_call_id initially+ if prev_assistant_idx is not None and tool_call_id:+ prev_assistant = fixed_messages[prev_assistant_idx]+ tool_calls = LiteLLMCompletionResponsesConfig._get_tool_calls_list(+ prev_assistant+ )++ if not LiteLLMCompletionResponsesConfig._check_tool_call_exists(+ tool_calls, tool_call_id+ ):+ _tool_use_definition = TOOL_CALLS_CACHE.get_cache(key=tool_call_id)++ if not _tool_use_definition and tools:+ _tool_use_definition = (+ LiteLLMCompletionResponsesConfig._reconstruct_tool_call_from_tools(+ tool_call_id, tools+ )+ )++ if _tool_use_definition:+ if not isinstance(_tool_use_definition, dict):+ _tool_use_definition = {}+ tool_call_chunk = (+ LiteLLMCompletionResponsesConfig._create_tool_call_chunk(+ _tool_use_definition, tool_call_id, len(tool_calls)+ )+ )+ LiteLLMCompletionResponsesConfig._add_tool_call_to_assistant(+ prev_assistant, tool_call_chunk+ )++ # Remove messages with empty tool_call_id that couldn't be fixed+ for idx in reversed(messages_to_remove):+ fixed_messages.pop(idx)++ return fixed_messages+@staticmethoddef _transform_responses_api_input_item_to_chat_completion_message(input_item: Any,@@ -443,10 +713,16 @@ class LiteLLMCompletionResponsesConfig:"""ChatCompletionToolMessage is used to indicate the output from a tool call"""+ call_id = tool_call_output.get("call_id")+ # If call_id is missing or empty, skip this message+ # Empty call_id means we can't create a valid tool message+ if not call_id:+ return []+tool_output_message = ChatCompletionToolMessage(role="tool",content=tool_call_output.get("output") or "",- tool_call_id=tool_call_output.get("call_id") or "",+ tool_call_id=str(call_id),)_tool_use_definition = TOOL_CALLS_CACHE.get_cache(diff --git a/tests/llm_responses_api_testing/test_anthropic_tool_result_empty_call_id.py b/tests/llm_responses_api_testing/test_anthropic_tool_result_empty_call_id.pynew file mode 100644index 00000000000..ba2d325f283--- /dev/null+++ b/tests/llm_responses_api_testing/test_anthropic_tool_result_empty_call_id.py@@ -0,0 +1,291 @@+"""+Test to reproduce and verify fix for Anthropic tool_result issue with empty call_id.++This test reproduces the exact error:+"messages.0.content.0: unexpected `tool_use_id` found in `tool_result` blocks: tool_use_id.+Each `tool_result` block must have a corresponding `tool_use` block in the previous message."++The issue occurs when:+1. Using previous_response_id to reconstruct messages+2. A tool_result message has an empty tool_call_id+3. The message is sent to Anthropic without a corresponding tool_use block+"""+import os+import sys+import pytest+from unittest.mock import patch, MagicMock++sys.path.insert(0, os.path.abspath("../.."))+import litellm+from litellm.responses.litellm_completion_transformation.transformation import (+ LiteLLMCompletionResponsesConfig,+ TOOL_CALLS_CACHE+)+from litellm.llms.anthropic.chat.transformation import AnthropicConfig+++def test_empty_tool_call_id_is_skipped():+ """+ Test that tool messages with empty tool_call_id are skipped+ when transforming function_call_output to chat completion messages.+ """+ # Simulate a function_call_output with empty call_id (the bug scenario)+ tool_call_output_empty = {+ "type": "function_call_output",+ "call_id": "", # Empty call_id - this causes the issue+ "output": '{"output":"test output","metadata":{"exit_code":0}}'+ }++ # Transform should return empty list (skip the message)+ result = LiteLLMCompletionResponsesConfig._transform_responses_api_tool_call_output_to_chat_completion_message(+ tool_call_output_empty+ )++ assert result == [], (+ "Tool messages with empty call_id should be skipped, not created"+ )+ print("[OK] Empty call_id messages are correctly skipped")+++def test_empty_tool_call_id_in_messages_list_is_removed():+ """+ Test that tool messages with empty tool_call_id are removed+ from the messages list when ensuring tool_results have corresponding tool_calls.+ """+ # Simulate messages with a tool message that has empty tool_call_id+ messages = [+ {+ "role": "assistant",+ "content": "I'll help you with that."+ },+ {+ "role": "tool",+ "content": '{"output":"test"}',+ "tool_call_id": "" # Empty tool_call_id - should be removed+ }+ ]++ # The fix should remove messages with empty tool_call_id+ fixed_messages = LiteLLMCompletionResponsesConfig._ensure_tool_results_have_corresponding_tool_calls(+ messages=messages,+ tools=None+ )++ # The tool message with empty tool_call_id should be removed+ tool_messages = [msg for msg in fixed_messages if msg.get("role") == "tool"]+ assert len(tool_messages) == 0, (+ "Tool messages with empty tool_call_id should be removed from the list"+ )+ print("[OK] Empty tool_call_id messages are correctly removed from messages list")+++def test_tool_call_id_recovered_from_previous_assistant():+ """+ Test that empty tool_call_id can be recovered from the previous assistant message's tool_calls.+ """+ tool_call_id = "toolu_0123456789abcdef"++ messages = [+ {+ "role": "assistant",+ "content": "I'll call the tool.",+ "tool_calls": [+ {+ "id": tool_call_id,+ "type": "function",+ "function": {+ "name": "shell",+ "arguments": '{"command": ["echo", "hello"]}'+ }+ }+ ]+ },+ {+ "role": "tool",+ "content": '{"output":"hello"}',+ "tool_call_id": "" # Empty, but should be recovered from assistant message+ }+ ]++ fixed_messages = LiteLLMCompletionResponsesConfig._ensure_tool_results_have_corresponding_tool_calls(+ messages=messages,+ tools=None+ )++ # The tool message should have its tool_call_id recovered+ tool_message = next((msg for msg in fixed_messages if msg.get("role") == "tool"), None)+ assert tool_message is not None, "Tool message should still be present"+ assert tool_message.get("tool_call_id") == tool_call_id, (+ f"Tool call_id should be recovered from assistant message. "+ f"Expected: {tool_call_id}, Got: {tool_message.get('tool_call_id')}"+ )+ print(f"[OK] Tool call_id recovered: {tool_message.get('tool_call_id')}")+++def test_tool_calls_added_when_missing():+ """+ Test that tool_calls are added to assistant message when tool_result is present+ but tool_calls are missing (the main fix scenario).+ """+ tool_call_id = "toolu_0123456789abcdef"++ # Cache the tool_call definition+ TOOL_CALLS_CACHE.set_cache(+ key=tool_call_id,+ value={+ "id": tool_call_id,+ "type": "function",+ "function": {+ "name": "shell",+ "arguments": '{"command": ["echo", "hello"]}'+ }+ }+ )++ shell_tool = {+ "type": "function",+ "function": {+ "name": "shell",+ "description": "Runs a shell command"+ }+ }++ # Messages with tool_result but missing tool_calls in assistant message+ messages = [+ {+ "role": "assistant",+ "content": "I'll call the tool."+ # Missing tool_calls - this is the bug scenario+ },+ {+ "role": "tool",+ "content": '{"output":"hello"}',+ "tool_call_id": tool_call_id+ }+ ]++ fixed_messages = LiteLLMCompletionResponsesConfig._ensure_tool_results_have_corresponding_tool_calls(+ messages=messages,+ tools=[shell_tool]+ )++ # The assistant message should now have tool_calls+ assistant_message = next((msg for msg in fixed_messages if msg.get("role") == "assistant"), None)+ assert assistant_message is not None, "Assistant message should be present"++ tool_calls = assistant_message.get("tool_calls", [])+ assert len(tool_calls) > 0, (+ "Assistant message should have tool_calls added when tool_result is present"+ )++ # Verify the tool_call has the correct ID+ first_tool_call = tool_calls[0]+ tool_call_id_from_message = first_tool_call.get("id") if isinstance(first_tool_call, dict) else getattr(first_tool_call, "id", None)+ assert tool_call_id_from_message == tool_call_id, (+ f"Tool call ID should match. Expected: {tool_call_id}, Got: {tool_call_id_from_message}"+ )+ print(f"[OK] Tool calls added to assistant message: {len(tool_calls)} tool_call(s)")+++def test_anthropic_transformation_with_fixed_messages():+ """+ Test that the fixed messages work correctly with Anthropic transformation.+ """+ tool_call_id = "toolu_0123456789abcdef"++ # Cache the tool_call+ TOOL_CALLS_CACHE.set_cache(+ key=tool_call_id,+ value={+ "id": tool_call_id,+ "type": "function",+ "function": {+ "name": "shell",+ "arguments": '{"command": ["echo", "hello"]}'+ }+ }+ )++ shell_tool = {+ "name": "shell",+ "input_schema": {+ "type": "object",+ "properties": {+ "command": {"type": "array", "items": {"type": "string"}}+ }+ },+ "description": "Runs a shell command"+ }++ # Messages that would cause the error without the fix+ messages = [+ {+ "role": "assistant",+ "content": "I'll help you."+ # Missing tool_calls+ },+ {+ "role": "tool",+ "content": '{"output":"hello"}',+ "tool_call_id": tool_call_id+ }+ ]++ # Apply the fix+ fixed_messages = LiteLLMCompletionResponsesConfig._ensure_tool_results_have_corresponding_tool_calls(+ messages=messages,+ tools=[shell_tool]+ )++ # Transform to Anthropic format+ anthropic_config = AnthropicConfig()+ optional_params = {"tools": [shell_tool]}++ anthropic_data = anthropic_config.transform_request(+ model="claude-3-7-sonnet-latest",+ messages=fixed_messages,+ optional_params=optional_params,+ litellm_params={},+ headers={}+ )++ anthropic_messages = anthropic_data.get("messages", [])++ # Find the assistant message+ anthropic_assistant_msg = next(+ (msg for msg in anthropic_messages if msg.get("role") == "assistant"),+ None+ )++ assert anthropic_assistant_msg is not None, "Assistant message should be present"++ # Verify it has tool_use blocks+ assistant_content = anthropic_assistant_msg.get("content", [])+ tool_use_blocks = [+ block for block in assistant_content+ if isinstance(block, dict) and block.get("type") == "tool_use"+ ]++ assert len(tool_use_blocks) > 0, (+ f"After fix, assistant message should have tool_use blocks. "+ f"Found content: {assistant_content}"+ )++ # Verify the tool_use block has the correct ID+ tool_use_id = tool_use_blocks[0].get("id")+ assert tool_use_id == tool_call_id, (+ f"Tool use ID should match. Expected: {tool_call_id}, Got: {tool_use_id}"+ )++ print(f"[OK] Anthropic transformation successful with {len(tool_use_blocks)} tool_use block(s)")+++if __name__ == "__main__":+ test_empty_tool_call_id_is_skipped()+ test_empty_tool_call_id_in_messages_list_is_removed()+ test_tool_call_id_recovered_from_previous_assistant()+ test_tool_calls_added_when_missing()+ test_anthropic_transformation_with_fixed_messages()+ print("\n" + "=" * 80)+ print("[PASS] All tests passed - fix verified!")+ print("=" * 80)diff --git a/tests/llm_responses_api_testing/test_anthropic_tool_result_fix.py b/tests/llm_responses_api_testing/test_anthropic_tool_result_fix.pynew file mode 100644index 00000000000..3f26a2a4130--- /dev/null+++ b/tests/llm_responses_api_testing/test_anthropic_tool_result_fix.py@@ -0,0 +1,163 @@+"""+Test to verify the fix for Anthropic tool_result issue.++This test verifies that when using previous_response_id with tool_result,+the fix ensures tool_calls are added to the previous assistant message.+"""+import os+import sys+import pytest+import json+from unittest.mock import patch, AsyncMock++sys.path.insert(0, os.path.abspath("../.."))+import litellm+from litellm.responses.litellm_completion_transformation.transformation import (+ LiteLLMCompletionResponsesConfig,+ TOOL_CALLS_CACHE+)+from litellm.llms.anthropic.chat.transformation import AnthropicConfig+++def test_fix_ensures_tool_calls_for_tool_results():+ """+ Test that the fix ensures tool_calls are added to assistant messages+ when tool_results are present but tool_calls are missing.+ """+ shell_tool = {+ "type": "function",+ "function": {+ "name": "shell",+ "description": "Runs a shell command, and returns its output.",+ "parameters": {+ "type": "object",+ "properties": {+ "command": {"type": "array", "items": {"type": "string"}},+ "workdir": {"type": "string", "description": "The working directory for the command."}+ },+ "required": ["command"]+ }+ }+ }++ tool_call_id = "toolu_0123456789abcdef"++ # Cache the tool_call definition (simulating what happens when a response is returned)+ TOOL_CALLS_CACHE.set_cache(+ key=tool_call_id,+ value={+ "id": tool_call_id,+ "type": "function",+ "function": {+ "name": "shell",+ "arguments": '{"command": ["echo", "hello"]}'+ }+ }+ )++ # Simulate messages that would be reconstructed from spend logs+ # The assistant message is missing tool_calls (the bug scenario)+ messages_missing_tool_calls = [+ {+ "role": "user",+ "content": [{"type": "text", "text": "make a hello world html file"}]+ },+ {+ "role": "assistant",+ "content": "I'll help you create that HTML file."+ # NOTE: Missing tool_calls here - this is the bug scenario+ },+ {+ "role": "tool",+ "content": '{"output":"<html>...</html>"}',+ "tool_call_id": tool_call_id+ }+ ]++ # Apply the fix+ fixed_messages = LiteLLMCompletionResponsesConfig._ensure_tool_results_have_corresponding_tool_calls(+ messages=messages_missing_tool_calls,+ tools=[shell_tool]+ )++ # Verify the fix worked+ assistant_message = None+ for msg in fixed_messages:+ if msg.get("role") == "assistant":+ assistant_message = msg+ break++ assert assistant_message is not None, "Assistant message should be present"++ # Check if tool_calls were added+ tool_calls = assistant_message.get("tool_calls") or []+ assert len(tool_calls) > 0, (+ f"Fix should have added tool_calls to assistant message. "+ f"Found: {json.dumps(assistant_message, indent=2)}"+ )++ # Verify the tool_call has the correct ID+ found_tool_call = False+ for tool_call in tool_calls:+ tool_call_id_from_msg = tool_call.get("id") if isinstance(tool_call, dict) else getattr(tool_call, "id", None)+ if tool_call_id_from_msg == tool_call_id:+ found_tool_call = True+ break++ assert found_tool_call, (+ f"Tool call with ID {tool_call_id} should be present in assistant message. "+ f"Found tool_calls: {json.dumps(tool_calls, indent=2, default=str)}"+ )++ # Now verify the Anthropic transformation works+ anthropic_config = AnthropicConfig()+ optional_params = {"tools": [shell_tool]}++ anthropic_data = anthropic_config.transform_request(+ model="claude-3-7-sonnet-latest",+ messages=fixed_messages,+ optional_params=optional_params,+ litellm_params={},+ headers={}+ )++ anthropic_messages = anthropic_data.get("messages", [])++ # Find the assistant message in Anthropic format+ anthropic_assistant_msg = None+ for msg in anthropic_messages:+ if msg.get("role") == "assistant":+ anthropic_assistant_msg = msg+ break++ assert anthropic_assistant_msg is not None, "Assistant message should be present in Anthropic format"++ # Verify the assistant message has tool_use blocks+ assistant_content = anthropic_assistant_msg.get("content", [])+ tool_use_blocks = [+ block for block in assistant_content+ if isinstance(block, dict) and block.get("type") == "tool_use"+ ]++ assert len(tool_use_blocks) > 0, (+ f"After fix, assistant message should have tool_use blocks. "+ f"Found content: {json.dumps(assistant_content, indent=2)}"+ )++ # Verify the tool_use block has the correct ID+ tool_use_id = tool_use_blocks[0].get("id")+ assert tool_use_id == tool_call_id, (+ f"Tool use ID {tool_use_id} should match tool_call_id {tool_call_id}"+ )++ print("\n" + "=" * 80)+ print("[PASS] Fix verified: tool_calls are added when missing")+ print("=" * 80)+ print(f" Tool use blocks: {len(tool_use_blocks)}")+ print(f" Tool use ID: {tool_use_id}")+ print("\nThe fix ensures that when tool_results are present but tool_calls are")+ print("missing from the assistant message, they are added from cache or tools.")+++if __name__ == "__main__":+ test_fix_ensures_tool_calls_for_tool_results()diff --git a/tests/test_team.py b/tests/test_team.pyindex 4ef9b8d9195..c1af79ebc0b 100644--- a/tests/test_team.py+++ b/tests/test_team.py@@ -15,9 +15,9 @@ async def get_user_info(session, get_user, call_user, view_all: Optional[bool] =Make sure only models user has access to are returned"""if view_all is True:- url = "http://0.0.0.0:4000/user/info"+ url = "http://localhost:4000/user/info"else:- url = f"http://0.0.0.0:4000/user/info?user_id={get_user}"+ url = f"http://localhost:4000/user/info?user_id={get_user}"headers = {"Authorization": f"Bearer {call_user}","Content-Type": "application/json",@@ -38,6 +38,53 @@ async def get_user_info(session, get_user, call_user, view_all: Optional[bool] =return await response.json()+async def wait_for_team_member_spend_update(+ session, user_id, team_id, expected_min_spend, max_wait=10+):+ """+ Wait for the team member spend update to be committed to the database.+ Polls the user info endpoint until the spend is updated.+ This is needed because spend updates are queued asynchronously and committed periodically.++ Note: If the model has no pricing (cost = 0), the spend will remain 0.0.+ In that case, we just wait a bit to ensure the spend update queue has been processed.+ """+ start_time = time.time()+ initial_spend = None+ while time.time() - start_time < max_wait:+ try:+ user_info = await get_user_info(session, user_id, call_user="sk-1234")+ if user_info.get("teams"):+ for team in user_info["teams"]:+ if team.get("team_id") == team_id:+ for membership in team.get("team_memberships", []):+ spend = membership.get("spend", 0.0)+ if initial_spend is None:+ initial_spend = spend+ print(f"Initial team member spend: {spend}")++ # If spend has been updated (even if still 0), the queue has been processed+ # For models with no pricing, spend will be 0, but we still need to wait+ # for the update to be committed so the budget check sees the current state+ if spend >= expected_min_spend:+ print(f"[OK] Team member spend updated: {spend} >= {expected_min_spend}")+ return True++ # If we've waited a reasonable amount and spend is still 0,+ # it likely means the model has no pricing, but we should still+ # wait a bit more to ensure the update queue has been processed+ elapsed = time.time() - start_time+ if elapsed > 3.0: # Wait at least 3 seconds for queue processing+ print(f"[OK] Waited {elapsed:.1f}s for spend update queue processing (spend: {spend})")+ return True+ await asyncio.sleep(0.5)+ except Exception as e:+ print(f"Error checking team member spend: {e}")+ await asyncio.sleep(0.5)+ print(f"[TIMEOUT] Timeout waiting for team member spend update (expected >= {expected_min_spend})")+ return False++async def new_user(session,i,@@ -48,7 +95,7 @@ async def new_user(team_id=None,user_email=None,):- url = "http://0.0.0.0:4000/user/new"+ url = "http://localhost:4000/user/new"headers = {"Authorization": "Bearer sk-1234", "Content-Type": "application/json"}data = {"models": models,@@ -84,7 +131,7 @@ async def new_user(async def add_member(session, i, team_id, user_id=None, user_email=None, max_budget=None, members=None):- url = "http://0.0.0.0:4000/team/member_add"+ url = "http://localhost:4000/team/member_add"headers = {"Authorization": "Bearer sk-1234", "Content-Type": "application/json"}data = {"team_id": team_id, "member": {"role": "user"}}if user_email is not None:@@ -120,7 +167,7 @@ async def update_member(user_email=None,max_budget=None,):- url = "http://0.0.0.0:4000/team/member_update"+ url = "http://localhost:4000/team/member_update"headers = {"Authorization": "Bearer sk-1234", "Content-Type": "application/json"}data = {"team_id": team_id}if user_id is not None:@@ -149,7 +196,7 @@ async def update_member(async def delete_member(session, i, team_id, user_id=None, user_email=None):- url = "http://0.0.0.0:4000/team/member_delete"+ url = "http://localhost:4000/team/member_delete"headers = {"Authorization": "Bearer sk-1234", "Content-Type": "application/json"}data = {"team_id": team_id}if user_id is not None:@@ -179,7 +226,7 @@ async def generate_key(models=["azure-models", "gpt-4", "dall-e-3"],team_id=None,):- url = "http://0.0.0.0:4000/key/generate"+ url = "http://localhost:4000/key/generate"headers = {"Authorization": "Bearer sk-1234", "Content-Type": "application/json"}data = {"models": models,@@ -207,7 +254,7 @@ async def generate_key(async def chat_completion(session, key, model="gpt-4"):- url = "http://0.0.0.0:4000/chat/completions"+ url = "http://localhost:4000/chat/completions"headers = {"Authorization": f"Bearer {key}","Content-Type": "application/json",@@ -245,7 +292,7 @@ async def chat_completion(session, key, model="gpt-4"):async def new_team(session, i, user_id=None, member_list=None, model_aliases=None):import json- url = "http://0.0.0.0:4000/team/new"+ url = "http://localhost:4000/team/new"headers = {"Authorization": "Bearer sk-1234", "Content-Type": "application/json"}data = {"team_alias": "my-new-team"}if user_id is not None:@@ -273,7 +320,7 @@ async def new_team(session, i, user_id=None, member_list=None, model_aliases=Nonasync def update_team(session, i, team_id, user_id=None, member_list=None, **kwargs):- url = "http://0.0.0.0:4000/team/update"+ url = "http://localhost:4000/team/update"headers = {"Authorization": "Bearer sk-1234", "Content-Type": "application/json"}data = {"team_id": team_id, **kwargs}if user_id is not None:@@ -300,7 +347,7 @@ async def delete_team(i,team_id,):- url = "http://0.0.0.0:4000/team/delete"+ url = "http://localhost:4000/team/delete"headers = {"Authorization": "Bearer sk-1234", "Content-Type": "application/json"}data = {"team_ids": [team_id],@@ -324,7 +371,7 @@ async def list_teams(session,i,):- url = "http://0.0.0.0:4000/team/list"+ url = "http://localhost:4000/team/list"headers = {"Authorization": "Bearer sk-1234", "Content-Type": "application/json"}async with session.get(url, headers=headers) as response:@@ -348,7 +395,7 @@ async def test_team_new():async def get_team_info(session, get_team, call_key):- url = f"http://0.0.0.0:4000/team/info?team_id={get_team}"+ url = f"http://localhost:4000/team/info?team_id={get_team}"headers = {"Authorization": f"Bearer {call_key}","Content-Type": "application/json",@@ -715,7 +762,18 @@ async def test_users_in_team_budget():result = await chat_completion(session, key, model="fake-openai-endpoint")print("Call 1 passed", result)- await asyncio.sleep(2)+ # Wait for spend to be committed to database before checking budget+ # Spend updates are queued asynchronously and committed periodically (every minute),+ # so we need to wait for the spend from Call 1 to be persisted+ # Note: Even if cost is 0 (model has no pricing), we wait to ensure the update queue is processed+ print("Waiting for team member spend to be committed to database...")+ print("Note: Spend updates are flushed periodically, this may take up to 60 seconds...")+ spend_updated = await wait_for_team_member_spend_update(+ session, get_user, team["team_id"], 0.0000001, max_wait=65+ )+ if not spend_updated:+ print("[WARNING] Team member spend not updated in time, but continuing test...")+ print("This may indicate the spend update queue hasn't been flushed yet.")# Call 2try: