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(proxy): backfill system prompt from the request body when estimating bridged failure tokens

mateo-berrif8c8b41bf5c3
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index c45b4ad17c0..a743526e975 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -480,12 +480,18 @@ _INPUT_ESTIMABLE_CALL_TYPES: Final = frozenset(
)
-def _failure_usage_to_lift(model_call_details: Mapping[str, object], dispatched: bool) -> tuple[object, object] | None:
+def _failure_usage_to_lift(
+ model_call_details: Mapping[str, object],
+ request_body: Mapping[str, object],
+ dispatched: bool,
+) -> tuple[object, object] | None:
"""A stream that broke mid-flight still billed the provider for the chunks
already delivered; the streaming handler stashes that recovered usage and
cost in model_call_details, so prefer it. Otherwise a request that was
dispatched to a provider and failed without upstream usage gets an
- estimated input-side Usage with zero cost. Returns the
+ estimated input-side Usage with zero cost. The raw request body backfills
+ the system prompt when the SDK bridges an endpoint (e.g. /v1/messages on a
+ chat-completions provider) without filling optional_params. Returns the
(combined_usage_object, response_cost) pair to lift, or None."""
recovered_usage: Final = model_call_details.get("combined_usage_object")
if recovered_usage is not None:
@@ -495,11 +501,12 @@ def _failure_usage_to_lift(model_call_details: Mapping[str, object], dispatched:
if str(model_call_details.get("call_type")) not in _INPUT_ESTIMABLE_CALL_TYPES:
return None
optional_params: Final = model_call_details.get("optional_params")
- system_input: Final = (
+ dispatched_system: Final = (
(optional_params.get("system") or optional_params.get("instructions"))
if isinstance(optional_params, dict)
else None
)
+ system_input: Final = dispatched_system or request_body.get("system") or request_body.get("instructions")
estimated_usage: Final = _estimate_dispatched_failure_usage(
model=str(model_call_details.get("model") or ""),
request_input=model_call_details.get("messages"),
@@ -2303,6 +2310,7 @@ class ProxyLogging:
# is popped) record real token counts instead of zero.
_usage_to_lift: Final = _failure_usage_to_lift(
model_call_details=_model_call_details,
+ request_body=request_data,
dispatched=_first_handoff is not None,
)
if _usage_to_lift is not None:
diff --git a/tests/test_litellm/proxy/test_proxy_utils.py b/tests/test_litellm/proxy/test_proxy_utils.py
index b70f93054d2..d6cf0e30139 100644
--- a/tests/test_litellm/proxy/test_proxy_utils.py
+++ b/tests/test_litellm/proxy/test_proxy_utils.py
@@ -738,6 +738,46 @@ class TestPostCallFailureHookEstimatesDispatchedInputTokens:
) + litellm_module.token_counter(model="gpt-3.5-turbo", text=instructions)
assert estimated.prompt_tokens == expected
+ @pytest.mark.asyncio
+ async def test_request_body_system_counted_when_optional_params_empty(self):
+ import litellm as litellm_module
+ from litellm.types.utils import Usage
+
+ system_prompt = "You are a meticulous cartographer who labels every landmark."
+ messages = [{"role": "user", "content": "draw me a map"}]
+ request_data = {
+ **self._dispatched_request_data(messages, {}, call_type="aanthropic_messages"),
+ "system": system_prompt,
+ }
+ await self._run(request_data)
+
+ estimated = request_data["combined_usage_object"]
+ assert isinstance(estimated, Usage)
+ expected = litellm_module.token_counter(model="gpt-3.5-turbo", messages=messages) + litellm_module.token_counter(
+ model="gpt-3.5-turbo", text=system_prompt
+ )
+ assert estimated.prompt_tokens == expected
+
+ @pytest.mark.asyncio
+ async def test_optional_params_system_wins_over_request_body_system(self):
+ import litellm as litellm_module
+ from litellm.types.utils import Usage
+
+ dispatched_system = "short dispatched system prompt"
+ messages = [{"role": "user", "content": "hello"}]
+ request_data = {
+ **self._dispatched_request_data(messages, {"system": dispatched_system}),
+ "system": "a much longer request body system prompt that must not be double counted here",
+ }
+ await self._run(request_data)
+
+ estimated = request_data["combined_usage_object"]
+ assert isinstance(estimated, Usage)
+ expected = litellm_module.token_counter(model="gpt-3.5-turbo", messages=messages) + litellm_module.token_counter(
+ model="gpt-3.5-turbo", text=dispatched_system
+ )
+ assert estimated.prompt_tokens == expected
+
from typing import cast