mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-03 01:38:46 +00:00
* fix(vertex_ai): price streamed pass-through calls with the regional uplift The streamed Vertex pass-through handler builds the response with stream_chunk_builder, which stamps a cost into _hidden_params without the vertex_location. The handler then prices the response again with the location from the URL, but only into kwargs, and the logger prefers the stamped cost. Streamed calls on a regional endpoint were billed at the global rate. Stamp the location-aware cost on the response in the shared generateContent payload builder so the logger records it. Fixes #44755 * style(vertex_ai): keep the response_cost assignment within the 120-char limit * refactor(vertex_ai): set the passthrough response cost with set_hidden_param Writing _hidden_params directly mutated a parameter and needed a pyright ignore, which the type discipline gate counts as LIT004 and LIT011. set_hidden_param is the shared helper for this. * test(integration): check Vertex pass-through spend rows keep the regional uplift when streamed * fix(proxy): price streamed Vertex pass-through spend like the non-streamed call Drop the location-blind cost stream_chunk_builder stores instead of stamping a cost, so the logger prices streamed generateContent and rawPredict calls with the URL's location and the deployment's custom pricing, the same way it prices non-streamed calls * fix(proxy): price custom-priced Vertex pass-through deployments at their own rates The stamped response_cost from the generateContent logging helper is returned before the logger checks custom pricing, so a deployment with custom input/output rates was billed at the cost-map price. The helper now passes custom_pricing and the deployment id into completion_cost, so the stamp holds the deployment rate for streamed and non-streamed calls, and deployments without custom pricing keep the regional uplift. * fix(proxy): bill Vertex /v1beta and interrupted pass-through streams by the deployment location and price * fix(proxy): give the new pyright ignore a reason for the LIT004 gate * test(integration): bill a custom-priced Vertex pass-through stream at the deployment price, cut-off streams included * fix(proxy): let the logger price non-streamed /gemini pass-through calls so both modes bill the same * fix(proxy): keep a client base_model out of pass-through pricing and price gateway Gemini streams as Gemini A top-level base_model in a pass-through body now reaches the logging params only for a key or team with allow_client_pricing_override, so a plain key cannot pick a cheaper model's price once the logger prices these calls. The test that pinned every litellm-owned body name into the logging params now leaves base_model to its own key-gated test. The Vertex handler now classifies a non-Google upstream host as Vertex only for Vertex resource paths, so a /gemini stream through a GEMINI_API_BASE gateway is priced as Gemini without the regional uplift. Adds the audit's integration spend test for Claude on Vertex, /v1beta, the named custom-priced /gemini deployment, and a cut OpenAI stream. * test(integration): price the gateway /gemini stream case as Gemini and cover client base_model and gateway host pricing The cost harness sends /gemini through GEMINI_API_BASE, which the pass-through now logs and bills as gemini, so the streamed case moves from the Vertex cases to the Gemini cases under the Gemini price. New spend tests cover a body base_model repricing only for keys allowed client pricing, a GEMINI_API_BASE gateway billing as Gemini in both modes, and a configured non-Google gateway picking the provider from the path. * fix(proxy): price pass-through Gemini by the route and ignore a non-string base_model The Vertex pass-through handler picked Gemini pricing from the URL path, so a configured pass-through to a Vertex gateway with a short path (no /projects/ segment) was billed as Gemini, and its Claude streams at $0. The provider now comes from the route: a call through /gemini or to generativelanguage.googleapis.com prices as Gemini, and everything else as Vertex, the same rule main used. Matching the GEMINI_API_BASE host was rejected because one gateway can serve both APIs, and the path rule was rejected because short gateway paths look like Gemini paths. A non-string base_model (a number, list or object) made the cost calculation fail and bill $0 once the stamped stream costs were gone. get_base_model_from_metadata now ignores it and falls back to the deployment's base_model, so the call bills the list price. A 400 was the other option, but the logger runs after the upstream answered. * test(integration): bill a non-string body base_model at the list price on every pass-through route * fix(proxy): bill a non-string model_info base_model at the list price and drop a non-object client model_info A key allowed client pricing can send metadata.model_info in a pass-through body. A non-string model_info.base_model made the cost lookup fail, and once the stamped stream and Gemini costs were gone those calls billed $0 on /gemini and on streamed /vertex_ai and /v1beta. The lookup now ignores a base_model that is not a string, the same rule the root base_model got, so the call bills the list price. A model_info that is not an object (a string or a list) broke several logging steps that read it as a mapping, so a non-streamed /gemini call fired no success callback and no pass-through call wrote a spend row. The pass-through route now leaves a non-object model_info out of the logging metadata, so the call bills the list price. A 400 was the other option, but it would turn calls that answer 200 today into errors, and guarding every reader of model_info would spread the same check over many files. * fix: reject a non-object model_info before the provider call again The previous commit made the base_model lookup return None for a model_info that is not an object. That lookup also runs during call setup on every router route and SDK entrypoint, where such a value used to fail before any provider request. With the early return the call went upstream, the provider billed it, and the request then failed in a later reader that still expects an object. On /v1/messages and /v1/responses the key was also charged for a response the client never got. The lookup again reads base_model from any truthy model_info, so a non-object value fails during setup the way it did before this PR. A non-string base_model inside an object still bills the list price, and the pass-through route still drops a non-object client model_info at intake, so pass-through calls keep billing the list price. * fix: match the Gemini API host exactly when picking the pass-through cost provider The provider check accepted any host ending in generativelanguage.googleapis.com, so a Vertex host such as vertex-generativelanguage.googleapis.com was priced as Gemini and lost the regional uplift. It now accepts that host or a subdomain of it. * test: pin that a subdomain of the Gemini API host keeps the Gemini price --------- Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
384 lines
14 KiB
Python
384 lines
14 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Test to verify the Google GenAI generate_content adapter functionality
|
|
"""
|
|
|
|
import json
|
|
from collections.abc import Iterator
|
|
from typing import Final
|
|
|
|
import pytest
|
|
|
|
|
|
|
|
|
|
import litellm
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_agenerate_content_stream():
|
|
"""
|
|
Test that the agenerate_content_stream function works
|
|
"""
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
from litellm.google_genai.main import (
|
|
agenerate_content_stream,
|
|
base_llm_http_handler,
|
|
)
|
|
|
|
with patch.object(
|
|
base_llm_http_handler, "generate_content_handler", new=AsyncMock()
|
|
) as mock_post:
|
|
result = await agenerate_content_stream(
|
|
model="gemini/gemini-2.0-flash-001",
|
|
contents="Hello, world!",
|
|
stream=True,
|
|
)
|
|
mock_post.assert_called_once()
|
|
assert mock_post.call_args.kwargs["stream"] is True
|
|
|
|
|
|
def _mock_gemini_post_response():
|
|
"""A minimal stand-in for a successful Gemini generateContent HTTP response."""
|
|
from unittest.mock import MagicMock
|
|
|
|
resp = MagicMock()
|
|
resp.status_code = 200
|
|
resp.headers = {}
|
|
resp.json.return_value = {
|
|
"candidates": [
|
|
{
|
|
"content": {"parts": [{"text": "hi"}], "role": "model"},
|
|
"finishReason": "STOP",
|
|
}
|
|
]
|
|
}
|
|
return resp
|
|
|
|
|
|
NATIVE_TOP_LEVEL_FIELD_CASES = [
|
|
(
|
|
"safetySettings",
|
|
[{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}],
|
|
),
|
|
("toolConfig", {"functionCallingConfig": {"mode": "AUTO"}}),
|
|
("cachedContent", "cachedContents/abc123"),
|
|
("labels", {"team": "search"}),
|
|
("continuationToken", "dG9rLTE="),
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize("field_name, field_value", NATIVE_TOP_LEVEL_FIELD_CASES)
|
|
def test_native_top_level_field_forwarded_to_request_body(field_name, field_value):
|
|
"""
|
|
Regression for https://github.com/BerriAI/litellm/issues/12671
|
|
|
|
Google's native generateContent body carries fields like safetySettings at the
|
|
top level (siblings of generationConfig). The proxy spreads them as loose kwargs
|
|
into generate_content. They must reach Google's request body at the top level and
|
|
must NOT be silently dropped nor nested under generationConfig.
|
|
"""
|
|
from unittest.mock import patch
|
|
|
|
from litellm.google_genai.main import generate_content
|
|
from litellm.llms.custom_httpx.http_handler import HTTPHandler
|
|
|
|
with patch.object(
|
|
HTTPHandler, "post", return_value=_mock_gemini_post_response()
|
|
) as mock_post:
|
|
generate_content(
|
|
model="gemini/gemini-2.0-flash",
|
|
contents=[{"role": "user", "parts": [{"text": "Say hi"}]}],
|
|
custom_llm_provider="gemini",
|
|
api_key="test-key",
|
|
**{field_name: field_value},
|
|
)
|
|
|
|
assert mock_post.called, "expected the request to reach the HTTP client"
|
|
body = mock_post.call_args.kwargs["json"]
|
|
assert (
|
|
body[field_name] == field_value
|
|
), f"{field_name} should be forwarded to Google at the top level"
|
|
assert field_name not in body.get("generationConfig", {}), (
|
|
f"{field_name} must be a top-level sibling of generationConfig, "
|
|
"not nested inside it"
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_native_safety_settings_forwarded_async():
|
|
"""The async path (used by the proxy's :generateContent route) must also forward
|
|
native top-level fields."""
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
from litellm.google_genai.main import agenerate_content
|
|
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
|
|
|
|
safety_settings = [
|
|
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}
|
|
]
|
|
|
|
with patch.object(
|
|
AsyncHTTPHandler,
|
|
"post",
|
|
new_callable=AsyncMock,
|
|
return_value=_mock_gemini_post_response(),
|
|
) as mock_post:
|
|
await agenerate_content(
|
|
model="gemini/gemini-2.0-flash",
|
|
contents=[{"role": "user", "parts": [{"text": "Say hi"}]}],
|
|
custom_llm_provider="gemini",
|
|
api_key="test-key",
|
|
safetySettings=safety_settings,
|
|
)
|
|
|
|
assert mock_post.called
|
|
body = mock_post.call_args.kwargs["json"]
|
|
assert body["safetySettings"] == safety_settings
|
|
assert "safetySettings" not in body.get("generationConfig", {})
|
|
|
|
|
|
def test_native_fields_coexist_with_generation_config():
|
|
"""Forwarding native top-level fields must not regress the already-working
|
|
generationConfig path; both must land in their correct positions."""
|
|
from unittest.mock import patch
|
|
|
|
from litellm.google_genai.main import generate_content
|
|
from litellm.llms.custom_httpx.http_handler import HTTPHandler
|
|
|
|
safety_settings = [
|
|
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}
|
|
]
|
|
|
|
with patch.object(
|
|
HTTPHandler, "post", return_value=_mock_gemini_post_response()
|
|
) as mock_post:
|
|
generate_content(
|
|
model="gemini/gemini-2.0-flash",
|
|
contents=[{"role": "user", "parts": [{"text": "Say hi"}]}],
|
|
custom_llm_provider="gemini",
|
|
api_key="test-key",
|
|
safetySettings=safety_settings,
|
|
generationConfig={"temperature": 0, "responseMimeType": "application/json"},
|
|
)
|
|
|
|
body = mock_post.call_args.kwargs["json"]
|
|
assert body["safetySettings"] == safety_settings
|
|
generation_config = body["generationConfig"]
|
|
assert generation_config["temperature"] == 0
|
|
assert generation_config["responseMimeType"] == "application/json"
|
|
|
|
|
|
def test_explicit_extra_body_overrides_native_top_level_field():
|
|
"""An explicit extra_body value takes precedence over the same top-level field."""
|
|
from unittest.mock import patch
|
|
|
|
from litellm.google_genai.main import generate_content
|
|
from litellm.llms.custom_httpx.http_handler import HTTPHandler
|
|
|
|
native = [{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}]
|
|
override = [
|
|
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_ONLY_HIGH"}
|
|
]
|
|
|
|
with patch.object(
|
|
HTTPHandler, "post", return_value=_mock_gemini_post_response()
|
|
) as mock_post:
|
|
generate_content(
|
|
model="gemini/gemini-2.0-flash",
|
|
contents=[{"role": "user", "parts": [{"text": "Say hi"}]}],
|
|
custom_llm_provider="gemini",
|
|
api_key="test-key",
|
|
safetySettings=native,
|
|
extra_body={"safetySettings": override},
|
|
)
|
|
|
|
body = mock_post.call_args.kwargs["json"]
|
|
assert body["safetySettings"] == override
|
|
|
|
|
|
def test_native_fields_and_system_instruction_forwarded_on_sync_stream():
|
|
"""The sync streaming path (generate_content_stream) must forward native top-level
|
|
fields AND systemInstruction. The PR changed the merge here and newly added the
|
|
systemInstruction kwarg; without coverage a regression on either ships green."""
|
|
from unittest.mock import patch
|
|
|
|
from litellm.google_genai.main import generate_content_stream
|
|
from litellm.llms.custom_httpx.http_handler import HTTPHandler
|
|
|
|
safety_settings = [
|
|
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}
|
|
]
|
|
system_instruction = {"parts": [{"text": "Be terse"}]}
|
|
|
|
with patch.object(
|
|
HTTPHandler, "post", return_value=_mock_gemini_post_response()
|
|
) as mock_post:
|
|
generate_content_stream(
|
|
model="gemini/gemini-2.0-flash",
|
|
contents=[{"role": "user", "parts": [{"text": "Say hi"}]}],
|
|
custom_llm_provider="gemini",
|
|
api_key="test-key",
|
|
safetySettings=safety_settings,
|
|
systemInstruction=system_instruction,
|
|
)
|
|
|
|
assert mock_post.called
|
|
body = mock_post.call_args.kwargs["json"]
|
|
assert body["safetySettings"] == safety_settings
|
|
assert body["systemInstruction"] == system_instruction
|
|
assert "safetySettings" not in body.get("generationConfig", {})
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_native_fields_forwarded_on_async_stream():
|
|
"""The async streaming path (agenerate_content_stream) backs the proxy's
|
|
:streamGenerateContent route and must forward native top-level fields too."""
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
from litellm.google_genai.main import agenerate_content_stream
|
|
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
|
|
|
|
safety_settings = [
|
|
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}
|
|
]
|
|
|
|
with patch.object(
|
|
AsyncHTTPHandler,
|
|
"post",
|
|
new_callable=AsyncMock,
|
|
return_value=_mock_gemini_post_response(),
|
|
) as mock_post:
|
|
await agenerate_content_stream(
|
|
model="gemini/gemini-2.0-flash",
|
|
contents=[{"role": "user", "parts": [{"text": "Say hi"}]}],
|
|
custom_llm_provider="gemini",
|
|
api_key="test-key",
|
|
safetySettings=safety_settings,
|
|
)
|
|
|
|
assert mock_post.called
|
|
body = mock_post.call_args.kwargs["json"]
|
|
assert body["safetySettings"] == safety_settings
|
|
assert "safetySettings" not in body.get("generationConfig", {})
|
|
|
|
|
|
@pytest.mark.parametrize("base_model, uses_native_api", [("gemini-2.5-flash", True), (None, False)])
|
|
def test_vertex_generate_content_routes_by_deployment_base_model(base_model, uses_native_api):
|
|
import datetime
|
|
|
|
from litellm.google_genai.main import GenerateContentHelper
|
|
from litellm.litellm_core_utils.litellm_logging import Logging
|
|
|
|
logging_obj = Logging(
|
|
model="vertex_ai/openai/tuned-endpoint",
|
|
messages=[],
|
|
stream=False,
|
|
call_type="agenerate_content",
|
|
start_time=datetime.datetime.now(),
|
|
litellm_call_id="route-test",
|
|
function_id="route-test",
|
|
)
|
|
setup = GenerateContentHelper.setup_generate_content_call(
|
|
model="vertex_ai/openai/tuned-endpoint",
|
|
contents=[{"role": "user", "parts": [{"text": "Say hi"}]}],
|
|
litellm_logging_obj=logging_obj,
|
|
**({} if base_model is None else {"base_model": base_model}),
|
|
)
|
|
|
|
assert (setup.generate_content_provider_config is not None) is uses_native_api
|
|
|
|
|
|
_UPLIFT_PROBE: Final = "gemini-regional-uplift-probe"
|
|
_UPLIFT_INPUT_RATE: Final = 1e-06
|
|
_UPLIFT_OUTPUT_RATE: Final = 2e-06
|
|
_UPLIFT_MULTIPLIER: Final = 1.1
|
|
|
|
|
|
@pytest.fixture
|
|
def vertex_regional_uplift_rate_card(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
|
|
rates: Final = {
|
|
"input_cost_per_token": _UPLIFT_INPUT_RATE,
|
|
"output_cost_per_token": _UPLIFT_OUTPUT_RATE,
|
|
"mode": "chat",
|
|
}
|
|
monkeypatch.setitem(litellm.model_cost, _UPLIFT_PROBE, {**rates, "litellm_provider": "vertex_ai-language-models"})
|
|
monkeypatch.setattr(litellm, "vertex_language_models", {*litellm.vertex_language_models, _UPLIFT_PROBE})
|
|
monkeypatch.setitem(
|
|
litellm.model_cost,
|
|
f"vertex_ai/{_UPLIFT_PROBE}",
|
|
{
|
|
**rates,
|
|
"litellm_provider": "vertex_ai-language-models",
|
|
"regional_endpoint_uplift_multiplier": _UPLIFT_MULTIPLIER,
|
|
},
|
|
)
|
|
monkeypatch.delenv("VERTEXAI_LOCATION", raising=False)
|
|
monkeypatch.delenv("VERTEX_LOCATION", raising=False)
|
|
litellm.get_model_info.cache_clear()
|
|
yield
|
|
litellm.get_model_info.cache_clear()
|
|
|
|
|
|
async def _logged_vertex_generate_content_cost(location: str, *, stream: bool) -> float:
|
|
import asyncio
|
|
import datetime
|
|
|
|
from litellm.google_genai.main import GenerateContentHelper
|
|
from litellm.google_genai.streaming_iterator import BaseGoogleGenAIGenerateContentStreamingIterator
|
|
from litellm.litellm_core_utils.litellm_logging import Logging
|
|
from litellm.types.google_genai.main import GenerateContentResponse
|
|
|
|
reply: Final = {
|
|
"candidates": [{"content": {"role": "model", "parts": [{"text": "hi"}]}, "finishReason": "STOP"}],
|
|
"usageMetadata": {"promptTokenCount": 7, "candidatesTokenCount": 1, "totalTokenCount": 8},
|
|
"modelVersion": _UPLIFT_PROBE,
|
|
}
|
|
logging_obj: Final = Logging(
|
|
model=f"vertex_ai/{_UPLIFT_PROBE}",
|
|
messages=[],
|
|
stream=stream,
|
|
call_type="agenerate_content_stream" if stream else "agenerate_content",
|
|
start_time=datetime.datetime(2026, 1, 1),
|
|
litellm_call_id="uplift-test",
|
|
function_id="uplift-test",
|
|
)
|
|
setup: Final = GenerateContentHelper.setup_generate_content_call(
|
|
model=f"vertex_ai/{_UPLIFT_PROBE}",
|
|
contents=[{"role": "user", "parts": [{"text": "hi"}]}],
|
|
litellm_logging_obj=logging_obj,
|
|
vertex_location=location,
|
|
stream=stream,
|
|
)
|
|
if stream:
|
|
iterator: Final = BaseGoogleGenAIGenerateContentStreamingIterator(
|
|
litellm_logging_obj=logging_obj,
|
|
request_body={},
|
|
model=setup.model,
|
|
custom_llm_provider=setup.custom_llm_provider,
|
|
)
|
|
iterator.collected_chunks.append(f"data: {json.dumps(reply)}\n\n".encode())
|
|
await iterator._handle_async_streaming_logging()
|
|
await asyncio.gather(*(task for task in asyncio.all_tasks() if task is not asyncio.current_task()))
|
|
else:
|
|
logging_obj._process_hidden_params_and_response_cost(
|
|
GenerateContentResponse(**reply),
|
|
datetime.datetime(2026, 1, 1),
|
|
datetime.datetime(2026, 1, 1),
|
|
build_logging_payload=False,
|
|
)
|
|
return logging_obj.model_call_details["response_cost"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("stream", [True, False], ids=["streamed", "non-streamed"])
|
|
@pytest.mark.parametrize("location, multiplier", [("global", 1.0), ("us", _UPLIFT_MULTIPLIER)])
|
|
async def test_vertex_generate_content_spend_follows_the_deployment_location(
|
|
vertex_regional_uplift_rate_card: None, stream: bool, location: str, multiplier: float
|
|
) -> None:
|
|
expected: Final = (7 * _UPLIFT_INPUT_RATE + 1 * _UPLIFT_OUTPUT_RATE) * multiplier
|
|
|
|
recorded: Final = await _logged_vertex_generate_content_cost(location, stream=stream)
|
|
|
|
assert recorded == pytest.approx(expected), (location, stream)
|