Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(logging): backfill streaming hidden response cost (#26606)

milan-berri52fb23a51289
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 57341472b4b..fb103afea04 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -1725,12 +1725,18 @@ class Logging(LiteLLMLoggingBaseClass):
return
if self.model_call_details.get("litellm_params") is None:
return
- self.model_call_details["litellm_params"].setdefault("metadata", {})
- if self.model_call_details["litellm_params"]["metadata"] is None:
- self.model_call_details["litellm_params"]["metadata"] = {}
- self.model_call_details["litellm_params"]["metadata"]["hidden_params"] = (
- getattr(logging_result, "_hidden_params", {})
- )
+ metadata_hidden_params = hidden_params.copy()
+ response_cost = self.model_call_details.get("response_cost")
+ if (
+ metadata_hidden_params.get("response_cost") is None
+ and response_cost is not None
+ ):
+ metadata_hidden_params["response_cost"] = response_cost
+
+ litellm_params = self.model_call_details["litellm_params"]
+ metadata = litellm_params.get("metadata") or {}
+ litellm_params["metadata"] = metadata
+ metadata["hidden_params"] = metadata_hidden_params
def _process_hidden_params_and_response_cost(
self,
@@ -5438,11 +5444,6 @@ def get_standard_logging_object_payload(
completion_start_time_float=completion_start_time_float,
stream=kwargs.get("stream", False),
)
- # clean up litellm hidden params
- clean_hidden_params = StandardLoggingPayloadSetup.get_hidden_params(
- hidden_params
- )
-
# clean up litellm metadata
clean_metadata = StandardLoggingPayloadSetup.get_standard_logging_metadata(
metadata=metadata,
@@ -5476,6 +5477,18 @@ def get_standard_logging_object_payload(
## Get model cost information ##
base_model = _get_base_model_from_metadata(model_call_details=kwargs)
custom_pricing = use_custom_pricing_for_model(litellm_params=litellm_params)
+ raw_response_cost = kwargs.get("response_cost")
+ response_cost: float = raw_response_cost or 0.0
+
+ # clean up litellm hidden params
+ clean_hidden_params = StandardLoggingPayloadSetup.get_hidden_params(
+ hidden_params
+ )
+ if (
+ clean_hidden_params["response_cost"] is None
+ and raw_response_cost is not None
+ ):
+ clean_hidden_params["response_cost"] = response_cost
model_cost_information = StandardLoggingPayloadSetup.get_model_cost_information(
base_model=base_model,
@@ -5484,7 +5497,6 @@ def get_standard_logging_object_payload(
init_response_obj=init_response_obj,
api_base=litellm_params.get("api_base"),
)
- response_cost: float = kwargs.get("response_cost", 0) or 0.0
error_information = StandardLoggingPayloadSetup.get_error_information(
original_exception=original_exception,
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index a212d56c1ae..ed29d49fc29 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -2659,7 +2659,7 @@ class StandardLoggingHiddenParams(TypedDict):
] # id of the model in the router, separates multiple models with the same name but different credentials
cache_key: Optional[str]
api_base: Optional[str]
- response_cost: Optional[str]
+ response_cost: Optional[Union[str, float]]
litellm_overhead_time_ms: Optional[float]
additional_headers: Optional[StandardLoggingAdditionalHeaders]
batch_models: Optional[List[str]]
diff --git a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
index cf7be6bf1c7..3348118a020 100644
--- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
+++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
@@ -2337,6 +2337,104 @@ def test_merge_hidden_params_from_response_into_metadata_populates_metadata():
assert meta["hidden_params"]["model_id"] == "mid-test"
+def test_merge_hidden_params_from_response_into_metadata_backfills_response_cost():
+ """Streaming metadata should include the already-calculated response cost."""
+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+
+ logging_obj = LiteLLMLoggingObj(
+ model="gpt-4o-mini",
+ messages=[{"role": "user", "content": "hi"}],
+ stream=True,
+ call_type="acompletion",
+ start_time=time.time(),
+ litellm_call_id="merge-hp-cost-test",
+ function_id="merge-hp-cost-fn",
+ )
+ logging_obj.model_call_details = {
+ "litellm_params": {"metadata": {}},
+ "response_cost": 0.002,
+ }
+
+ class _Resp:
+ _hidden_params = {"response_cost": None, "model_id": "mid-test"}
+
+ response = _Resp()
+ logging_obj._merge_hidden_params_from_response_into_metadata(response)
+ meta = logging_obj.model_call_details["litellm_params"]["metadata"]
+ assert meta["hidden_params"]["response_cost"] == 0.002
+ assert meta["hidden_params"]["model_id"] == "mid-test"
+ assert response._hidden_params["response_cost"] is None
+
+
+def test_standard_logging_hidden_params_backfills_response_cost_without_mutating_response():
+ """Streaming standard logging payload should expose the calculated response cost."""
+ from datetime import datetime
+
+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+ from litellm.types.utils import Usage
+
+ logging_obj = LiteLLMLoggingObj(
+ model="gpt-4o-mini",
+ messages=[{"role": "user", "content": "hi"}],
+ stream=True,
+ call_type="acompletion",
+ start_time=time.time(),
+ litellm_call_id="standard-hp-cost-test",
+ function_id="standard-hp-cost-fn",
+ )
+ logging_obj.model_call_details = {
+ "litellm_params": {"metadata": {}, "proxy_server_request": {}},
+ "litellm_call_id": "standard-hp-cost-test",
+ "call_type": "acompletion",
+ "stream": True,
+ "model": "gpt-4o-mini",
+ "custom_llm_provider": "openai",
+ "optional_params": {"stream": True},
+ "response_cost": 0.002,
+ }
+ response = ModelResponse(
+ id="standard-hp-cost-response",
+ model="gpt-4o-mini",
+ usage=Usage(prompt_tokens=10, completion_tokens=5, total_tokens=15),
+ )
+ response._hidden_params = {"response_cost": None, "model_id": "mid-test"}
+
+ payload = logging_obj._build_standard_logging_payload(
+ response, datetime.now(), datetime.now()
+ )
+
+ assert payload is not None
+ assert payload["hidden_params"]["response_cost"] == 0.002
+ assert response._hidden_params["response_cost"] is None
+
+
+def test_merge_hidden_params_from_response_into_metadata_preserves_response_cost():
+ """Do not overwrite provider-supplied response cost when it already exists."""
+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+
+ logging_obj = LiteLLMLoggingObj(
+ model="gpt-4o-mini",
+ messages=[{"role": "user", "content": "hi"}],
+ stream=True,
+ call_type="acompletion",
+ start_time=time.time(),
+ litellm_call_id="merge-hp-preserve-cost-test",
+ function_id="merge-hp-preserve-cost-fn",
+ )
+ logging_obj.model_call_details = {
+ "litellm_params": {"metadata": {}},
+ "response_cost": 0.002,
+ }
+
+ class _Resp:
+ _hidden_params = {"response_cost": 0.001, "model_id": "mid-test"}
+
+ logging_obj._merge_hidden_params_from_response_into_metadata(_Resp())
+ meta = logging_obj.model_call_details["litellm_params"]["metadata"]
+ assert meta["hidden_params"]["response_cost"] == 0.001
+ assert meta["hidden_params"]["model_id"] == "mid-test"
+
+
def test_merge_hidden_params_from_response_into_metadata_no_op_when_empty():
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj