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]

Litellm gemini grounding metadata stream (#12673)

Krish Dholakiaab09d0621d4a
diff --git a/litellm/litellm_core_utils/core_helpers.py b/litellm/litellm_core_utils/core_helpers.py
index 6336b419843..86e7eb89a21 100644
--- a/litellm/litellm_core_utils/core_helpers.py
+++ b/litellm/litellm_core_utils/core_helpers.py
@@ -10,6 +10,8 @@ from litellm.types.llms.openai import AllMessageValues
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
+ from litellm.types.utils import ModelResponseStream
+
Span = Union[_Span, Any]
else:
Span = Any
@@ -189,3 +191,15 @@ def process_response_headers(response_headers: Union[httpx.Headers, dict]) -> di
**additional_headers,
}
return additional_headers
+
+
+def preserve_upstream_non_openai_attributes(
+ model_response: "ModelResponseStream", original_chunk: "ModelResponseStream"
+):
+ """
+ Preserve non-OpenAI attributes from the original chunk.
+ """
+ expected_keys = set(model_response.model_fields.keys()).union({"usage"})
+ for key, value in original_chunk.model_dump().items():
+ if key not in expected_keys:
+ setattr(model_response, key, value)
diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.py
index a8589cf8e4e..98fdd133eb6 100644
--- a/litellm/litellm_core_utils/streaming_handler.py
+++ b/litellm/litellm_core_utils/streaming_handler.py
@@ -751,6 +751,10 @@ class CustomStreamWrapper:
model_response: ModelResponseStream,
response_obj: Dict[str, Any],
):
+ from litellm.litellm_core_utils.core_helpers import (
+ preserve_upstream_non_openai_attributes,
+ )
+
print_verbose(
f"completion_obj: {completion_obj}, model_response.choices[0]: {model_response.choices[0]}, response_obj: {response_obj}"
)
@@ -796,6 +800,10 @@ class CustomStreamWrapper:
"citations",
getattr(original_chunk, "citations", None),
)
+ preserve_upstream_non_openai_attributes(
+ model_response=model_response,
+ original_chunk=original_chunk,
+ )
print_verbose(f"self.sent_first_chunk: {self.sent_first_chunk}")
if self.sent_first_chunk is False:
model_response.choices[0].delta["role"] = "assistant"
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 2c72046e2ab..d09599e8789 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
@@ -1174,10 +1174,12 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
if reasoning_content is not None:
chat_completion_message["reasoning_content"] = reasoning_content
- functions, tools, cumulative_tool_call_index = VertexGeminiConfig._transform_parts(
- parts=candidate["content"]["parts"],
- cumulative_tool_call_idx=cumulative_tool_call_index,
- is_function_call=is_function_call(standard_optional_params),
+ functions, tools, cumulative_tool_call_index = (
+ VertexGeminiConfig._transform_parts(
+ parts=candidate["content"]["parts"],
+ cumulative_tool_call_idx=cumulative_tool_call_index,
+ is_function_call=is_function_call(standard_optional_params),
+ )
)
if "logprobsResult" in candidate:
@@ -1952,6 +1954,7 @@ class ModelResponseIterator:
) = VertexGeminiConfig._process_candidates(
_candidates, model_response, self.logging_obj.optional_params
)
+
setattr(model_response, "vertex_ai_grounding_metadata", grounding_metadata) # type: ignore
setattr(model_response, "vertex_ai_url_context_metadata", url_context_metadata) # type: ignore
setattr(model_response, "vertex_ai_safety_ratings", safety_ratings) # type: ignore
diff --git a/tests/local_testing/test_amazing_vertex_completion.py b/tests/local_testing/test_amazing_vertex_completion.py
index be28ae92a67..bdca05a59aa 100644
--- a/tests/local_testing/test_amazing_vertex_completion.py
+++ b/tests/local_testing/test_amazing_vertex_completion.py
@@ -3951,3 +3951,35 @@ async def test_vertex_ai_deepseek():
print(f"mock_post.call_args: {mock_post.call_args[0][0]}")
assert "v1beta1" not in mock_post.call_args[0][0]
assert "v1" in mock_post.call_args[0][0]
+
+
+def test_gemini_grounding_on_streaming():
+ from litellm import completion
+
+ load_vertex_ai_credentials()
+ # litellm._turn_on_debug()
+ args = {
+ "model": "vertex_ai/gemini-2.0-flash",
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "What is the weather like on San Francisco today ?",
+ }
+ ],
+ }
+ ],
+ "stream": True,
+ "tools": [{"googleSearch": {}}],
+ "fallbacks": [],
+ }
+
+ result = completion(**args)
+ vertex_ai_grounding_metadata_shows_up = False
+ for chunk in result:
+ if hasattr(chunk, "vertex_ai_grounding_metadata"):
+ vertex_ai_grounding_metadata_shows_up = True
+ print(chunk)
+ assert vertex_ai_grounding_metadata_shows_up
diff --git a/tests/test_litellm/litellm_core_utils/test_core_helpers.py b/tests/test_litellm/litellm_core_utils/test_core_helpers.py
index 215663cae80..d7869e6b800 100644
--- a/tests/test_litellm/litellm_core_utils/test_core_helpers.py
+++ b/tests/test_litellm/litellm_core_utils/test_core_helpers.py
@@ -35,3 +35,25 @@ def test_add_missing_spend_metadata_to_litellm_metadata():
"test_key": "test_value",
"user_api_key_hash_value": "1234567890",
}
+
+
+def test_preserve_upstream_non_openai_attributes():
+ from litellm.litellm_core_utils.core_helpers import (
+ preserve_upstream_non_openai_attributes,
+ )
+ from litellm.types.utils import ModelResponseStream
+
+ model_response = ModelResponseStream(
+ id="123",
+ object="text_completion",
+ created=1715811200,
+ model="gpt-3.5-turbo",
+ )
+
+ setattr(model_response, "test_key", "test_value")
+ preserve_upstream_non_openai_attributes(
+ model_response=ModelResponseStream(),
+ original_chunk=model_response,
+ )
+
+ assert model_response.test_key == "test_value"