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(responses): propagate message cache_control safely through objects and models
Elliott de Launay18101345a015
diff --git a/litellm/llms/vertex_ai/context_caching/transformation.py b/litellm/llms/vertex_ai/context_caching/transformation.pyindex f0ce3323ef6..183d9743f13 100644--- a/litellm/llms/vertex_ai/context_caching/transformation.py+++ b/litellm/llms/vertex_ai/context_caching/transformation.py@@ -62,23 +62,27 @@ def extract_ttl_from_cached_messages(messages: List[AllMessageValues]) -> Optionif not is_cached_message(message):continue- content = message.get("content")+ content = message.get("content") if isinstance(message, dict) else getattr(message, "content", None)if not content or isinstance(content, str):continuefor content_item in content:- # Type check to ensure content_item is a dictionary before calling .get()- if not isinstance(content_item, dict):- continue+ # Check if content_item is dict or object model+ if isinstance(content_item, dict):+ cache_control = content_item.get("cache_control")+ else:+ cache_control = getattr(content_item, "cache_control", None)- cache_control = content_item.get("cache_control")- if not cache_control or not isinstance(cache_control, dict):+ if not cache_control:continue- if cache_control.get("type") != "ephemeral":+ cc_type = (+ cache_control.get("type") if isinstance(cache_control, dict) else getattr(cache_control, "type", None)+ )+ if cc_type != "ephemeral":continue- ttl = cache_control.get("ttl")+ ttl = cache_control.get("ttl") if isinstance(cache_control, dict) else getattr(cache_control, "ttl", None)if ttl and _is_valid_ttl_format(ttl):return str(ttl)diff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.pyindex 6b1ca3564e3..8052f69f22b 100644--- a/litellm/responses/litellm_completion_transformation/transformation.py+++ b/litellm/responses/litellm_completion_transformation/transformation.py@@ -892,26 +892,38 @@ class LiteLLMCompletionResponsesConfig:function_call=input_item)else:- content = input_item.get("content")+ content = (+ input_item.get("content") if isinstance(input_item, dict) else getattr(input_item, "content", None)+ )# Handle None content: Responses API allows None content, but GenericChatCompletionMessage requires content# Since guardrails skip None content anyway, we return empty list to exclude it from structured messagesif content is None:return []- return [- GenericChatCompletionMessage(- role=input_item.get("role") or "user",- content=LiteLLMCompletionResponsesConfig._transform_responses_api_content_to_chat_completion_content(- content- ),- )- ]++ role = input_item.get("role") if isinstance(input_item, dict) else getattr(input_item, "role", None)+ cache_control = (+ input_item.get("cache_control")+ if isinstance(input_item, dict)+ else getattr(input_item, "cache_control", None)+ )++ msg = GenericChatCompletionMessage(+ role=role or "user",+ content=LiteLLMCompletionResponsesConfig._transform_responses_api_content_to_chat_completion_content(+ content+ ),+ )+ if cache_control is not None:+ msg["cache_control"] = cache_control+ return [msg]@staticmethoddef _is_input_item_tool_call_output(input_item: Any) -> bool:"""Check if the input item is a tool call output"""- return input_item.get("type") in [+ val = input_item.get("type") if isinstance(input_item, dict) else getattr(input_item, "type", None)+ return val in ["function_call_output","custom_tool_call_output","web_search_call",@@ -926,7 +938,8 @@ class LiteLLMCompletionResponsesConfig:Both need to be reconstructed as assistant tool_calls for ChatCompletions providers."""- return input_item.get("type") in ("function_call", "custom_tool_call")+ val = input_item.get("type") if isinstance(input_item, dict) else getattr(input_item, "type", None)+ return val in ("function_call", "custom_tool_call")@staticmethoddef _transform_responses_api_tool_call_output_to_chat_completion_message(@@ -1155,6 +1168,31 @@ class LiteLLMCompletionResponsesConfig:return ChatCompletionImageObject(type="image_url", image_url=image_url_obj)+ @staticmethod+ def _normalize_responses_api_object_to_dict(item: Any) -> dict[str, Any]:+ """+ Normalize a Responses API object (Pydantic model or custom class) to a dictionary+ """+ if hasattr(item, "model_dump"):+ return item.model_dump()+ elif hasattr(item, "dict"):+ return item.dict()++ item_dict = {}+ for attr in [+ "type",+ "text",+ "cache_control",+ "file_id",+ "file_data",+ "file_url",+ "image_url",+ "detail",+ ]:+ if hasattr(item, attr):+ item_dict[attr] = getattr(item, attr)+ return item_dict+@staticmethoddef _transform_responses_api_content_to_chat_completion_content(content: Any,@@ -1176,7 +1214,10 @@ class LiteLLMCompletionResponsesConfig:for item in content:if isinstance(item, str):content_list.append(item)- elif isinstance(item, dict):+ elif isinstance(item, dict) or (item is not None and not isinstance(item, (str, int, float, bool))):+ if not isinstance(item, dict):+ item = LiteLLMCompletionResponsesConfig._normalize_responses_api_object_to_dict(item)+if item.get("type") == "input_file":content_list.append(LiteLLMCompletionResponsesConfig._transform_input_file_item_to_file_item(item)diff --git a/litellm/utils.py b/litellm/utils.pyindex a11c5500503..3fdf0a5eee6 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -7209,36 +7209,51 @@ def is_cached_message(message: AllMessageValues) -> bool:return False# Check message-level cache_control (set by cache_control_injection_points hook for string content)- message_level_cache_control = message.get("cache_control")- if (- message_level_cache_control is not None- and isinstance(message_level_cache_control, dict)- and message_level_cache_control.get("type") == "ephemeral"- ):- return True-- if "content" not in message:- return False+ message_level_cache_control = (+ message.get("cache_control")+ if isinstance(message, dict)+ else getattr(message, "cache_control", None)+ )+ if message_level_cache_control is not None:+ cc_type = (+ message_level_cache_control.get("type")+ if isinstance(message_level_cache_control, dict)+ else getattr(message_level_cache_control, "type", None)+ )+ if cc_type == "ephemeral":+ return True- content = message["content"]+ if isinstance(message, dict):+ if "content" not in message:+ return False+ content = message["content"]+ else:+ content = getattr(message, "content", None)# Handle non-list content types (None, str, etc.)if not isinstance(content, list):return Falsefor content_item in content:- # Ensure content_item is a dictionary before accessing keys- if not isinstance(content_item, dict):- continue+ # Check if content_item is dict or object model+ if isinstance(content_item, dict):+ cache_control = content_item.get("cache_control")+ item_type = content_item.get("type")+ else:+ cache_control = getattr(content_item, "cache_control", None)+ item_type = getattr(content_item, "type", None)- cache_control = content_item.get("cache_control")if (- content_item.get("type") == "text"+ item_type == "text"and cache_control is not None- and isinstance(cache_control, dict)- and cache_control.get("type") == "ephemeral"):- return True+ cc_type = (+ cache_control.get("type")+ if isinstance(cache_control, dict)+ else getattr(cache_control, "type", None)+ )+ if cc_type == "ephemeral":+ return Truereturn Falsediff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.pyindex d8e3f495ced..4b07d638261 100644--- a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py+++ b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py@@ -3,9 +3,7 @@ import sysimport pytest-sys.path.insert(- 0, os.path.abspath("../../..")-) # Adds the parent directory to the system path+sys.path.insert(0, os.path.abspath("../../..")) # Adds the parent directory to the system pathfrom litellm.responses.litellm_completion_transformation.transformation import (TOOL_CALLS_CACHE,@@ -34,11 +32,7 @@ class TestLiteLLMCompletionResponsesConfig:input_item = {"type": "input_file", "file_id": "file-abc123xyz"}# Execute- result = (- LiteLLMCompletionResponsesConfig._transform_input_file_item_to_file_item(- input_item- )- )+ result = LiteLLMCompletionResponsesConfig._transform_input_file_item_to_file_item(input_item)# Assertexpected = {"type": "file", "file": {"file_id": "file-abc123xyz"}}@@ -53,11 +47,7 @@ class TestLiteLLMCompletionResponsesConfig:input_item = {"type": "input_file", "file_data": file_data}# Execute- result = (- LiteLLMCompletionResponsesConfig._transform_input_file_item_to_file_item(- input_item- )- )+ result = LiteLLMCompletionResponsesConfig._transform_input_file_item_to_file_item(input_item)# Assertexpected = {"type": "file", "file": {"file_data": file_data}}@@ -75,11 +65,7 @@ class TestLiteLLMCompletionResponsesConfig:}# Execute- result = (- LiteLLMCompletionResponsesConfig._transform_input_file_item_to_file_item(- input_item- )- )+ result = LiteLLMCompletionResponsesConfig._transform_input_file_item_to_file_item(input_item)# Assertexpected = {@@ -97,11 +83,7 @@ class TestLiteLLMCompletionResponsesConfig:input_item = {"type": "input_file"}# Execute- result = (- LiteLLMCompletionResponsesConfig._transform_input_file_item_to_file_item(- input_item- )- )+ result = LiteLLMCompletionResponsesConfig._transform_input_file_item_to_file_item(input_item)# Assertexpected = {"type": "file", "file": {}}@@ -120,11 +102,7 @@ class TestLiteLLMCompletionResponsesConfig:}# Execute- result = (- LiteLLMCompletionResponsesConfig._transform_input_file_item_to_file_item(- input_item- )- )+ result = LiteLLMCompletionResponsesConfig._transform_input_file_item_to_file_item(input_item)# Assertexpected = {"type": "file", "file": {"file_id": "file-abc123xyz"}}@@ -134,10 +112,8 @@ class TestLiteLLMCompletionResponsesConfig:def test_transform_input_file_item_to_file_item_with_file_url(self):"""file_url should be mapped to file_id for downstream URL handling"""- result = (- LiteLLMCompletionResponsesConfig._transform_input_file_item_to_file_item(- {"type": "input_file", "file_url": "https://example.com/doc.pdf"}- )+ result = LiteLLMCompletionResponsesConfig._transform_input_file_item_to_file_item(+ {"type": "input_file", "file_url": "https://example.com/doc.pdf"})assert result == {"type": "file",@@ -146,14 +122,12 @@ class TestLiteLLMCompletionResponsesConfig:def test_transform_input_file_item_file_id_takes_precedence_over_file_url(self):"""explicit file_id should not be overwritten by file_url"""- result = (- LiteLLMCompletionResponsesConfig._transform_input_file_item_to_file_item(- {- "type": "input_file",- "file_id": "file-abc123",- "file_url": "https://example.com/doc.pdf",- }- )+ result = LiteLLMCompletionResponsesConfig._transform_input_file_item_to_file_item(+ {+ "type": "input_file",+ "file_id": "file-abc123",+ "file_url": "https://example.com/doc.pdf",+ })assert result == {"type": "file", "file": {"file_id": "file-abc123"}}@@ -164,11 +138,7 @@ class TestLiteLLMCompletionResponsesConfig:input_item = {"type": "input_image", "image_url": image_url, "detail": "high"}# Execute- result = (- LiteLLMCompletionResponsesConfig._transform_input_image_item_to_image_item(- input_item- )- )+ result = LiteLLMCompletionResponsesConfig._transform_input_image_item_to_image_item(input_item)# Assertexpected = {@@ -187,11 +157,7 @@ class TestLiteLLMCompletionResponsesConfig:input_item = {"type": "input_image", "image_url": image_url, "detail": "high"}# Execute- result = (- LiteLLMCompletionResponsesConfig._transform_input_image_item_to_image_item(- input_item- )- )+ result = LiteLLMCompletionResponsesConfig._transform_input_image_item_to_image_item(input_item)# Assertexpected = {@@ -210,11 +176,7 @@ class TestLiteLLMCompletionResponsesConfig:input_item = {"type": "input_image", "image_url": image_url}# Execute- result = (- LiteLLMCompletionResponsesConfig._transform_input_image_item_to_image_item(- input_item- )- )+ result = LiteLLMCompletionResponsesConfig._transform_input_image_item_to_image_item(input_item)# Assertexpected = {@@ -232,11 +194,7 @@ class TestLiteLLMCompletionResponsesConfig:input_item = {"type": "input_image"}# Execute- result = (- LiteLLMCompletionResponsesConfig._transform_input_image_item_to_image_item(- input_item- )- )+ result = LiteLLMCompletionResponsesConfig._transform_input_image_item_to_image_item(input_item)# Assertexpected = {"type": "image_url", "image_url": {"url": "", "detail": "auto"}}@@ -256,11 +214,7 @@ class TestLiteLLMCompletionResponsesConfig:}# Execute- result = (- LiteLLMCompletionResponsesConfig._transform_input_image_item_to_image_item(- input_item- )- )+ result = LiteLLMCompletionResponsesConfig._transform_input_image_item_to_image_item(input_item)# Assertexpected = {@@ -296,28 +250,26 @@ class TestLiteLLMCompletionResponsesConfig:)# Execute- responses_api_response = LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(- request_input="What is the meaning of life?",- responses_api_request={},- chat_completion_response=chat_completion_response,+ responses_api_response = (+ LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(+ request_input="What is the meaning of life?",+ responses_api_request={},+ chat_completion_response=chat_completion_response,+ ))# Assertassert hasattr(responses_api_response, "output")assert len(responses_api_response.output) >= 2- reasoning_items = [- item for item in responses_api_response.output if item.type == "reasoning"- ]+ reasoning_items = [item for item in responses_api_response.output if item.type == "reasoning"]assert len(reasoning_items) == 1, "Should have exactly one reasoning item"reasoning_item = reasoning_items[0]# Note: ID auto-generation was disabled, so reasoning items may not have IDs# Only assert ID format if an ID is presentif hasattr(reasoning_item, "id") and reasoning_item.id:- assert reasoning_item.id.startswith(- "rs_"- ), f"Expected ID to start with 'rs_', got: {reasoning_item.id}"+ assert reasoning_item.id.startswith("rs_"), f"Expected ID to start with 'rs_', got: {reasoning_item.id}"assert reasoning_item.status == "completed"assert reasoning_item.role == "assistant"assert len(reasoning_item.content) == 1@@ -325,9 +277,7 @@ class TestLiteLLMCompletionResponsesConfig:assert "step by step" in reasoning_item.content[0].textassert "42" in reasoning_item.content[0].text- message_items = [- item for item in responses_api_response.output if item.type == "message"- ]+ message_items = [item for item in responses_api_response.output if item.type == "message"]assert len(message_items) == 1, "Should have exactly one message item"message_item = message_items[0]@@ -354,21 +304,19 @@ class TestLiteLLMCompletionResponsesConfig:)# Execute- responses_api_response = LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(- request_input="A simple question?",- responses_api_request={},- chat_completion_response=chat_completion_response,+ responses_api_response = (+ LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(+ request_input="A simple question?",+ responses_api_request={},+ chat_completion_response=chat_completion_response,+ ))# Assert- reasoning_items = [- item for item in responses_api_response.output if item.type == "reasoning"- ]+ reasoning_items = [item for item in responses_api_response.output if item.type == "reasoning"]assert len(reasoning_items) == 0, "Should have no reasoning items"- message_items = [- item for item in responses_api_response.output if item.type == "message"- ]+ message_items = [item for item in responses_api_response.output if item.type == "message"]assert len(message_items) == 1, "Should have exactly one message item"assert message_items[0].content[0].text == "Just a regular answer."assert responses_api_response.object == "response"@@ -404,22 +352,20 @@ class TestLiteLLMCompletionResponsesConfig:)# Execute- responses_api_response = LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(- request_input="A question with multiple answers?",- responses_api_request={},- chat_completion_response=chat_completion_response,+ responses_api_response = (+ LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(+ request_input="A question with multiple answers?",+ responses_api_request={},+ chat_completion_response=chat_completion_response,+ ))# Assert- reasoning_items = [- item for item in responses_api_response.output if item.type == "reasoning"- ]+ reasoning_items = [item for item in responses_api_response.output if item.type == "reasoning"]assert len(reasoning_items) == 1, "Should have exactly one reasoning item"assert reasoning_items[0].content[0].text == "First reasoning process."- message_items = [- item for item in responses_api_response.output if item.type == "message"- ]+ message_items = [item for item in responses_api_response.output if item.type == "message"]assert len(message_items) == 2, "Should have two message items"def test_transform_chat_completion_response_status_with_stop(self):@@ -446,10 +392,12 @@ class TestLiteLLMCompletionResponsesConfig:],)- responses_api_response = LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(- request_input="this is a test",- responses_api_request={},- chat_completion_response=chat_completion_response,+ responses_api_response = (+ LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(+ request_input="this is a test",+ responses_api_request={},+ chat_completion_response=chat_completion_response,+ ))assert responses_api_response.status == "completed"@@ -485,15 +433,15 @@ class TestLiteLLMCompletionResponsesConfig:],)- responses_api_response = LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(- request_input="this is a test",- responses_api_request={},- chat_completion_response=chat_completion_response,+ responses_api_response = (+ LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(+ request_input="this is a test",+ responses_api_request={},+ chat_completion_response=chat_completion_response,+ ))- message_items = [- item for item in responses_api_response.output if item.type == "message"- ]+ message_items = [item for item in responses_api_response.output if item.type == "message"]assert len(message_items) > 0for item in message_items:@@ -528,10 +476,12 @@ class TestLiteLLMCompletionResponsesConfig:],)- responses_api_response = LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(- request_input="this is a test",- responses_api_request={},- chat_completion_response=chat_completion_response,+ responses_api_response = (+ LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(+ request_input="this is a test",+ responses_api_request={},+ chat_completion_response=chat_completion_response,+ ))assert responses_api_response.status == "incomplete"@@ -563,10 +513,12 @@ class TestLiteLLMCompletionResponsesConfig:}# Execute- responses_api_response = LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(- request_input="Test",- responses_api_request={},- chat_completion_response=chat_completion_response,+ responses_api_response = (+ LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(+ request_input="Test",+ responses_api_request={},+ chat_completion_response=chat_completion_response,+ ))# Assert@@ -598,10 +550,12 @@ class TestLiteLLMCompletionResponsesConfig:)# Execute- responses_api_response = LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(- request_input="Test",- responses_api_request={},- chat_completion_response=chat_completion_response,+ responses_api_response = (+ LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(+ request_input="Test",+ responses_api_request={},+ chat_completion_response=chat_completion_response,+ ))# Assert - should default to empty dict@@ -630,26 +584,14 @@ class TestFunctionCallTransformation:regular_message = {"type": "message", "role": "user", "content": "Hello"}# Test function_call detection- assert LiteLLMCompletionResponsesConfig._is_input_item_function_call(- function_call_item- )- assert not LiteLLMCompletionResponsesConfig._is_input_item_function_call(- function_call_output_item- )- assert not LiteLLMCompletionResponsesConfig._is_input_item_function_call(- regular_message- )+ assert LiteLLMCompletionResponsesConfig._is_input_item_function_call(function_call_item)+ assert not LiteLLMCompletionResponsesConfig._is_input_item_function_call(function_call_output_item)+ assert not LiteLLMCompletionResponsesConfig._is_input_item_function_call(regular_message)# Test function_call_output detection (should still work)- assert LiteLLMCompletionResponsesConfig._is_input_item_tool_call_output(- function_call_output_item- )- assert not LiteLLMCompletionResponsesConfig._is_input_item_tool_call_output(- function_call_item- )- assert not LiteLLMCompletionResponsesConfig._is_input_item_tool_call_output(- regular_message- )+ assert LiteLLMCompletionResponsesConfig._is_input_item_tool_call_output(function_call_output_item)+ assert not LiteLLMCompletionResponsesConfig._is_input_item_tool_call_output(function_call_item)+ assert not LiteLLMCompletionResponsesConfig._is_input_item_tool_call_output(regular_message)def test_function_call_transformation(self):"""Test that function_call items are correctly transformed to assistant messages with tool calls"""@@ -733,9 +675,7 @@ class TestFunctionCallTransformation:tool_msg = messages[2]assert tool_msg.get("role") == "tool"assert tool_msg.get("content") == "Rainy"- assert (- tool_msg.get("tool_call_id") == "call_1fe70e2a-a596-45ef-b72c-9b8567c460e5"- )+ assert tool_msg.get("tool_call_id") == "call_1fe70e2a-a596-45ef-b72c-9b8567c460e5"def test_complete_request_transformation_with_function_calls(self):"""Test the complete request transformation that would be used by the responses API"""@@ -940,9 +880,7 @@ class TestToolChoiceTransformation:Test that {"type": "tool"} is transformed to "required".This fixes the Anthropic error: "tool_choice.tool.name: Field required""""- result = LiteLLMCompletionResponsesConfig._transform_tool_choice(- {"type": "tool"}- )+ result = LiteLLMCompletionResponsesConfig._transform_tool_choice({"type": "tool"})assert result == "required"def test_transform_tool_choice_preserves_function_with_name(self):@@ -954,23 +892,17 @@ class TestToolChoiceTransformation:def test_transform_tool_choice_responses_flat_function_name(self):"""Responses-API forced-function with a top-level name maps to the nested ChatCompletions shape instead of degrading to required and dropping the name"""- result = LiteLLMCompletionResponsesConfig._transform_tool_choice(- {"type": "function", "name": "get_weather"}- )+ result = LiteLLMCompletionResponsesConfig._transform_tool_choice({"type": "function", "name": "get_weather"})assert result == {"type": "function", "function": {"name": "get_weather"}}def test_transform_tool_choice_function_without_name_falls_back_to_required(self):"""A function-type dict with no name still falls back to required"""- result = LiteLLMCompletionResponsesConfig._transform_tool_choice(- {"type": "function"}- )+ result = LiteLLMCompletionResponsesConfig._transform_tool_choice({"type": "function"})assert result == "required"def test_transform_tool_choice_function_empty_name_falls_back_to_required(self):"""An empty top-level name is falsy and must not produce an empty function name"""- result = LiteLLMCompletionResponsesConfig._transform_tool_choice(- {"type": "function", "name": ""}- )+ result = LiteLLMCompletionResponsesConfig._transform_tool_choice({"type": "function", "name": ""})assert result == "required"@@ -982,20 +914,12 @@ class TestContentTypeTransformation:Test that 'tool_result' content type is transformed to 'text'.This fixes: Invalid user message - content type 'tool_result' not valid."""- result = (- LiteLLMCompletionResponsesConfig._get_chat_completion_request_content_type(- "tool_result"- )- )+ result = LiteLLMCompletionResponsesConfig._get_chat_completion_request_content_type("tool_result")assert result == "text"def test_input_text_content_type_transformed_to_text(self):"""Test that 'input_text' content type is transformed to 'text'"""- result = (- LiteLLMCompletionResponsesConfig._get_chat_completion_request_content_type(- "input_text"- )- )+ result = LiteLLMCompletionResponsesConfig._get_chat_completion_request_content_type("input_text")assert result == "text"def test_none_text_blocks_filtered_out(self):@@ -1009,9 +933,7 @@ class TestContentTypeTransformation:{"type": "text", "text": None}, # Should be filtered out{"type": "text", "text": "another valid"},]- result = LiteLLMCompletionResponsesConfig._transform_responses_api_content_to_chat_completion_content(- content- )+ result = LiteLLMCompletionResponsesConfig._transform_responses_api_content_to_chat_completion_content(content)assert len(result) == 2assert result[0]["text"] == "valid text"assert result[1]["text"] == "another valid"@@ -1033,9 +955,7 @@ class TestToolTransformation:(result_tools,web_search_options,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assertassert len(result_tools) == 1@@ -1057,9 +977,7 @@ class TestToolTransformation:(result_tools,web_search_options,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assertassert len(result_tools) == 1@@ -1087,9 +1005,7 @@ class TestToolTransformation:(result_tools,web_search_options,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assert - computer_use has no Chat Completions equivalent, so it is droppedassert len(result_tools) == 0@@ -1114,9 +1030,7 @@ class TestToolTransformation:(result_tools,web_search_options,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assert - custom tool is converted to a function toolassert len(result_tools) == 1@@ -1141,9 +1055,7 @@ class TestToolTransformation:(result_tools,web_search_options,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assertassert len(result_tools) == 1@@ -1167,9 +1079,7 @@ class TestToolTransformation:(result_tools,_,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assertassert len(result_tools) == 1@@ -1190,9 +1100,7 @@ class TestToolTransformation:(result_tools,_,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assertassert len(result_tools) == 1@@ -1211,9 +1119,7 @@ class TestToolTransformation:tools = [custom_tool]with pytest.raises(ValueError, match="allowed_callers must be a list of strings"):- LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)def test_transform_web_search_tools_to_web_search_options(self):"""Test that web_search tools are converted to web_search_options"""@@ -1229,9 +1135,7 @@ class TestToolTransformation:(result_tools,web_search_options,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assertassert len(result_tools) == 0 # Web search is not added to tools@@ -1262,9 +1166,7 @@ class TestToolTransformation:(result_tools,web_search_options,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assertassert len(result_tools) == 1@@ -1294,9 +1196,7 @@ class TestToolTransformation:(result_tools,_,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assertassert len(result_tools) == 1@@ -1322,9 +1222,7 @@ class TestToolTransformation:(result_tools,_,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assertassert len(result_tools) == 1@@ -1350,9 +1248,7 @@ class TestToolTransformation:(result_tools,_,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assertassert len(result_tools) == 1@@ -1376,9 +1272,7 @@ class TestToolTransformation:(result_tools,_,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assertassert len(result_tools) == 2@@ -1410,14 +1304,10 @@ class TestToolTransformation:(result_tools,web_search_options,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assert- assert (- len(result_tools) == 3- ) # function, mcp, vertex (web_search becomes options)+ assert len(result_tools) == 3 # function, mcp, vertex (web_search becomes options)assert web_search_options is not None# Check function tool@@ -1447,9 +1337,7 @@ class TestToolTransformation:(result_tools,_,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assertassert len(result_tools) == 1@@ -1472,9 +1360,7 @@ class TestToolTransformation:(result_tools,_,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assertassert len(result_tools) == 1@@ -1495,9 +1381,7 @@ class TestToolTransformation:(result_tools,_,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assertassert len(result_tools) == 1@@ -1519,19 +1403,14 @@ class TestToolTransformation:(result_tools,_,- ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(- tools=tools- )+ ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(tools=tools)# Assertassert len(result_tools) == 1result_tool = result_tools[0]assert result_tool["function"]["parameters"]["type"] == "object"assert "properties" in result_tool["function"]["parameters"]- assert (- result_tool["function"]["parameters"]["properties"]["arg"]["type"]- == "string"- )+ assert result_tool["function"]["parameters"]["properties"]["arg"]["type"] == "string"def test_bedrock_anthropic_drops_derived_web_search_options(self):"""@@ -1657,11 +1536,7 @@ class TestToolTransformation:assert "web_search_options" not in resultbedrock_tool_blocks = _bedrock_tools_pt(tools=result["tools"], model=model)- names = [- block["toolSpec"]["name"]- for block in bedrock_tool_blocks- if "toolSpec" in block- ]+ names = [block["toolSpec"]["name"] for block in bedrock_tool_blocks if "toolSpec" in block]assert names == ["noop"]assert not any(name.startswith("litellm_unnamed_tool_") for name in names)@@ -1940,9 +1815,7 @@ class TestUsageTransformation:Choices(finish_reason="stop",index=0,- message=Message(- content="Here is the generated image.", role="assistant"- ),+ message=Message(content="Here is the generated image.", role="assistant"),)],)@@ -2166,9 +2039,7 @@ class TestStreamingIDConsistency:# Verify the cached ID is set and matchesassert iterator._cached_item_id is not None, "Iterator should cache the item_id"assert iterator._cached_item_id == item_id_1, "Cached ID should match event IDs"- assert (- iterator._cached_item_id == "chatcmpl-first-id"- ), "Should use the first chunk's ID"+ assert iterator._cached_item_id == "chatcmpl-first-id", "Should use the first chunk's ID"def test_streaming_iterator_initial_events_use_cached_id(self):"""@@ -2258,9 +2129,7 @@ class TestStreamingIDConsistency:# Create done eventstext_done_event = iterator.create_output_text_done_event(complete_response)- content_done_event = iterator.create_output_content_part_done_event(- complete_response- )+ content_done_event = iterator.create_output_content_part_done_event(complete_response)item_done_event = iterator.create_output_item_done_event(complete_response)# Extract IDs@@ -2320,27 +2189,19 @@ class TestStreamingIDConsistency:input=input_items)- roles = [- m.get("role") if isinstance(m, dict) else getattr(m, "role", None)- for m in messages- ]+ roles = [m.get("role") if isinstance(m, dict) else getattr(m, "role", None) for m in messages]# Must not have two consecutive assistant messagesfor i in range(len(roles) - 1):- assert not (- roles[i] == "assistant" and roles[i + 1] == "assistant"- ), f"Consecutive assistant messages at indices {i} and {i+1}: {roles}"+ assert not (roles[i] == "assistant" and roles[i + 1] == "assistant"), (+ f"Consecutive assistant messages at indices {i} and {i + 1}: {roles}"+ )# The single assistant message must contain BOTH tool_callsassistant_messages = [- m- for m in messages- if (m.get("role") if isinstance(m, dict) else getattr(m, "role", None))- == "assistant"+ m for m in messages if (m.get("role") if isinstance(m, dict) else getattr(m, "role", None)) == "assistant"]- assert (- len(assistant_messages) == 1- ), f"Expected 1 assistant message, got {len(assistant_messages)}"+ assert len(assistant_messages) == 1, f"Expected 1 assistant message, got {len(assistant_messages)}"assistant_msg = assistant_messages[0]tool_calls = (@@ -2348,27 +2209,19 @@ class TestStreamingIDConsistency:if isinstance(assistant_msg, dict)else getattr(assistant_msg, "tool_calls", None))- assert (- tool_calls is not None and len(tool_calls) == 2- ), f"Expected 2 tool_calls in the merged assistant message, got: {tool_calls}"+ assert tool_calls is not None and len(tool_calls) == 2, (+ f"Expected 2 tool_calls in the merged assistant message, got: {tool_calls}"+ )- call_ids = [- (tc.get("id") if isinstance(tc, dict) else getattr(tc, "id", None))- for tc in tool_calls- ]+ call_ids = [(tc.get("id") if isinstance(tc, dict) else getattr(tc, "id", None)) for tc in tool_calls]assert "toolu_01" in call_ids, f"toolu_01 missing from tool_calls: {call_ids}"assert "toolu_02" in call_ids, f"toolu_02 missing from tool_calls: {call_ids}"# Both tool messages must be presenttool_messages = [- m- for m in messages- if (m.get("role") if isinstance(m, dict) else getattr(m, "role", None))- == "tool"+ m for m in messages if (m.get("role") if isinstance(m, dict) else getattr(m, "role", None)) == "tool"]- assert (- len(tool_messages) == 2- ), f"Expected 2 tool messages, got {len(tool_messages)}"+ assert len(tool_messages) == 2, f"Expected 2 tool messages, got {len(tool_messages)}"def test_single_tool_call_still_works_after_merge_fix(self):"""@@ -2390,20 +2243,14 @@ class TestStreamingIDConsistency:input=input_items)- roles = [- m.get("role") if isinstance(m, dict) else getattr(m, "role", None)- for m in messages- ]+ roles = [m.get("role") if isinstance(m, dict) else getattr(m, "role", None) for m in messages]assert "user" in rolesassert "assistant" in rolesassert "tool" in rolesassistant_messages = [- m- for m in messages- if (m.get("role") if isinstance(m, dict) else getattr(m, "role", None))- == "assistant"+ m for m in messages if (m.get("role") if isinstance(m, dict) else getattr(m, "role", None)) == "assistant"]assert len(assistant_messages) == 1@@ -2576,9 +2423,7 @@ class TestEnsureOutputItemContentPartAdded:LiteLLMCompletionStreamingIterator,)- iterator = LiteLLMCompletionStreamingIterator.__new__(- LiteLLMCompletionStreamingIterator- )+ iterator = LiteLLMCompletionStreamingIterator.__new__(LiteLLMCompletionStreamingIterator)iterator.sent_output_item_added_event = Falseiterator.sent_content_part_added_event = Falseiterator._sequence_number = 0@@ -2671,9 +2516,7 @@ class TestEnsureOutputItemContentPartAdded:usage=Usage(prompt_tokens=10, completion_tokens=1, total_tokens=11),)- completed_event = iterator._emit_response_completed_event(- litellm_model_response- )+ completed_event = iterator._emit_response_completed_event(litellm_model_response)assert completed_event is not Noneassert completed_event.response.status == "incomplete"@@ -2716,9 +2559,7 @@ class TestCacheControlPreservation:"cache_control": {"type": "ephemeral"},}]- result = LiteLLMCompletionResponsesConfig._transform_responses_api_content_to_chat_completion_content(- content- )+ result = LiteLLMCompletionResponsesConfig._transform_responses_api_content_to_chat_completion_content(content)assert isinstance(result, list)assert len(result) == 1assert result[0]["cache_control"] == {"type": "ephemeral"}@@ -2726,9 +2567,7 @@ class TestCacheControlPreservation:def test_content_without_cache_control_unaffected(self):"""Content blocks that don't have cache_control should be unaffected."""content = [{"type": "text", "text": "hello"}]- result = LiteLLMCompletionResponsesConfig._transform_responses_api_content_to_chat_completion_content(- content- )+ result = LiteLLMCompletionResponsesConfig._transform_responses_api_content_to_chat_completion_content(content)assert isinstance(result, list)assert len(result) == 1assert "cache_control" not in result[0]@@ -2750,9 +2589,7 @@ class TestCacheControlPreservation:)assert len(messages) == 1msg_content = (- messages[0].get("content")- if isinstance(messages[0], dict)- else getattr(messages[0], "content", None)+ messages[0].get("content") if isinstance(messages[0], dict) else getattr(messages[0], "content", None))assert isinstance(msg_content, list)assert msg_content[0]["cache_control"] == {"type": "ephemeral"}@@ -2765,9 +2602,7 @@ class TestCacheControlPreservation:"cache_control": {"type": "ephemeral"},}]- result = LiteLLMCompletionResponsesConfig._transform_responses_api_content_to_chat_completion_content(- content- )+ result = LiteLLMCompletionResponsesConfig._transform_responses_api_content_to_chat_completion_content(content)assert isinstance(result, list)assert len(result) == 1assert result[0]["cache_control"] == {"type": "ephemeral"}@@ -2780,13 +2615,121 @@ class TestCacheControlPreservation:"cache_control": {"type": "ephemeral"},}]- result = LiteLLMCompletionResponsesConfig._transform_responses_api_content_to_chat_completion_content(- content- )+ result = LiteLLMCompletionResponsesConfig._transform_responses_api_content_to_chat_completion_content(content)assert isinstance(result, list)assert len(result) == 1assert result[0]["cache_control"] == {"type": "ephemeral"}+ def test_cache_control_preserved_for_object_input_item(self):+ """Test that cache_control is preserved when input_item is a custom object / model."""++ class MockInputItem:+ def __init__(self):+ self.role = "user"+ self.content = "hello"+ self.cache_control = {"type": "ephemeral"}++ input_item = MockInputItem()+ messages = LiteLLMCompletionResponsesConfig._transform_responses_api_input_item_to_chat_completion_message(+ input_item+ )+ assert len(messages) == 1+ assert messages[0].get("cache_control") == {"type": "ephemeral"}++ def test_cache_control_preserved_for_object_content_item(self):+ """Test that cache_control is preserved when content items are custom objects."""++ class MockContentBlock:+ def __init__(self):+ self.type = "text"+ self.text = "hello"+ self.cache_control = {"type": "ephemeral"}++ class MockPydanticV2Block:+ def __init__(self):+ self.type = "text"+ self.text = "hello v2"+ self.cache_control = {"type": "ephemeral"}++ def model_dump(self):+ return {"type": self.type, "text": self.text, "cache_control": self.cache_control}++ class MockPydanticV1Block:+ def __init__(self):+ self.type = "text"+ self.text = "hello v1"+ self.cache_control = {"type": "ephemeral"}++ def dict(self):+ return {"type": self.type, "text": self.text, "cache_control": self.cache_control}++ content = [MockContentBlock(), MockPydanticV2Block(), MockPydanticV1Block()]+ result = LiteLLMCompletionResponsesConfig._transform_responses_api_content_to_chat_completion_content(content)+ assert isinstance(result, list)+ assert len(result) == 3+ assert result[0]["cache_control"] == {"type": "ephemeral"}+ assert result[1]["cache_control"] == {"type": "ephemeral"}+ assert result[2]["cache_control"] == {"type": "ephemeral"}+ assert result[1]["text"] == "hello v2"+ assert result[2]["text"] == "hello v1"++ def test_is_cached_message_for_object_message_and_content_item(self):+ """Test is_cached_message on custom objects / models."""+ from litellm.utils import is_cached_message++ # Test message level cache_control object+ class MockCacheControl:+ def __init__(self):+ self.type = "ephemeral"++ class MockMessageLevelObj:+ def __init__(self):+ self.role = "system"+ self.content = "hello"+ self.cache_control = MockCacheControl()++ msg = MockMessageLevelObj()+ assert is_cached_message(msg) is True++ # Test content level cache_control object+ class MockContentItem:+ def __init__(self):+ self.type = "text"+ self.text = "hello"+ self.cache_control = MockCacheControl()++ class MockContentLevelObj:+ def __init__(self):+ self.role = "system"+ self.content = [MockContentItem()]++ msg = MockContentLevelObj()+ assert is_cached_message(msg) is True++ def test_extract_ttl_from_cached_messages_for_object_models(self):+ """Test extract_ttl_from_cached_messages with object-based messages and content items."""+ from litellm.llms.vertex_ai.context_caching.transformation import extract_ttl_from_cached_messages++ class MockCacheControl:+ def __init__(self):+ self.type = "ephemeral"+ self.ttl = "3600s"++ class MockContentItem:+ def __init__(self):+ self.type = "text"+ self.text = "hello"+ self.cache_control = MockCacheControl()++ class MockMessageObj:+ def __init__(self):+ self.role = "system"+ self.content = [MockContentItem()]++ messages = [MockMessageObj()]+ ttl = extract_ttl_from_cached_messages(messages)+ assert ttl == "3600s"+def test_function_call_tool_id_falls_back_to_unique_id_for_degenerate_call_id():"""Bedrock Mantle returns a non-unique, index-based ``call_id`` (``call_0`` that@@ -2798,16 +2741,10 @@ def test_function_call_tool_id_falls_back_to_unique_id_for_degenerate_call_id():for the bedrock-mantle gpt-5.5 non-streaming path."""from types import SimpleNamespace- convert = (- LiteLLMCompletionResponsesConfig.convert_response_function_tool_call_to_chat_completion_tool_call- )+ convert = LiteLLMCompletionResponsesConfig.convert_response_function_tool_call_to_chat_completion_tool_call- mantle = SimpleNamespace(- id="fc_unique_abc123", call_id="call_0", name="get_weather", arguments="{}"- )+ mantle = SimpleNamespace(id="fc_unique_abc123", call_id="call_0", name="get_weather", arguments="{}")assert convert(mantle)["id"] == "fc_unique_abc123"- openai = SimpleNamespace(- id="fc_2", call_id="call_tokyo", name="get_weather", arguments="{}"- )+ openai = SimpleNamespace(id="fc_2", call_id="call_tokyo", name="get_weather", arguments="{}")assert convert(openai)["id"] == "call_tokyo"