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
[QA] Allow managing sessions with `litellm_session_id` (#10348)
Ishaan Jaff6f3c158266c6
diff --git a/docs/my-website/docs/proxy/ui_logs_sessions.md b/docs/my-website/docs/proxy/ui_logs_sessions.mdindex 31b5517f14d..a1a3003478b 100644--- a/docs/my-website/docs/proxy/ui_logs_sessions.md+++ b/docs/my-website/docs/proxy/ui_logs_sessions.md@@ -13,7 +13,7 @@ Group requests into sessions. This allows you to group related requests together### `/chat/completions`-To group multiple requests into a single session, pass the same `litellm_trace_id` in the metadata for each request. Here's how to do it:+To group multiple requests into a single session, pass the same `litellm_session_id` in the metadata for each request. Here's how to do it:<Tabs><TabItem value="openai" label="OpenAI Python v1.0.0+">@@ -44,7 +44,7 @@ response1 = client.chat.completions.create(],extra_body={"metadata": {- "litellm_trace_id": session_id # Pass the session ID+ "litellm_session_id": session_id # Pass the session ID}})@@ -65,7 +65,7 @@ response2 = client.chat.completions.create(],extra_body={"metadata": {- "litellm_trace_id": session_id # Reuse the same session ID+ "litellm_session_id": session_id # Reuse the same session ID}})@@ -90,7 +90,7 @@ chat = ChatOpenAI(model="gpt-4o",extra_body={"metadata": {- "litellm_trace_id": session_id # Pass the session ID+ "litellm_session_id": session_id # Pass the session ID}})@@ -133,7 +133,7 @@ curl --location 'http://0.0.0.0:4000/chat/completions' \}],"metadata": {- "litellm_trace_id": "'$SESSION_ID'"+ "litellm_session_id": "'$SESSION_ID'"}}'```@@ -155,7 +155,7 @@ curl --location 'http://0.0.0.0:4000/chat/completions' \}],"metadata": {- "litellm_trace_id": "'$SESSION_ID'"+ "litellm_session_id": "'$SESSION_ID'"}}'```@@ -180,7 +180,7 @@ response1 = litellm.completion(api_base="http://0.0.0.0:4000",api_key="<your litellm api key>",metadata={- "litellm_trace_id": session_id # Pass the session ID+ "litellm_session_id": session_id # Pass the session ID})```@@ -196,7 +196,7 @@ response2 = litellm.completion(api_base="http://0.0.0.0:4000",api_key="<your litellm api key>",metadata={- "litellm_trace_id": session_id # Reuse the same session ID+ "litellm_session_id": session_id # Reuse the same session ID})```diff --git a/litellm/litellm_core_utils/get_litellm_params.py b/litellm/litellm_core_utils/get_litellm_params.pyindex f40f1ae4c7b..7e8f60bd4fd 100644--- a/litellm/litellm_core_utils/get_litellm_params.py+++ b/litellm/litellm_core_utils/get_litellm_params.py@@ -48,6 +48,7 @@ def get_litellm_params(user_continue_message=None,base_model: Optional[str] = None,litellm_trace_id: Optional[str] = None,+ litellm_session_id: Optional[str] = None,hf_model_name: Optional[str] = None,custom_prompt_dict: Optional[dict] = None,litellm_metadata: Optional[dict] = None,@@ -91,6 +92,7 @@ def get_litellm_params("base_model": base_modelor _get_base_model_from_litellm_call_metadata(metadata=metadata),"litellm_trace_id": litellm_trace_id,+ "litellm_session_id": litellm_session_id,"hf_model_name": hf_model_name,"custom_prompt_dict": custom_prompt_dict,"litellm_metadata": litellm_metadata,diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex 1e419387bc9..441392a1192 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -251,9 +251,9 @@ class Logging(LiteLLMLoggingBaseClass):self.litellm_trace_id: str = litellm_trace_id or str(uuid.uuid4())self.function_id = function_idself.streaming_chunks: List[Any] = [] # for generating complete stream response- self.sync_streaming_chunks: List[- Any- ] = [] # for generating complete stream response+ self.sync_streaming_chunks: List[Any] = (+ []+ ) # for generating complete stream responseself.log_raw_request_response = log_raw_request_response# Initialize dynamic callbacks@@ -541,9 +541,9 @@ class Logging(LiteLLMLoggingBaseClass):if anthropic_cache_control_logger := AnthropicCacheControlHook.get_custom_logger_for_anthropic_cache_control_hook(non_default_params):- self.model_call_details[- "prompt_integration"- ] = anthropic_cache_control_logger.__class__.__name__+ self.model_call_details["prompt_integration"] = (+ anthropic_cache_control_logger.__class__.__name__+ )return anthropic_cache_control_loggerreturn None@@ -595,9 +595,9 @@ class Logging(LiteLLMLoggingBaseClass):model): # if model name was changes pre-call, overwrite the initial model call name with the new oneself.model_call_details["model"] = model- self.model_call_details["litellm_params"][- "api_base"- ] = self._get_masked_api_base(additional_args.get("api_base", ""))+ self.model_call_details["litellm_params"]["api_base"] = (+ self._get_masked_api_base(additional_args.get("api_base", ""))+ )def pre_call(self, input, api_key, model=None, additional_args={}): # noqa: PLR0915# Log the exact input to the LLM API@@ -626,10 +626,10 @@ class Logging(LiteLLMLoggingBaseClass):try:# [Non-blocking Extra Debug Information in metadata]if turn_off_message_logging is True:- _metadata[- "raw_request"- ] = "redacted by litellm. \+ _metadata["raw_request"] = (+ "redacted by litellm. \'litellm.turn_off_message_logging=True'"+ )else:curl_command = self._get_request_curl_command(api_base=additional_args.get("api_base", ""),@@ -640,32 +640,32 @@ class Logging(LiteLLMLoggingBaseClass):_metadata["raw_request"] = str(curl_command)# split up, so it's easier to parse in the UI- self.model_call_details[- "raw_request_typed_dict"- ] = RawRequestTypedDict(- raw_request_api_base=str(- additional_args.get("api_base") or ""- ),- raw_request_body=self._get_raw_request_body(- additional_args.get("complete_input_dict", {})- ),- raw_request_headers=self._get_masked_headers(- additional_args.get("headers", {}) or {},- ignore_sensitive_headers=True,- ),- error=None,+ self.model_call_details["raw_request_typed_dict"] = (+ RawRequestTypedDict(+ raw_request_api_base=str(+ additional_args.get("api_base") or ""+ ),+ raw_request_body=self._get_raw_request_body(+ additional_args.get("complete_input_dict", {})+ ),+ raw_request_headers=self._get_masked_headers(+ additional_args.get("headers", {}) or {},+ ignore_sensitive_headers=True,+ ),+ error=None,+ ))except Exception as e:- self.model_call_details[- "raw_request_typed_dict"- ] = RawRequestTypedDict(- error=str(e),+ self.model_call_details["raw_request_typed_dict"] = (+ RawRequestTypedDict(+ error=str(e),+ ))- _metadata[- "raw_request"- ] = "Unable to Log \+ _metadata["raw_request"] = (+ "Unable to Log \raw request: {}".format(- str(e)+ str(e)+ ))if self.logger_fn and callable(self.logger_fn):try:@@ -995,9 +995,9 @@ class Logging(LiteLLMLoggingBaseClass):verbose_logger.debug(f"response_cost_failure_debug_information: {debug_info}")- self.model_call_details[- "response_cost_failure_debug_information"- ] = debug_info+ self.model_call_details["response_cost_failure_debug_information"] = (+ debug_info+ )return Nonetry:@@ -1022,9 +1022,9 @@ class Logging(LiteLLMLoggingBaseClass):verbose_logger.debug(f"response_cost_failure_debug_information: {debug_info}")- self.model_call_details[- "response_cost_failure_debug_information"- ] = debug_info+ self.model_call_details["response_cost_failure_debug_information"] = (+ debug_info+ )return None@@ -1084,9 +1084,9 @@ class Logging(LiteLLMLoggingBaseClass):end_time = datetime.datetime.now()if self.completion_start_time is None:self.completion_start_time = end_time- self.model_call_details[- "completion_start_time"- ] = self.completion_start_time+ self.model_call_details["completion_start_time"] = (+ self.completion_start_time+ )self.model_call_details["log_event_type"] = "successful_api_call"self.model_call_details["end_time"] = end_timeself.model_call_details["cache_hit"] = cache_hit@@ -1165,39 +1165,39 @@ class Logging(LiteLLMLoggingBaseClass):"response_cost"]else:- self.model_call_details[- "response_cost"- ] = self._response_cost_calculator(result=logging_result)+ self.model_call_details["response_cost"] = (+ self._response_cost_calculator(result=logging_result)+ )## STANDARDIZED LOGGING PAYLOAD- self.model_call_details[- "standard_logging_object"- ] = get_standard_logging_object_payload(- kwargs=self.model_call_details,- init_response_obj=logging_result,- start_time=start_time,- end_time=end_time,- logging_obj=self,- status="success",- standard_built_in_tools_params=self.standard_built_in_tools_params,+ self.model_call_details["standard_logging_object"] = (+ get_standard_logging_object_payload(+ kwargs=self.model_call_details,+ init_response_obj=logging_result,+ start_time=start_time,+ end_time=end_time,+ logging_obj=self,+ status="success",+ standard_built_in_tools_params=self.standard_built_in_tools_params,+ ))elif isinstance(result, dict) or isinstance(result, list):## STANDARDIZED LOGGING PAYLOAD- self.model_call_details[- "standard_logging_object"- ] = get_standard_logging_object_payload(- kwargs=self.model_call_details,- init_response_obj=result,- start_time=start_time,- end_time=end_time,- logging_obj=self,- status="success",- standard_built_in_tools_params=self.standard_built_in_tools_params,+ self.model_call_details["standard_logging_object"] = (+ get_standard_logging_object_payload(+ kwargs=self.model_call_details,+ init_response_obj=result,+ start_time=start_time,+ end_time=end_time,+ logging_obj=self,+ status="success",+ standard_built_in_tools_params=self.standard_built_in_tools_params,+ ))elif standard_logging_object is not None:- self.model_call_details[- "standard_logging_object"- ] = standard_logging_object+ self.model_call_details["standard_logging_object"] = (+ standard_logging_object+ )else: # streaming chunks + image gen.self.model_call_details["response_cost"] = None@@ -1253,23 +1253,23 @@ class Logging(LiteLLMLoggingBaseClass):verbose_logger.debug("Logging Details LiteLLM-Success Call streaming complete")- self.model_call_details[- "complete_streaming_response"- ] = complete_streaming_response- self.model_call_details[- "response_cost"- ] = self._response_cost_calculator(result=complete_streaming_response)+ self.model_call_details["complete_streaming_response"] = (+ complete_streaming_response+ )+ self.model_call_details["response_cost"] = (+ self._response_cost_calculator(result=complete_streaming_response)+ )## STANDARDIZED LOGGING PAYLOAD- self.model_call_details[- "standard_logging_object"- ] = get_standard_logging_object_payload(- kwargs=self.model_call_details,- init_response_obj=complete_streaming_response,- start_time=start_time,- end_time=end_time,- logging_obj=self,- status="success",- standard_built_in_tools_params=self.standard_built_in_tools_params,+ self.model_call_details["standard_logging_object"] = (+ get_standard_logging_object_payload(+ kwargs=self.model_call_details,+ init_response_obj=complete_streaming_response,+ start_time=start_time,+ end_time=end_time,+ logging_obj=self,+ status="success",+ standard_built_in_tools_params=self.standard_built_in_tools_params,+ ))callbacks = self.get_combined_callback_list(dynamic_success_callbacks=self.dynamic_success_callbacks,@@ -1618,10 +1618,10 @@ class Logging(LiteLLMLoggingBaseClass):)else:if self.stream and complete_streaming_response:- self.model_call_details[- "complete_response"- ] = self.model_call_details.get(- "complete_streaming_response", {}+ self.model_call_details["complete_response"] = (+ self.model_call_details.get(+ "complete_streaming_response", {}+ ))result = self.model_call_details["complete_response"]openMeterLogger.log_success_event(@@ -1661,10 +1661,10 @@ class Logging(LiteLLMLoggingBaseClass):)else:if self.stream and complete_streaming_response:- self.model_call_details[- "complete_response"- ] = self.model_call_details.get(- "complete_streaming_response", {}+ self.model_call_details["complete_response"] = (+ self.model_call_details.get(+ "complete_streaming_response", {}+ ))result = self.model_call_details["complete_response"]@@ -1771,9 +1771,9 @@ class Logging(LiteLLMLoggingBaseClass):if complete_streaming_response is not None:print_verbose("Async success callbacks: Got a complete streaming response")- self.model_call_details[- "async_complete_streaming_response"- ] = complete_streaming_response+ self.model_call_details["async_complete_streaming_response"] = (+ complete_streaming_response+ )try:if self.model_call_details.get("cache_hit", False) is True:self.model_call_details["response_cost"] = 0.0@@ -1783,10 +1783,10 @@ class Logging(LiteLLMLoggingBaseClass):model_call_details=self.model_call_details)# base_model defaults to None if not set on model_info- self.model_call_details[- "response_cost"- ] = self._response_cost_calculator(- result=complete_streaming_response+ self.model_call_details["response_cost"] = (+ self._response_cost_calculator(+ result=complete_streaming_response+ ))verbose_logger.debug(@@ -1799,16 +1799,16 @@ class Logging(LiteLLMLoggingBaseClass):self.model_call_details["response_cost"] = None## STANDARDIZED LOGGING PAYLOAD- self.model_call_details[- "standard_logging_object"- ] = get_standard_logging_object_payload(- kwargs=self.model_call_details,- init_response_obj=complete_streaming_response,- start_time=start_time,- end_time=end_time,- logging_obj=self,- status="success",- standard_built_in_tools_params=self.standard_built_in_tools_params,+ self.model_call_details["standard_logging_object"] = (+ get_standard_logging_object_payload(+ kwargs=self.model_call_details,+ init_response_obj=complete_streaming_response,+ start_time=start_time,+ end_time=end_time,+ logging_obj=self,+ status="success",+ standard_built_in_tools_params=self.standard_built_in_tools_params,+ ))callbacks = self.get_combined_callback_list(dynamic_success_callbacks=self.dynamic_async_success_callbacks,@@ -2014,18 +2014,18 @@ class Logging(LiteLLMLoggingBaseClass):## STANDARDIZED LOGGING PAYLOAD- self.model_call_details[- "standard_logging_object"- ] = get_standard_logging_object_payload(- kwargs=self.model_call_details,- init_response_obj={},- start_time=start_time,- end_time=end_time,- logging_obj=self,- status="failure",- error_str=str(exception),- original_exception=exception,- standard_built_in_tools_params=self.standard_built_in_tools_params,+ self.model_call_details["standard_logging_object"] = (+ get_standard_logging_object_payload(+ kwargs=self.model_call_details,+ init_response_obj={},+ start_time=start_time,+ end_time=end_time,+ logging_obj=self,+ status="failure",+ error_str=str(exception),+ original_exception=exception,+ standard_built_in_tools_params=self.standard_built_in_tools_params,+ ))return start_time, end_time@@ -2799,9 +2799,9 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915endpoint=arize_config.endpoint,)- os.environ[- "OTEL_EXPORTER_OTLP_TRACES_HEADERS"- ] = f"space_key={arize_config.space_key},api_key={arize_config.api_key}"+ os.environ["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = (+ f"space_key={arize_config.space_key},api_key={arize_config.api_key}"+ )for callback in _in_memory_loggers:if (isinstance(callback, ArizeLogger)@@ -2825,9 +2825,9 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915# auth can be disabled on local deployments of arize phoenixif arize_phoenix_config.otlp_auth_headers is not None:- os.environ[- "OTEL_EXPORTER_OTLP_TRACES_HEADERS"- ] = arize_phoenix_config.otlp_auth_headers+ os.environ["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = (+ arize_phoenix_config.otlp_auth_headers+ )for callback in _in_memory_loggers:if (@@ -2918,9 +2918,9 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915exporter="otlp_http",endpoint="https://langtrace.ai/api/trace",)- os.environ[- "OTEL_EXPORTER_OTLP_TRACES_HEADERS"- ] = f"api_key={os.getenv('LANGTRACE_API_KEY')}"+ os.environ["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = (+ f"api_key={os.getenv('LANGTRACE_API_KEY')}"+ )for callback in _in_memory_loggers:if (isinstance(callback, OpenTelemetry)@@ -3427,10 +3427,10 @@ class StandardLoggingPayloadSetup:for key in StandardLoggingHiddenParams.__annotations__.keys():if key in hidden_params:if key == "additional_headers":- clean_hidden_params[- "additional_headers"- ] = StandardLoggingPayloadSetup.get_additional_headers(- hidden_params[key]+ clean_hidden_params["additional_headers"] = (+ StandardLoggingPayloadSetup.get_additional_headers(+ hidden_params[key]+ ))else:clean_hidden_params[key] = hidden_params[key] # type: ignore@@ -3507,10 +3507,17 @@ class StandardLoggingPayloadSetup:This helps link sessions when multiple requests are made in a single session"""- dynamic_trace_id = litellm_params.get("litellm_trace_id")- if dynamic_trace_id:- return str(dynamic_trace_id)- return logging_obj.litellm_trace_id+ dynamic_litellm_session_id = litellm_params.get("litellm_session_id")+ dynamic_litellm_trace_id = litellm_params.get("litellm_trace_id")++ # Note: we recommend using `litellm_session_id` for session tracking+ # `litellm_trace_id` is an internal litellm param+ if dynamic_litellm_session_id:+ return str(dynamic_litellm_session_id)+ elif dynamic_litellm_trace_id:+ return str(dynamic_litellm_trace_id)+ else:+ return logging_obj.litellm_trace_iddef get_standard_logging_object_payload(@@ -3791,9 +3798,9 @@ def scrub_sensitive_keys_in_metadata(litellm_params: Optional[dict]):):for k, v in metadata["user_api_key_metadata"].items():if k == "logging": # prevent logging user logging keys- cleaned_user_api_key_metadata[- k- ] = "scrubbed_by_litellm_for_sensitive_keys"+ cleaned_user_api_key_metadata[k] = (+ "scrubbed_by_litellm_for_sensitive_keys"+ )else:cleaned_user_api_key_metadata[k] = vdiff --git a/litellm/main.py b/litellm/main.pyindex c8a3ce55acc..ff21824fac5 100644--- a/litellm/main.py+++ b/litellm/main.py@@ -1179,6 +1179,7 @@ def completion( # type: ignore # noqa: PLR0915user_continue_message=kwargs.get("user_continue_message"),base_model=base_model,litellm_trace_id=kwargs.get("litellm_trace_id"),+ litellm_session_id=kwargs.get("litellm_session_id"),hf_model_name=hf_model_name,custom_prompt_dict=custom_prompt_dict,litellm_metadata=kwargs.get("litellm_metadata"),diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 532162e60f8..c126f143e8c 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -1988,6 +1988,7 @@ all_litellm_params = ["merge_reasoning_content_in_choices","litellm_credential_name","allowed_openai_params",+ "litellm_session_id",] + list(StandardCallbackDynamicParams.__annotations__.keys())