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
[Feat] Responses API Session Handling - Multi media support (#13347)
Ishaan Jaff4d941c914ed4
diff --git a/cookbook/misc/test_responses_api.py b/cookbook/misc/test_responses_api.pynew file mode 100644index 00000000000..5fd19c6f66f--- /dev/null+++ b/cookbook/misc/test_responses_api.py@@ -0,0 +1,53 @@+import base64+from openai import OpenAI+import time+client = OpenAI(+ base_url="http://0.0.0.0:4001",+ api_key="sk-1234"+)++# Function to encode the image+def encode_image(image_path):+ with open(image_path, "rb") as image_file:+ return base64.b64encode(image_file.read()).decode("utf-8")+++# Path to your image+image_path = "litellm/proxy/logo.jpg"++# Getting the Base64 string+base64_image = encode_image(image_path)+++response = client.responses.create(+ model="bedrock/us.anthropic.claude-3-5-sonnet-20241022-v2:0",+ input=[+ {+ "role": "user",+ "content": [+ { "type": "input_text", "text": "what color is the image"},+ {+ "type": "input_image",+ "image_url": f"data:image/jpeg;base64,{base64_image}",+ },+ ],+ }+ ],+)++++print(response.output_text)+print("response1 id===", response.id)+print("sleeping for 20 seconds...")+time.sleep(20)+print("making follow up request for existing id")+response2 = client.responses.create(+ model="bedrock/us.anthropic.claude-3-5-sonnet-20241022-v2:0",+ previous_response_id=response.id,+ input="ok, and what objects are in the image?"+)++print(response2.output_text)++diff --git a/enterprise/litellm_enterprise/enterprise_callbacks/session_handler.py b/enterprise/litellm_enterprise/enterprise_callbacks/session_handler.pydeleted file mode 100644index 1a08a8f9101..00000000000--- a/enterprise/litellm_enterprise/enterprise_callbacks/session_handler.py+++ /dev/null@@ -1,160 +0,0 @@-import json-from typing import TYPE_CHECKING, Any, List, Optional, Union, cast--from litellm._logging import verbose_proxy_logger-from litellm.proxy._types import SpendLogsPayload-from litellm.responses.utils import ResponsesAPIRequestUtils-from litellm.types.llms.openai import (- AllMessageValues,- ChatCompletionResponseMessage,- GenericChatCompletionMessage,- ResponseInputParam,-)-from litellm.types.utils import ChatCompletionMessageToolCall, Message, ModelResponse--if TYPE_CHECKING:- from litellm.responses.litellm_completion_transformation.transformation import (- ChatCompletionSession,- )-else:- ChatCompletionSession = Any---class _ENTERPRISE_ResponsesSessionHandler:- @staticmethod- async def get_chat_completion_message_history_for_previous_response_id(- previous_response_id: str,- ) -> ChatCompletionSession:- """- Return the chat completion message history for a previous response id- """- from litellm.responses.litellm_completion_transformation.transformation import (- ChatCompletionSession,- LiteLLMCompletionResponsesConfig,- )-- verbose_proxy_logger.debug(- "inside get_chat_completion_message_history_for_previous_response_id"- )- all_spend_logs: List[- SpendLogsPayload- ] = await _ENTERPRISE_ResponsesSessionHandler.get_all_spend_logs_for_previous_response_id(- previous_response_id- )- verbose_proxy_logger.debug(- "found %s spend logs for this response id", len(all_spend_logs)- )-- litellm_session_id: Optional[str] = None- if len(all_spend_logs) > 0:- litellm_session_id = all_spend_logs[0].get("session_id")-- chat_completion_message_history: List[- Union[- AllMessageValues,- GenericChatCompletionMessage,- ChatCompletionMessageToolCall,- ChatCompletionResponseMessage,- Message,- ]- ] = []- for spend_log in all_spend_logs:- proxy_server_request: Union[str, dict] = (- spend_log.get("proxy_server_request") or "{}"- )- proxy_server_request_dict: Optional[dict] = None- response_input_param: Optional[Union[str, ResponseInputParam]] = None- if isinstance(proxy_server_request, dict):- proxy_server_request_dict = proxy_server_request- else:- proxy_server_request_dict = json.loads(proxy_server_request)-- ############################################################- # Add Input messages for this Spend Log- ############################################################- if proxy_server_request_dict:- _response_input_param = proxy_server_request_dict.get("input", None)- if isinstance(_response_input_param, str):- response_input_param = _response_input_param- elif isinstance(_response_input_param, dict):- response_input_param = cast(- ResponseInputParam, _response_input_param- )-- if response_input_param:- chat_completion_messages = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(- input=response_input_param,- responses_api_request=proxy_server_request_dict or {},- )- chat_completion_message_history.extend(chat_completion_messages)-- ############################################################- # Add Output messages for this Spend Log- ############################################################- _response_output = spend_log.get("response", "{}")- if isinstance(_response_output, dict):- # transform `ChatCompletion Response` to `ResponsesAPIResponse`- model_response = ModelResponse(**_response_output)- for choice in model_response.choices:- if hasattr(choice, "message"):- chat_completion_message_history.append(- getattr(choice, "message")- )-- verbose_proxy_logger.debug(- "chat_completion_message_history %s",- json.dumps(chat_completion_message_history, indent=4, default=str),- )- return ChatCompletionSession(- messages=chat_completion_message_history,- litellm_session_id=litellm_session_id,- )-- @staticmethod- async def get_all_spend_logs_for_previous_response_id(- previous_response_id: str,- ) -> List[SpendLogsPayload]:- """- Get all spend logs for a previous response id--- SQL query-- SELECT session_id FROM spend_logs WHERE response_id = previous_response_id, SELECT * FROM spend_logs WHERE session_id = session_id- """- from litellm.proxy.proxy_server import prisma_client-- verbose_proxy_logger.debug("decoding response id=%s", previous_response_id)-- decoded_response_id = (- ResponsesAPIRequestUtils._decode_responses_api_response_id(- previous_response_id- )- )- previous_response_id = decoded_response_id.get(- "response_id", previous_response_id- )- if prisma_client is None:- return []-- query = """- WITH matching_session AS (- SELECT session_id- FROM "LiteLLM_SpendLogs"- WHERE request_id = $1- )- SELECT *- FROM "LiteLLM_SpendLogs"- WHERE session_id IN (SELECT session_id FROM matching_session)- ORDER BY "endTime" ASC;- """-- spend_logs = await prisma_client.db.query_raw(query, previous_response_id)-- verbose_proxy_logger.debug(- "Found the following spend logs for previous response id %s: %s",- previous_response_id,- json.dumps(spend_logs, indent=4, default=str),- )-- return spend_logsdiff --git a/litellm/constants.py b/litellm/constants.pyindex 27cea0eb040..c7404f10a78 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -766,6 +766,7 @@ MAXIMUM_TRACEBACK_LINES_TO_LOG = int(os.getenv("MAXIMUM_TRACEBACK_LINES_TO_LOG",X_LITELLM_DISABLE_CALLBACKS = "x-litellm-disable-callbacks"LITELLM_METADATA_FIELD = "litellm_metadata"OLD_LITELLM_METADATA_FIELD = "metadata"+LITELLM_TRUNCATED_PAYLOAD_FIELD = "litellm_truncated"########################### LiteLLM Proxy Specific Constants ###################################################################################################################diff --git a/litellm/integrations/custom_logger.py b/litellm/integrations/custom_logger.pyindex b5c7101dde9..ee7e771faa6 100644--- a/litellm/integrations/custom_logger.py+++ b/litellm/integrations/custom_logger.py@@ -541,3 +541,14 @@ class CustomLogger: # https://docs.litellm.ai/docs/observability/custom_callbacmodel_call_details_copy["standard_logging_object"] = standard_logging_object_copyreturn model_call_details_copy++++ async def get_proxy_server_request_from_cold_storage_with_object_key(+ self,+ object_key: str,+ ) -> Optional[dict]:+ """+ Get the proxy server request from cold storage using the object key directly.+ """+ passdiff --git a/litellm/integrations/s3_v2.py b/litellm/integrations/s3_v2.pyindex 7df3e58b2da..efe18cb68ad 100644--- a/litellm/integrations/s3_v2.py+++ b/litellm/integrations/s3_v2.py@@ -304,7 +304,10 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):data=prepped.body,headers=prepped.headers,)- SigV4Auth(credentials, "s3", self.s3_region_name).add_auth(aws_request)+ aws_region_name = self.get_aws_region_name_for_non_llm_api_calls(+ aws_region_name=self.s3_region_name+ )+ SigV4Auth(credentials, "s3", aws_region_name).add_auth(aws_request)# Prepare the signed headerssigned_headers = dict(aws_request.headers.items())@@ -444,7 +447,10 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):data=prepped.body,headers=prepped.headers,)- SigV4Auth(credentials, "s3", self.s3_region_name).add_auth(aws_request)+ aws_region_name = self.get_aws_region_name_for_non_llm_api_calls(+ aws_region_name=self.s3_region_name+ )+ SigV4Auth(credentials, "s3", aws_region_name).add_auth(aws_request)# Prepare the signed headerssigned_headers = dict(aws_request.headers.items())@@ -455,3 +461,108 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):response.raise_for_status()except Exception as e:verbose_logger.exception(f"Error uploading to s3: {str(e)}")+++ async def _download_object_from_s3(self, s3_object_key: str) -> Optional[dict]:+ """+ Download and parse JSON object from S3.++ Args:+ s3_object_key: The S3 object key to download++ Returns:+ Optional[dict]: The parsed JSON object or None if not found/error+ """+ try:+ import hashlib++ import requests+ from botocore.auth import SigV4Auth+ from botocore.awsrequest import AWSRequest+ except ImportError:+ raise ImportError("Missing boto3 to call S3. Run 'pip install boto3'.")++ try:+ from litellm.litellm_core_utils.asyncify import asyncify++ # Get AWS credentials+ asyncified_get_credentials = asyncify(self.get_credentials)+ credentials = await asyncified_get_credentials(+ aws_access_key_id=self.s3_aws_access_key_id,+ aws_secret_access_key=self.s3_aws_secret_access_key,+ aws_session_token=self.s3_aws_session_token,+ aws_region_name=self.s3_region_name,+ aws_session_name=self.s3_aws_session_name,+ aws_profile_name=self.s3_aws_profile_name,+ aws_role_name=self.s3_aws_role_name,+ aws_web_identity_token=self.s3_aws_web_identity_token,+ aws_sts_endpoint=self.s3_aws_sts_endpoint,+ )++ verbose_logger.debug(+ f"s3_v2 logger - downloading data from s3 - {s3_object_key}"+ )++ # Prepare the URL+ url = f"https://{self.s3_bucket_name}.s3.{self.s3_region_name}.amazonaws.com/{s3_object_key}"++ if self.s3_endpoint_url:+ url = self.s3_endpoint_url + "/" + s3_object_key++ # Prepare the request for GET operation+ # For GET requests, we need x-amz-content-sha256 with hash of empty string+ empty_string_hash = hashlib.sha256(b"").hexdigest()+ headers = {+ "x-amz-content-sha256": empty_string_hash,+ }+ req = requests.Request("GET", url, headers=headers)+ prepped = req.prepare()++ # Sign the request+ aws_request = AWSRequest(+ method=prepped.method,+ url=prepped.url,+ headers=prepped.headers,+ )+ SigV4Auth(credentials, "s3", self.s3_region_name).add_auth(aws_request)++ # Prepare the signed headers+ signed_headers = dict(aws_request.headers.items())++ # Make the request+ response = await self.async_httpx_client.get(url, headers=signed_headers)++ if response.status_code != 200:+ verbose_logger.exception("S3 object not found, saw response=", response.text)+ return None++ # Parse JSON response+ return response.json()++ except Exception as e:+ verbose_logger.exception(f"Error downloading from S3: {str(e)}")+ return None++ async def get_proxy_server_request_from_cold_storage_with_object_key(+ self,+ object_key: str,+ ) -> Optional[dict]:+ """+ Get the proxy server request from cold storage++ Allows fetching a dict of the proxy server request from s3 or GCS bucket.++ Args:+ request_id: The unique request ID to search for+ start_time: The start time of the request (datetime or ISO string)++ Returns:+ Optional[dict]: The request data dictionary or None if not found+ """+ try:+ # Download and return the object from S3+ downloaded_object = await self._download_object_from_s3(object_key)+ return downloaded_object+ except Exception as e:+ verbose_logger.exception(f"Error retrieving object {object_key} from cold storage: {str(e)}")+ return None\ No newline at end of filediff --git a/litellm/litellm_core_utils/custom_logger_registry.py b/litellm/litellm_core_utils/custom_logger_registry.pyindex 9606b47b9b8..fd82ecdf2b2 100644--- a/litellm/litellm_core_utils/custom_logger_registry.py+++ b/litellm/litellm_core_utils/custom_logger_registry.py@@ -10,6 +10,7 @@ Example:from typing import Union+from litellm import _custom_logger_compatible_callbacks_literalfrom litellm.integrations.agentops import AgentOpsfrom litellm.integrations.anthropic_cache_control_hook import AnthropicCacheControlHookfrom litellm.integrations.argilla import ArgillaLogger@@ -150,3 +151,14 @@ class CustomLoggerRegistry:if callback_class == class_type:callback_strs.append(callback_str)return callback_strs+++ @classmethod+ def get_class_type_for_custom_logger_name(+ cls,+ custom_logger_name: _custom_logger_compatible_callbacks_literal,+ ) -> type:+ """+ Get the class type for a given custom logger name+ """+ return cls.CALLBACK_CLASS_STR_TO_CLASS_TYPE[custom_logger_name]diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex dfa941d8301..5462257c9b7 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -3830,6 +3830,8 @@ class StandardLoggingPayloadSetup:] = None,usage_object: Optional[dict] = None,proxy_server_request: Optional[dict] = None,+ start_time: Optional[dt_object] = None,+ response_id: Optional[str] = None,) -> StandardLoggingMetadata:"""Clean and filter the metadata dictionary to include only the specified keys in StandardLoggingMetadata.@@ -3881,6 +3883,7 @@ class StandardLoggingPayloadSetup:usage_object=usage_object,requester_custom_headers=None,user_api_key_request_route=None,+ cold_storage_object_key=None,)if isinstance(metadata, dict):# Filter the metadata dictionary to include only the specified keys@@ -3913,6 +3916,16 @@ class StandardLoggingPayloadSetup:proxy_server_request=proxy_server_request,)+ # Generate cold storage object key if cold storage is configured+ if start_time is not None and response_id is not None:+ cold_storage_object_key = StandardLoggingPayloadSetup._generate_cold_storage_object_key(+ start_time=start_time,+ response_id=response_id,+ team_alias=clean_metadata.get("user_api_key_team_alias"),+ )+ if cold_storage_object_key:+ clean_metadata["cold_storage_object_key"] = cold_storage_object_key+return clean_metadata@staticmethod@@ -4071,6 +4084,49 @@ class StandardLoggingPayloadSetup:return api_base.rstrip("/")return api_base+ @staticmethod+ def _generate_cold_storage_object_key(+ start_time: dt_object,+ response_id: str,+ team_alias: Optional[str] = None,+ ) -> Optional[str]:+ """+ Generate cold storage object key in the same format as S3Logger.++ Args:+ start_time: The start time of the request+ response_id: The response ID+ team_alias: Optional team alias for team-based prefixing++ Returns:+ Optional[str]: The generated object key or None if cold storage not configured+ """+ # Generate object key in same format as S3Logger+ from litellm.integrations.s3 import get_s3_object_key+ from litellm.proxy.spend_tracking.cold_storage_handler import ColdStorageHandler++ # Only generate object key if cold storage is configured+ configured_cold_storage_logger = ColdStorageHandler._get_configured_cold_storage_custom_logger()+ if configured_cold_storage_logger is None:+ return None++ try:+ # Generate file name in same format as litellm.utils.get_logging_id+ s3_file_name = f"time-{start_time.strftime('%H-%M-%S-%f')}_{response_id}"+++ s3_object_key = get_s3_object_key(+ s3_path="", # Use empty path as default+ team_alias_prefix="", # Don't split by team alias for cold storage+ start_time=start_time,+ s3_file_name=s3_file_name,+ )++ return s3_object_key+ except Exception:+ # If any error occurs in generating the key, return None+ return None+@staticmethoddef get_error_information(original_exception: Optional[Exception],@@ -4322,6 +4378,8 @@ def get_standard_logging_object_payload(),usage_object=usage.model_dump(),proxy_server_request=proxy_server_request,+ start_time=start_time,+ response_id=id,)_request_body = proxy_server_request.get("body", {})@@ -4469,6 +4527,7 @@ def get_standard_logging_metadata(usage_object=None,requester_custom_headers=None,user_api_key_request_route=None,+ cold_storage_object_key=None,)if isinstance(metadata, dict):# Filter the metadata dictionary to include only the specified keysdiff --git a/litellm/litellm_core_utils/logging_callback_manager.py b/litellm/litellm_core_utils/logging_callback_manager.pyindex 44cb146f91a..9ec346c20a1 100644--- a/litellm/litellm_core_utils/logging_callback_manager.py+++ b/litellm/litellm_core_utils/logging_callback_manager.py@@ -1,4 +1,4 @@-from typing import Callable, List, Set, Type, Union+from typing import TYPE_CHECKING, Callable, List, Optional, Set, Type, Unionimport litellmfrom litellm._logging import verbose_logger@@ -6,6 +6,11 @@ from litellm.integrations.additional_logging_utils import AdditionalLoggingUtilsfrom litellm.integrations.custom_logger import CustomLoggerfrom litellm.types.utils import CallbacksByType+if TYPE_CHECKING:+ from litellm import _custom_logger_compatible_callbacks_literal+else:+ _custom_logger_compatible_callbacks_literal = str+class LoggingCallbackManager:"""@@ -343,3 +348,26 @@ class LoggingCallbackManager:elif callable(callback):return getattr(callback, "__name__", str(callback))return str(callback)+++ def get_active_custom_logger_for_callback_name(+ self,+ callback_name: _custom_logger_compatible_callbacks_literal,+ ) -> Optional[CustomLogger]:+ """+ Get the active custom logger for a given callback name+ """+ from litellm.litellm_core_utils.custom_logger_registry import (+ CustomLoggerRegistry,+ )++ # get the custom logger class type+ custom_logger_class_type = CustomLoggerRegistry.get_class_type_for_custom_logger_name(callback_name)++ # get the active custom logger+ custom_logger = self.get_custom_loggers_for_type(custom_logger_class_type)++ if len(custom_logger) == 0:+ raise ValueError(f"No active custom logger found for callback name: {callback_name}")++ return custom_logger[0]diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 17257e09c5f..bb59f2e94b6 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -2264,6 +2264,7 @@ class SpendLogsMetadata(TypedDict):error_information: Optional[StandardLoggingPayloadErrorInformation]usage_object: Optional[dict]model_map_information: Optional[StandardLoggingModelInformation]+ cold_storage_object_key: Optional[str] # S3/GCS object key for cold storage retrievalclass SpendLogsPayload(TypedDict):diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yamlindex c8d148f7086..aa63369ef2b 100644--- a/litellm/proxy/proxy_config.yaml+++ b/litellm/proxy/proxy_config.yaml@@ -1,6 +1,15 @@model_list:- - model_name: anthropic/*+ - model_name: bedrock/*litellm_params:- model: anthropic/*+ model: bedrock/*+litellm_settings:+ callbacks: ["s3_v2"]+ s3_callback_params:+ s3_bucket_name: litellm-logs # AWS Bucket Name for S3+ s3_region_name: us-west-2++general_settings:+ cold_storage_custom_logger: s3_v2+ store_prompts_in_cold_storage: true\ No newline at end of filediff --git a/litellm/proxy/spend_tracking/cold_storage_handler.py b/litellm/proxy/spend_tracking/cold_storage_handler.pynew file mode 100644index 00000000000..21e785425ad--- /dev/null+++ b/litellm/proxy/spend_tracking/cold_storage_handler.py@@ -0,0 +1,73 @@+"""+This module is responsible for handling Getting/Setting the proxy server request from cold storage.++It allows fetching a dict of the proxy server request from s3 or GCS bucket.+"""+from typing import Optional, cast++import litellm+from litellm import _custom_logger_compatible_callbacks_literal+from litellm._logging import verbose_proxy_logger+from litellm.integrations.custom_logger import CustomLogger+++class ColdStorageHandler:+ """+ This class is responsible for handling Getting/Setting the proxy server request from cold storage.++ It allows fetching a dict of the proxy server request from s3 or GCS bucket.+ """++ async def get_proxy_server_request_from_cold_storage_with_object_key(+ self,+ object_key: str,+ ) -> Optional[dict]:+ """+ Get the proxy server request from cold storage using the object key directly.++ Args:+ object_key: The S3/GCS object key to retrieve++ Returns:+ Optional[dict]: The proxy server request dict or None if not found+ """++ # select the custom logger to use for cold storage+ custom_logger_name: Optional[_custom_logger_compatible_callbacks_literal] = self._select_custom_logger_for_cold_storage()++ # if no custom logger name is configured, return None+ if custom_logger_name is None:+ return None++ # get the active/initialized custom logger+ custom_logger: Optional[CustomLogger] = litellm.logging_callback_manager.get_active_custom_logger_for_callback_name(custom_logger_name)++ # if no custom logger is found, return None+ if custom_logger is None:+ return None++ proxy_server_request = await custom_logger.get_proxy_server_request_from_cold_storage_with_object_key(+ object_key=object_key,+ )++ return proxy_server_request++++ def _select_custom_logger_for_cold_storage(+ self,+ ) -> Optional[_custom_logger_compatible_callbacks_literal]:+ cold_storage_custom_logger: Optional[_custom_logger_compatible_callbacks_literal] = ColdStorageHandler._get_configured_cold_storage_custom_logger()++ return cold_storage_custom_logger+++ @staticmethod+ def _get_configured_cold_storage_custom_logger() -> Optional[_custom_logger_compatible_callbacks_literal]:+ from litellm.proxy.proxy_server import general_settings+ cold_storage_custom_logger: Optional[str] = general_settings.get("cold_storage_custom_logger")+ if not cold_storage_custom_logger:+ verbose_proxy_logger.debug("No cold storage custom logger found in general settings")+ return None++ return cast(_custom_logger_compatible_callbacks_literal, cold_storage_custom_logger)\ No newline at end of filediff --git a/litellm/proxy/spend_tracking/spend_tracking_utils.py b/litellm/proxy/spend_tracking/spend_tracking_utils.pyindex ad5cad29e60..653426e8bd2 100644--- a/litellm/proxy/spend_tracking/spend_tracking_utils.py+++ b/litellm/proxy/spend_tracking/spend_tracking_utils.py@@ -53,6 +53,7 @@ def _get_spend_logs_metadata(guardrail_information: Optional[StandardLoggingGuardrailInformation] = None,usage_object: Optional[dict] = None,model_map_information: Optional[StandardLoggingModelInformation] = None,+ cold_storage_object_key: Optional[str] = None) -> SpendLogsMetadata:if metadata is None:return SpendLogsMetadata(@@ -75,6 +76,7 @@ def _get_spend_logs_metadata(model_map_information=None,usage_object=None,guardrail_information=None,+ cold_storage_object_key=cold_storage_object_key,)verbose_proxy_logger.debug("getting payload for SpendLogs, available keys in metadata: "@@ -98,6 +100,8 @@ def _get_spend_logs_metadata(clean_metadata["guardrail_information"] = guardrail_informationclean_metadata["usage_object"] = usage_objectclean_metadata["model_map_information"] = model_map_information+ clean_metadata["cold_storage_object_key"] = cold_storage_object_key+return clean_metadata@@ -267,6 +271,11 @@ def get_logging_payload( # noqa: PLR0915if standard_logging_payload is not Noneelse None),+ cold_storage_object_key=(+ standard_logging_payload["metadata"].get("cold_storage_object_key", None)+ if standard_logging_payload is not None+ else None+ ),)special_usage_fields = ["completion_tokens", "prompt_tokens", "total_tokens"]@@ -474,6 +483,7 @@ def _sanitize_request_body_for_spend_logs_payload(Recursively sanitize request body to prevent logging large base64 strings or other large values.Truncates strings longer than 1000 characters and handles nested dictionaries."""+ from litellm.constants import LITELLM_TRUNCATED_PAYLOAD_FIELDMAX_STRING_LENGTH = 1000if visited is None:@@ -492,7 +502,7 @@ def _sanitize_request_body_for_spend_logs_payload(return [_sanitize_value(item) for item in value]elif isinstance(value, str):if len(value) > MAX_STRING_LENGTH:- return f"{value[:MAX_STRING_LENGTH]}... (truncated {len(value) - MAX_STRING_LENGTH} chars)"+ return f"{value[:MAX_STRING_LENGTH]}... ({LITELLM_TRUNCATED_PAYLOAD_FIELD} {len(value) - MAX_STRING_LENGTH} chars)"return valuereturn valuediff --git a/litellm/responses/litellm_completion_transformation/session_handler.py b/litellm/responses/litellm_completion_transformation/session_handler.pynew file mode 100644index 00000000000..28e76ca893f--- /dev/null+++ b/litellm/responses/litellm_completion_transformation/session_handler.py@@ -0,0 +1,301 @@+import json+from typing import TYPE_CHECKING, Any, List, Optional, Union, cast++from litellm._logging import verbose_proxy_logger+from litellm.proxy._types import SpendLogsPayload+from litellm.proxy.spend_tracking.cold_storage_handler import ColdStorageHandler+from litellm.responses.utils import ResponsesAPIRequestUtils+from litellm.types.llms.openai import (+ AllMessageValues,+ ChatCompletionResponseMessage,+ GenericChatCompletionMessage,+ ResponseInputParam,+)+from litellm.types.utils import ChatCompletionMessageToolCall, Message, ModelResponse++if TYPE_CHECKING:+ from litellm.responses.litellm_completion_transformation.transformation import (+ ChatCompletionSession,+ )+else:+ ChatCompletionSession = Any++########################################################+# Cold Storage Handler+########################################################+COLD_STORAGE_HANDLER = ColdStorageHandler()+########################################################++class ResponsesSessionHandler:+ @staticmethod+ async def get_chat_completion_message_history_for_previous_response_id(+ previous_response_id: str,+ ) -> ChatCompletionSession:+ """+ Return the chat completion message history for a previous response id+ """+ from litellm.responses.litellm_completion_transformation.transformation import (+ ChatCompletionSession,+ )++ verbose_proxy_logger.debug(+ "inside get_chat_completion_message_history_for_previous_response_id"+ )+ all_spend_logs: List[+ SpendLogsPayload+ ] = await ResponsesSessionHandler.get_all_spend_logs_for_previous_response_id(+ previous_response_id+ )+ verbose_proxy_logger.debug(+ "found %s spend logs for this response id", len(all_spend_logs)+ )++ litellm_session_id: Optional[str] = None+ if len(all_spend_logs) > 0:+ litellm_session_id = all_spend_logs[0].get("session_id")++ chat_completion_message_history: List[+ Union[+ AllMessageValues,+ GenericChatCompletionMessage,+ ChatCompletionMessageToolCall,+ ChatCompletionResponseMessage,+ Message,+ ]+ ] = []+ for spend_log in all_spend_logs:+ chat_completion_message_history = await ResponsesSessionHandler.extend_chat_completion_message_with_spend_log_payload(+ spend_log=spend_log,+ chat_completion_message_history=chat_completion_message_history,+ )++ verbose_proxy_logger.debug(+ "chat_completion_message_history %s",+ json.dumps(chat_completion_message_history, indent=4, default=str),+ )+ return ChatCompletionSession(+ messages=chat_completion_message_history,+ litellm_session_id=litellm_session_id,+ )++ @staticmethod+ async def extend_chat_completion_message_with_spend_log_payload(+ spend_log: SpendLogsPayload,+ chat_completion_message_history: List[+ Union[+ AllMessageValues,+ GenericChatCompletionMessage,+ ChatCompletionMessageToolCall,+ ChatCompletionResponseMessage,+ Message,+ ]+ ]+ ):+ """+ Extend the chat completion message history with the spend log payload+ """+ from litellm.responses.litellm_completion_transformation.transformation import (+ LiteLLMCompletionResponsesConfig,+ )++ proxy_server_request_dict = await ResponsesSessionHandler.get_proxy_server_request_from_spend_log(+ spend_log=spend_log,+ )+ response_input_param: Optional[Union[str, ResponseInputParam]] = None+ _messages: Optional[Union[str, ResponseInputParam]] = None++ ############################################################+ # Add Input messages for this Spend Log+ ############################################################+ if proxy_server_request_dict:+ _response_input_param = proxy_server_request_dict.get("input", None)+ _messages = proxy_server_request_dict.get("messages", None)+ if isinstance(_response_input_param, str):+ response_input_param = _response_input_param+ elif isinstance(_response_input_param, dict):+ response_input_param = cast(+ ResponseInputParam, _response_input_param+ )++ if response_input_param:+ chat_completion_messages = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=response_input_param,+ responses_api_request=proxy_server_request_dict or {},+ )+ chat_completion_message_history.extend(chat_completion_messages)++ ############################################################+ # Check if `messages` field is present in the proxy server request dict+ ############################################################+ elif _messages:+ # ensure all messages are /chat/completions/messages+ # certain requests can be stored as Responses API format - this ensures they are transformed to /chat/completions/messages+ chat_completion_messages = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=_messages,+ responses_api_request=proxy_server_request_dict or {},+ )+ chat_completion_message_history.extend(chat_completion_messages)++ ############################################################+ # Add Output messages for this Spend Log+ ############################################################+ _response_output = spend_log.get("response", "{}")+ if isinstance(_response_output, dict):+ # transform `ChatCompletion Response` to `ResponsesAPIResponse`+ model_response = ModelResponse(**_response_output)+ for choice in model_response.choices:+ if hasattr(choice, "message"):+ chat_completion_message_history.append(+ getattr(choice, "message")+ )+ return chat_completion_message_history++ @staticmethod+ async def get_proxy_server_request_from_spend_log(+ spend_log: SpendLogsPayload,+ ) -> Optional[dict]:+ """+ Get the parsed proxy server request from the spend log+ """+ proxy_server_request: Union[str, dict] = (+ spend_log.get("proxy_server_request") or "{}"+ )+ proxy_server_request_dict: Optional[dict] = None+ if isinstance(proxy_server_request, dict):+ proxy_server_request_dict = proxy_server_request+ else:+ proxy_server_request_dict = json.loads(proxy_server_request)+++ ############################################################+ # Check if user has setup cold storage for session handling+ ############################################################+ if ResponsesSessionHandler._should_check_cold_storage_for_full_payload(proxy_server_request_dict):+ # Try to get cold storage object key from spend log metadata+ _proxy_server_request_dict: Optional[dict] = None+ cold_storage_object_key = ResponsesSessionHandler._get_cold_storage_object_key_from_spend_log(spend_log)+ if cold_storage_object_key:+ # Use the object key directly from metadata+ _proxy_server_request_dict = await ResponsesSessionHandler.get_proxy_server_request_from_cold_storage_with_object_key(+ object_key=cold_storage_object_key,+ )+ if _proxy_server_request_dict:+ proxy_server_request_dict = _proxy_server_request_dict++ return proxy_server_request_dict++ @staticmethod+ def _get_cold_storage_object_key_from_spend_log(spend_log: SpendLogsPayload) -> Optional[str]:+ """+ Extract the cold storage object key from spend log metadata.++ Args:+ spend_log: The spend log payload containing metadata++ Returns:+ Optional[str]: The cold storage object key if found, None otherwise+ """+ try:+ metadata_str = spend_log.get("metadata", "{}")+ if isinstance(metadata_str, str):+ metadata_dict = json.loads(metadata_str)+ return metadata_dict.get("cold_storage_object_key")+ elif isinstance(metadata_str, dict):+ return metadata_str.get("cold_storage_object_key")+ return None+ except (json.JSONDecodeError, TypeError, AttributeError):+ verbose_proxy_logger.debug("Failed to parse metadata from spend log to extract cold storage object key")+ return None++ @staticmethod+ async def get_proxy_server_request_from_cold_storage_with_object_key(+ object_key: str,+ ) -> Optional[dict]:+ """+ Get the proxy server request from cold storage using the object key directly.++ Args:+ object_key: The S3/GCS object key to retrieve++ Returns:+ Optional[dict]: The proxy server request dict or None if not found+ """+ verbose_proxy_logger.debug("inside get_proxy_server_request_from_cold_storage_with_object_key...")++ proxy_server_request_dict = await COLD_STORAGE_HANDLER.get_proxy_server_request_from_cold_storage_with_object_key(+ object_key=object_key,+ )++ return proxy_server_request_dict++ @staticmethod+ def _should_check_cold_storage_for_full_payload(+ proxy_server_request_dict: Optional[dict],+ ) -> bool:+ """+ Only check cold storage when both are true+ 1. `LITELLM_TRUNCATED_PAYLOAD_FIELD` is in the proxy server request dict+ 2. `ColdStorageHandler._get_configured_cold_storage_custom_logger()` is not None+ """+ from litellm.constants import LITELLM_TRUNCATED_PAYLOAD_FIELD+ configured_cold_storage_custom_logger = ColdStorageHandler._get_configured_cold_storage_custom_logger()+ if configured_cold_storage_custom_logger is None:+ return False+ if proxy_server_request_dict is None:+ return True+ if len(proxy_server_request_dict) == 0:+ return True+ if LITELLM_TRUNCATED_PAYLOAD_FIELD in proxy_server_request_dict:+ return True+ return False++++ @staticmethod+ async def get_all_spend_logs_for_previous_response_id(+ previous_response_id: str,+ ) -> List[SpendLogsPayload]:+ """+ Get all spend logs for a previous response id+++ SQL query++ SELECT session_id FROM spend_logs WHERE response_id = previous_response_id, SELECT * FROM spend_logs WHERE session_id = session_id+ """+ from litellm.proxy.proxy_server import prisma_client++ verbose_proxy_logger.debug("decoding response id=%s", previous_response_id)++ decoded_response_id = (+ ResponsesAPIRequestUtils._decode_responses_api_response_id(+ previous_response_id+ )+ )+ previous_response_id = decoded_response_id.get(+ "response_id", previous_response_id+ )+ if prisma_client is None:+ return []++ query = """+ WITH matching_session AS (+ SELECT session_id+ FROM "LiteLLM_SpendLogs"+ WHERE request_id = $1+ )+ SELECT *+ FROM "LiteLLM_SpendLogs"+ WHERE session_id IN (SELECT session_id FROM matching_session)+ ORDER BY "endTime" ASC;+ """++ spend_logs = await prisma_client.db.query_raw(query, previous_response_id)++ verbose_proxy_logger.debug(+ "Found the following spend logs for previous response id %s: %s",+ previous_response_id,+ json.dumps(spend_logs, indent=4, default=str),+ )++ return spend_logsdiff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.pyindex 13791666044..3706b2f7fc9 100644--- a/litellm/responses/litellm_completion_transformation/transformation.py+++ b/litellm/responses/litellm_completion_transformation/transformation.py@@ -7,21 +7,14 @@ from typing import Any, Dict, List, Literal, Optional, Tuple, Union, castfrom openai.types.responses.tool_param import FunctionToolParamfrom typing_extensions import TypedDict-from litellm._logging import verbose_logger--try:- from litellm_enterprise.enterprise_callbacks.session_handler import (- _ENTERPRISE_ResponsesSessionHandler,- )-except Exception as e:- verbose_logger.debug(- f"[Non-Blocking] Unable to import _ENTERPRISE_ResponsesSessionHandler - LiteLLM Enterprise Feature - {str(e)}"- )- _ENTERPRISE_ResponsesSessionHandler = Nonefrom litellm.caching import InMemoryCachefrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.responses.litellm_completion_transformation.session_handler import (+ ResponsesSessionHandler,+)from litellm.types.llms.openai import (AllMessageValues,+ ChatCompletionImageObject,ChatCompletionImageUrlObject,ChatCompletionResponseMessage,ChatCompletionSystemMessage,@@ -75,13 +68,6 @@ class ChatCompletionSession(TypedDict, total=False):litellm_session_id: Optional[str]-class ChatCompletionImageItem(TypedDict):- """TypedDict for image items in chat completion content"""-- type: Literal["image"]- image_url: ChatCompletionImageUrlObject--########### End of Initialize Classes used for Responses API ###########@@ -210,20 +196,19 @@ class LiteLLMCompletionResponsesConfig:"""Async hook to get the chain of previous input and output pairs and return a list of Chat Completion messages"""- if _ENTERPRISE_ResponsesSessionHandler is not None:- chat_completion_session = ChatCompletionSession(- messages=[], litellm_session_id=None+ chat_completion_session = ChatCompletionSession(+ messages=[], litellm_session_id=None+ )+ if previous_response_id:+ chat_completion_session = await ResponsesSessionHandler.get_chat_completion_message_history_for_previous_response_id(+ previous_response_id=previous_response_id)- if previous_response_id:- chat_completion_session = await _ENTERPRISE_ResponsesSessionHandler.get_chat_completion_message_history_for_previous_response_id(- previous_response_id=previous_response_id- )- _messages = litellm_completion_request.get("messages") or []- session_messages = chat_completion_session.get("messages") or []- litellm_completion_request["messages"] = session_messages + _messages- litellm_completion_request[- "litellm_trace_id"- ] = chat_completion_session.get("litellm_session_id")+ _messages = litellm_completion_request.get("messages") or []+ session_messages = chat_completion_session.get("messages") or []+ litellm_completion_request["messages"] = session_messages + _messages+ litellm_completion_request[+ "litellm_trace_id"+ ] = chat_completion_session.get("litellm_session_id")return litellm_completion_request@staticmethod@@ -485,7 +470,7 @@ class LiteLLMCompletionResponsesConfig:return new_item@staticmethod- def _transform_input_image_item_to_image_item(item: Dict[str, Any]) -> ChatCompletionImageItem:+ def _transform_input_image_item_to_image_item(item: Dict[str, Any]) -> ChatCompletionImageObject:"""Transform a Responses API input_image item to a Chat Completion image item"""@@ -494,8 +479,8 @@ class LiteLLMCompletionResponsesConfig:detail=item.get("detail") or "auto")- return ChatCompletionImageItem(- type="image",+ return ChatCompletionImageObject(+ type="image_url",image_url=image_url_obj)@@ -506,7 +491,6 @@ class LiteLLMCompletionResponsesConfig:"""Transform a Responses API content into a Chat Completion content"""-if isinstance(content, str):return contentelif isinstance(content, list):diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 6606b0e0b89..75c7d28460b 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -1910,6 +1910,7 @@ class StandardLoggingMetadata(StandardLoggingUserAPIKeyMetadata):vector_store_request_metadata: Optional[List[StandardLoggingVectorStoreRequest]]applied_guardrails: Optional[List[str]]usage_object: Optional[dict]+ cold_storage_object_key: Optional[str] # S3/GCS object key for cold storage retrievalclass StandardLoggingAdditionalHeaders(TypedDict, total=False):diff --git a/tests/logging_callback_tests/test_amazing_s3_logs.py b/tests/logging_callback_tests/test_amazing_s3_logs.pyindex 37666d72b79..c9d0987e86f 100644--- a/tests/logging_callback_tests/test_amazing_s3_logs.py+++ b/tests/logging_callback_tests/test_amazing_s3_logs.py@@ -476,3 +476,18 @@ def test_s3_logging_r2():# post, close log file and verify# Reset stdout to the original valueprint("Passed! Testing async s3 logging")++from litellm.integrations.s3_v2 import S3Logger++class TestS3Logger(S3Logger):+ def __init__(self, *args, **kwargs):+ self.recorded_requests = {}+ self.logged_standard_logging_payload: Optional[StandardLoggingPayload] = None+ super().__init__(*args, **kwargs)++ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):+ self.recorded_requests[response_obj["id"]] = start_time+ print("recorded request", self.recorded_requests)+ self.logged_standard_logging_payload = kwargs["standard_logging_object"]+ return await super().async_log_success_event(kwargs, response_obj, start_time, end_time)+diff --git a/tests/logging_callback_tests/test_gcs_pub_sub.py b/tests/logging_callback_tests/test_gcs_pub_sub.pyindex f231d01d3fb..4172659e659 100644--- a/tests/logging_callback_tests/test_gcs_pub_sub.py+++ b/tests/logging_callback_tests/test_gcs_pub_sub.py@@ -38,6 +38,7 @@ ignored_keys = ["endTime","metadata.model_map_information","metadata.usage_object",+ "metadata.cold_storage_object_key",]diff --git a/tests/logging_callback_tests/test_otel_logging.py b/tests/logging_callback_tests/test_otel_logging.pyindex ff9d8300fef..aeb42bdaf79 100644--- a/tests/logging_callback_tests/test_otel_logging.py+++ b/tests/logging_callback_tests/test_otel_logging.py@@ -279,6 +279,7 @@ def validate_redacted_message_span_attributes(span):"metadata.mcp_tool_call_metadata","metadata.vector_store_request_metadata","metadata.requester_custom_headers",+ "metadata.cold_storage_object_key",]_all_attributes = set(diff --git a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py b/tests/test_litellm/litellm_core_utils/test_litellm_logging.pyindex e9b962f189f..317491d3172 100644--- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py+++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py@@ -394,3 +394,73 @@ def test_get_masked_values():sensitive_object, unmasked_length=4, number_of_asterisks=4)assert masked_values["presidio_anonymizer_api_base"] is None+++async def test_e2e_generate_cold_storage_object_key_successful():+ """+ Test end-to-end generation of cold storage object key when cold storage is properly configured.+ """+ from datetime import datetime, timezone+ from unittest.mock import patch++ from litellm.litellm_core_utils.litellm_logging import StandardLoggingPayloadSetup++ # Create test data+ start_time = datetime(2025, 1, 15, 10, 30, 45, 123456, timezone.utc)+ response_id = "chatcmpl-test-12345"+ team_alias = "test-team"++ with patch("litellm.proxy.spend_tracking.cold_storage_handler.ColdStorageHandler._get_configured_cold_storage_custom_logger", return_value="s3"), \+ patch("litellm.integrations.s3.get_s3_object_key") as mock_get_s3_key:++ # Mock the S3 object key generation to return a predictable result+ mock_get_s3_key.return_value = "2025-01-15/time-10-30-45-123456_chatcmpl-test-12345.json"++ # Call the function+ result = StandardLoggingPayloadSetup._generate_cold_storage_object_key(+ start_time=start_time,+ response_id=response_id,+ team_alias=team_alias+ )++ # Verify the S3 function was called with correct parameters+ mock_get_s3_key.assert_called_once_with(+ s3_path="", # Empty path as default+ team_alias_prefix="", # No team alias prefix for cold storage+ start_time=start_time,+ s3_file_name="time-10-30-45-123456_chatcmpl-test-12345"+ )++ # Verify the result+ assert result == "2025-01-15/time-10-30-45-123456_chatcmpl-test-12345.json"+ assert result is not None+ assert isinstance(result, str)+++async def test_e2e_generate_cold_storage_object_key_not_configured():+ """+ Test end-to-end generation of cold storage object key when cold storage is not configured.+ """+ from datetime import datetime, timezone+ from unittest.mock import patch++ from litellm.litellm_core_utils.litellm_logging import StandardLoggingPayloadSetup++ # Create test data+ start_time = datetime(2025, 1, 15, 10, 30, 45, 123456, timezone.utc)+ response_id = "chatcmpl-test-67890"+ team_alias = "another-team"++ with patch("litellm.proxy.spend_tracking.cold_storage_handler.ColdStorageHandler._get_configured_cold_storage_custom_logger", return_value=None):++ # Call the function+ result = StandardLoggingPayloadSetup._generate_cold_storage_object_key(+ start_time=start_time,+ response_id=response_id,+ team_alias=team_alias+ )++ # Verify the result is None when cold storage is not configured+ assert result is Nonediff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.pyindex 93be9717e96..5b1e784caa3 100644--- a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py@@ -29,6 +29,7 @@ ignored_keys = ["endTime","metadata.model_map_information","metadata.usage_object",+ "metadata.cold_storage_object_key",]diff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py b/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.pyindex 26f41b76d3b..eac631bdb0d 100644--- a/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py@@ -16,7 +16,7 @@ sys.path.insert(from unittest.mock import MagicMock, patchimport litellm-from litellm.constants import REDACTED_BY_LITELM_STRING+from litellm.constants import LITELLM_TRUNCATED_PAYLOAD_FIELD, REDACTED_BY_LITELM_STRINGfrom litellm.litellm_core_utils.safe_json_dumps import safe_dumpsfrom litellm.proxy.spend_tracking.spend_tracking_utils import (_get_vector_store_request_for_spend_logs_payload,@@ -35,7 +35,7 @@ def test_sanitize_request_body_for_spend_logs_payload_long_string():long_string = "a" * 2000 # Create a string longer than MAX_STRING_LENGTHrequest_body = {"text": long_string, "normal_text": "short text"}sanitized = _sanitize_request_body_for_spend_logs_payload(request_body)- assert len(sanitized["text"]) == 1000 + len("... (truncated 1000 chars)")+ assert len(sanitized["text"]) == 1000 + len(f"... ({LITELLM_TRUNCATED_PAYLOAD_FIELD} 1000 chars)")assert sanitized["normal_text"] == "short text"@@ -43,7 +43,7 @@ def test_sanitize_request_body_for_spend_logs_payload_nested_dict():request_body = {"outer": {"inner": {"text": "a" * 2000, "normal": "short"}}}sanitized = _sanitize_request_body_for_spend_logs_payload(request_body)assert len(sanitized["outer"]["inner"]["text"]) == 1000 + len(- "... (truncated 1000 chars)"+ f"... ({LITELLM_TRUNCATED_PAYLOAD_FIELD} 1000 chars)")assert sanitized["outer"]["inner"]["normal"] == "short"@@ -54,11 +54,11 @@ def test_sanitize_request_body_for_spend_logs_payload_nested_list():}sanitized = _sanitize_request_body_for_spend_logs_payload(request_body)assert len(sanitized["items"][0]["text"]) == 1000 + len(- "... (truncated 1000 chars)"+ f"... ({LITELLM_TRUNCATED_PAYLOAD_FIELD} 1000 chars)")assert sanitized["items"][1]["text"] == "short"assert len(sanitized["items"][2][0]["text"]) == 1000 + len(- "... (truncated 1000 chars)"+ f"... ({LITELLM_TRUNCATED_PAYLOAD_FIELD} 1000 chars)")@@ -81,14 +81,14 @@ def test_sanitize_request_body_for_spend_logs_payload_mixed_types():"nested": {"list": ["short", "a" * 2000], "dict": {"key": "a" * 2000}},}sanitized = _sanitize_request_body_for_spend_logs_payload(request_body)- assert len(sanitized["text"]) == 1000 + len("... (truncated 1000 chars)")+ assert len(sanitized["text"]) == 1000 + len(f"... ({LITELLM_TRUNCATED_PAYLOAD_FIELD} 1000 chars)")assert sanitized["number"] == 42assert sanitized["nested"]["list"][0] == "short"assert len(sanitized["nested"]["list"][1]) == 1000 + len(- "... (truncated 1000 chars)"+ f"... ({LITELLM_TRUNCATED_PAYLOAD_FIELD} 1000 chars)")assert len(sanitized["nested"]["dict"]["key"]) == 1000 + len(- "... (truncated 1000 chars)"+ f"... ({LITELLM_TRUNCATED_PAYLOAD_FIELD} 1000 chars)")diff --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 00c55b9f60f..8e38011279d 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@@ -134,9 +134,9 @@ class TestLiteLLMCompletionResponsesConfig:)# Assert- expected = {"type": "image", "image_url": {"url": image_url, "detail": "high"}}+ expected = {"type": "image_url", "image_url": {"url": image_url, "detail": "high"}}assert result == expected- assert result["type"] == "image"+ assert result["type"] == "image_url"assert result["image_url"]["url"] == image_urlassert result["image_url"]["detail"] == "high"@@ -154,9 +154,9 @@ class TestLiteLLMCompletionResponsesConfig:)# Assert- expected = {"type": "image", "image_url": {"url": image_url, "detail": "high"}}+ expected = {"type": "image_url", "image_url": {"url": image_url, "detail": "high"}}assert result == expected- assert result["type"] == "image"+ assert result["type"] == "image_url"assert result["image_url"]["url"] == image_urlassert result["image_url"]["detail"] == "high"@@ -174,9 +174,9 @@ class TestLiteLLMCompletionResponsesConfig:)# Assert- expected = {"type": "image", "image_url": {"url": image_url, "detail": "auto"}}+ expected = {"type": "image_url", "image_url": {"url": image_url, "detail": "auto"}}assert result == expected- assert result["type"] == "image"+ assert result["type"] == "image_url"assert result["image_url"]["url"] == image_urlassert result["image_url"]["detail"] == "auto"@@ -193,9 +193,9 @@ class TestLiteLLMCompletionResponsesConfig:)# Assert- expected = {"type": "image", "image_url": {"url": "", "detail": "auto"}}+ expected = {"type": "image_url", "image_url": {"url": "", "detail": "auto"}}assert result == expected- assert result["type"] == "image"+ assert result["type"] == "image_url"assert result["image_url"]["url"] == ""assert result["image_url"]["detail"] == "auto"@@ -217,9 +217,9 @@ class TestLiteLLMCompletionResponsesConfig:)# Assert- expected = {"type": "image", "image_url": {"url": "https://example.com/image.png", "detail": "auto"}}+ expected = {"type": "image_url", "image_url": {"url": "https://example.com/image.png", "detail": "auto"}}assert result == expected- assert result["type"] == "image"+ assert result["type"] == "image_url"assert result["image_url"]["url"] == "https://example.com/image.png"assert result["image_url"]["detail"] == "auto"assert "extra_field" not in resultdiff --git a/tests/enterprise/litellm_enterprise/enterprise_callbacks/test_session_handler.py b/tests/test_litellm/responses/litellm_completion_transformation/test_session_handler.pysimilarity index 58%rename from tests/enterprise/litellm_enterprise/enterprise_callbacks/test_session_handler.pyrename to tests/test_litellm/responses/litellm_completion_transformation/test_session_handler.pyindex dbe163560b0..27edfef3eb5 100644--- a/tests/enterprise/litellm_enterprise/enterprise_callbacks/test_session_handler.py+++ b/tests/test_litellm/responses/litellm_completion_transformation/test_session_handler.py@@ -11,9 +11,9 @@ sys.path.insert(0, os.path.abspath("../../..")) # Adds the parent directory to the system path--from enterprise.litellm_enterprise.enterprise_callbacks.session_handler import (- _ENTERPRISE_ResponsesSessionHandler,+from litellm.responses.litellm_completion_transformation import session_handler+from litellm.responses.litellm_completion_transformation.session_handler import (+ ResponsesSessionHandler,)@@ -111,7 +111,7 @@ async def test_get_chat_completion_message_history_for_previous_response_id():# Mock the get_all_spend_logs_for_previous_response_id methodwith patch.object(- _ENTERPRISE_ResponsesSessionHandler,+ ResponsesSessionHandler,"get_all_spend_logs_for_previous_response_id",new_callable=AsyncMock,) as mock_get_spend_logs:@@ -119,7 +119,7 @@ async def test_get_chat_completion_message_history_for_previous_response_id():# Test the functionprevious_response_id = "chatcmpl-935b8dad-fdc2-466e-a8ca-e26e5a8a21bb"- result = await _ENTERPRISE_ResponsesSessionHandler.get_chat_completion_message_history_for_previous_response_id(+ result = await ResponsesSessionHandler.get_chat_completion_message_history_for_previous_response_id(previous_response_id)@@ -166,17 +166,130 @@ async def test_get_chat_completion_message_history_empty_spend_logs():Test get_chat_completion_message_history_for_previous_response_id with empty spend logs"""with patch.object(- _ENTERPRISE_ResponsesSessionHandler,+ ResponsesSessionHandler,"get_all_spend_logs_for_previous_response_id",new_callable=AsyncMock,) as mock_get_spend_logs:mock_get_spend_logs.return_value = []previous_response_id = "non-existent-id"- result = await _ENTERPRISE_ResponsesSessionHandler.get_chat_completion_message_history_for_previous_response_id(+ result = await ResponsesSessionHandler.get_chat_completion_message_history_for_previous_response_id(previous_response_id)# Verify empty result structureassert result.get("messages") == []assert result.get("litellm_session_id") is None+++async def test_e2e_cold_storage_successful_retrieval():+ """+ Test end-to-end cold storage functionality with successful retrieval of full proxy request from cold storage.+ """+ # Mock spend logs with cold storage object key in metadata+ mock_spend_logs = [+ {+ "request_id": "chatcmpl-test-123",+ "session_id": "session-456",+ "metadata": '{"cold_storage_object_key": "s3://test-bucket/requests/session_456_req1.json"}',+ "proxy_server_request": '{"litellm_truncated": true}', # Truncated payload+ "response": {+ "id": "chatcmpl-test-123",+ "object": "chat.completion",+ "choices": [+ {+ "index": 0,+ "message": {+ "role": "assistant",+ "content": "I am an AI assistant."+ }+ }+ ]+ }+ }+ ]++ # Full proxy request data from cold storage+ full_proxy_request = {+ "input": "Hello, who are you?",+ "model": "gpt-4",+ "messages": [{"role": "user", "content": "Hello, who are you?"}]+ }++ with patch.object(+ ResponsesSessionHandler,+ "get_all_spend_logs_for_previous_response_id",+ new_callable=AsyncMock,+ ) as mock_get_spend_logs, \+ patch.object(session_handler, "COLD_STORAGE_HANDLER") as mock_cold_storage, \+ patch("litellm.proxy.spend_tracking.cold_storage_handler.ColdStorageHandler._get_configured_cold_storage_custom_logger", return_value="s3"):++ # Setup mocks+ mock_get_spend_logs.return_value = mock_spend_logs+ mock_cold_storage.get_proxy_server_request_from_cold_storage_with_object_key = AsyncMock(return_value=full_proxy_request)++ # Call the main function+ result = await ResponsesSessionHandler.get_chat_completion_message_history_for_previous_response_id(+ "chatcmpl-test-123"+ )++ # Verify cold storage was called with correct object key+ mock_cold_storage.get_proxy_server_request_from_cold_storage_with_object_key.assert_called_once_with(+ object_key="s3://test-bucket/requests/session_456_req1.json"+ )++ # Verify result structure+ assert result.get("litellm_session_id") == "session-456"+ assert len(result.get("messages", [])) >= 1 # At least the assistant response+++async def test_e2e_cold_storage_fallback_to_truncated_payload():+ """+ Test end-to-end cold storage functionality when object key is missing, falling back to truncated payload.+ """+ # Mock spend logs without cold storage object key+ mock_spend_logs = [+ {+ "request_id": "chatcmpl-test-789",+ "session_id": "session-999",+ "metadata": '{"user_api_key": "test-key"}', # No cold storage object key+ "proxy_server_request": '{"input": "Truncated message", "model": "gpt-4"}', # Regular payload+ "response": {+ "id": "chatcmpl-test-789",+ "object": "chat.completion",+ "choices": [+ {+ "index": 0,+ "message": {+ "role": "assistant",+ "content": "This is a response."+ }+ }+ ]+ }+ }+ ]++ with patch.object(+ ResponsesSessionHandler,+ "get_all_spend_logs_for_previous_response_id",+ new_callable=AsyncMock,+ ) as mock_get_spend_logs, \+ patch.object(session_handler, "COLD_STORAGE_HANDLER") as mock_cold_storage:++ # Setup mocks+ mock_get_spend_logs.return_value = mock_spend_logs++ # Call the main function+ result = await ResponsesSessionHandler.get_chat_completion_message_history_for_previous_response_id(+ "chatcmpl-test-789"+ )++ # Verify cold storage was NOT called since no object key in metadata+ mock_cold_storage.get_proxy_server_request_from_cold_storage_with_object_key.assert_not_called()++ # Verify result structure+ assert result.get("litellm_session_id") == "session-999"+ assert len(result.get("messages", [])) >= 1 # At least the assistant responsediff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_session_handler_with_cold_storage.py b/tests/test_litellm/responses/litellm_completion_transformation/test_session_handler_with_cold_storage.pynew file mode 100644index 00000000000..976152db353--- /dev/null+++ b/tests/test_litellm/responses/litellm_completion_transformation/test_session_handler_with_cold_storage.py@@ -0,0 +1,186 @@+"""+Unit tests for cold storage object key integration.++Tests for the changes to integrate cold storage handling across different components:+1. Add cold_storage_object_key field to StandardLoggingMetadata and SpendLogsMetadata+2. S3Logger generates object key when cold storage is enabled+3. Store object key in SpendLogsMetadata via spend_tracking_utils+4. Session handler uses object key from spend logs metadata+5. S3Logger supports retrieval using provided object key+"""++import json+from datetime import datetime, timezone+from typing import Optional+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from litellm.integrations.s3_v2 import S3Logger+from litellm.proxy._types import SpendLogsMetadata, SpendLogsPayload+from litellm.proxy.spend_tracking.cold_storage_handler import ColdStorageHandler+from litellm.proxy.spend_tracking.spend_tracking_utils import _get_spend_logs_metadata+from litellm.responses.litellm_completion_transformation.session_handler import (+ ResponsesSessionHandler,+)+from litellm.types.utils import StandardLoggingMetadata, StandardLoggingPayload+++class TestColdStorageObjectKeyIntegration:+ """Test suite for cold storage object key integration."""++ def test_standard_logging_metadata_has_cold_storage_object_key_field(self):+ """+ Test: Add cold_storage_object_key field to StandardLoggingMetadata.++ This test verifies that the StandardLoggingMetadata TypedDict has the+ cold_storage_object_key field for storing S3/GCS object keys.+ """+ from litellm.types.utils import StandardLoggingMetadata++ # Create a StandardLoggingMetadata instance with cold_storage_object_key+ metadata = StandardLoggingMetadata(+ user_api_key_hash="test_hash",+ cold_storage_object_key="test/path/to/object.json"+ )++ # Verify the field can be set and accessed+ assert metadata.get("cold_storage_object_key") == "test/path/to/object.json"++ assert "cold_storage_object_key" in StandardLoggingMetadata.__annotations__++ def test_spend_logs_metadata_has_cold_storage_object_key_field(self):+ """+ Test: Add cold_storage_object_key field to SpendLogsMetadata.++ This test verifies that the SpendLogsMetadata TypedDict has the+ cold_storage_object_key field for storing S3/GCS object keys.+ """+ # Create a SpendLogsMetadata instance with cold_storage_object_key+ metadata = SpendLogsMetadata(+ user_api_key="test_key",+ cold_storage_object_key="test/path/to/object.json"+ )++ # Verify the field can be set and accessed+ assert metadata.get("cold_storage_object_key") == "test/path/to/object.json"++ # Verify it's part of the SpendLogsMetadata annotations+ assert "cold_storage_object_key" in SpendLogsMetadata.__annotations__+++ def test_spend_tracking_utils_stores_object_key_in_metadata(self):+ """+ Test: Store object key in SpendLogsMetadata via spend_tracking_utils.++ This test verifies that the _get_spend_logs_metadata function extracts+ the cold_storage_object_key from StandardLoggingPayload and stores it+ in SpendLogsMetadata.+ """+ # Create test data+ metadata = {+ "user_api_key": "test_key",+ "user_api_key_team_id": "test_team"+ }+++ # Call the function+ result = _get_spend_logs_metadata(+ metadata=metadata,+ cold_storage_object_key="test/path/to/object.json"+ )++ # Verify the object key is stored in the result+ assert result.get("cold_storage_object_key") == "test/path/to/object.json"+++ def test_session_handler_extracts_object_key_from_spend_log(self):+ """+ Test: Session handler extracts object key from spend logs metadata.++ This test verifies that the ResponsesSessionHandler can extract the+ cold_storage_object_key from spend log metadata.+ """+ # Create test spend log+ spend_log = {+ "request_id": "test_request_id",+ "metadata": json.dumps({+ "cold_storage_object_key": "test/path/to/object.json",+ "user_api_key": "test_key"+ })+ }++ # Test the extraction method+ object_key = ResponsesSessionHandler._get_cold_storage_object_key_from_spend_log(spend_log)++ assert object_key == "test/path/to/object.json"++ def test_session_handler_handles_dict_metadata_in_spend_log(self):+ """+ Test: Session handler handles dict metadata in spend log.++ This test verifies that the method works when metadata is already a dict.+ """+ # Create test spend log with dict metadata+ spend_log = {+ "request_id": "test_request_id",+ "metadata": {+ "cold_storage_object_key": "test/path/to/object.json",+ "user_api_key": "test_key"+ }+ }++ # Test the extraction method+ object_key = ResponsesSessionHandler._get_cold_storage_object_key_from_spend_log(spend_log)++ assert object_key == "test/path/to/object.json"+++ @pytest.mark.asyncio+ async def test_cold_storage_handler_supports_object_key_retrieval(self):+ """+ Test: ColdStorageHandler supports object key retrieval.++ This test verifies that the ColdStorageHandler has the new method+ for retrieving objects using object keys directly.+ """+ handler = ColdStorageHandler()++ # Mock the custom logger+ mock_logger = AsyncMock()+ mock_logger.get_proxy_server_request_from_cold_storage_with_object_key = AsyncMock(+ return_value={"test": "data"}+ )++ with patch.object(handler, '_select_custom_logger_for_cold_storage', return_value="s3_v2"), \+ patch('litellm.logging_callback_manager.get_active_custom_logger_for_callback_name', return_value=mock_logger):++ result = await handler.get_proxy_server_request_from_cold_storage_with_object_key(+ object_key="test/path/to/object.json"+ )++ assert result == {"test": "data"}+ mock_logger.get_proxy_server_request_from_cold_storage_with_object_key.assert_called_once_with(+ object_key="test/path/to/object.json"+ )++ @pytest.mark.asyncio+ @patch('asyncio.create_task') # Mock asyncio.create_task to avoid event loop issues+ async def test_s3_logger_supports_object_key_retrieval(self, mock_create_task):+ """+ Test: S3Logger supports retrieval using provided object key.++ This test verifies that the S3Logger can retrieve objects using+ the object key directly without generating it from request_id and start_time.+ """+ # Create S3Logger instance+ s3_logger = S3Logger(s3_bucket_name="test-bucket")++ # Mock the _download_object_from_s3 method+ with patch.object(s3_logger, '_download_object_from_s3', return_value={"test": "data"}) as mock_download:+ result = await s3_logger.get_proxy_server_request_from_cold_storage_with_object_key(+ object_key="test/path/to/object.json"+ )++ assert result == {"test": "data"}+ mock_download.assert_called_once_with("test/path/to/object.json")\ No newline at end of file