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]

Merge pull request #36593 from BerriAI/devin_ai_lit_5445_perplexity_stream_dict_cost

Mateo Wangeec27a9cb33c
diff --cc litellm/litellm_core_utils/streaming_handler.py
index 43bcf892865,48e58c578e6..485091bccd0
--- a/litellm/litellm_core_utils/streaming_handler.py
+++ b/litellm/litellm_core_utils/streaming_handler.py
@@@ -1820,16 -1789,20 +1820,30 @@@ class CustomStreamWrapper
model_response.choices[0].finish_reason = "tool_calls"
return model_response
+ def _record_usage_only_chunk(self, model_response: "ModelResponseStream") -> None:
+ """
+ Keep provider usage-only chunks (e.g. OpenRouter's post-finish chunk, which carries a
+ provider-reported cost) available to cost tracking. They are never returned to the
+ caller; ``stream_options.include_usage`` only controls what the caller sees.
+ """
+ if getattr(model_response, "usage", None) is None:
+ return
+ self.chunks.append(model_response.model_copy(update={"choices": []}))
+
+ @staticmethod
+ def _resolve_provider_reported_cost(usage_cost: object) -> float | None:
+ """
+ Providers report usage.cost either as a number or, for Perplexity, as a
+ breakdown object whose total lives under ``total_cost``.
+ """
+ if isinstance(usage_cost, bool):
+ return None
+ if isinstance(usage_cost, (int, float)):
+ return float(usage_cost)
+ if isinstance(usage_cost, dict):
+ return CustomStreamWrapper._resolve_provider_reported_cost(usage_cost.get("total_cost"))
+ return None
+
@staticmethod
def _propagate_usage_cost_to_hidden_params(
response: "ModelResponse",