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(cost_calculator): log per-token-type reasoning and cache cost breakdown (#31623) (#31686)

Sameer Kankute6d5de7444712
diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.py
index 8ddc69f5396..e8535a570c8 100644
--- a/litellm/cost_calculator.py
+++ b/litellm/cost_calculator.py
@@ -29,6 +29,7 @@ from litellm.litellm_core_utils.llm_cost_calc.utils import (
_parse_prompt_tokens_details,
calculate_cost_component,
generic_cost_per_token,
+ get_token_type_cost_breakdown,
get_billable_input_tokens,
select_cost_metric_for_model,
)
@@ -1050,6 +1051,7 @@ def _store_cost_breakdown_in_logging_obj(
margin_total_amount: Optional[float] = None,
cache_read_cost: Optional[float] = None,
cache_creation_cost: Optional[float] = None,
+ reasoning_cost: Optional[float] = None,
) -> None:
"""
Helper function to store cost breakdown in the logging object.
@@ -1087,6 +1089,7 @@ def _store_cost_breakdown_in_logging_obj(
margin_total_amount=margin_total_amount,
cache_read_cost=cache_read_cost,
cache_creation_cost=cache_creation_cost,
+ reasoning_cost=reasoning_cost,
)
except Exception as breakdown_error:
@@ -1628,28 +1631,23 @@ def completion_cost(
# Store cost breakdown in logging object if available
if litellm_logging_obj is not None:
+ _reasoning_cost: Optional[float] = None
_cache_read_cost: Optional[float] = None
_cache_creation_cost: Optional[float] = None
- if cost_per_token_usage_object is not None:
- _cr = getattr(cost_per_token_usage_object, "cache_read_input_tokens", None) or (
- cost_per_token_usage_object.model_extra or {}
- ).get("cache_read_input_tokens")
- _cc = getattr(
- cost_per_token_usage_object,
- "cache_creation_input_tokens",
- None,
- ) or (cost_per_token_usage_object.model_extra or {}).get("cache_creation_input_tokens")
- if (_cr or _cc) and model:
- try:
- _mi = litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider)
- _cr_rate = _mi.get("cache_read_input_token_cost")
- if _cr and _cr_rate is not None:
- _cache_read_cost = float(_cr) * float(_cr_rate)
- _cc_rate = _mi.get("cache_creation_input_token_cost")
- if _cc and _cc_rate is not None:
- _cache_creation_cost = float(_cc) * float(_cc_rate)
- except Exception:
- pass
+ if cost_per_token_usage_object is not None and model:
+ _breakdown_provider: Optional[str] = (
+ custom_llm_provider if isinstance(custom_llm_provider, str) else None
+ )
+ _token_type_breakdown = get_token_type_cost_breakdown(
+ model=model,
+ custom_llm_provider=_breakdown_provider,
+ usage=cost_per_token_usage_object,
+ service_tier=service_tier,
+ data_residency=data_residency,
+ )
+ _reasoning_cost = _token_type_breakdown.reasoning_cost
+ _cache_read_cost = _token_type_breakdown.cache_read_cost
+ _cache_creation_cost = _token_type_breakdown.cache_creation_cost
_store_cost_breakdown_in_logging_obj(
litellm_logging_obj=litellm_logging_obj,
prompt_tokens_cost_usd_dollar=prompt_tokens_cost_usd_dollar,
@@ -1665,6 +1663,7 @@ def completion_cost(
margin_total_amount=margin_total_amount,
cache_read_cost=_cache_read_cost,
cache_creation_cost=_cache_creation_cost,
+ reasoning_cost=_reasoning_cost,
)
return _final_cost
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 245084b7c4a..da204855465 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -1297,6 +1297,7 @@ class Logging(LiteLLMLoggingBaseClass):
margin_total_amount: Optional[float] = None,
cache_read_cost: Optional[float] = None,
cache_creation_cost: Optional[float] = None,
+ reasoning_cost: Optional[float] = None,
) -> None:
"""
Helper method to store cost breakdown in the logging object.
@@ -1325,6 +1326,8 @@ class Logging(LiteLLMLoggingBaseClass):
self.cost_breakdown["cache_read_cost"] = cache_read_cost
if cache_creation_cost is not None and cache_creation_cost > 0:
self.cost_breakdown["cache_creation_cost"] = cache_creation_cost
+ if reasoning_cost is not None and reasoning_cost > 0:
+ self.cost_breakdown["reasoning_cost"] = reasoning_cost
# Store additional costs if provided (free-form dict for extensibility)
if additional_costs and isinstance(additional_costs, dict) and len(additional_costs) > 0:
diff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.py
index e013c587f0f..c039f0f43ee 100644
--- a/litellm/litellm_core_utils/llm_cost_calc/utils.py
+++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py
@@ -1,6 +1,7 @@
# What is this?
## Helper utilities for cost_per_token()
+from dataclasses import dataclass
from typing import Any, Literal, Optional, Tuple, TypedDict, cast
import litellm
@@ -813,6 +814,107 @@ def generic_cost_per_token(
return prompt_cost, completion_cost
+def _coerce_token_count(value: object) -> int:
+ return value if isinstance(value, int) and value > 0 else 0
+
+
+@dataclass(frozen=True, slots=True)
+class TokenTypeCostBreakdown:
+ reasoning_cost: float
+ cache_read_cost: float
+ cache_creation_cost: float
+
+
+def get_token_type_cost_breakdown(
+ model: str,
+ custom_llm_provider: Optional[str],
+ usage: Usage,
+ service_tier: Optional[str] = None,
+ data_residency: Optional[str] = None,
+) -> TokenTypeCostBreakdown:
+ """
+ Provider-agnostic cost of reasoning and cache tokens, derived from the usage
+ object and model pricing alone.
+
+ This works for every provider, including Perplexity/Cerebras/Dashscope whose
+ cost calculators bypass ``generic_cost_per_token``, because cache tokens always
+ land on ``prompt_tokens_details`` (via the Usage constructor and provider
+ transformations) and reasoning tokens on ``completion_tokens_details``. It reuses
+ the same rate-resolution primitives as the total-cost path so the breakdown can
+ never drift from the totals. Returns zeros (never raises) when the model or its
+ pricing cannot be resolved.
+ """
+ try:
+ model_info = get_model_info(model=model, custom_llm_provider=custom_llm_provider)
+ except Exception:
+ return TokenTypeCostBreakdown(0.0, 0.0, 0.0)
+
+ (
+ _prompt_base_cost,
+ completion_base_cost,
+ cache_creation_cost_rate,
+ cache_creation_cost_above_1hr_rate,
+ cache_read_cost_rate,
+ ) = _get_token_base_cost(model_info=model_info, usage=usage, service_tier=service_tier)
+
+ reasoning_tokens = (
+ _parse_completion_tokens_details(usage)["reasoning_tokens"]
+ if usage.completion_tokens_details is not None
+ else 0
+ )
+ if not reasoning_tokens:
+ reasoning_tokens = _coerce_token_count(getattr(usage, "reasoning_tokens", 0))
+
+ # Reasoning is billed at the explicit per-reasoning-token rate when the model
+ # defines one, otherwise at the standard output-token rate - this mirrors how the
+ # total completion cost is computed, so the breakdown can never diverge from it.
+ reasoning_rate = _get_cost_per_unit(model_info, "output_cost_per_reasoning_token", None)
+ if reasoning_rate is None:
+ reasoning_rate = completion_base_cost
+ reasoning_cost = float(reasoning_tokens) * reasoning_rate
+
+ cache_read_tokens = 0
+ cache_creation_tokens = 0
+ cache_creation_token_details: Optional[CacheCreationTokenDetails] = None
+ if usage.prompt_tokens_details is not None:
+ prompt_tokens_details = _parse_prompt_tokens_details(usage)
+ cache_read_tokens = prompt_tokens_details["cache_hit_tokens"]
+ cache_creation_tokens = prompt_tokens_details["cache_creation_tokens"]
+ cache_creation_token_details = prompt_tokens_details["cache_creation_token_details"]
+ # Some OpenAI-compatible providers (e.g. kimi-k2) report cache-write tokens
+ # under `cache_write_tokens`; mirror the total-cost normalization path.
+ if not cache_creation_tokens:
+ cache_creation_tokens = _coerce_token_count(getattr(usage.prompt_tokens_details, "cache_write_tokens", 0))
+ # Fall back to the private top-level counters the Usage constructor mirrors cache
+ # tokens onto, so providers/callers that bypass prompt_tokens_details are covered.
+ if not cache_read_tokens:
+ cache_read_tokens = _coerce_token_count(getattr(usage, "_cache_read_input_tokens", 0))
+ if not cache_creation_tokens:
+ cache_creation_tokens = _coerce_token_count(getattr(usage, "_cache_creation_input_tokens", 0))
+
+ cache_read_cost = float(cache_read_tokens) * cache_read_cost_rate
+ cache_creation_cost = calculate_cache_writing_cost(
+ cache_creation_tokens=cache_creation_tokens,
+ cache_creation_token_details=cache_creation_token_details,
+ cache_creation_cost_above_1hr=cache_creation_cost_above_1hr_rate,
+ cache_creation_cost=cache_creation_cost_rate,
+ )
+
+ # Apply the same flat regional-processing uplift the totals get, so per-type
+ # costs stay reconciled with input_cost/output_cost for regionalized OpenAI hosts.
+ uplift = _get_regional_uplift_multiplier(model_info, data_residency)
+ if uplift != 1.0:
+ reasoning_cost *= uplift
+ cache_read_cost *= uplift
+ cache_creation_cost *= uplift
+
+ return TokenTypeCostBreakdown(
+ reasoning_cost=reasoning_cost,
+ cache_read_cost=cache_read_cost,
+ cache_creation_cost=cache_creation_cost,
+ )
+
+
def calculate_image_response_cost_from_usage(
model: str,
image_response: ImageResponse,
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 279e9b15fe7..dff4e4af89e 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -2812,6 +2812,7 @@ class CostBreakdown(TypedDict, total=False):
cache_read_cost: float # Cost of cache-read tokens (discounted rate)
cache_creation_cost: float # Cost of cache-write tokens (premium rate)
output_cost: float # Cost of output/completion tokens (includes reasoning if applicable)
+ reasoning_cost: float # Cost of reasoning tokens (subset of output_cost)
total_cost: float # Total cost (input + output + tool usage)
tool_usage_cost: float # Cost of usage of built-in tools
additional_costs: Dict[str, float] # Free-form additional costs (e.g., {"azure_model_router_flat_cost": 0.00014})
diff --git a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py
index b75b6d78090..e9977efe47d 100644
--- a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py
+++ b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py
@@ -34,10 +34,12 @@ sys.path.insert(
from litellm.litellm_core_utils.llm_cost_calc.utils import (
PromptTokensDetailsResult,
+ TokenTypeCostBreakdown,
_calculate_input_cost,
_get_token_base_cost,
calculate_cache_writing_cost,
generic_cost_per_token,
+ get_token_type_cost_breakdown,
)
from litellm.types.utils import CacheCreationTokenDetails, Usage
@@ -1768,3 +1770,271 @@ def test_threshold_keys_exclude_service_tier_variants():
usage = Usage(prompt_tokens=350_000, completion_tokens=1_000, total_tokens=351_000)
prompt_base, *_ = _get_token_base_cost(model_info=model_info, usage=usage)
assert prompt_base == 3e-6
+
+
+ "model,custom_llm_provider,reasoning_tokens,cached_tokens",
+ [
+ ("gemini-2.5-flash", "vertex_ai", 3114, 100),
+ ("o3", "openai", 500, 200),
+ ("azure/gpt-5", "azure", 300, 150),
+ ("us.amazon.nova-2-lite-v1:0", "bedrock", 120, 80),
+ ("perplexity/sonar-reasoning", "perplexity", 400, 0),
+ ("cerebras/qwen-3-32b", "cerebras", 250, 0),
+ ],
+)
+def test_token_type_cost_breakdown_is_provider_agnostic(
+ model, custom_llm_provider, reasoning_tokens, cached_tokens
+):
+ """
+ Reasoning and cache-read costs must be surfaced for every provider that reports
+ those tokens, regardless of which cost calculator the provider routes through
+ (Perplexity, Cerebras, Dashscope bypass generic_cost_per_token entirely).
+
+ Cache tokens always land in prompt_tokens_details.cached_tokens, so reading from
+ there - not the top-level cache_read_input_tokens attribute the old breakdown code
+ relied on - is what makes Vertex/OpenAI/Azure cache costs show up at all.
+ """
+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
+ litellm.model_cost = litellm.get_model_cost_map(url="")
+
+ usage = Usage(
+ prompt_tokens=1000,
+ completion_tokens=2000,
+ total_tokens=3000,
+ completion_tokens_details=CompletionTokensDetailsWrapper(
+ reasoning_tokens=reasoning_tokens, text_tokens=2000 - reasoning_tokens
+ ),
+ prompt_tokens_details=PromptTokensDetailsWrapper(
+ cached_tokens=cached_tokens, text_tokens=1000 - cached_tokens
+ ),
+ )
+
+ breakdown = get_token_type_cost_breakdown(
+ model=model, custom_llm_provider=custom_llm_provider, usage=usage
+ )
+
+ model_info = litellm.get_model_info(
+ model=model, custom_llm_provider=custom_llm_provider
+ )
+ reasoning_rate = (
+ model_info.get("output_cost_per_reasoning_token")
+ or model_info["output_cost_per_token"]
+ )
+ cache_read_rate = model_info.get("cache_read_input_token_cost") or 0.0
+
+ assert breakdown.reasoning_cost == pytest.approx(reasoning_tokens * reasoning_rate)
+ assert breakdown.cache_read_cost == pytest.approx(cached_tokens * cache_read_rate)
+
+
+def test_token_type_cost_breakdown_matches_real_gemini_numbers():
+ """Hard-coded against the exact gemini-2.5-flash response that exposed the gap."""
+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
+ litellm.model_cost = litellm.get_model_cost_map(url="")
+
+ usage = Usage(
+ prompt_tokens=209,
+ completion_tokens=3996,
+ total_tokens=4205,
+ completion_tokens_details=CompletionTokensDetailsWrapper(
+ reasoning_tokens=3114, text_tokens=882
+ ),
+ prompt_tokens_details=PromptTokensDetailsWrapper(
+ cached_tokens=100, text_tokens=109
+ ),
+ )
+
+ breakdown = get_token_type_cost_breakdown(
+ model="gemini-2.5-flash", custom_llm_provider="vertex_ai", usage=usage
+ )
+
+ assert breakdown.reasoning_cost == pytest.approx(3114 * 2.5e-06)
+ assert breakdown.cache_read_cost == pytest.approx(100 * 3e-08)
+ assert breakdown.cache_creation_cost == 0.0
+
+
+def test_token_type_cost_breakdown_includes_cache_creation_from_top_level_usage():
+ """
+ Bedrock/Anthropic report cache tokens as top-level usage fields; the Usage
+ constructor maps them onto prompt_tokens_details, so the breakdown must still
+ pick up both cache-read and cache-creation costs.
+ """
+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
+ litellm.model_cost = litellm.get_model_cost_map(url="")
+
+ model = "anthropic.claude-3-5-haiku-20241022-v1:0"
+ usage = Usage(
+ prompt_tokens=500,
+ completion_tokens=50,
+ total_tokens=550,
+ cache_creation_input_tokens=300,
+ cache_read_input_tokens=120,
+ )
+
+ breakdown = get_token_type_cost_breakdown(
+ model=model, custom_llm_provider="bedrock", usage=usage
+ )
+
+ model_info = litellm.get_model_info(model=model, custom_llm_provider="bedrock")
+ assert breakdown.cache_creation_cost == pytest.approx(
+ 300 * model_info["cache_creation_input_token_cost"]
+ )
+ assert breakdown.cache_read_cost == pytest.approx(
+ 120 * model_info["cache_read_input_token_cost"]
+ )
+
+
+def test_token_type_cost_breakdown_reads_cache_write_tokens():
+ """
+ Some OpenAI-compatible providers (e.g. kimi-k2) report cache-write tokens under
+ `cache_write_tokens` rather than `cache_creation_tokens`. The breakdown must read
+ it the same way the total-cost normalization does, so the two agree.
+ """
+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
+ litellm.model_cost = litellm.get_model_cost_map(url="")
+
+ model = "anthropic.claude-3-5-haiku-20241022-v1:0"
+ usage = Usage(
+ prompt_tokens=500,
+ completion_tokens=50,
+ total_tokens=550,
+ prompt_tokens_details=PromptTokensDetailsWrapper(
+ cached_tokens=0, cache_write_tokens=300
+ ),
+ )
+
+ breakdown = get_token_type_cost_breakdown(
+ model=model, custom_llm_provider="bedrock", usage=usage
+ )
+ model_info = litellm.get_model_info(model=model, custom_llm_provider="bedrock")
+ assert breakdown.cache_creation_cost == pytest.approx(
+ 300 * model_info["cache_creation_input_token_cost"]
+ )
+
+
+def test_token_type_cost_breakdown_reconciles_with_generic_total():
+ """
+ Both-ways check: the reasoning subset must sum with the remaining (text) output
+ cost to exactly the completion total, and the cache-read subset with the remaining
+ input cost to exactly the prompt total, as computed by generic_cost_per_token.
+ A mismatch here would mean the breakdown misrepresents what was actually billed.
+ """
+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
+ litellm.model_cost = litellm.get_model_cost_map(url="")
+
+ model = "gemini-2.5-flash"
+ custom_llm_provider = "vertex_ai"
+ usage = Usage(
+ prompt_tokens=1000,
+ completion_tokens=2000,
+ total_tokens=3000,
+ completion_tokens_details=CompletionTokensDetailsWrapper(
+ reasoning_tokens=1200, text_tokens=800
+ ),
+ prompt_tokens_details=PromptTokensDetailsWrapper(
+ cached_tokens=300, text_tokens=700
+ ),
+ )
+
+ prompt_cost, completion_cost = generic_cost_per_token(
+ model=model, usage=usage, custom_llm_provider=custom_llm_provider
+ )
+ breakdown = get_token_type_cost_breakdown(
+ model=model, custom_llm_provider=custom_llm_provider, usage=usage
+ )
+
+ model_info = litellm.get_model_info(
+ model=model, custom_llm_provider=custom_llm_provider
+ )
+ text_output_cost = 800 * model_info["output_cost_per_token"]
+ text_input_cost = 700 * model_info["input_cost_per_token"]
+
+ assert text_output_cost + breakdown.reasoning_cost == pytest.approx(completion_cost)
+ assert text_input_cost + breakdown.cache_read_cost == pytest.approx(prompt_cost)
+
+
+def test_token_type_cost_breakdown_zero_without_special_tokens():
+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
+ litellm.model_cost = litellm.get_model_cost_map(url="")
+
+ usage = Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150)
+ breakdown = get_token_type_cost_breakdown(
+ model="gpt-4o", custom_llm_provider="openai", usage=usage
+ )
+
+ assert breakdown == TokenTypeCostBreakdown(
+ reasoning_cost=0.0, cache_read_cost=0.0, cache_creation_cost=0.0
+ )
+
+
+def test_token_type_cost_breakdown_handles_unknown_model_gracefully():
+ """A model with no pricing must yield zeros, never raise."""
+ breakdown = get_token_type_cost_breakdown(
+ model="this-model-does-not-exist-anywhere",
+ custom_llm_provider="openai",
+ usage=Usage(
+ prompt_tokens=10,
+ completion_tokens=10,
+ total_tokens=20,
+ completion_tokens_details=CompletionTokensDetailsWrapper(reasoning_tokens=5),
+ ),
+ )
+ assert breakdown == TokenTypeCostBreakdown(
+ reasoning_cost=0.0, cache_read_cost=0.0, cache_creation_cost=0.0
+ )
+
+
+def test_token_type_cost_breakdown_applies_regional_uplift():
+ """
+ Regional OpenAI hosts (eu./us.) apply a flat uplift to every token cost. The
+ per-type breakdown must apply the same uplift via data_residency so it stays
+ reconciled with the uplifted input_cost/output_cost totals, instead of being
+ logged at the base rate.
+ """
+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
+ litellm.model_cost = litellm.get_model_cost_map(url="")
+
+ model = "gpt-5.4"
+ custom_llm_provider = "openai"
+ usage = Usage(
+ prompt_tokens=1000,
+ completion_tokens=500,
+ total_tokens=1500,
+ completion_tokens_details=CompletionTokensDetailsWrapper(
+ reasoning_tokens=200, text_tokens=300
+ ),
+ prompt_tokens_details=PromptTokensDetailsWrapper(
+ cached_tokens=400, text_tokens=600
+ ),
+ )
+
+ model_info = litellm.get_model_info(
+ model=model, custom_llm_provider=custom_llm_provider
+ )
+ uplift = model_info["regional_processing_uplift_multiplier_eu"]
+ assert uplift > 1.0
+
+ base = get_token_type_cost_breakdown(
+ model=model, custom_llm_provider=custom_llm_provider, usage=usage
+ )
+ eu = get_token_type_cost_breakdown(
+ model=model,
+ custom_llm_provider=custom_llm_provider,
+ usage=usage,
+ data_residency="eu",
+ )
+
+ assert eu.reasoning_cost == pytest.approx(base.reasoning_cost * uplift)
+ assert eu.cache_read_cost == pytest.approx(base.cache_read_cost * uplift)
+
+ # The uplifted breakdown must still reconcile with the uplifted totals.
+ prompt_cost, completion_cost = generic_cost_per_token(
+ model=model,
+ usage=usage,
+ custom_llm_provider=custom_llm_provider,
+ data_residency="eu",
+ )
+ text_output_cost = 300 * model_info["output_cost_per_token"] * uplift
+ text_input_cost = 600 * model_info["input_cost_per_token"] * uplift
+ assert text_output_cost + eu.reasoning_cost == pytest.approx(completion_cost)
+ assert text_input_cost + eu.cache_read_cost == pytest.approx(prompt_cost)
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 dcbc5002ee4..41560c18d15 100644
--- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
+++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
@@ -3650,3 +3650,43 @@ def test_failure_handler_zeroes_spend_without_recovered_usage(logging_obj):
assert payload["status"] == "failure"
assert payload["response_cost"] == 0
assert payload["total_tokens"] == 0
+
+
+def test_set_cost_breakdown_stores_reasoning_cost():
+ """reasoning_cost is stored only when positive, mirroring the cache-cost fields."""
+ from datetime import datetime
+
+ logging_obj = LitellmLogging(
+ model="gpt-4o",
+ messages=[{"role": "user", "content": "hi"}],
+ stream=False,
+ call_type="completion",
+ start_time=datetime.now(),
+ litellm_call_id="reasoning-cost-set",
+ function_id="f",
+ )
+ logging_obj.set_cost_breakdown(
+ input_cost=0.001,
+ output_cost=0.002,
+ total_cost=0.003,
+ cost_for_built_in_tools_cost_usd_dollar=0.0,
+ reasoning_cost=0.0005,
+ )
+ assert logging_obj.cost_breakdown["reasoning_cost"] == 0.0005
+
+ no_reasoning = LitellmLogging(
+ model="gpt-4o",
+ messages=[{"role": "user", "content": "hi"}],
+ stream=False,
+ call_type="completion",
+ start_time=datetime.now(),
+ litellm_call_id="reasoning-cost-absent",
+ function_id="f",
+ )
+ no_reasoning.set_cost_breakdown(
+ input_cost=0.001,
+ output_cost=0.002,
+ total_cost=0.003,
+ cost_for_built_in_tools_cost_usd_dollar=0.0,
+ )
+ assert "reasoning_cost" not in no_reasoning.cost_breakdown
diff --git a/tests/test_litellm/test_cost_calculator.py b/tests/test_litellm/test_cost_calculator.py
index db6f945ff78..81627cd3393 100644
--- a/tests/test_litellm/test_cost_calculator.py
+++ b/tests/test_litellm/test_cost_calculator.py
@@ -3115,3 +3115,64 @@ def test_openrouter_gemini_3_1_flash_lite_stable_pricing():
assert model_info["cache_read_input_token_cost"] == 2.5e-08
assert model_info["max_input_tokens"] == 1048576
assert model_info["max_output_tokens"] == 65536
+
+
+def test_completion_cost_logs_reasoning_and_cache_breakdown():
+ """
+ completion_cost must surface explicit reasoning and cache-read costs into the
+ cost_breakdown stored on the logging object, so they end up in the spend logs
+ rather than being silently folded into the output/input totals.
+ """
+ from datetime import datetime
+
+ from litellm.litellm_core_utils.litellm_logging import Logging
+ from litellm.types.utils import Choices, CompletionTokensDetailsWrapper, Message
+
+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
+ litellm.model_cost = litellm.get_model_cost_map(url="")
+
+ logging_obj = Logging(
+ model="gemini-2.5-flash",
+ messages=[{"role": "user", "content": "Hello"}],
+ stream=False,
+ call_type="completion",
+ start_time=datetime.now(),
+ litellm_call_id="reasoning-cache-breakdown",
+ function_id="f",
+ )
+
+ response = ModelResponse(
+ id="x",
+ created=1,
+ model="gemini-2.5-flash",
+ object="chat.completion",
+ choices=[
+ Choices(
+ index=0,
+ message=Message(role="assistant", content="hi"),
+ finish_reason="length",
+ )
+ ],
+ usage=Usage(
+ prompt_tokens=209,
+ completion_tokens=3996,
+ total_tokens=4205,
+ completion_tokens_details=CompletionTokensDetailsWrapper(
+ reasoning_tokens=3114, text_tokens=882
+ ),
+ prompt_tokens_details=PromptTokensDetailsWrapper(
+ cached_tokens=100, text_tokens=109
+ ),
+ ),
+ )
+
+ litellm.completion_cost(
+ completion_response=response,
+ model="gemini-2.5-flash",
+ custom_llm_provider="vertex_ai",
+ litellm_logging_obj=logging_obj,
+ )
+
+ assert logging_obj.cost_breakdown is not None
+ assert logging_obj.cost_breakdown["reasoning_cost"] == pytest.approx(3114 * 2.5e-06)
+ assert logging_obj.cost_breakdown["cache_read_cost"] == pytest.approx(100 * 3e-08)