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(vertex_ai): preserve usageMetadata in _hidden_params (#20559)

Lei Nie68d2306dd4a4
diff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
index ad046cf7109..bef83b6d35e 100644
--- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
+++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
@@ -480,7 +480,10 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
tool = {VertexToolName.COMPUTER_USE.value: computer_use_config}
# Handle OpenAI-style web_search and web_search_preview tools
# Transform them to Gemini's googleSearch tool
- elif "type" in tool and tool["type"] in ("web_search", "web_search_preview"):
+ elif "type" in tool and tool["type"] in (
+ "web_search",
+ "web_search_preview",
+ ):
verbose_logger.info(
f"Gemini: Transforming OpenAI-style '{tool['type']}' tool to googleSearch"
)
@@ -1632,7 +1635,9 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
completion_image_tokens = response_tokens_details.image_tokens or 0
completion_audio_tokens = response_tokens_details.audio_tokens or 0
calculated_text_tokens = (
- candidates_token_count - completion_image_tokens - completion_audio_tokens
+ candidates_token_count
+ - completion_image_tokens
+ - completion_audio_tokens
)
response_tokens_details.text_tokens = calculated_text_tokens
#########################################################
@@ -2250,6 +2255,13 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
citation_metadata # older approach - maintaining to prevent regressions
)
+ ## ADD TRAFFIC TYPE ##
+ traffic_type = completion_response.get("usageMetadata", {}).get(
+ "trafficType"
+ )
+ if traffic_type:
+ model_response._hidden_params.setdefault("provider_specific_fields", {})["traffic_type"] = traffic_type
+
except Exception as e:
raise VertexAIError(
message="Received={}, Error converting to valid response block={}. File an issue if litellm error - https://github.com/BerriAI/litellm/issues".format(
@@ -2908,6 +2920,12 @@ class ModelResponseIterator:
PromptTokensDetailsWrapper, usage.prompt_tokens_details
).web_search_requests = web_search_requests
+ traffic_type = processed_chunk.get("usageMetadata", {}).get(
+ "trafficType"
+ )
+ if traffic_type:
+ model_response._hidden_params.setdefault("provider_specific_fields", {})["traffic_type"] = traffic_type
+
setattr(model_response, "usage", usage) # type: ignore
model_response._hidden_params["is_finished"] = False
diff --git a/litellm/main.py b/litellm/main.py
index bca023e65ec..80a2f74c571 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -7383,6 +7383,16 @@ def stream_chunk_builder( # noqa: PLR0915
setattr(response, "usage", usage)
+ # Propagate provider_specific_fields from the last chunk (contains provider
+ # metadata like traffic_type set during streaming)
+ for chunk in reversed(chunks):
+ hidden = getattr(chunk, "_hidden_params", None)
+ if hidden and "provider_specific_fields" in hidden:
+ response._hidden_params.setdefault(
+ "provider_specific_fields", {}
+ ).update(hidden["provider_specific_fields"])
+ break
+
# Add cost to usage object if include_cost_in_streaming_usage is True
if litellm.include_cost_in_streaming_usage and logging_obj is not None:
setattr(
diff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.py
index 2bff4e23c78..08e31c59662 100644
--- a/litellm/responses/litellm_completion_transformation/transformation.py
+++ b/litellm/responses/litellm_completion_transformation/transformation.py
@@ -1512,6 +1512,12 @@ class LiteLLMCompletionResponsesConfig:
user=getattr(chat_completion_response, "user", None),
)
responses_api_response._hidden_params = getattr(chat_completion_response, "_hidden_params", {})
+
+ # Surface provider-specific fields (generic passthrough from any provider)
+ provider_fields = responses_api_response._hidden_params.get("provider_specific_fields")
+ if provider_fields:
+ responses_api_response.provider_specific_fields = provider_fields
+
return responses_api_response
@staticmethod
diff --git a/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py b/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
index 75fd597ffa1..581d1e603dd 100644
--- a/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
+++ b/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
@@ -3338,3 +3338,94 @@ def test_chunk_parser_handles_prompt_feedback_block_with_usage():
assert result.usage.completion_tokens == 0, f"completion_tokens should be 0, got {result.usage.completion_tokens}"
assert result.usage.total_tokens == 8175, f"total_tokens should be 8175, got {result.usage.total_tokens}"
+
+def test_vertex_ai_traffic_type_preserved_in_hidden_params_streaming():
+ """Test trafficType is preserved in _hidden_params for streaming."""
+ from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (
+ ModelResponseIterator,
+ )
+
+ chunk = {
+ "candidates": [{"content": {"parts": [{"text": "Hello"}]}}],
+ "usageMetadata": {
+ "promptTokenCount": 100,
+ "candidatesTokenCount": 200,
+ "totalTokenCount": 300,
+ "trafficType": "ON_DEMAND",
+ },
+ }
+
+ iterator = ModelResponseIterator(
+ streaming_response=[], sync_stream=True, logging_obj=MagicMock()
+ )
+ result = iterator.chunk_parser(chunk)
+
+ assert result._hidden_params["provider_specific_fields"]["traffic_type"] == "ON_DEMAND"
+
+
+def test_vertex_ai_traffic_type_preserved_in_hidden_params_non_streaming():
+ """Test trafficType is preserved in _hidden_params for non-streaming."""
+ from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (
+ VertexGeminiConfig,
+ )
+
+ completion_response = {
+ "candidates": [
+ {
+ "content": {"parts": [{"text": "Hello"}], "role": "model"},
+ "finishReason": "STOP",
+ }
+ ],
+ "usageMetadata": {
+ "promptTokenCount": 50,
+ "candidatesTokenCount": 100,
+ "totalTokenCount": 150,
+ "trafficType": "PROVISIONED_THROUGHPUT",
+ },
+ }
+
+ raw_response = MagicMock()
+ raw_response.json.return_value = completion_response
+
+ result = VertexGeminiConfig().transform_response(
+ model="gemini-pro",
+ raw_response=raw_response,
+ model_response=ModelResponse(),
+ logging_obj=MagicMock(),
+ request_data={},
+ messages=[],
+ optional_params={},
+ litellm_params={},
+ encoding=None,
+ )
+
+ assert result._hidden_params["provider_specific_fields"]["traffic_type"] == "PROVISIONED_THROUGHPUT"
+
+
+def test_vertex_ai_traffic_type_surfaced_in_responses_api():
+ """Test trafficType is surfaced as provider_specific_fields in ResponsesAPIResponse."""
+ from litellm.responses.litellm_completion_transformation.transformation import (
+ LiteLLMCompletionResponsesConfig,
+ )
+
+ # Create a ModelResponse with provider_specific_fields in _hidden_params
+ from litellm.types.utils import Choices, Message
+
+ model_response = ModelResponse()
+ model_response._hidden_params["provider_specific_fields"] = {"traffic_type": "ON_DEMAND"}
+ model_response.choices = [
+ Choices(
+ message=Message(content="Hello", role="assistant"),
+ finish_reason="stop",
+ index=0,
+ )
+ ]
+
+ responses_api_response = LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(
+ request_input="test",
+ chat_completion_response=model_response,
+ responses_api_request={},
+ )
+
+ assert responses_api_response.provider_specific_fields["traffic_type"] == "ON_DEMAND"
+