Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1731,18 +1731,18 @@ def is_candidate_token_count_inclusive(usage_metadata: UsageMetadata) -> bool:
"""
Check if the candidate token count is inclusive of the thinking token count

if prompttokencount + candidatesTokenCount == totalTokenCount, then the candidate token count is inclusive of the thinking token count
if promptTokenCount + candidatesTokenCount + toolUsePromptTokenCount == totalTokenCount, then the candidate token count is inclusive of the thinking token count

else the candidate token count is exclusive of the thinking token count

Addresses - https://github.com/BerriAI/litellm/pull/10141#discussion_r2052272035
"""
if usage_metadata.get("promptTokenCount", 0) + usage_metadata.get(
"candidatesTokenCount", 0
) == usage_metadata.get("totalTokenCount", 0):
return True
else:
return False
non_thinking_tokens = (
usage_metadata.get("promptTokenCount", 0)
+ usage_metadata.get("candidatesTokenCount", 0)
+ usage_metadata.get("toolUsePromptTokenCount", 0)
)
return non_thinking_tokens == usage_metadata.get("totalTokenCount", 0)

@staticmethod
def _calculate_usage(
Expand Down Expand Up @@ -1888,20 +1888,23 @@ def _get_token_count(detail: Mapping[str, Any]) -> int:
response_tokens_details = CompletionTokensDetailsWrapper()
response_tokens_details.reasoning_tokens = reasoning_tokens

tool_use_prompt_tokens = usage_metadata.get("toolUsePromptTokenCount") or None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 toolUsePromptTokensDetails declared but not parsed — when Gemini returns per-entry grounding detail (a list with per-modality breakdowns), _calculate_usage only reads the scalar toolUsePromptTokenCount and ignores the list entirely. Any caller inspecting prompt_tokens_details will see the aggregate count via tool_use_tokens but has no way to recover the per-entry breakdown. If a grounded call returns both fields, the detail list is silently dropped.


prompt_tokens_details = PromptTokensDetailsWrapper(
cached_tokens=cached_tokens,
audio_tokens=prompt_audio_tokens,
text_tokens=prompt_text_tokens,
image_tokens=prompt_image_tokens,
video_tokens=prompt_video_tokens,
tool_use_tokens=tool_use_prompt_tokens,
)

completion_tokens = response_tokens or completion_response["usageMetadata"].get("candidatesTokenCount", 0)
if not VertexGeminiConfig.is_candidate_token_count_inclusive(usage_metadata) and reasoning_tokens:
completion_tokens = reasoning_tokens + completion_tokens
## GET USAGE ##
usage = Usage(
prompt_tokens=usage_metadata.get("promptTokenCount", 0),
prompt_tokens=usage_metadata.get("promptTokenCount", 0) + (tool_use_prompt_tokens or 0),
completion_tokens=completion_tokens,
total_tokens=usage_metadata.get("totalTokenCount", 0),
prompt_tokens_details=prompt_tokens_details,
Expand Down
2 changes: 2 additions & 0 deletions litellm/types/llms/vertex_ai.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,8 @@ class UsageMetadata(TypedDict, total=False):
candidatesTokenCount: int
responseTokenCount: int
cachedContentTokenCount: int
toolUsePromptTokenCount: int
toolUsePromptTokensDetails: List[PromptTokensDetails]
promptTokensDetails: List[PromptTokensDetails]
cacheTokensDetails: List[PromptTokensDetails]
thoughtsTokenCount: int
Expand Down
5 changes: 5 additions & 0 deletions litellm/types/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1474,6 +1474,9 @@ class PromptTokensDetailsWrapper(
web_search_requests: Optional[int] = None
"""Number of web search requests made by the tool call. Used for Anthropic to calculate web search cost."""

tool_use_tokens: Optional[int] = None
"""Prompt tokens consumed by server-side tool use (e.g. Gemini grounding via googleSearch)."""

character_count: Optional[int] = None
"""Character count sent to the model. Used for Vertex AI multimodal embeddings."""

Expand Down Expand Up @@ -1504,6 +1507,8 @@ def __init__(self, *args, **kwargs):
del self.audio_length_seconds
if self.web_search_requests is None:
del self.web_search_requests
if self.tool_use_tokens is None:
del self.tool_use_tokens
if self.cache_creation_tokens is None:
del self.cache_creation_tokens
if self.cache_creation_token_details is None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,22 @@ def test_vertex_ai_empty_content():
reasoning_tokens=5,
),
),
(
UsageMetadata(
promptTokenCount=4647,
candidatesTokenCount=1495,
totalTokenCount=29426,
thoughtsTokenCount=10785,
toolUsePromptTokenCount=12499,
),
False,
Usage(
prompt_tokens=17146,
completion_tokens=12280,
total_tokens=29426,
reasoning_tokens=10785,
),
),
],
)
def test_vertex_ai_candidate_token_count_inclusive(
Expand All @@ -494,6 +510,43 @@ def test_vertex_ai_candidate_token_count_inclusive(
assert usage.total_tokens == expected_usage.total_tokens


def test_vertex_ai_grounded_usage_surfaces_tool_use_tokens():
"""
Grounded Gemini requests (googleSearch) return toolUsePromptTokenCount as part of totalTokenCount.
Regression for https://github.com/BerriAI/litellm/issues/33530: it must be folded into
prompt_tokens (so prompt_tokens + completion_tokens == total_tokens) and surfaced on
prompt_tokens_details.tool_use_tokens.
"""
v = VertexGeminiConfig()
usage_metadata = UsageMetadata(
promptTokenCount=4647,
candidatesTokenCount=1495,
totalTokenCount=29426,
thoughtsTokenCount=10785,
toolUsePromptTokenCount=12499,
)

usage = v._calculate_usage(completion_response={"usageMetadata": usage_metadata})

assert usage.prompt_tokens + usage.completion_tokens == usage.total_tokens
assert usage.prompt_tokens_details.tool_use_tokens == 12499


def test_vertex_ai_non_grounded_usage_omits_tool_use_tokens():
"""Non-grounded responses must not surface a tool_use_tokens field on prompt_tokens_details."""
v = VertexGeminiConfig()
usage_metadata = UsageMetadata(
promptTokenCount=10,
candidatesTokenCount=10,
totalTokenCount=20,
)

usage = v._calculate_usage(completion_response={"usageMetadata": usage_metadata})

assert usage.prompt_tokens == 10
assert not hasattr(usage.prompt_tokens_details, "tool_use_tokens")


def test_streaming_chunk_includes_reasoning_tokens():
from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (
ModelResponseIterator,
Expand Down
Loading