Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ ci = [
# Pin to 1.0.8 so it pairs correctly with langgraph==1.0.10.
"langgraph-prebuilt==1.0.8",
"claude-agent-sdk==0.1.44",
"google-genai==1.37.0",
]
healthcheck = [
"httpx==0.28.1",
Expand Down
145 changes: 145 additions & 0 deletions tests/unified_google_tests/base_google_genai_proxy_sdk_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
from __future__ import annotations

import os
from abc import ABC, abstractmethod
from typing import List, Optional

import pytest

try:
from google import genai
from google.genai import types

GOOGLE_GENAI_SDK_AVAILABLE = True
except ImportError:
GOOGLE_GENAI_SDK_AVAILABLE = False

from base_google_test import load_vertex_ai_credentials

MASTER_KEY = "sk-1234"
PROMPT = "Reply with only the single word: pong"


def _make_client(proxy_url: str) -> "genai.Client":
return genai.Client(
api_key=MASTER_KEY,
http_options={"base_url": proxy_url},
)


def _generation_config() -> "types.GenerateContentConfig":
return types.GenerateContentConfig(
temperature=0,
top_p=0.95,
top_k=20,
)


def _collect_stream_text(chunks: List["types.GenerateContentResponse"]) -> str:
return "".join(chunk.text for chunk in chunks if chunk.text)


class BaseGoogleGenAIProxySDKTest(ABC):
@property
@abstractmethod
def proxy_model_name(self) -> str: ...

def _skip_reason_if_credentials_missing(self) -> Optional[str]:
model = self.model_config.get("model", "")
if model.startswith("gemini/"):
if not os.getenv("GEMINI_API_KEY"):
return "GEMINI_API_KEY not set — skipping Gemini proxy SDK tests"
return None

if "vertex_ai" in model:
credentials_file = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", "")
if credentials_file and os.path.isfile(credentials_file):
return None
private_key = os.environ.get("VERTEX_AI_PRIVATE_KEY", "")
private_key_id = os.environ.get("VERTEX_AI_PRIVATE_KEY_ID", "")
if private_key and private_key_id:
return None
return "Vertex AI credentials not set — skipping Vertex AI proxy SDK tests"

return f"Unsupported model for proxy SDK tests: {model}"

def _require_proxy_sdk(self) -> None:
if not GOOGLE_GENAI_SDK_AVAILABLE:
pytest.skip("google-genai SDK not installed")
reason = self._skip_reason_if_credentials_missing()
if reason:
pytest.skip(reason)

def _setup_vertex_credentials_if_needed(self) -> None:
if "vertex_ai" not in self.model_config.get("model", ""):
return
credentials_file = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", "")
if credentials_file and os.path.isfile(credentials_file):
return
temp_file_path = load_vertex_ai_credentials(model=self.model_config["model"])
if temp_file_path:
self._temp_files_to_cleanup.append(temp_file_path)
Comment thread
Sameerlite marked this conversation as resolved.
Resolved

def test_proxy_genai_sdk_non_streaming(self, google_genai_proxy_url: str) -> None:
self._require_proxy_sdk()
self._setup_vertex_credentials_if_needed()

client = _make_client(google_genai_proxy_url)
response = client.models.generate_content(
model=self.proxy_model_name,
contents=types.Part.from_text(text=PROMPT),
config=_generation_config(),
)

assert response is not None
assert response.text is not None
assert len(response.text.strip()) > 0

def test_proxy_genai_sdk_streaming_completes_without_errors(
self, google_genai_proxy_url: str
) -> None:
self._require_proxy_sdk()
self._setup_vertex_credentials_if_needed()

client = _make_client(google_genai_proxy_url)
stream = client.models.generate_content_stream(
model=self.proxy_model_name,
contents=types.Part.from_text(text=PROMPT),
config=_generation_config(),
)

chunks: List[types.GenerateContentResponse] = []
stream_error: Optional[BaseException] = None

try:
for chunk in stream:
chunks.append(chunk)
except BaseException as exc:
stream_error = exc

assert (
stream_error is None
), f"Streaming raised {type(stream_error).__name__}: {stream_error}"
assert len(chunks) > 0, "Expected at least one streaming chunk"
assert _collect_stream_text(chunks).strip(), "Expected non-empty streamed text"

def test_proxy_genai_sdk_streaming_dict_style(
self, google_genai_proxy_url: str
) -> None:
self._require_proxy_sdk()
self._setup_vertex_credentials_if_needed()

client = _make_client(google_genai_proxy_url)
stream = client.models.generate_content_stream(
model=self.proxy_model_name,
contents={"text": PROMPT},
config={
"temperature": 0,
"top_p": 0.95,
"top_k": 20,
},
)

chunks = list(stream)
assert len(chunks) > 0
assert _collect_stream_text(chunks).strip()
Comment thread
Sameerlite marked this conversation as resolved.
Resolved
103 changes: 102 additions & 1 deletion tests/unified_google_tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,18 @@
import asyncio
import importlib
import os
import socket
import sys
import threading
import time
from pathlib import Path
from typing import Iterator, Tuple

import pytest
import uvicorn
from dotenv import load_dotenv

load_dotenv()

sys.path.insert(
0, os.path.abspath("../..")
Expand All @@ -28,6 +37,91 @@

_verbose_state = VerboseReporterState()

PROXY_CONFIG_PATH = Path(__file__).parent / "google_genai_proxy_test_config.yaml"
PROXY_MASTER_KEY = "sk-1234"
PROXY_START_TIMEOUT_S = 30.0


def _initialize_proxy(config_path: str) -> None:
from litellm.proxy.proxy_server import cleanup_router_config_variables, initialize

cleanup_router_config_variables()
asyncio.run(initialize(config=config_path, debug=True))
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved


def _start_proxy_server(
config_path: str,
) -> Tuple[str, uvicorn.Server, threading.Thread, socket.socket]:
from litellm.proxy.proxy_server import app as proxy_app

_initialize_proxy(config_path)

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", 0))
host, port = sock.getsockname()

config = uvicorn.Config(proxy_app, host=host, port=port, log_level="warning")
server = uvicorn.Server(config)

def _run() -> None:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(server.serve(sockets=[sock]))

thread = threading.Thread(target=_run, daemon=True)
thread.start()

start_time = time.time()
while not server.started:
if not thread.is_alive():
raise RuntimeError("LiteLLM proxy failed to start")
if time.time() - start_time > PROXY_START_TIMEOUT_S:
raise TimeoutError("LiteLLM proxy did not start in time")
time.sleep(0.05)

return f"http://{host}:{port}", server, thread, sock


@pytest.fixture(scope="module")
def google_genai_proxy_url() -> Iterator[str]:
from base_google_test import load_vertex_ai_credentials

saved_env = {
key: os.environ.get(key)
for key in (
"DATABASE_URL",
"DIRECT_URL",
"LITELLM_MASTER_KEY",
"STORE_MODEL_IN_DB",
)
}
os.environ.pop("DATABASE_URL", None)
os.environ.pop("DIRECT_URL", None)
os.environ["LITELLM_MASTER_KEY"] = PROXY_MASTER_KEY
os.environ["STORE_MODEL_IN_DB"] = "False"

credentials_file = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", "")
if not (credentials_file and os.path.isfile(credentials_file)):
vertex_credentials_path = load_vertex_ai_credentials(
model="vertex_ai/gemini-2.5-flash-lite"
)
if vertex_credentials_path:
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = vertex_credentials_path

server_url, server, thread, sock = _start_proxy_server(str(PROXY_CONFIG_PATH))
try:
yield server_url
finally:
server.should_exit = True
thread.join(timeout=10)
sock.close()
for key, value in saved_env.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
Comment thread
Sameerlite marked this conversation as resolved.
Resolved


@pytest.fixture(scope="session")
def event_loop():
Expand Down Expand Up @@ -95,7 +189,14 @@ def pytest_runtest_logreport(report):


def pytest_collection_modifyitems(config, items):
apply_vcr_auto_marker_to_items(items)
apply_vcr_auto_marker_to_items(
items,
skip_nodeid_suffixes=(
"test_proxy_genai_sdk_non_streaming",
"test_proxy_genai_sdk_streaming_completes_without_errors",
"test_proxy_genai_sdk_streaming_dict_style",
),
)

# Separate tests in 'test_amazing_proxy_custom_logger.py' and other tests
custom_logger_tests = [
Expand Down
16 changes: 16 additions & 0 deletions tests/unified_google_tests/google_genai_proxy_test_config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
model_list:
- model_name: gemini-2.5-flash-lite
litellm_params:
model: gemini/gemini-2.5-flash-lite
api_key: os.environ/GEMINI_API_KEY

- model_name: vertex-gemini-2.5-flash-lite
litellm_params:
model: vertex_ai/gemini-2.5-flash-lite

general_settings:
master_key: sk-1234
store_model_in_db: false

litellm_settings:
drop_params: true
7 changes: 6 additions & 1 deletion tests/unified_google_tests/test_google_ai_studio.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from base_google_genai_proxy_sdk_test import BaseGoogleGenAIProxySDKTest
from base_google_test import BaseGoogleGenAITest
import sys
import os
Expand All @@ -11,7 +12,7 @@
import json


class TestGoogleGenAIStudio(BaseGoogleGenAITest):
class TestGoogleGenAIStudio(BaseGoogleGenAITest, BaseGoogleGenAIProxySDKTest):
"""Test Google GenAI Studio"""

@property
Expand All @@ -20,6 +21,10 @@ def model_config(self):
"model": "gemini/gemini-2.5-flash-lite",
}

@property
def proxy_model_name(self) -> str:
return "gemini-2.5-flash-lite"


@pytest.mark.asyncio
async def test_mock_stream_generate_content_with_tools():
Expand Down
7 changes: 6 additions & 1 deletion tests/unified_google_tests/test_vertex_ai_native.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
from base_google_genai_proxy_sdk_test import BaseGoogleGenAIProxySDKTest
from base_google_test import BaseGoogleGenAITest


class TestVertexAIGenerateContent(BaseGoogleGenAITest):
class TestVertexAIGenerateContent(BaseGoogleGenAITest, BaseGoogleGenAIProxySDKTest):
"""Test Vertex AI"""

@property
def model_config(self):
return {
"model": "vertex_ai/gemini-2.5-flash-lite",
}

@property
def proxy_model_name(self) -> str:
return "vertex-gemini-2.5-flash-lite"
4 changes: 3 additions & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading