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] gemini-cli integration - Add Logging + Cost tracking for stream + non-stream Vertex / Google AI Studio routes (#12058)

Ishaan Jaff5b8e30015093
diff --git a/litellm/google_genai/main.py b/litellm/google_genai/main.py
index 171569bbcbc..237e195c9a8 100644
--- a/litellm/google_genai/main.py
+++ b/litellm/google_genai/main.py
@@ -1,7 +1,7 @@
import asyncio
import contextvars
from functools import partial
-from typing import TYPE_CHECKING, Any, AsyncIterator, Dict, Iterator, Optional, Union
+from typing import TYPE_CHECKING, Any, Dict, Iterator, Optional, Union
import httpx
from pydantic import BaseModel
diff --git a/litellm/google_genai/streaming_iterator.py b/litellm/google_genai/streaming_iterator.py
index a38d3c18361..d0fa5a0be6c 100644
--- a/litellm/google_genai/streaming_iterator.py
+++ b/litellm/google_genai/streaming_iterator.py
@@ -1,7 +1,12 @@
+import asyncio
from datetime import datetime
from typing import TYPE_CHECKING, Any, List, Optional
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+from litellm.proxy.pass_through_endpoints.success_handler import (
+ PassThroughEndpointLogging,
+)
+from litellm.types.passthrough_endpoints.pass_through_endpoints import EndpointType
if TYPE_CHECKING:
from litellm.llms.base_llm.google_genai.transformation import (
@@ -10,6 +15,8 @@ if TYPE_CHECKING:
else:
BaseGoogleGenAIGenerateContentConfig = Any
+GLOBAL_PASS_THROUGH_SUCCESS_HANDLER_OBJ = PassThroughEndpointLogging()
+
class BaseGoogleGenAIGenerateContentStreamingIterator:
"""
Base class for Google GenAI Generate Content streaming iterators that provides common logic
@@ -20,14 +27,35 @@ class BaseGoogleGenAIGenerateContentStreamingIterator:
self,
litellm_logging_obj: LiteLLMLoggingObj,
request_body: dict,
+ model: str,
):
self.litellm_logging_obj = litellm_logging_obj
self.request_body = request_body
self.start_time = datetime.now()
+ self.collected_chunks: List[bytes] = []
+ self.model = model
- async def _handle_streaming_logging(self, collected_chunks: List[bytes]):
+ async def _handle_async_streaming_logging(
+ self,
+ ):
"""Handle the logging after all chunks have been collected."""
- pass
+ from litellm.proxy.pass_through_endpoints.streaming_handler import (
+ PassThroughStreamingHandler,
+ )
+ end_time = datetime.now()
+ asyncio.create_task(
+ PassThroughStreamingHandler._route_streaming_logging_to_handler(
+ litellm_logging_obj=self.litellm_logging_obj,
+ passthrough_success_handler_obj=GLOBAL_PASS_THROUGH_SUCCESS_HANDLER_OBJ,
+ url_route="/v1/generateContent",
+ request_body=self.request_body or {},
+ endpoint_type=EndpointType.VERTEX_AI,
+ start_time=self.start_time,
+ raw_bytes=self.collected_chunks,
+ end_time=end_time,
+ model=self.model,
+ )
+ )
class GoogleGenAIGenerateContentStreamingIterator(BaseGoogleGenAIGenerateContentStreamingIterator):
@@ -48,6 +76,7 @@ class GoogleGenAIGenerateContentStreamingIterator(BaseGoogleGenAIGenerateContent
super().__init__(
litellm_logging_obj=logging_obj,
request_body=request_body or {},
+ model=model,
)
self.response = response
self.model = model
@@ -64,6 +93,7 @@ class GoogleGenAIGenerateContentStreamingIterator(BaseGoogleGenAIGenerateContent
try:
# Get the next chunk from the stored iterator
chunk = next(self.stream_iterator)
+ self.collected_chunks.append(chunk)
# Just yield raw bytes
return chunk
except StopIteration:
@@ -96,6 +126,7 @@ class AsyncGoogleGenAIGenerateContentStreamingIterator(BaseGoogleGenAIGenerateCo
super().__init__(
litellm_logging_obj=logging_obj,
request_body=request_body or {},
+ model=model,
)
self.response = response
self.model = model
@@ -112,7 +143,9 @@ class AsyncGoogleGenAIGenerateContentStreamingIterator(BaseGoogleGenAIGenerateCo
try:
# Get the next chunk from the stored async iterator
chunk = await self.stream_iterator.__anext__()
+ self.collected_chunks.append(chunk)
# Just yield raw bytes
return chunk
except StopAsyncIteration:
+ await self._handle_async_streaming_logging()
raise StopAsyncIteration
\ No newline at end of file
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index aa0280210d4..59b3e870c62 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -1270,9 +1270,13 @@ class Logging(LiteLLMLoggingBaseClass):
self.model_call_details["log_event_type"] = "successful_api_call"
self.model_call_details["end_time"] = end_time
self.model_call_details["cache_hit"] = cache_hit
-
if self.call_type == CallTypes.anthropic_messages.value:
result = self._handle_anthropic_messages_response_logging(result=result)
+ elif (
+ self.call_type == CallTypes.generate_content.value or
+ self.call_type == CallTypes.agenerate_content.value
+ ):
+ result = self._handle_non_streaming_google_genai_generate_content_response_logging(result=result)
## if model in model cost map - log the response cost
## else set cost to None
@@ -2737,6 +2741,27 @@ class Logging(LiteLLMLoggingBaseClass):
json_mode=None,
)
return result
+
+ def _handle_non_streaming_google_genai_generate_content_response_logging(self, result: Any) -> ModelResponse:
+ """
+ Handles logging for Google GenAI generate content responses.
+ """
+ import httpx
+ httpx_response = self.model_call_details.get("httpx_response", None)
+ if httpx_response is None:
+ raise ValueError("Google GenAI Generate Content: httpx_response is None")
+ dict_result = httpx_response.json()
+ result = litellm.VertexGeminiConfig()._transform_google_generate_content_to_openai_model_response(
+ completion_response=dict_result,
+ model_response=litellm.ModelResponse(),
+ model=self.model,
+ logging_obj=self,
+ raw_response=httpx.Response(
+ status_code=200,
+ headers={},
+ ),
+ )
+ return result
def _get_masked_values(
diff --git a/litellm/llms/base_llm/google_genai/transformation.py b/litellm/llms/base_llm/google_genai/transformation.py
index 0b0df98800c..9706b226c47 100644
--- a/litellm/llms/base_llm/google_genai/transformation.py
+++ b/litellm/llms/base_llm/google_genai/transformation.py
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
import httpx
if TYPE_CHECKING:
+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.types.google_genai.main import (
GenerateContentConfigDict,
GenerateContentContentListUnionDict,
@@ -14,6 +15,7 @@ else:
GenerateContentConfigDict = Any
GenerateContentContentListUnionDict = Any
GenerateContentResponse = Any
+ LiteLLMLoggingObj = Any
from litellm.types.router import GenericLiteLLMParams
@@ -165,6 +167,7 @@ class BaseGoogleGenAIGenerateContentConfig(ABC):
self,
model: str,
raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
) -> GenerateContentResponse:
"""
Transform the raw response from the generate content API.
diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py
index 769cfe75b62..132063cc59d 100644
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@ -3010,6 +3010,7 @@ class BaseLLMHTTPHandler:
return generate_content_provider_config.transform_generate_content_response(
model=model,
raw_response=response,
+ logging_obj=logging_obj,
)
async def async_generate_content_handler(
@@ -3111,4 +3112,5 @@ class BaseLLMHTTPHandler:
return generate_content_provider_config.transform_generate_content_response(
model=model,
raw_response=response,
+ logging_obj=logging_obj,
)
diff --git a/litellm/llms/gemini/google_genai/transformation.py b/litellm/llms/gemini/google_genai/transformation.py
index 1fe2f4e6548..9910e478063 100644
--- a/litellm/llms/gemini/google_genai/transformation.py
+++ b/litellm/llms/gemini/google_genai/transformation.py
@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple, Uni
import httpx
import litellm
+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.llms.base_llm.google_genai.transformation import (
BaseGoogleGenAIGenerateContentConfig,
)
@@ -271,6 +272,7 @@ class GoogleGenAIConfig(BaseGoogleGenAIGenerateContentConfig, VertexLLM):
self,
model: str,
raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
) -> GenerateContentResponse:
"""
Transform the raw response from the generate content API.
@@ -292,4 +294,6 @@ class GoogleGenAIConfig(BaseGoogleGenAIGenerateContentConfig, VertexLLM):
headers=raw_response.headers,
)
+ logging_obj.model_call_details["httpx_response"] = raw_response
+
return GenerateContentResponse(**response)
\ No newline at end of file
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 e058aa675d7..20cf076d415 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
@@ -1261,6 +1261,30 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
status_code=422,
headers=raw_response.headers,
)
+
+
+ return self._transform_google_generate_content_to_openai_model_response(
+ completion_response=completion_response,
+ model_response=model_response,
+ model=model,
+ logging_obj=logging_obj,
+ raw_response=raw_response,
+ )
+
+
+ def _transform_google_generate_content_to_openai_model_response(
+ self,
+ completion_response: Union[GenerateContentResponseBody, dict],
+ model_response: ModelResponse,
+ model: str,
+ logging_obj: LoggingClass,
+ raw_response: httpx.Response,
+ ) -> ModelResponse:
+ """
+ Transforms a Google GenAI generate content response to an OpenAI model response.
+ """
+ if isinstance(completion_response, dict):
+ completion_response = GenerateContentResponseBody(**completion_response) # type: ignore
## GET MODEL ##
model_response.model = model
diff --git a/litellm/proxy/anthropic_endpoints/endpoints.py b/litellm/proxy/anthropic_endpoints/endpoints.py
index be8ce40566b..52dc01a86b9 100644
--- a/litellm/proxy/anthropic_endpoints/endpoints.py
+++ b/litellm/proxy/anthropic_endpoints/endpoints.py
@@ -3,16 +3,11 @@ Unified /v1/messages endpoint - (Anthropic Spec)
"""
import asyncio
-import json
-import time
-import traceback
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
import litellm
from litellm._logging import verbose_proxy_logger
-from litellm.constants import STREAM_SSE_DATA_PREFIX
-from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
from litellm.proxy._types import *
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.common_request_processing import (
@@ -21,7 +16,6 @@ from litellm.proxy.common_request_processing import (
)
from litellm.proxy.common_utils.http_parsing_utils import _read_request_body
from litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_request
-from litellm.proxy.utils import ProxyLogging
router = APIRouter()
diff --git a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/vertex_passthrough_logging_handler.py b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/vertex_passthrough_logging_handler.py
index 5ef1a98ef8d..4dcb10ceb34 100644
--- a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/vertex_passthrough_logging_handler.py
+++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/vertex_passthrough_logging_handler.py
@@ -190,6 +190,7 @@ class VertexPassthroughLoggingHandler:
endpoint_type: EndpointType,
start_time: datetime,
all_chunks: List[str],
+ model: Optional[str],
end_time: datetime,
) -> PassThroughEndpointLoggingTypedDict:
"""
@@ -200,7 +201,7 @@ class VertexPassthroughLoggingHandler:
- Logs in litellm callbacks
"""
kwargs: Dict[str, Any] = {}
- model = VertexPassthroughLoggingHandler.extract_model_from_url(url_route)
+ model = model or VertexPassthroughLoggingHandler.extract_model_from_url(url_route)
complete_streaming_response = (
VertexPassthroughLoggingHandler._build_complete_streaming_response(
all_chunks=all_chunks,
diff --git a/litellm/proxy/pass_through_endpoints/streaming_handler.py b/litellm/proxy/pass_through_endpoints/streaming_handler.py
index 4efd43c9ff1..08b49bac383 100644
--- a/litellm/proxy/pass_through_endpoints/streaming_handler.py
+++ b/litellm/proxy/pass_through_endpoints/streaming_handler.py
@@ -70,6 +70,7 @@ class PassThroughStreamingHandler:
start_time: datetime,
raw_bytes: List[bytes],
end_time: datetime,
+ model: Optional[str] = None,
):
"""
Route the logging for the collected chunks to the appropriate handler
@@ -111,6 +112,7 @@ class PassThroughStreamingHandler:
start_time=start_time,
all_chunks=all_chunks,
end_time=end_time,
+ model=model,
)
)
standard_logging_response_object = (
@@ -122,7 +124,6 @@ class PassThroughStreamingHandler:
standard_logging_response_object = StandardPassThroughResponseObject(
response=f"cannot parse chunks to standard response object. Chunks={all_chunks}"
)
-
await litellm_logging_obj.async_success_handler(
result=standard_logging_response_object,
start_time=start_time,
diff --git a/litellm/types/google_genai/main.py b/litellm/types/google_genai/main.py
index 1d690125476..33da5a06f49 100644
--- a/litellm/types/google_genai/main.py
+++ b/litellm/types/google_genai/main.py
@@ -5,14 +5,21 @@ from typing import TYPE_CHECKING, Any, Optional, TypeAlias, TypedDict
from google.genai import types as _genai_types # type: ignore
from pydantic import BaseModel
+from litellm.types.llms.openai import BaseLiteLLMOpenAIResponseObject
+
ContentListUnion = _genai_types.ContentListUnion
ContentListUnionDict = _genai_types.ContentListUnionDict
GenerateContentConfigOrDict = _genai_types.GenerateContentConfigOrDict
-GenerateContentResponse = _genai_types.GenerateContentResponse
+GoogleGenAIGenerateContentResponse = _genai_types.GenerateContentResponse
GenerateContentContentListUnionDict = _genai_types.ContentListUnionDict
GenerateContentConfigDict = _genai_types.GenerateContentConfigDict
GenerateContentRequestParametersDict = _genai_types._GenerateContentParametersDict
class GenerateContentRequestDict(GenerateContentRequestParametersDict): # type: ignore[misc]
- generationConfig: Optional[Any]
\ No newline at end of file
+ generationConfig: Optional[Any]
+
+
+class GenerateContentResponse(GoogleGenAIGenerateContentResponse, BaseLiteLLMOpenAIResponseObject): # type: ignore[misc]
+ _hidden_params: dict = {}
+ pass
\ No newline at end of file
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 68d861cbc11..733335ef548 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -277,6 +277,14 @@ class CallTypes(Enum):
aresponses = "aresponses"
alist_input_items = "alist_input_items"
+ #########################################################
+ # Google GenAI Native Call Types
+ #########################################################
+ generate_content = "generate_content"
+ agenerate_content = "agenerate_content"
+ generate_content_stream = "generate_content_stream"
+ agenerate_content_stream = "agenerate_content_stream"
+
CallTypesLiteral = Literal[
"embedding",
@@ -304,6 +312,10 @@ CallTypesLiteral = Literal[
"anthropic_messages",
"aretrieve_batch",
"retrieve_batch",
+ "generate_content",
+ "agenerate_content",
+ "generate_content_stream",
+ "agenerate_content_stream",
]
diff --git a/litellm/utils.py b/litellm/utils.py
index 8d151805352..9b176dfc411 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -772,7 +772,12 @@ def function_setup( # noqa: PLR0915
messages = args[0] if len(args) > 0 else kwargs["input"]
else:
messages = "default-message-value"
- stream = True if "stream" in kwargs and kwargs["stream"] is True else False
+ stream = False
+ if _is_streaming_request(
+ kwargs=kwargs,
+ call_type=call_type,
+ ):
+ stream = True
logging_obj = LiteLLMLogging(
model=model, # type: ignore
messages=messages,
@@ -1025,7 +1030,10 @@ def client(original_function): # noqa: PLR0915
# MODEL CALL
result = original_function(*args, **kwargs)
- if "stream" in kwargs and kwargs["stream"] is True:
+ if _is_streaming_request(
+ kwargs=kwargs,
+ call_type=call_type,
+ ):
if (
"complete_response" in kwargs
and kwargs["complete_response"] is True
@@ -1169,7 +1177,10 @@ def client(original_function): # noqa: PLR0915
# MODEL CALL
result = original_function(*args, **kwargs)
end_time = datetime.datetime.now()
- if "stream" in kwargs and kwargs["stream"] is True:
+ if _is_streaming_request(
+ kwargs=kwargs,
+ call_type=call_type,
+ ):
if (
"complete_response" in kwargs
and kwargs["complete_response"] is True
@@ -1361,7 +1372,10 @@ def client(original_function): # noqa: PLR0915
# MODEL CALL
result = await original_function(*args, **kwargs)
end_time = datetime.datetime.now()
- if "stream" in kwargs and kwargs["stream"] is True:
+ if _is_streaming_request(
+ kwargs=kwargs,
+ call_type=call_type,
+ ):
if (
"complete_response" in kwargs
and kwargs["complete_response"] is True
@@ -1541,6 +1555,35 @@ def _is_async_request(
return False
+def _is_streaming_request(
+ kwargs: Dict[str, Any],
+ call_type: Union[CallTypes, str],
+) -> bool:
+ """
+ Returns True if the call type is a streaming request.
+ Returns True if:
+ - if "stream=True" in kwargs (litellm chat completion, litellm text completion, litellm messages)
+ - if call_type is generate_content_stream or agenerate_content_stream (litellm google genai)
+ """
+ if "stream" in kwargs and kwargs["stream"] is True:
+ return True
+
+ #########################################################
+ # Check if it's a google genai streaming request
+ if isinstance(call_type, str):
+ # check if it can be casted to CallTypes
+ try:
+ call_type = CallTypes(call_type)
+ except ValueError:
+ return False
+
+ if call_type == CallTypes.generate_content_stream or call_type == CallTypes.agenerate_content_stream:
+ return True
+ #########################################################
+
+ return False
+
+
def update_response_metadata(
result: Any,
logging_obj: LiteLLMLoggingObject,
diff --git a/requirements.txt b/requirements.txt
index 41a61ced81d..e133d227174 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,6 +1,6 @@
# LITELLM PROXY DEPENDENCIES #
anyio==4.8.0 # openai + http req.
-httpx==0.27.0 # Pin Httpx dependency
+httpx==0.28.1
openai==1.81.0 # openai req.
fastapi==0.115.5 # server dep
backoff==2.2.1 # server dep
@@ -14,6 +14,7 @@ prisma==0.11.0 # for db
mangum==0.17.0 # for aws lambda functions
pynacl==1.5.0 # for encrypting keys
google-cloud-aiplatform==1.47.0 # for vertex ai calls
+google-genai==1.22.0
anthropic[vertex]==0.54.0
mcp==1.9.3 # for MCP server
google-generativeai==0.5.0 # for vertex ai calls
diff --git a/tests/test_litellm/llms/azure/test_azure_common_utils.py b/tests/test_litellm/llms/azure/test_azure_common_utils.py
index 8c5fd7e5e08..477549bd79e 100644
--- a/tests/test_litellm/llms/azure/test_azure_common_utils.py
+++ b/tests/test_litellm/llms/azure/test_azure_common_utils.py
@@ -427,6 +427,8 @@ def test_select_azure_base_url_called(setup_mocks):
"afile_list",
"aimage_edit",
"image_edit",
+ "agenerate_content_stream",
+ "agenerate_content",
]
],
)
diff --git a/tests/unified_google_tests/base_google_test.py b/tests/unified_google_tests/base_google_test.py
index c0bfd2c62b0..0f8503638e0 100644
--- a/tests/unified_google_tests/base_google_test.py
+++ b/tests/unified_google_tests/base_google_test.py
@@ -17,6 +17,21 @@ from litellm.google_genai import (
agenerate_content_stream,
)
from google.genai.types import ContentDict, PartDict, GenerateContentResponse
+from litellm.integrations.custom_logger import CustomLogger
+from litellm.types.utils import StandardLoggingPayload
+
+
+class TestCustomLogger(CustomLogger):
+ def __init__(
+ self,
+ ):
+ self.standard_logging_object: Optional[StandardLoggingPayload] = None
+
+ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
+ print("in async_log_success_event")
+ print("kwargs=", json.dumps(kwargs, indent=4, default=str))
+ self.standard_logging_object = kwargs["standard_logging_object"]
+ pass
class BaseGoogleGenAITest:
@@ -47,6 +62,35 @@ class BaseGoogleGenAITest:
assert len(chunks) >= 0, "Should have at least 0 chunks"
print(f"Total chunks received: {len(chunks)}")
+ def _validate_standard_logging_payload(
+ self, slp: StandardLoggingPayload, response: Any
+ ):
+ """
+ Validate that a StandardLoggingPayload object matches the expected response for Google GenAI
+
+ Args:
+ slp (StandardLoggingPayload): The standard logging payload object to validate
+ response: The Google GenAI response to compare against
+ """
+ # Validate payload exists
+ assert slp is not None, "Standard logging payload should not be None"
+
+ # Validate basic structure
+ assert "prompt_tokens" in slp, "Standard logging payload should have prompt_tokens"
+ assert "completion_tokens" in slp, "Standard logging payload should have completion_tokens"
+ assert "total_tokens" in slp, "Standard logging payload should have total_tokens"
+ assert "response_cost" in slp, "Standard logging payload should have response_cost"
+
+ # Validate token counts are reasonable (non-negative numbers)
+ assert slp["prompt_tokens"] >= 0, "Prompt tokens should be non-negative"
+ assert slp["completion_tokens"] >= 0, "Completion tokens should be non-negative"
+ assert slp["total_tokens"] >= 0, "Total tokens should be non-negative"
+
+ # Validate spend
+ assert slp["response_cost"] >= 0, "Response cost should be non-negative"
+
+ print(f"Standard logging payload validation passed: prompt_tokens={slp['prompt_tokens']}, completion_tokens={slp['completion_tokens']}, total_tokens={slp['total_tokens']}, cost={slp['response_cost']}")
+
@pytest.mark.parametrize("is_async", [False, True])
@pytest.mark.asyncio
async def test_non_streaming_base(self, is_async: bool):
@@ -124,3 +168,88 @@ class BaseGoogleGenAITest:
self._validate_streaming_response(chunks)
return chunks
+
+ @pytest.mark.asyncio
+ async def test_async_non_streaming_with_logging(self):
+ """Test async non-streaming Google GenAI generate content with logging"""
+ litellm._turn_on_debug()
+ litellm.logging_callback_manager._reset_all_callbacks()
+ litellm.set_verbose = True
+ test_custom_logger = TestCustomLogger()
+ litellm.callbacks = [test_custom_logger]
+
+ request_params = self.model_config
+ contents = ContentDict(
+ parts=[
+ PartDict(
+ text="Hello, can you tell me a short joke?"
+ )
+ ],
+ role="user",
+ )
+
+ print("\n--- Testing async agenerate_content with logging ---")
+ response = await agenerate_content(
+ contents=contents,
+ **request_params
+ )
+
+ print("Google GenAI response=", json.dumps(response, indent=4, default=str))
+
+ print("sleeping for 5 seconds...")
+ await asyncio.sleep(5)
+ print(
+ "standard logging payload=",
+ json.dumps(test_custom_logger.standard_logging_object, indent=4, default=str),
+ )
+
+ assert response is not None
+ assert test_custom_logger.standard_logging_object is not None
+
+ self._validate_standard_logging_payload(
+ test_custom_logger.standard_logging_object, response
+ )
+
+ @pytest.mark.asyncio
+ async def test_async_streaming_with_logging(self):
+ """Test async streaming Google GenAI generate content with logging"""
+ litellm._turn_on_debug()
+ litellm.set_verbose = True
+ litellm.logging_callback_manager._reset_all_callbacks()
+ test_custom_logger = TestCustomLogger()
+ litellm.callbacks = [test_custom_logger]
+
+ request_params = self.model_config
+ contents = ContentDict(
+ parts=[
+ PartDict(
+ text="Hello, can you tell me a short joke?"
+ )
+ ],
+ role="user",
+ )
+
+ print("\n--- Testing async agenerate_content_stream with logging ---")
+ response = await agenerate_content_stream(
+ contents=contents,
+ **request_params
+ )
+
+ chunks = []
+ async for chunk in response:
+ print(f"Google GenAI chunk: {chunk}")
+ chunks.append(chunk)
+
+ print("sleeping for 5 seconds...")
+ await asyncio.sleep(5)
+ print(
+ "standard logging payload=",
+ json.dumps(test_custom_logger.standard_logging_object, indent=4, default=str),
+ )
+
+ assert len(chunks) >= 0
+ assert test_custom_logger.standard_logging_object is not None
+
+ self._validate_standard_logging_payload(
+ test_custom_logger.standard_logging_object, chunks
+ )