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]

feat(spend): store litellm_call_id on spend logs for DB-to-trace correlation (#31344)

yucheng-berri920348857847
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 7db0156bbe0..be5d7a2db78 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -3181,6 +3181,7 @@ class SpendLogsMetadata(TypedDict):
dict
] # special param to log k,v pairs to spendlogs for a call
requester_ip_address: Optional[str]
+ litellm_call_id: Optional[str]
applied_guardrails: Optional[List[str]]
mcp_tool_call_metadata: Optional[StandardLoggingMCPToolCall]
vector_store_request_metadata: Optional[List[StandardLoggingVectorStoreRequest]]
diff --git a/litellm/proxy/spend_tracking/spend_tracking_utils.py b/litellm/proxy/spend_tracking/spend_tracking_utils.py
index 8d89ff4a1ff..f6e0303e349 100644
--- a/litellm/proxy/spend_tracking/spend_tracking_utils.py
+++ b/litellm/proxy/spend_tracking/spend_tracking_utils.py
@@ -79,6 +79,7 @@ def _get_spend_logs_metadata(
cold_storage_object_key: Optional[str] = None,
litellm_overhead_time_ms: Optional[float] = None,
cost_breakdown: Optional[CostBreakdown] = None,
+ litellm_call_id: Optional[str] = None,
) -> SpendLogsMetadata:
if metadata is None:
return SpendLogsMetadata(
@@ -109,6 +110,7 @@ def _get_spend_logs_metadata(
attempted_retries=None,
max_retries=None,
cost_breakdown=None,
+ litellm_call_id=litellm_call_id,
)
verbose_proxy_logger.debug(
"getting payload for SpendLogs, available keys in metadata: "
@@ -133,6 +135,7 @@ def _get_spend_logs_metadata(
clean_metadata["cold_storage_object_key"] = cold_storage_object_key
clean_metadata["litellm_overhead_time_ms"] = litellm_overhead_time_ms
clean_metadata["cost_breakdown"] = cost_breakdown
+ clean_metadata["litellm_call_id"] = litellm_call_id
return clean_metadata
@@ -383,6 +386,10 @@ def get_logging_payload(kwargs, response_obj, start_time, end_time) -> SpendLogs
if standard_logging_payload is not None
else None
),
+ litellm_call_id=cast(
+ Optional[str],
+ kwargs.get("litellm_call_id") or litellm_params.get("litellm_call_id"),
+ ),
)
special_usage_fields = ["completion_tokens", "prompt_tokens", "total_tokens"]
diff --git a/tests/logging_callback_tests/test_gcs_pub_sub.py b/tests/logging_callback_tests/test_gcs_pub_sub.py
index f4cc9735177..c37a2e3f65d 100644
--- a/tests/logging_callback_tests/test_gcs_pub_sub.py
+++ b/tests/logging_callback_tests/test_gcs_pub_sub.py
@@ -31,6 +31,7 @@ verbose_logger.setLevel(logging.DEBUG)
ignored_keys = [
"request_id",
+ "metadata.litellm_call_id",
"session_id",
"startTime",
"endTime",
diff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py
index 0b583129591..6d0b4509b45 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
@@ -342,6 +342,7 @@ def test_ui_view_request_response_forbids_non_admin_without_db(client, monkeypat
ignored_keys = [
"request_id",
+ "metadata.litellm_call_id",
"session_id",
"startTime",
"endTime",
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.py
index e305054d075..874e0654a1f 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
@@ -2120,3 +2120,112 @@ def test_get_logging_payload_failure_without_recovered_usage_is_zero():
)
assert payload["total_tokens"] == 0
+
+
+def test_get_logging_payload_sets_litellm_call_id_for_correlation():
+ """LIT-3868: a successful spend log must carry the x-litellm-call-id (the
+ trace id) in its metadata, distinct from request_id, which stays the
+ provider response id. Without this there is no way to correlate a DB row
+ with its trace for a successful call.
+ """
+ provider_response_id = "chatcmpl-e6e6f3e9-c392-404e-9a71-5361c79d8470"
+ trace_call_id = "c6a77556-19ce-4406-b287-53f5fb4b2b55"
+
+ kwargs = {
+ "model": "openai/gpt-4o-mini",
+ "call_type": "acompletion",
+ "litellm_call_id": trace_call_id,
+ "litellm_params": {"metadata": {"user_api_key": "sk-test"}},
+ }
+ response_obj = {
+ "id": provider_response_id,
+ "usage": {"prompt_tokens": 5, "completion_tokens": 7, "total_tokens": 12},
+ }
+ now = datetime.datetime.now(timezone.utc)
+
+ payload = get_logging_payload(
+ kwargs=kwargs, response_obj=response_obj, start_time=now, end_time=now
+ )
+ metadata = json.loads(payload["metadata"])
+
+ assert payload["request_id"] == provider_response_id
+ assert metadata["litellm_call_id"] == trace_call_id
+ assert metadata["litellm_call_id"] != payload["request_id"]
+
+
+def test_get_logging_payload_litellm_call_id_falls_back_to_litellm_params():
+ """litellm_call_id may only be present in litellm_params; it must still land
+ in the spend log metadata so correlation works on that path too.
+ """
+ trace_call_id = "fallback-7a1c-42d9-9f0e-2b6c5d4e3f21"
+ kwargs = {
+ "model": "openai/gpt-4o-mini",
+ "call_type": "acompletion",
+ "litellm_params": {
+ "litellm_call_id": trace_call_id,
+ "metadata": {"user_api_key": "sk-test"},
+ },
+ }
+ response_obj = {
+ "id": "chatcmpl-abc123",
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ }
+ now = datetime.datetime.now(timezone.utc)
+
+ payload = get_logging_payload(
+ kwargs=kwargs, response_obj=response_obj, start_time=now, end_time=now
+ )
+
+ assert json.loads(payload["metadata"])["litellm_call_id"] == trace_call_id
+
+
+def test_get_logging_payload_litellm_call_id_when_response_has_no_id():
+ """When the provider returns no id, request_id falls back to the call id, so
+ request_id and the metadata call id hold the same value and correlation
+ still resolves.
+ """
+ trace_call_id = "noid-5b2e-4c7a-9d10-3f8a1c2b4e6d"
+ kwargs = {
+ "model": "openai/gpt-4o-mini",
+ "call_type": "acompletion",
+ "litellm_call_id": trace_call_id,
+ "litellm_params": {"metadata": {"user_api_key": "sk-test"}},
+ }
+ response_obj = {
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
+ }
+ now = datetime.datetime.now(timezone.utc)
+
+ payload = get_logging_payload(
+ kwargs=kwargs, response_obj=response_obj, start_time=now, end_time=now
+ )
+
+ assert json.loads(payload["metadata"])["litellm_call_id"] == trace_call_id
+ assert payload["request_id"] == trace_call_id
+
+
+def test_get_logging_payload_cache_hit_keeps_raw_litellm_call_id():
+ """On a cache hit request_id is suffixed to stay unique, but the metadata
+ litellm_call_id stays the raw trace id so the row still points at its trace.
+ """
+ trace_call_id = "cache-9a1c-42d9-9f0e-2b6c5d4e3f21"
+ kwargs = {
+ "model": "openai/gpt-4o-mini",
+ "call_type": "acompletion",
+ "litellm_call_id": trace_call_id,
+ "cache_hit": True,
+ "litellm_params": {"metadata": {"user_api_key": "sk-test"}},
+ }
+ response_obj = {
+ "id": "chatcmpl-cache-src",
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ }
+ now = datetime.datetime.now(timezone.utc)
+
+ payload = get_logging_payload(
+ kwargs=kwargs, response_obj=response_obj, start_time=now, end_time=now
+ )
+
+ assert json.loads(payload["metadata"])["litellm_call_id"] == trace_call_id
+ assert "_cache_hit" in payload["request_id"]
+ assert json.loads(payload["metadata"])["litellm_call_id"] != payload["request_id"]