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]

fix(vertex_ai): price streamed pass-through calls with the regional uplift (#44795)

alexcastgonz6762d65eb866
diff --git a/litellm/google_genai/main.py b/litellm/google_genai/main.py
index beb4b96d787..40c9c7bc36c 100644
--- a/litellm/google_genai/main.py
+++ b/litellm/google_genai/main.py
@@ -16,6 +16,7 @@ from litellm.llms.base_llm.google_genai.transformation import (
BaseGoogleGenAIGenerateContentConfig,
)
from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
+from litellm.llms.vertex_ai.vertex_llm_base import VertexBase
from litellm.types.llms.base import LiteLLMBaseModel
from litellm.types.router import GenericLiteLLMParams
from litellm.types.utils import CallTypes
@@ -194,12 +195,14 @@ class GenerateContentHelper:
if litellm_logging_obj is None:
raise ValueError("litellm_logging_obj is required, but got None")
+ vertex_location: Final = VertexBase.explicit_vertex_ai_location(dict(litellm_params))
litellm_logging_obj.update_from_kwargs(
kwargs=kwargs,
model=model,
optional_params=dict(generate_content_config_dict),
litellm_params={
"litellm_call_id": litellm_call_id,
+ **({"vertex_location": vertex_location} if vertex_location else {}),
},
custom_llm_provider=custom_llm_provider,
)
diff --git a/litellm/litellm_core_utils/get_litellm_params.py b/litellm/litellm_core_utils/get_litellm_params.py
index 9dee3714c60..6ca02cbbe64 100644
--- a/litellm/litellm_core_utils/get_litellm_params.py
+++ b/litellm/litellm_core_utils/get_litellm_params.py
@@ -142,14 +142,12 @@ def get_base_model_from_litellm_call_metadata(
if metadata is None:
return None
model_info: Final = metadata.get("model_info")
- if model_info:
- model_info_mapping: Final = cast( # cast-ok: model metadata is caller-provided and preserves its mapping shape
- Mapping[str, object], model_info
- )
- return cast( # cast-ok: model metadata values are caller-provided
- str | None, model_info_mapping.get("base_model")
- )
- return None
+ if not model_info:
+ return None
+ base_model: Final = cast( # cast-ok: model metadata is caller-provided and preserves its mapping shape
+ Mapping[str, object], model_info
+ ).get("base_model")
+ return base_model if isinstance(base_model, str) else None
_get_base_model_from_litellm_call_metadata = get_base_model_from_litellm_call_metadata
diff --git a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/gemini_passthrough_logging_handler.py b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/gemini_passthrough_logging_handler.py
index 0093c6f386d..7a5d5a1e259 100644
--- a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/gemini_passthrough_logging_handler.py
+++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/gemini_passthrough_logging_handler.py
@@ -245,5 +245,4 @@ class GeminiPassthroughLoggingHandler:
logging_obj.model = litellm_model_response.model or model
logging_obj.model_call_details["model"] = logging_obj.model
logging_obj.model_call_details["custom_llm_provider"] = custom_llm_provider
- logging_obj.model_call_details["response_cost"] = response_cost
return kwargs
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 c3af6f534c2..5010de46fcb 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
@@ -11,6 +11,7 @@ from pydantic import ConfigDict, TypeAdapter
import litellm
from litellm._logging import verbose_proxy_logger
from litellm.constants import VERTEX_BATCH_PREDICTION_JOBS_ROUTE
+from litellm.litellm_core_utils.hidden_params import get_hidden_params
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.litellm_core_utils.llm_cost_calc.usage_object_transformation import (
InteractionsUsageObjectTransformation,
@@ -225,7 +226,7 @@ class VertexPassthroughLoggingHandler:
start_time=start_time,
end_time=end_time,
logging_obj=logging_obj,
- custom_llm_provider=VertexPassthroughLoggingHandler._get_custom_llm_provider_from_url(url_route),
+ custom_llm_provider=VertexPassthroughLoggingHandler._get_custom_llm_provider(url_route, logging_obj),
vertex_location=vertex_location,
)
@@ -549,7 +550,7 @@ class VertexPassthroughLoggingHandler:
response_json=response_json,
)
- custom_llm_provider: Final = VertexPassthroughLoggingHandler._get_custom_llm_provider_from_url(url_route)
+ custom_llm_provider: Final = VertexPassthroughLoggingHandler._get_custom_llm_provider(url_route, logging_obj)
litellm_embedding_response.model = model
logging_obj.model = model
@@ -621,7 +622,9 @@ class VertexPassthroughLoggingHandler:
start_time=start_time,
end_time=end_time,
logging_obj=litellm_logging_obj,
- custom_llm_provider=VertexPassthroughLoggingHandler._get_custom_llm_provider_from_url(url_route),
+ custom_llm_provider=VertexPassthroughLoggingHandler._get_custom_llm_provider(
+ url_route, litellm_logging_obj
+ ),
vertex_location=vertex_location,
)
@@ -669,9 +672,16 @@ class VertexPassthroughLoggingHandler:
all_openai_chunks: Final = [parsed_chunk for parsed_chunk in parsed_chunks if parsed_chunk is not None]
complete_streaming_response: Final = litellm.stream_chunk_builder(chunks=all_openai_chunks)
+ VertexPassthroughLoggingHandler._drop_location_blind_stream_builder_cost(complete_streaming_response)
return complete_streaming_response
+ @staticmethod
+ def _drop_location_blind_stream_builder_cost(response: ModelResponse | TextCompletionResponse | None) -> None:
+ hidden_params: Final = get_hidden_params(response)
+ if hidden_params is not None:
+ hidden_params.pop("response_cost", None)
+
@staticmethod
def extract_model_from_url(url: str) -> str:
pattern: Final = r"/models/([^:]+)"
@@ -724,9 +734,15 @@ class VertexPassthroughLoggingHandler:
return None
@staticmethod
- def _get_custom_llm_provider_from_url(url: str) -> str:
- parsed_url: Final = urlparse(url)
- if parsed_url.hostname and parsed_url.hostname.endswith("generativelanguage.googleapis.com"):
+ def _get_custom_llm_provider(url: str, logging_obj: LiteLLMLoggingObj) -> str:
+ hostname: Final = urlparse(url).hostname
+ if logging_obj.model_call_details.get("custom_llm_provider") == litellm.LlmProviders.GEMINI.value or (
+ hostname is not None
+ and (
+ hostname == "generativelanguage.googleapis.com"
+ or hostname.endswith(".generativelanguage.googleapis.com")
+ )
+ ):
return litellm.LlmProviders.GEMINI.value
return litellm.LlmProviders.VERTEX_AI.value
diff --git a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
index 46b7a724809..311dab058a4 100644
--- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
+++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
@@ -161,6 +161,12 @@ pass_through_endpoint_logging: Final = PassThroughEndpointLogging()
_METADATA_KEYS: Final = frozenset(("litellm_metadata", "metadata"))
_DECODED_JSON: Final = TypeAdapter(object)
_KEPT_OUT_OF_LITELLM_PARAMS: Final = _METADATA_KEYS | frozenset(wire_names(ProxyRequestState))
+_PRICING_MODEL_OVERRIDE_PARAMS: Final = frozenset(("base_model",))
+
+
+def _is_mergeable_client_metadata(key: str, value: object) -> bool:
+ return not key.startswith("user_api_key_") and (key != "model_info" or isinstance(value, Mapping))
+
# Global registry to track registered pass-through routes and prevent memory leaks
_registered_pass_through_routes: Final[dict[str, dict[str, str | bool | list[str] | Mapping[str, object]]]] = {}
@@ -633,8 +639,13 @@ class HttpPassThroughEndpointHelpers(BasePassthroughUtils):
litellm_keys_in_body: Final = MappingProxyType(
{k: _parsed_body.pop(k) for k in types_utils.all_litellm_params if k in _parsed_body}
)
+ kept_out_of_litellm_params: Final = (
+ _KEPT_OUT_OF_LITELLM_PARAMS
+ if _key_or_team_allows_client_pricing_override(user_api_key_dict)
+ else _KEPT_OUT_OF_LITELLM_PARAMS | _PRICING_MODEL_OVERRIDE_PARAMS
+ )
litellm_params_in_body: Final = MappingProxyType(
- {k: v for k, v in litellm_keys_in_body.items() if k not in _KEPT_OUT_OF_LITELLM_PARAMS}
+ {k: v for k, v in litellm_keys_in_body.items() if k not in kept_out_of_litellm_params}
)
_metadata = dict(
@@ -645,7 +656,13 @@ class HttpPassThroughEndpointHelpers(BasePassthroughUtils):
metadata: Final = litellm_keys_in_body.get("metadata")
for client_metadata in (litellm_metadata, metadata):
if isinstance(client_metadata, dict):
- _metadata.update({k: v for k, v in client_metadata.items() if not k.startswith("user_api_key_")})
+ _metadata.update(
+ {
+ k: v
+ for k, v in cast(Mapping[str, object], client_metadata).items() # cast-ok: json
+ if _is_mergeable_client_metadata(k, v)
+ }
+ )
_metadata = _apply_key_team_project_controls(user_api_key_dict=user_api_key_dict, metadata=_metadata)
_metadata = _update_metadata_with_tags_in_header(
diff --git a/litellm/proxy/pass_through_endpoints/streaming_handler.py b/litellm/proxy/pass_through_endpoints/streaming_handler.py
index 6799b82bf06..1fcfe2e279a 100644
--- a/litellm/proxy/pass_through_endpoints/streaming_handler.py
+++ b/litellm/proxy/pass_through_endpoints/streaming_handler.py
@@ -129,10 +129,11 @@ class PassThroughStreamingHandler:
usage: Final = getattr(partial_response, "usage", None)
if not isinstance(usage, Usage):
return
- response_cost: Final = kwargs.get("response_cost")
+ logger_cost: Final = litellm_logging_obj.response_cost_calculator(result=partial_response)
+ handler_cost: Final = kwargs.get("response_cost")
+ fallback_cost: Final = float(handler_cost) if isinstance(handler_cost, (int, float)) else 0.0
litellm_logging_obj.record_partial_usage_for_failure(
- usage=usage,
- response_cost=float(response_cost) if isinstance(response_cost, (int, float)) else 0.0,
+ usage=usage, response_cost=fallback_cost if logger_cost is None else logger_cost
)
@staticmethod
diff --git a/litellm/utils.py b/litellm/utils.py
index ab97b69897f..66d78a03075 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -8306,8 +8306,8 @@ def get_base_model_from_metadata(model_call_details: Mapping[str, object] | None
litellm_params: Final = cast(Mapping[str, object], model_call_details.get("litellm_params", {}))
if litellm_params is not None:
base_model: Final = litellm_params.get("base_model", None)
- if base_model is not None:
- return cast(str | None, base_model)
+ if isinstance(base_model, str):
+ return base_model
metadata: Final = cast(Mapping[str, object], litellm_params.get("metadata") or {})
base_model_metadata_getter: Final[_BaseModelFromMetadataGetter] = (
litellm_utils.get_base_model_from_litellm_call_metadata
diff --git a/tests/integration/cost_calculation/cases/gemini.py b/tests/integration/cost_calculation/cases/gemini.py
index ceca816c300..bc6665c423f 100644
--- a/tests/integration/cost_calculation/cases/gemini.py
+++ b/tests/integration/cost_calculation/cases/gemini.py
@@ -1544,6 +1544,73 @@ GEMINI_3_1_PRO_PASSTHROUGH_GENERATE_CONTENT_PRICED_VIA_GEMINI_KEY: Final = CostT
),
)
+GEMINI_3_1_PRO_PASSTHROUGH_STREAM_GENERATE_CONTENT_PRICED_VIA_GEMINI_KEY: Final = CostTrackingTestCase(
+ name="gemini-3.1-pro-passthrough-stream_generate_content_priced_via_gemini_key",
+ covers="quota_management.spend_tracking.scripted_wire.logs_cost",
+ model="gemini/gemini-3.1-pro",
+ endpoint="/gemini/v1beta/models/$MODEL:streamGenerateContent?alt=sse",
+ request={
+ "model": "$MODEL",
+ "messages": [
+ {
+ "role": "system",
+ "content": [
+ {
+ "type": "text",
+ "text": "You are a deterministic pricing-harness assistant. Keep answers to a single short line.",
+ }
+ ],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "52b6a80ff038 summarize the attached material in one line and name the city weather",
+ }
+ ],
+ },
+ ],
+ "stream": True,
+ "stream_options": {"include_usage": True},
+ "allowed_openai_params": [],
+ },
+ response=SseResponse(
+ content_type="text/event-stream",
+ frames=sse_frames(
+ {
+ "candidates": [
+ {
+ "content": {"parts": [{"text": "scripted answer 52b6a80ff038"}], "role": "model"},
+ "finishReason": "STOP",
+ "index": 0,
+ }
+ ],
+ "modelVersion": "gemini-3.1-pro",
+ },
+ {
+ "candidates": [],
+ "usageMetadata": {
+ "promptTokenCount": 1840,
+ "candidatesTokenCount": 412,
+ "totalTokenCount": 2252,
+ "promptTokensDetails": [{"modality": "TEXT", "tokenCount": 1840}],
+ },
+ "modelVersion": "gemini-3.1-pro",
+ },
+ ),
+ ),
+ expected=ExactExpected(
+ spend=0.008624,
+ input_cost=0.00368,
+ output_cost=0.004944,
+ prompt_tokens=1840,
+ completion_tokens=412,
+ breakdown_persisted=False,
+ cost_header=False,
+ ),
+)
+
# gemini/gemini-3.8-flash
GEMINI_GEMINI_3_8_FLASH_INPUT_TEXT: Final = CostTrackingTestCase(
@@ -3475,6 +3542,7 @@ CASES: Final[tuple[CostTrackingTestCase, ...]] = (
GEMINI_GEMINI_3_8_FLASH_STREAM_FULL_USAGE,
GEMINI_EMBEDDINGS_002,
GEMINI_3_1_PRO_PASSTHROUGH_GENERATE_CONTENT_PRICED_VIA_GEMINI_KEY,
+ GEMINI_3_1_PRO_PASSTHROUGH_STREAM_GENERATE_CONTENT_PRICED_VIA_GEMINI_KEY,
GEMINI_GEMINI_3_8_FLASH_LITE_INPUT_BELOW_128K,
GEMINI_GEMINI_3_8_FLASH_LITE_INPUT_ABOVE_128K,
GEMINI_NANO_BANANA_2_1_INPUT_TEXT,
diff --git a/tests/integration/cost_calculation/cases/vertex_ai.py b/tests/integration/cost_calculation/cases/vertex_ai.py
index 0e95eb865bf..b512df46d1d 100644
--- a/tests/integration/cost_calculation/cases/vertex_ai.py
+++ b/tests/integration/cost_calculation/cases/vertex_ai.py
@@ -1659,73 +1659,6 @@ GEMINI_3_1_PRO_STREAM_FULL_USAGE: Final = CostTrackingTestCase(
),
)
-GEMINI_3_1_PRO_PASSTHROUGH_STREAM_GENERATE_CONTENT_PRICED_VIA_VERTEX_KEY: Final = CostTrackingTestCase(
- name="gemini-3.1-pro-passthrough-stream_generate_content_priced_via_vertex_key",
- covers="quota_management.spend_tracking.scripted_wire.logs_cost",
- model="gemini-3.1-pro",
- endpoint="/gemini/v1beta/models/$MODEL:streamGenerateContent?alt=sse",
- request={
- "model": "$MODEL",
- "messages": [
- {
- "role": "system",
- "content": [
- {
- "type": "text",
- "text": "You are a deterministic pricing-harness assistant. Keep answers to a single short line.",
- }
- ],
- },
- {
- "role": "user",
- "content": [
- {
- "type": "text",
- "text": "52b6a80ff038 summarize the attached material in one line and name the city weather",
- }
- ],
- },
- ],
- "stream": True,
- "stream_options": {"include_usage": True},
- "allowed_openai_params": [],
- },
- response=SseResponse(
- content_type="text/event-stream",
- frames=sse_frames(
- {
- "candidates": [
- {
- "content": {"parts": [{"text": "scripted answer 52b6a80ff038"}], "role": "model"},
- "finishReason": "STOP",
- "index": 0,
- }
- ],
- "modelVersion": "gemini-3.1-pro",
- },
- {
- "candidates": [],
- "usageMetadata": {
- "promptTokenCount": 1840,
- "candidatesTokenCount": 412,
- "totalTokenCount": 2252,
- "promptTokensDetails": [{"modality": "TEXT", "tokenCount": 1840}],
- },
- "modelVersion": "gemini-3.1-pro",
- },
- ),
- ),
- expected=ExactExpected(
- spend=0.0090552,
- input_cost=0.003864,
- output_cost=0.0051912,
- prompt_tokens=1840,
- completion_tokens=412,
- breakdown_persisted=False,
- cost_header=False,
- ),
-)
-
# gemini-3.8-flash
GEMINI_3_8_FLASH_INPUT_TEXT: Final = CostTrackingTestCase(
@@ -3647,7 +3580,6 @@ CASES: Final[tuple[CostTrackingTestCase, ...]] = (
GEMINI_3_8_FLASH_STREAM_FULL_USAGE,
IMAGEN_NEXT_IMAGES_ONE,
VERTEX_EMBEDDINGS_TEXT_006,
- GEMINI_3_1_PRO_PASSTHROUGH_STREAM_GENERATE_CONTENT_PRICED_VIA_VERTEX_KEY,
VERTEX_AI_CLAUDE_SONNET_5_5_INPUT_TEXT,
VERTEX_AI_CLAUDE_SONNET_5_5_STREAM,
VERTEX_AI_CLAUDE_OPUS_5_5_INPUT_TEXT,
diff --git a/tests/integration/spend/test_passthrough_stream_pricing_paths_spend.py b/tests/integration/spend/test_passthrough_stream_pricing_paths_spend.py
new file mode 100644
index 00000000000..f091a8f8376
--- /dev/null
+++ b/tests/integration/spend/test_passthrough_stream_pricing_paths_spend.py
@@ -0,0 +1,583 @@
+import json
+import uuid
+from collections.abc import Iterator, Mapping
+from dataclasses import dataclass
+from hashlib import sha256
+from pathlib import Path
+from types import MappingProxyType
+from typing import Final
+from urllib.parse import urlsplit
+
+import httpx
+import pytest
+import yaml
+from integration._support.client import Gateway, eventually, gateway_from_environment
+from integration._support.database import read_rows
+from integration._support.forward_proxy import tunnelling_forward_proxy
+from integration._support.process import graceful_stop_seconds, owned_proxy
+from integration._support.tls import server_context, write_self_signed_cert
+from integration._support.vertex import service_account_json
+from integration._support.wire import Reply, Request, Wire, wire_server
+from pydantic import JsonValue, TypeAdapter
+
+pytestmark: Final = pytest.mark.timeout(2 * graceful_stop_seconds() + 120)
+
+_PROJECT: Final = "caller-project"
+_CALLER_GOOGLE_TOKEN: Final = "caller-google-token"
+_GEMINI: Final = "gemini-3.5-flash-lite"
+_CLAUDE_ROUTE_MODEL: Final = "claude-haiku-4-5"
+_CLAUDE_SERVED_MODEL: Final = "claude-haiku-4-5-20251001"
+_OPENAI_MODEL: Final = "gpt-5.6"
+_PROMPT_TOKENS: Final = 1200
+_COMPLETION_TOKENS: Final = 300
+_CUSTOM_INPUT_RATE: Final = 1e-05
+_CUSTOM_OUTPUT_RATE: Final = 2e-05
+_CUSTOM_PRICED_GEMINI_ID: Final = "audit-gemini-custom-priced"
+_HOSTS: Final = (
+ "aiplatform.googleapis.com",
+ "aiplatform.us.rep.googleapis.com",
+ "us-east5-aiplatform.googleapis.com",
+ "generativelanguage.googleapis.com",
+ "api.openai.com",
+)
+_COST_MAP: Final = Path("litellm/model_prices_and_context_window_backup.json")
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+_CUT_MARKER: Final = "cut this stream after the usage frame"
+_GEMINI_USAGE: Final = {
+ "promptTokenCount": _PROMPT_TOKENS,
+ "candidatesTokenCount": _COMPLETION_TOKENS,
+ "totalTokenCount": _PROMPT_TOKENS + _COMPLETION_TOKENS,
+}
+_DEPLOYMENT_LOCATIONS: Final = MappingProxyType({"audit-vertex-global": "global", "audit-vertex-us": "us"})
+_GEMINI_ACTIONS: Final = ("generateContent", "streamGenerateContent?alt=sse")
+_CONFIGURED_GATEWAY_PATH: Final = "/google-egress"
+
+
+@dataclass(frozen=True, slots=True)
+class _Rig:
+ proxy: Gateway
+ upstream: Wire
+
+
+def _gemini_reply(request: Request) -> Reply:
+ body: Final = json.dumps(
+ {
+ "candidates": [{"content": {"role": "model", "parts": [{"text": "scripted"}]}, "finishReason": "STOP"}],
+ "usageMetadata": _GEMINI_USAGE,
+ "modelVersion": _GEMINI,
+ "responseId": uuid.uuid4().hex,
+ }
+ )
+ if ":streamGenerateContent" in request.target:
+ return Reply(chunks=(f"data: {body}\r\n\r\n".encode(),), content_type="text/event-stream")
+ return Reply(body=body.encode())
+
+
+def _sse(event: str, payload: Mapping[str, JsonValue]) -> bytes:
+ return f"event: {event}\ndata: {json.dumps(payload)}\n\n".encode()
+
+
+def _claude_reply(request: Request) -> Reply:
+ message_id: Final = f"msg_vrtx_{uuid.uuid4().hex}"
+ if ":streamRawPredict" not in request.target:
+ return Reply(
+ body=json.dumps(
+ {
+ "model": _CLAUDE_SERVED_MODEL,
+ "id": message_id,
+ "type": "message",
+ "role": "assistant",
+ "content": [{"type": "text", "text": "scripted"}],
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": {"input_tokens": _PROMPT_TOKENS, "output_tokens": _COMPLETION_TOKENS},
+ }
+ ).encode()
+ )
+ return Reply(
+ content_type="text/event-stream",
+ chunks=(
+ _sse(
+ "message_start",
+ {
+ "type": "message_start",
+ "message": {
+ "model": _CLAUDE_SERVED_MODEL,
+ "id": message_id,
+ "type": "message",
+ "role": "assistant",
+ "content": [],
+ "stop_reason": None,
+ "stop_sequence": None,
+ "usage": {"input_tokens": _PROMPT_TOKENS, "output_tokens": 1},
+ },
+ },
+ ),
+ _sse(
+ "content_block_start",
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
+ ),
+ _sse(
+ "content_block_delta",
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "scripted"}},
+ ),
+ _sse("content_block_stop", {"type": "content_block_stop", "index": 0}),
+ _sse(
+ "message_delta",
+ {
+ "type": "message_delta",
+ "delta": {"stop_reason": "end_turn", "stop_sequence": None},
+ "usage": {"output_tokens": _COMPLETION_TOKENS},
+ },
+ ),
+ _sse("message_stop", {"type": "message_stop"}),
+ ),
+ )
+
+
+def _openai_reply(request: Request) -> Reply:
+ identity: Final = f"chatcmpl-{uuid.uuid4().hex}"
+ chunk: Final = {"id": identity, "object": "chat.completion.chunk", "created": 1, "model": _OPENAI_MODEL}
+ frames: Final = (
+ {**chunk, "choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}}]},
+ {**chunk, "choices": [{"index": 0, "delta": {"content": "scripted"}}]},
+ {**chunk, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
+ {
+ **chunk,
+ "choices": [],
+ "usage": {
+ "prompt_tokens": _PROMPT_TOKENS,
+ "completion_tokens": _COMPLETION_TOKENS,
+ "total_tokens": _PROMPT_TOKENS + _COMPLETION_TOKENS,
+ },
+ },
+ )
+ encoded: Final = tuple(f"data: {json.dumps(frame)}\n\n".encode() for frame in frames)
+ if _CUT_MARKER.encode() in request.body:
+ return Reply(chunks=(*encoded, b"data: [DONE]\n\n"), content_type="text/event-stream", abort_after=len(encoded))
+ return Reply(chunks=(*encoded, b"data: [DONE]\n\n"), content_type="text/event-stream")
+
+
+def _upstream(request: Request) -> Reply:
+ if request.target.startswith("/v1/chat/completions"):
+ return _openai_reply(request)
+ if "/publishers/anthropic/models/" in request.target:
+ assert f"/v1/projects/{_PROJECT}/locations/" in request.target, request.target
+ return _claude_reply(request)
+ return _gemini_reply(request)
+
+
+def _port(url: str) -> int:
+ port: Final = urlsplit(url).port
+ assert port is not None, url
+ return port
+
+
+def _cost_row(name: str) -> dict[str, JsonValue]:
+ return _JSON_OBJECT.validate_python(_JSON_OBJECT.validate_json(_COST_MAP.read_bytes())[name])
+
+
+def _list_price(name: str) -> float:
+ row: Final = _cost_row(name)
+ input_rate: Final = row["input_cost_per_token"]
+ output_rate: Final = row["output_cost_per_token"]
+ assert isinstance(input_rate, float) and isinstance(output_rate, float), row
+ return _PROMPT_TOKENS * input_rate + _COMPLETION_TOKENS * output_rate
+
+
+def _uplift(name: str) -> float:
+ multiplier: Final = _cost_row(name).get("regional_endpoint_uplift_multiplier")
+ assert isinstance(multiplier, int | float) and multiplier > 1, name
+ return float(multiplier)
+
+
+def _config(directory: Path, token_url: str) -> Path:
+ base: Final = _JSON_OBJECT.validate_python(yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text()))
+ existing: Final = base.get("model_list") or []
+ assert isinstance(existing, list), base
+ deployments: Final = [
+ {
+ "model_name": name,
+ "litellm_params": {
+ "model": f"vertex_ai/{_GEMINI}",
+ "vertex_project": _PROJECT,
+ "vertex_location": location,
+ "vertex_credentials": service_account_json(_PROJECT, token_url),
+ },
+ }
+ for name, location in _DEPLOYMENT_LOCATIONS.items()
+ ]
+ custom_priced_gemini: Final = {
+ "model_name": _CUSTOM_PRICED_GEMINI_ID,
+ "litellm_params": {
+ "model": f"gemini/{_GEMINI}",
+ "api_key": "scripted-gemini-key",
+ "input_cost_per_token": _CUSTOM_INPUT_RATE,
+ "output_cost_per_token": _CUSTOM_OUTPUT_RATE,
+ },
+ "model_info": {"id": _CUSTOM_PRICED_GEMINI_ID},
+ }
+ path: Final = directory / "config.yaml"
+ path.write_text(yaml.safe_dump({**base, "model_list": [*existing, *deployments, custom_priced_gemini]}))
+ return path
+
+
[email protected](scope="module")
+def rig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[_Rig]:
+ directory: Final = tmp_path_factory.mktemp("passthrough-stream-pricing")
+ certificate: Final = write_self_signed_cert(directory, _HOSTS)
+ with (
+ wire_server(_upstream, tls=server_context(*certificate)) as upstream,
+ tunnelling_forward_proxy(_port(upstream.url)) as tunnel,
+ gateway_from_environment() as base,
+ owned_proxy(
+ base,
+ directory,
+ {
+ "HTTPS_PROXY": tunnel.url,
+ "NO_PROXY": "127.0.0.1,localhost",
+ "AIOHTTP_TRUST_ENV": "True",
+ "SSL_VERIFY": "False",
+ "LITELLM_LOCAL_MODEL_COST_MAP": "True",
+ "OPENAI_API_KEY": "sk-scripted-openai",
+ "GEMINI_API_KEY": "scripted-gemini-key",
+ },
+ config=_config(directory, base.upstream_url.rstrip("/")),
+ workers=2,
+ ) as proxy,
+ ):
+ yield _Rig(proxy, upstream)
+
+
+def _gateway_config(directory: Path, upstream_url: str) -> Path:
+ base: Final = _JSON_OBJECT.validate_python(yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text()))
+ general_settings: Final = base.get("general_settings")
+ assert isinstance(general_settings, dict), base
+ configured_endpoint: Final = {
+ "path": _CONFIGURED_GATEWAY_PATH,
+ "target": f"{upstream_url}/egress",
+ "include_subpath": True,
+ "auth": True,
+ }
+ path: Final = directory / "config.yaml"
+ path.write_text(
+ yaml.safe_dump(
+ {**base, "general_settings": {**general_settings, "pass_through_endpoints": [configured_endpoint]}}
+ )
+ )
+ return path
+
+
[email protected](scope="module")
+def gateway_rig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[_Rig]:
+ directory: Final = tmp_path_factory.mktemp("passthrough-google-gateway")
+ with (
+ wire_server(_gemini_reply) as upstream,
+ gateway_from_environment() as base,
+ owned_proxy(
+ base,
+ directory,
+ {
+ "GEMINI_API_BASE": f"{upstream.url}/google",
+ "GEMINI_API_KEY": "scripted-gemini-key",
+ "LITELLM_LOCAL_MODEL_COST_MAP": "True",
+ },
+ config=_gateway_config(directory, upstream.url),
+ workers=2,
+ ) as proxy,
+ ):
+ yield _Rig(proxy, upstream)
+
+
+def _spend_row(key: str) -> dict[str, JsonValue]:
+ rows: Final = eventually(
+ lambda: read_rows(
+ 'SELECT spend, custom_llm_provider FROM "LiteLLM_SpendLogs" WHERE api_key=%s',
+ (sha256(key.encode()).hexdigest(),),
+ ),
+ lambda found: len(found) == 1,
+ seconds=70,
+ )
+ return rows[0]
+
+
+def _spend_for_key(key: str) -> float:
+ spend: Final = _spend_row(key)["spend"]
+ assert isinstance(spend, float), key
+ return spend
+
+
+def _provider_for_key(key: str) -> JsonValue:
+ return _spend_row(key)["custom_llm_provider"]
+
+
+def _post_and_read(rig: _Rig, path: str, body: Mapping[str, JsonValue], headers: Mapping[str, str]) -> None:
+ with rig.proxy.client.stream("POST", path, json=body, headers=dict(headers)) as response:
+ payload: Final = response.read()
+ assert response.status_code == 200, payload
+
+
+def _claude_path(location: str, action: str) -> str:
+ return (
+ f"/vertex_ai/v1/projects/{_PROJECT}/locations/{location}/publishers/anthropic/models/"
+ f"{_CLAUDE_ROUTE_MODEL}:{action}"
+ )
+
+
+def test_claude_on_vertex_passthrough_spend_carries_the_regional_uplift_whether_or_not_the_call_streams(
+ rig: _Rig,
+) -> None:
+ body: Final[Mapping[str, JsonValue]] = {
+ "anthropic_version": "vertex-2023-10-16",
+ "max_tokens": 64,
+ "messages": [{"role": "user", "content": "hi"}],
+ }
+ cells: Final = (
+ ("global", "rawPredict"),
+ ("global", "streamRawPredict"),
+ ("us-east5", "rawPredict"),
+ ("us-east5", "streamRawPredict"),
+ )
+ with rig.proxy.scenario() as scenario:
+ keys: Final = {cell: scenario.key() for cell in cells}
+ for (location, action), key in keys.items():
+ _post_and_read(
+ rig,
+ _claude_path(location, action),
+ {**body, "stream": action == "streamRawPredict"},
+ {"x-litellm-api-key": f"Bearer {key}", "Authorization": f"Bearer {_CALLER_GOOGLE_TOKEN}"},
+ )
+ spend: Final = {cell: _spend_for_key(key) for cell, key in keys.items()}
+ standard: Final = _list_price(f"vertex_ai/{_CLAUDE_ROUTE_MODEL}")
+ regional: Final = standard * _uplift(f"vertex_ai/{_CLAUDE_ROUTE_MODEL}")
+ assert spend == pytest.approx(
+ {
+ ("global", "rawPredict"): standard,
+ ("global", "streamRawPredict"): standard,
+ ("us-east5", "rawPredict"): regional,
+ ("us-east5", "streamRawPredict"): regional,
+ }
+ )
+
+
+def test_v1beta_generate_content_on_a_vertex_deployment_bills_the_deployment_location_in_both_modes(
+ rig: _Rig,
+) -> None:
+ body: Final[Mapping[str, JsonValue]] = {"contents": [{"role": "user", "parts": [{"text": "hi"}]}]}
+ actions: Final = ("generateContent", "streamGenerateContent?alt=sse")
+ cells: Final = tuple((deployment, action) for deployment in _DEPLOYMENT_LOCATIONS for action in actions)
+ with rig.proxy.scenario() as scenario:
+ keys: Final = {cell: scenario.key() for cell in cells}
+ for (deployment, action), key in keys.items():
+ _post_and_read(rig, f"/v1beta/models/{deployment}:{action}", body, {"x-goog-api-key": key})
+ spend: Final = {cell: _spend_for_key(key) for cell, key in keys.items()}
+ standard: Final = _list_price(f"vertex_ai/{_GEMINI}")
+ regional: Final = standard * _uplift(f"vertex_ai/{_GEMINI}")
+ assert spend == pytest.approx(
+ {
+ ("audit-vertex-global", "generateContent"): standard,
+ ("audit-vertex-global", "streamGenerateContent?alt=sse"): standard,
+ ("audit-vertex-us", "generateContent"): regional,
+ ("audit-vertex-us", "streamGenerateContent?alt=sse"): regional,
+ }
+ )
+
+
+def test_gemini_passthrough_bills_a_named_custom_priced_deployment_only_for_keys_that_allow_it_in_both_modes(
+ rig: _Rig,
+) -> None:
+ body: Final[Mapping[str, JsonValue]] = {
+ "contents": [{"role": "user", "parts": [{"text": "hi"}]}],
+ "metadata": {
+ "model_info": {
+ "id": _CUSTOM_PRICED_GEMINI_ID,
+ "input_cost_per_token": _CUSTOM_INPUT_RATE,
+ "output_cost_per_token": _CUSTOM_OUTPUT_RATE,
+ }
+ },
+ }
+ actions: Final = ("generateContent", "streamGenerateContent?alt=sse")
+ with rig.proxy.scenario() as scenario:
+ allowed: Final = {action: scenario.key(metadata={"allow_client_pricing_override": True}) for action in actions}
+ plain: Final = {action: scenario.key() for action in actions}
+ for action in actions:
+ for key in (allowed[action], plain[action]):
+ _post_and_read(rig, f"/gemini/v1beta/models/{_GEMINI}:{action}", body, {"x-goog-api-key": key})
+ spend: Final = {
+ **{("allowed", action): _spend_for_key(key) for action, key in allowed.items()},
+ **{("plain", action): _spend_for_key(key) for action, key in plain.items()},
+ }
+ custom_price: Final = _PROMPT_TOKENS * _CUSTOM_INPUT_RATE + _COMPLETION_TOKENS * _CUSTOM_OUTPUT_RATE
+ list_price: Final = _list_price(f"gemini/{_GEMINI}")
+ assert spend == pytest.approx(
+ {
+ ("allowed", "generateContent"): custom_price,
+ ("allowed", "streamGenerateContent?alt=sse"): custom_price,
+ ("plain", "generateContent"): list_price,
+ ("plain", "streamGenerateContent?alt=sse"): list_price,
+ }
+ )
+
+
+def test_openai_passthrough_stream_cut_off_after_its_usage_bills_what_the_finished_stream_bills(rig: _Rig) -> None:
+ def body(prompt: str) -> Mapping[str, JsonValue]:
+ return {
+ "model": _OPENAI_MODEL,
+ "stream": True,
+ "stream_options": {"include_usage": True},
+ "messages": [{"role": "user", "content": prompt}],
+ }
+
+ with rig.proxy.scenario() as scenario:
+ finished_key: Final = scenario.key()
+ cut_key: Final = scenario.key()
+ _post_and_read(rig, "/openai/v1/chat/completions", body("hi"), {"Authorization": f"Bearer {finished_key}"})
+ with rig.proxy.client.stream(
+ "POST",
+ "/openai/v1/chat/completions",
+ json=dict(body(_CUT_MARKER)),
+ headers={"Authorization": f"Bearer {cut_key}"},
+ ) as response:
+ assert response.status_code == 200
+ with pytest.raises(httpx.RemoteProtocolError):
+ response.read()
+ spend: Final = {"finished": _spend_for_key(finished_key), "cut off": _spend_for_key(cut_key)}
+ list_price: Final = _list_price(_OPENAI_MODEL)
+ assert spend == pytest.approx({"finished": list_price, "cut off": list_price})
+
+
+def _caller_headers(route: str, key: str) -> Mapping[str, str]:
+ if route == "vertex_ai":
+ return {"x-litellm-api-key": f"Bearer {key}", "Authorization": f"Bearer {_CALLER_GOOGLE_TOKEN}"}
+ return {"x-goog-api-key": key}
+
+
+def test_a_body_base_model_reprices_passthrough_spend_only_for_keys_that_allow_client_pricing(rig: _Rig) -> None:
+ routes: Final = MappingProxyType(
+ {
+ "vertex_ai": (
+ f"/vertex_ai/v1/projects/{_PROJECT}/locations/global/publishers/google/models/{_GEMINI}",
+ "gemini-2.5-flash-lite",
+ ),
+ "gemini": (f"/gemini/v1beta/models/{_GEMINI}", "gemini/gemini-2.5-flash-lite"),
+ }
+ )
+ cells: Final = tuple(
+ (route, action, grant) for route in routes for action in _GEMINI_ACTIONS for grant in ("allowed", "plain")
+ )
+ markers: Final = {cell: uuid.uuid4().hex for cell in cells}
+ with rig.proxy.scenario() as scenario:
+ keys: Final = {
+ cell: scenario.key(metadata={"allow_client_pricing_override": True})
+ if cell[2] == "allowed"
+ else scenario.key()
+ for cell in cells
+ }
+ for (route, action, grant), key in keys.items():
+ path, base_model = routes[route]
+ _post_and_read(
+ rig,
+ f"{path}:{action}",
+ {
+ "contents": [{"role": "user", "parts": [{"text": markers[(route, action, grant)]}]}],
+ "base_model": base_model,
+ },
+ _caller_headers(route, key),
+ )
+ spend: Final = {cell: _spend_for_key(key) for cell, key in keys.items()}
+ forwarded: Final = rig.upstream.drain()
+ marked_bodies: Final = {
+ cell: tuple(request.body for request in forwarded if marker.encode() in request.body)
+ for cell, marker in markers.items()
+ }
+ assert all(len(bodies) == 1 and b"base_model" not in bodies[0] for bodies in marked_bodies.values()), marked_bodies
+ expected_price: Final = {
+ "vertex_ai": {"allowed": _list_price("gemini-2.5-flash-lite"), "plain": _list_price(f"vertex_ai/{_GEMINI}")},
+ "gemini": {"allowed": _list_price("gemini/gemini-2.5-flash-lite"), "plain": _list_price(f"gemini/{_GEMINI}")},
+ }
+ assert spend == pytest.approx({cell: expected_price[cell[0]][cell[2]] for cell in cells})
+
+
+def test_a_non_string_body_base_model_bills_the_list_price_instead_of_nothing(rig: _Rig) -> None:
+ routes: Final = MappingProxyType(
+ {
+ "vertex_ai": f"/vertex_ai/v1/projects/{_PROJECT}/locations/global/publishers/google/models/{_GEMINI}",
+ "gemini": f"/gemini/v1beta/models/{_GEMINI}",
+ "v1beta": "/v1beta/models/audit-vertex-global",
+ }
+ )
+ cells: Final = tuple((route, action) for route in routes for action in _GEMINI_ACTIONS)
+ with rig.proxy.scenario() as scenario:
+ keys: Final = {
+ cell: scenario.key()
+ if cell[0] == "v1beta"
+ else scenario.key(metadata={"allow_client_pricing_override": True})
+ for cell in cells
+ }
+ for (route, action), key in keys.items():
+ _post_and_read(
+ rig,
+ f"{routes[route]}:{action}",
+ {"contents": [{"role": "user", "parts": [{"text": uuid.uuid4().hex}]}], "base_model": 123},
+ _caller_headers(route, key),
+ )
+ spend: Final = {cell: _spend_for_key(key) for cell, key in keys.items()}
+ list_price: Final = {
+ "vertex_ai": _list_price(f"vertex_ai/{_GEMINI}"),
+ "gemini": _list_price(f"gemini/{_GEMINI}"),
+ "v1beta": _list_price(f"vertex_ai/{_GEMINI}"),
+ }
+ assert spend == pytest.approx({cell: list_price[cell[0]] for cell in cells})
+
+
+def test_gemini_passthrough_through_a_gemini_api_base_gateway_logs_and_bills_as_gemini_in_both_modes(
+ gateway_rig: _Rig,
+) -> None:
+ body: Final[Mapping[str, JsonValue]] = {"contents": [{"role": "user", "parts": [{"text": "hi"}]}]}
+ with gateway_rig.proxy.scenario() as scenario:
+ keys: Final = {action: scenario.key() for action in _GEMINI_ACTIONS}
+ for action, key in keys.items():
+ _post_and_read(gateway_rig, f"/gemini/v1beta/models/{_GEMINI}:{action}", body, {"x-goog-api-key": key})
+ providers: Final = {action: _provider_for_key(key) for action, key in keys.items()}
+ spend: Final = {action: _spend_for_key(key) for action, key in keys.items()}
+ forwarded: Final = tuple(
+ path
+ for path in (urlsplit(request.target).path for request in gateway_rig.upstream.drain())
+ if path.startswith("/google/")
+ )
+ assert sorted(forwarded) == sorted(
+ f"/google/v1beta/models/{_GEMINI}:{action.split('?')[0]}" for action in _GEMINI_ACTIONS
+ )
+ assert providers == {action: "gemini" for action in _GEMINI_ACTIONS}
+ assert spend == pytest.approx({action: _list_price(f"gemini/{_GEMINI}") for action in _GEMINI_ACTIONS})
+
+
+def test_a_configured_passthrough_to_a_non_google_gateway_bills_as_vertex_whatever_the_path(gateway_rig: _Rig) -> None:
+ body: Final[Mapping[str, JsonValue]] = {"contents": [{"role": "user", "parts": [{"text": "hi"}]}]}
+ routes: Final = MappingProxyType(
+ {
+ "vertex resource": f"/v1/projects/{_PROJECT}/locations/us/publishers/google/models/{_GEMINI}",
+ "short gateway path": f"/vx/models/{_GEMINI}",
+ }
+ )
+ cells: Final = tuple((route, action) for route in routes for action in _GEMINI_ACTIONS)
+ with gateway_rig.proxy.scenario() as scenario:
+ keys: Final = {cell: scenario.key(allowed_passthrough_routes=[_CONFIGURED_GATEWAY_PATH]) for cell in cells}
+ for (route, action), key in keys.items():
+ _post_and_read(
+ gateway_rig,
+ f"{_CONFIGURED_GATEWAY_PATH}{routes[route]}:{action}",
+ body,
+ {"Authorization": f"Bearer {key}"},
+ )
+ providers: Final = {cell: _provider_for_key(key) for cell, key in keys.items()}
+ spend: Final = {cell: _spend_for_key(key) for cell, key in keys.items()}
+ short_path_spend: Final = {action: spend[("short gateway path", action)] for action in _GEMINI_ACTIONS}
+ assert providers == {cell: "vertex_ai" for cell in cells}
+ assert {action: spend[("vertex resource", action)] for action in _GEMINI_ACTIONS} == pytest.approx(
+ {action: _list_price(f"vertex_ai/{_GEMINI}") * _uplift(f"vertex_ai/{_GEMINI}") for action in _GEMINI_ACTIONS}
+ )
+ assert min(short_path_spend.values()) > 0
+ assert short_path_spend == pytest.approx(
+ {action: short_path_spend[_GEMINI_ACTIONS[0]] for action in _GEMINI_ACTIONS}
+ )
diff --git a/tests/integration/spend/test_vertex_passthrough_regional_uplift_spend.py b/tests/integration/spend/test_vertex_passthrough_regional_uplift_spend.py
new file mode 100644
index 00000000000..eaa8f52d4f4
--- /dev/null
+++ b/tests/integration/spend/test_vertex_passthrough_regional_uplift_spend.py
@@ -0,0 +1,200 @@
+import itertools
+import json
+from collections.abc import Iterator, Mapping
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Final
+from urllib.parse import urlsplit
+
+import httpx
+import pytest
+import yaml
+from integration._support.client import Gateway, eventually, gateway_from_environment
+from integration._support.database import read_rows
+from integration._support.forward_proxy import ForwardProxy, tunnelling_forward_proxy
+from integration._support.process import graceful_stop_seconds, owned_proxy
+from integration._support.tls import server_context, write_self_signed_cert
+from integration._support.vertex import service_account_json
+from integration._support.wire import Reply, Request, wire_server
+from pydantic import JsonValue, TypeAdapter
+
+pytestmark: Final = pytest.mark.timeout(2 * graceful_stop_seconds() + 120)
+
+_MODEL: Final = "gemini-3.5-flash-lite"
+_PROJECT: Final = "caller-project"
+_CALLER_GOOGLE_TOKEN: Final = "caller-google-token"
+_GLOBAL_HOST: Final = "aiplatform.googleapis.com"
+_US_HOST: Final = "aiplatform.us.rep.googleapis.com"
+_GENERATE: Final = "generateContent"
+_STREAM: Final = "streamGenerateContent?alt=sse"
+_LOCATIONS: Final = ("global", "us")
+_ACTIONS: Final = (_GENERATE, _STREAM)
+_COST_MAP: Final = Path("litellm/model_prices_and_context_window_backup.json")
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+_BODY: Final[Mapping[str, JsonValue]] = {"contents": [{"role": "user", "parts": [{"text": "hi"}]}]}
+_CUT_PROMPT: Final = "end this stream early"
+_CUT_BODY: Final[Mapping[str, JsonValue]] = {"contents": [{"role": "user", "parts": [{"text": _CUT_PROMPT}]}]}
+_PROMPT_TOKENS: Final = 1200
+_COMPLETION_TOKENS: Final = 300
+_USAGE: Final = {
+ "promptTokenCount": _PROMPT_TOKENS,
+ "candidatesTokenCount": _COMPLETION_TOKENS,
+ "totalTokenCount": _PROMPT_TOKENS + _COMPLETION_TOKENS,
+}
+_REPLY: Final = json.dumps(
+ {
+ "candidates": [{"content": {"role": "model", "parts": [{"text": "scripted"}]}, "finishReason": "STOP"}],
+ "usageMetadata": _USAGE,
+ "modelVersion": _MODEL,
+ "responseId": "scripted-response",
+ }
+)
+_UNFINISHED_FRAME: Final = json.dumps(
+ {
+ "candidates": [{"content": {"role": "model", "parts": [{"text": "scripted"}]}}],
+ "usageMetadata": _USAGE,
+ "modelVersion": _MODEL,
+ "responseId": "scripted-cut-response",
+ }
+)
+_CUSTOM_DEPLOYMENT: Final = "vertex-custom-priced"
+_CUSTOM_INPUT_RATE: Final = 1e-06
+_CUSTOM_OUTPUT_RATE: Final = 2e-06
+
+
+@dataclass(frozen=True, slots=True)
+class _Rig:
+ proxy: Gateway
+ tunnel: ForwardProxy
+
+
+def _vertex(request: Request) -> Reply:
+ assert f"/v1/projects/{_PROJECT}/locations/" in request.target, request.target
+ if _CUT_PROMPT.encode() in request.body:
+ frame: Final = f"data: {_UNFINISHED_FRAME}\r\n\r\n".encode()
+ return Reply(chunks=(frame, frame), content_type="text/event-stream", abort_after=1)
+ if ":streamGenerateContent" in request.target:
+ return Reply(chunks=(f"data: {_REPLY}\r\n\r\n".encode(),), content_type="text/event-stream")
+ return Reply(body=_REPLY.encode())
+
+
+def _port(url: str) -> int:
+ port: Final = urlsplit(url).port
+ assert port is not None, url
+ return port
+
+
+def _uplift() -> float:
+ row: Final = _JSON_OBJECT.validate_python(_JSON_OBJECT.validate_json(_COST_MAP.read_bytes())[f"vertex_ai/{_MODEL}"])
+ multiplier: Final = row.get("regional_endpoint_uplift_multiplier")
+ assert isinstance(multiplier, int | float) and multiplier > 1, row
+ return float(multiplier)
+
+
+def _config_with_custom_priced_deployment(directory: Path, token_url: str) -> Path:
+ base: Final = _JSON_OBJECT.validate_python(yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text()))
+ existing: Final = base.get("model_list") or []
+ assert isinstance(existing, list), base
+ deployment: Final = {
+ "model_name": _CUSTOM_DEPLOYMENT,
+ "litellm_params": {
+ "model": f"vertex_ai/{_MODEL}",
+ "vertex_project": _PROJECT,
+ "vertex_location": "us",
+ "vertex_credentials": service_account_json(_PROJECT, token_url),
+ "use_in_pass_through": True,
+ "input_cost_per_token": _CUSTOM_INPUT_RATE,
+ "output_cost_per_token": _CUSTOM_OUTPUT_RATE,
+ },
+ }
+ path: Final = directory / "config.yaml"
+ path.write_text(yaml.safe_dump({**base, "model_list": [*existing, deployment]}))
+ return path
+
+
[email protected](scope="module")
+def rig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[_Rig]:
+ directory: Final = tmp_path_factory.mktemp("vertex-passthrough-uplift")
+ certificate: Final = write_self_signed_cert(directory, (_GLOBAL_HOST, _US_HOST))
+ with (
+ wire_server(_vertex, tls=server_context(*certificate)) as vertex,
+ tunnelling_forward_proxy(_port(vertex.url)) as tunnel,
+ gateway_from_environment() as base,
+ owned_proxy(
+ base,
+ directory,
+ {
+ "HTTPS_PROXY": tunnel.url,
+ "NO_PROXY": "127.0.0.1,localhost",
+ "AIOHTTP_TRUST_ENV": "True",
+ "SSL_VERIFY": "False",
+ "LITELLM_LOCAL_MODEL_COST_MAP": "True",
+ },
+ config=_config_with_custom_priced_deployment(directory, base.upstream_url.rstrip("/")),
+ workers=2,
+ ) as proxy,
+ ):
+ yield _Rig(proxy, tunnel)
+
+
+def _path(location: str, model: str, action: str) -> str:
+ return f"/vertex_ai/v1/projects/{_PROJECT}/locations/{location}/publishers/google/models/{model}:{action}"
+
+
+def _headers(key: str) -> dict[str, str]:
+ return {"x-litellm-api-key": f"Bearer {key}", "Authorization": f"Bearer {_CALLER_GOOGLE_TOKEN}"}
+
+
+def _spend(rig: _Rig, key: str, location: str, action: str, model: str = _MODEL) -> float:
+ with rig.proxy.client.stream("POST", _path(location, model, action), json=_BODY, headers=_headers(key)) as response:
+ body: Final = response.read()
+ assert response.status_code == 200, body
+ call_id: Final = response.headers["x-litellm-call-id"]
+ return _logged_spend(call_id)
+
+
+def _logged_spend(call_id: str) -> float:
+ rows: Final = eventually(
+ lambda: read_rows('SELECT spend FROM "LiteLLM_SpendLogs" WHERE request_id=%s', (call_id,)),
+ lambda found: len(found) == 1,
+ seconds=70,
+ )
+ spend: Final = rows[0]["spend"]
+ assert isinstance(spend, float), rows
+ return spend
+
+
+def test_vertex_passthrough_spend_carries_the_regional_uplift_whether_or_not_the_call_streams(rig: _Rig) -> None:
+ with rig.proxy.scenario() as scenario:
+ key: Final = scenario.key()
+ spend: Final = {cell: _spend(rig, key, *cell) for cell in itertools.product(_LOCATIONS, _ACTIONS)}
+ standard: Final = spend[("global", _GENERATE)]
+ regional: Final = standard * _uplift()
+ assert standard > 0, spend
+ assert spend == pytest.approx(
+ {
+ ("global", _GENERATE): standard,
+ ("global", _STREAM): standard,
+ ("us", _GENERATE): regional,
+ ("us", _STREAM): regional,
+ }
+ )
+ assert set(rig.tunnel.targets()) == {f"{_GLOBAL_HOST}:443", f"{_US_HOST}:443"}
+
+
+def test_custom_priced_vertex_passthrough_bills_the_deployment_price_even_when_the_stream_is_cut_off(rig: _Rig) -> None:
+ with rig.proxy.scenario() as scenario:
+ key: Final = scenario.key()
+ finished: Final = {action: _spend(rig, key, "us", action, _CUSTOM_DEPLOYMENT) for action in _ACTIONS}
+ with rig.proxy.client.stream(
+ "POST", _path("us", _CUSTOM_DEPLOYMENT, _STREAM), json=_CUT_BODY, headers=_headers(key)
+ ) as response:
+ assert response.status_code == 200
+ call_id: Final = response.headers["x-litellm-call-id"]
+ with pytest.raises(httpx.RemoteProtocolError):
+ response.read()
+ cut_off: Final = _logged_spend(call_id)
+ custom_price: Final = _PROMPT_TOKENS * _CUSTOM_INPUT_RATE + _COMPLETION_TOKENS * _CUSTOM_OUTPUT_RATE
+ assert {**finished, "cut off": cut_off} == pytest.approx(
+ {_GENERATE: custom_price, _STREAM: custom_price, "cut off": custom_price}
+ )
diff --git a/tests/unit/google_genai/test_google_genai_main.py b/tests/unit/google_genai/test_google_genai_main.py
index 21f42ca2dff..5cac61e727e 100644
--- a/tests/unit/google_genai/test_google_genai_main.py
+++ b/tests/unit/google_genai/test_google_genai_main.py
@@ -4,6 +4,8 @@ Test to verify the Google GenAI generate_content adapter functionality
"""
import json
+from collections.abc import Iterator
+from typing import Final
import pytest
@@ -286,3 +288,97 @@ def test_vertex_generate_content_routes_by_deployment_base_model(base_model, use
)
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
+
+
+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"]
+
+
[email protected]("stream", [True, False], ids=["streamed", "non-streamed"])
[email protected]("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)
diff --git a/tests/unit/litellm_core_utils/test_get_litellm_params.py b/tests/unit/litellm_core_utils/test_get_litellm_params.py
index f21e475fd16..251bfa624a5 100644
--- a/tests/unit/litellm_core_utils/test_get_litellm_params.py
+++ b/tests/unit/litellm_core_utils/test_get_litellm_params.py
@@ -6,9 +6,12 @@ Ensures backward compatibility after sparse kwargs extraction optimization.
from typing import Final
+import httpx
import pytest
+from openai import OpenAI
from pydantic import ValidationError
+import litellm
from litellm.constants import CONTROL_OPTIONS_KEY
from litellm.litellm_core_utils.get_litellm_params import (
_OPTIONAL_KWARGS_KEYS,
@@ -75,10 +78,39 @@ class TestGetBaseModelFromLitellmCallMetadata:
)
assert result == "gpt-4"
- def test_returns_non_string_base_model_without_filtering(self):
- result = get_base_model_from_litellm_call_metadata({"model_info": {"base_model": 123}})
+ @pytest.mark.parametrize(
+ "model_info",
+ [{"base_model": 123}, {"base_model": ["gpt-4"]}, {"base_model": {"model": "gpt-4"}}],
+ )
+ def test_ignores_a_non_string_base_model(self, model_info: object):
+ assert get_base_model_from_litellm_call_metadata({"model_info": model_info}) is None
+
+
[email protected]("model_info", ["malformed", ["malformed"], 123])
+def test_a_call_with_a_non_object_model_info_fails_before_reaching_the_provider(model_info: object) -> None:
+ sent: Final[list[httpx.Request]] = [] # mutable-ok: the transport records each outbound request
+
+ def record(request: httpx.Request) -> httpx.Response:
+ sent.append(request)
+ return httpx.Response(500)
+
+ client: Final = OpenAI(
+ api_key="sk-test",
+ base_url="https://api.openai.test/v1",
+ http_client=httpx.Client(transport=httpx.MockTransport(record)),
+ max_retries=0,
+ )
+
+ with pytest.raises(AttributeError):
+ litellm.completion(
+ model="openai/gpt-5.4-mini",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"model_info": model_info},
+ client=client,
+ num_retries=0,
+ )
- assert result == 123
+ assert sent == []
class TestGetLitellmParamsKwargsExtraction:
diff --git a/tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_gemini_passthrough_logging_handler.py b/tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_gemini_passthrough_logging_handler.py
index c30f6d9f15a..f780c056f64 100644
--- a/tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_gemini_passthrough_logging_handler.py
+++ b/tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_gemini_passthrough_logging_handler.py
@@ -1,4 +1,6 @@
+import asyncio
import json
+from collections.abc import Iterator
from datetime import datetime
from typing import Final
from unittest.mock import AsyncMock, MagicMock, patch
@@ -11,6 +13,8 @@ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLogging
from litellm.proxy.pass_through_endpoints.llm_provider_handlers.gemini_passthrough_logging_handler import (
GeminiPassthroughLoggingHandler,
)
+from litellm.proxy.pass_through_endpoints.pass_through_endpoints import HttpPassThroughEndpointHelpers
+from litellm.proxy.pass_through_endpoints.streaming_handler import PassThroughStreamingHandler
from litellm.proxy.pass_through_endpoints.success_handler import (
PassThroughEndpointLogging,
)
@@ -186,7 +190,6 @@ class TestGeminiPassthroughLoggingHandler:
mock_completion_cost.assert_called_once()
# Verify logging object was updated
- assert mock_logging_obj.model_call_details["response_cost"] == 0.000045
assert mock_logging_obj.model_call_details["model"] == "gemini-1.5-flash"
assert mock_logging_obj.model_call_details["custom_llm_provider"] == "gemini"
@@ -310,8 +313,6 @@ class TestGeminiPassthroughLoggingHandler:
# Assert - The success handler returns None on success (following the pattern from other tests)
assert result is None
- # Verify that the logging object has the cost set (from Gemini handler)
- assert mock_logging_obj.model_call_details["response_cost"] == 0.000050
assert mock_logging_obj.model_call_details["model"] == "gemini-2.0-flash"
assert mock_logging_obj.model_call_details["custom_llm_provider"] == "gemini"
@@ -479,3 +480,114 @@ def test_build_complete_streaming_response_assembles_gemini_sse_chunks():
assert response.choices[0].message.content == "Hello there!"
assert response.choices[0].finish_reason == "stop"
assert (response.usage.prompt_tokens, response.usage.completion_tokens, response.usage.total_tokens) == (10, 8, 18)
+
+
+_PROBE_MODEL: Final = "gemini-pricing-probe"
+_LIST_INPUT_RATE: Final = 1e-06
+_LIST_OUTPUT_RATE: Final = 4e-06
+_CUSTOM_RATES: Final = {"input_cost_per_token": 2e-09, "output_cost_per_token": 3e-09}
+_CUSTOM_PRICED_DEPLOYMENT: Final = "gemini-custom-priced-deployment"
+_PROBE_REPLY: Final = {
+ "candidates": [{"content": {"parts": [{"text": "pong"}], "role": "model"}, "finishReason": "STOP", "index": 0}],
+ "usageMetadata": {"promptTokenCount": 7, "candidatesTokenCount": 1, "totalTokenCount": 8},
+ "modelVersion": _PROBE_MODEL,
+}
+
+
+def probe_rate_card(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
+ rates: Final = {
+ "input_cost_per_token": _LIST_INPUT_RATE,
+ "output_cost_per_token": _LIST_OUTPUT_RATE,
+ "litellm_provider": "gemini",
+ "mode": "chat",
+ }
+ monkeypatch.setitem(litellm.model_cost, f"gemini/{_PROBE_MODEL}", rates)
+ monkeypatch.setitem(
+ litellm.model_cost, _CUSTOM_PRICED_DEPLOYMENT, {**_CUSTOM_RATES, "litellm_provider": "gemini", "mode": "chat"}
+ )
+ litellm.get_model_info.cache_clear()
+ yield
+ litellm.get_model_info.cache_clear()
+
+
+def _cost_the_logger_records_for_gemini(*, stream: bool, model_info: dict[str, object] | None) -> float:
+ method: Final = "streamGenerateContent?alt=sse" if stream else "generateContent"
+ url_route: Final = f"https://generativelanguage.googleapis.com/v1beta/models/{_PROBE_MODEL}:{method}"
+ logging_obj: Final = LiteLLMLoggingObj(
+ model="unknown",
+ messages=[{"role": "user", "content": "ping"}],
+ stream=stream,
+ call_type="pass_through_endpoint",
+ start_time=datetime(2026, 1, 1),
+ litellm_call_id="call-1",
+ function_id="fn-1",
+ )
+ logging_obj.update_environment_variables(
+ litellm_params={"metadata": {"model_info": model_info}} if model_info is not None else {}, optional_params={}
+ )
+ if stream:
+ asyncio.run(
+ PassThroughStreamingHandler.route_streaming_logging_to_handler(
+ litellm_logging_obj=logging_obj,
+ passthrough_success_handler_obj=PassThroughEndpointLogging(),
+ url_route=url_route,
+ request_body={},
+ endpoint_type=HttpPassThroughEndpointHelpers.get_endpoint_type(url_route),
+ start_time=datetime(2026, 1, 1),
+ raw_bytes=[f"data: {json.dumps(_PROBE_REPLY)}\n\n".encode()],
+ end_time=datetime(2026, 1, 1),
+ )
+ )
+ return logging_obj.model_call_details["response_cost"]
+ response: Final = httpx.Response(200, json=_PROBE_REPLY)
+ result: Final = GeminiPassthroughLoggingHandler.gemini_passthrough_handler(
+ httpx_response=response,
+ response_body=_PROBE_REPLY,
+ logging_obj=logging_obj,
+ url_route=url_route,
+ result=response.text,
+ start_time=datetime(2026, 1, 1),
+ end_time=datetime(2026, 1, 1),
+ cache_hit=False,
+ request_body={},
+ )
+ logging_obj._process_hidden_params_and_response_cost(
+ result["result"], datetime(2026, 1, 1), datetime(2026, 1, 1), build_logging_payload=False
+ )
+ return logging_obj.model_call_details["response_cost"]
+
+
[email protected]("stream", [True, False], ids=["streamed", "non-streamed"])
+ "model_info, input_rate, output_rate",
+ [
+ (None, _LIST_INPUT_RATE, _LIST_OUTPUT_RATE),
+ (
+ {"id": _CUSTOM_PRICED_DEPLOYMENT, **_CUSTOM_RATES},
+ _CUSTOM_RATES["input_cost_per_token"],
+ _CUSTOM_RATES["output_cost_per_token"],
+ ),
+ ],
+ ids=["list-price", "custom-price"],
+)
+def test_gemini_passthrough_spend_matches_whether_or_not_the_call_streams(
+ probe_rate_card: None,
+ stream: bool,
+ model_info: dict[str, object] | None,
+ input_rate: float,
+ output_rate: float,
+) -> None:
+ recorded: Final = _cost_the_logger_records_for_gemini(stream=stream, model_info=model_info)
+
+ assert recorded == pytest.approx(7 * input_rate + 1 * output_rate), stream
+
+
[email protected]("stream", [True, False], ids=["streamed", "non-streamed"])
[email protected]("base_model", [123, [f"gemini/{_PROBE_MODEL}"], {"model": f"gemini/{_PROBE_MODEL}"}])
+def test_gemini_passthrough_bills_the_list_price_when_the_model_info_base_model_is_not_a_string(
+ probe_rate_card: None, stream: bool, base_model: object
+) -> None:
+ recorded: Final = _cost_the_logger_records_for_gemini(stream=stream, model_info={"base_model": base_model})
+
+ assert recorded == pytest.approx(7 * _LIST_INPUT_RATE + 1 * _LIST_OUTPUT_RATE), stream
diff --git a/tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_vertex_passthrough_logging_handler.py b/tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_vertex_passthrough_logging_handler.py
index cc1246f4ede..d05ab8a9bcf 100644
--- a/tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_vertex_passthrough_logging_handler.py
+++ b/tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_vertex_passthrough_logging_handler.py
@@ -1,4 +1,6 @@
+import asyncio
import json
+from collections.abc import Iterator
from datetime import datetime
from typing import Final
@@ -6,11 +8,15 @@ import httpx
import pytest
from pydantic import ValidationError
+import litellm
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.proxy._types import PassThroughEndpointLoggingTypedDict
from litellm.proxy.pass_through_endpoints.llm_provider_handlers.vertex_passthrough_logging_handler import (
VertexPassthroughLoggingHandler,
)
+from litellm.proxy.pass_through_endpoints.streaming_handler import PassThroughStreamingHandler
+from litellm.proxy.pass_through_endpoints.success_handler import PassThroughEndpointLogging
+from litellm.types.passthrough_endpoints.pass_through_endpoints import EndpointType
from litellm.types.utils import EmbeddingResponse, ModelResponse
_PREDICT_ROUTE = "/v1/projects/p/locations/us-central1/publishers/google/models/text-embedding-004:predict"
@@ -97,6 +103,359 @@ def test_interactions_usage_object_is_read_into_prompt_and_completion_tokens():
assert result["kwargs"]["custom_llm_provider"] == "vertex_ai"
+_UPLIFT_MODEL: Final = "gemini-regional-uplift-probe"
+_UPLIFT_INPUT_RATE: Final = 1e-06
+_UPLIFT_OUTPUT_RATE: Final = 4e-06
+_UPLIFT_MULTIPLIER: Final = 1.1
+
+
+def 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,
+ "litellm_provider": "vertex_ai-language-models",
+ "mode": "chat",
+ }
+ monkeypatch.setitem(litellm.model_cost, _UPLIFT_MODEL, rates)
+ monkeypatch.setattr(litellm, "vertex_language_models", {*litellm.vertex_language_models, _UPLIFT_MODEL})
+ monkeypatch.setitem(
+ litellm.model_cost,
+ f"vertex_ai/{_UPLIFT_MODEL}",
+ {**rates, "regional_endpoint_uplift_multiplier": _UPLIFT_MULTIPLIER},
+ )
+ litellm.get_model_info.cache_clear()
+ yield
+ litellm.get_model_info.cache_clear()
+
+
+def _generate_content_payload() -> dict[str, object]:
+ return {
+ "candidates": [{"content": {"parts": [{"text": "pong"}], "role": "model"}, "finishReason": "STOP", "index": 0}],
+ "usageMetadata": {"promptTokenCount": 7, "candidatesTokenCount": 1, "totalTokenCount": 8},
+ "modelVersion": _UPLIFT_MODEL,
+ }
+
+
+def _cost_the_logger_records_for(
+ url_route: str,
+ *,
+ stream: bool,
+ reply: dict[str, object],
+ stream_events: list[dict[str, object]],
+ model_info: dict[str, object] | None = None,
+ route_provider: str | None = None,
+ base_model: object = None,
+) -> float:
+ logging_obj: Final = Logging(
+ model="unknown",
+ messages=[{"role": "user", "content": "ping"}],
+ stream=stream,
+ call_type="pass_through_endpoint",
+ start_time=datetime(2026, 1, 1),
+ litellm_call_id="call-1",
+ function_id="fn-1",
+ )
+ logging_obj.update_environment_variables(
+ litellm_params={"metadata": {"model_info": model_info}} if model_info is not None else {}, optional_params={}
+ )
+ if route_provider is not None:
+ logging_obj.model_call_details["custom_llm_provider"] = route_provider
+ if base_model is not None:
+ logging_obj.model_call_details["litellm_params"] = {"base_model": base_model}
+ if stream:
+ asyncio.run(
+ PassThroughStreamingHandler.route_streaming_logging_to_handler(
+ litellm_logging_obj=logging_obj,
+ passthrough_success_handler_obj=PassThroughEndpointLogging(),
+ url_route=url_route,
+ request_body={},
+ endpoint_type=EndpointType.VERTEX_AI,
+ start_time=datetime(2026, 1, 1),
+ raw_bytes=[f"data: {json.dumps(event)}\n\n".encode() for event in stream_events],
+ end_time=datetime(2026, 1, 1),
+ )
+ )
+ return logging_obj.model_call_details["response_cost"]
+ response: Final = httpx.Response(200, json=reply)
+ result: Final = VertexPassthroughLoggingHandler.vertex_passthrough_handler(
+ httpx_response=response,
+ logging_obj=logging_obj,
+ url_route=url_route,
+ result=response.text,
+ start_time=datetime(2026, 1, 1),
+ end_time=datetime(2026, 1, 1),
+ cache_hit=False,
+ request_body={},
+ )
+ logging_obj._process_hidden_params_and_response_cost(
+ result["result"], datetime(2026, 1, 1), datetime(2026, 1, 1), build_logging_payload=False
+ )
+ return logging_obj.model_call_details["response_cost"]
+
+
+def _cost_the_logger_records(location: str, *, stream: bool, model_info: dict[str, object] | None = None) -> float:
+ method: Final = "streamGenerateContent" if stream else "generateContent"
+ url_route: Final = (
+ f"https://aiplatform.googleapis.com/v1/projects/p/locations/{location}"
+ f"/publishers/google/models/{_UPLIFT_MODEL}:{method}"
+ )
+ return _cost_the_logger_records_for(
+ url_route,
+ stream=stream,
+ reply=_generate_content_payload(),
+ stream_events=[_generate_content_payload()],
+ model_info=model_info,
+ )
+
+
[email protected]("stream", [True, False], ids=["streamed", "non-streamed"])
[email protected]("location, multiplier", [("global", 1.0), ("us", _UPLIFT_MULTIPLIER)])
+def test_generate_content_spend_follows_the_vertex_location(
+ regional_uplift_rate_card: None, stream: bool, location: str, multiplier: float
+) -> None:
+ expected: Final = (7 * _UPLIFT_INPUT_RATE + 1 * _UPLIFT_OUTPUT_RATE) * multiplier
+
+ assert _cost_the_logger_records(location, stream=stream) == pytest.approx(expected), (location, stream)
+
+
+ "gemini_api_base", ["https://generativelanguage.googleapis.com", "https://llm-egress.internal.example/google"]
+)
[email protected]("stream", [True, False], ids=["streamed", "non-streamed"])
+def test_gemini_route_spend_has_no_vertex_uplift_whatever_host_serves_it(
+ regional_uplift_rate_card: None, monkeypatch: pytest.MonkeyPatch, gemini_api_base: str, stream: bool
+) -> None:
+ monkeypatch.setitem(
+ litellm.model_cost,
+ f"gemini/{_UPLIFT_MODEL}",
+ {
+ "input_cost_per_token": _UPLIFT_INPUT_RATE,
+ "output_cost_per_token": _UPLIFT_OUTPUT_RATE,
+ "litellm_provider": "gemini",
+ "mode": "chat",
+ },
+ )
+ method: Final = "streamGenerateContent?alt=sse" if stream else "generateContent"
+
+ recorded: Final = _cost_the_logger_records_for(
+ f"{gemini_api_base}/v1beta/models/{_UPLIFT_MODEL}:{method}",
+ stream=stream,
+ reply=_generate_content_payload(),
+ stream_events=[_generate_content_payload()],
+ route_provider="gemini",
+ )
+
+ assert recorded == pytest.approx(7 * _UPLIFT_INPUT_RATE + 1 * _UPLIFT_OUTPUT_RATE), (gemini_api_base, stream)
+
+
[email protected]("stream", [True, False], ids=["streamed", "non-streamed"])
+def test_a_vertex_host_that_only_ends_with_the_gemini_host_name_keeps_the_vertex_uplift(
+ regional_uplift_rate_card: None, stream: bool
+) -> None:
+ method: Final = "streamGenerateContent" if stream else "generateContent"
+
+ recorded: Final = _cost_the_logger_records_for(
+ "https://vertex-generativelanguage.googleapis.com/v1/projects/p/locations/us/publishers/google/models/"
+ f"{_UPLIFT_MODEL}:{method}",
+ stream=stream,
+ reply=_generate_content_payload(),
+ stream_events=[_generate_content_payload()],
+ )
+
+ assert recorded == pytest.approx((7 * _UPLIFT_INPUT_RATE + 1 * _UPLIFT_OUTPUT_RATE) * _UPLIFT_MULTIPLIER), stream
+
+
[email protected]("stream", [True, False], ids=["streamed", "non-streamed"])
+def test_a_subdomain_of_the_gemini_host_bills_the_gemini_price(
+ regional_uplift_rate_card: None, monkeypatch: pytest.MonkeyPatch, stream: bool
+) -> None:
+ monkeypatch.setitem(
+ litellm.model_cost,
+ f"gemini/{_UPLIFT_MODEL}",
+ {
+ "input_cost_per_token": _UPLIFT_INPUT_RATE,
+ "output_cost_per_token": _UPLIFT_OUTPUT_RATE,
+ "litellm_provider": "gemini",
+ "mode": "chat",
+ },
+ )
+ method: Final = "streamGenerateContent?alt=sse" if stream else "generateContent"
+
+ recorded: Final = _cost_the_logger_records_for(
+ f"https://eu.generativelanguage.googleapis.com/v1beta/models/{_UPLIFT_MODEL}:{method}",
+ stream=stream,
+ reply=_generate_content_payload(),
+ stream_events=[_generate_content_payload()],
+ )
+
+ assert recorded == pytest.approx(7 * _UPLIFT_INPUT_RATE + 1 * _UPLIFT_OUTPUT_RATE), stream
+
+
[email protected]("value", [123, ["gemini-2.5-flash-lite"], {"model": "gemini-2.5-flash-lite"}])
[email protected]("carrier", ["root", "model_info"])
[email protected]("stream", [True, False], ids=["streamed", "non-streamed"])
+def test_a_non_string_base_model_bills_the_list_price(
+ regional_uplift_rate_card: None, stream: bool, carrier: str, value: object
+) -> None:
+ method: Final = "streamGenerateContent" if stream else "generateContent"
+
+ recorded: Final = _cost_the_logger_records_for(
+ f"https://aiplatform.googleapis.com/v1/projects/p/locations/us/publishers/google/models/{_UPLIFT_MODEL}:{method}",
+ stream=stream,
+ reply=_generate_content_payload(),
+ stream_events=[_generate_content_payload()],
+ model_info={"base_model": value} if carrier == "model_info" else None,
+ base_model=value if carrier == "root" else None,
+ )
+
+ assert recorded == pytest.approx((7 * _UPLIFT_INPUT_RATE + 1 * _UPLIFT_OUTPUT_RATE) * _UPLIFT_MULTIPLIER), stream
+
+
+_CUSTOM_PRICED_DEPLOYMENT: Final = "vertex-custom-priced-deployment"
+_CUSTOM_INPUT_RATE: Final = 2e-09
+_CUSTOM_OUTPUT_RATE: Final = 3e-09
+
+
[email protected]("stream", [True, False], ids=["streamed", "non-streamed"])
[email protected]("location", ["global", "us"])
+def test_generate_content_spend_uses_the_deployment_custom_price(
+ regional_uplift_rate_card: None, monkeypatch: pytest.MonkeyPatch, stream: bool, location: str
+) -> None:
+ custom_rates: Final = {"input_cost_per_token": _CUSTOM_INPUT_RATE, "output_cost_per_token": _CUSTOM_OUTPUT_RATE}
+ monkeypatch.setitem(
+ litellm.model_cost, _CUSTOM_PRICED_DEPLOYMENT, {**custom_rates, "litellm_provider": "vertex_ai", "mode": "chat"}
+ )
+ expected: Final = 7 * _CUSTOM_INPUT_RATE + 1 * _CUSTOM_OUTPUT_RATE
+
+ recorded: Final = _cost_the_logger_records(
+ location, stream=stream, model_info={"id": _CUSTOM_PRICED_DEPLOYMENT, **custom_rates}
+ )
+
+ assert recorded == pytest.approx(expected), (location, stream)
+
+
+_CLAUDE_UPLIFT_MODEL: Final = "claude-regional-uplift-probe"
+_CLAUDE_INPUT_RATE: Final = 3e-06
+_CLAUDE_OUTPUT_RATE: Final = 1.5e-05
+
+
+def claude_regional_uplift_rate_card(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
+ rates: Final = {
+ "input_cost_per_token": _CLAUDE_INPUT_RATE,
+ "output_cost_per_token": _CLAUDE_OUTPUT_RATE,
+ "mode": "chat",
+ }
+ monkeypatch.setitem(litellm.model_cost, _CLAUDE_UPLIFT_MODEL, {**rates, "litellm_provider": "anthropic"})
+ monkeypatch.setattr(litellm, "anthropic_models", {*litellm.anthropic_models, _CLAUDE_UPLIFT_MODEL})
+ monkeypatch.setitem(
+ litellm.model_cost,
+ f"vertex_ai/{_CLAUDE_UPLIFT_MODEL}",
+ {
+ **rates,
+ "litellm_provider": "vertex_ai-anthropic_models",
+ "regional_endpoint_uplift_multiplier": _UPLIFT_MULTIPLIER,
+ },
+ )
+ litellm.get_model_info.cache_clear()
+ yield
+ litellm.get_model_info.cache_clear()
+
+
+def _claude_message() -> dict[str, object]:
+ return {
+ "id": "msg_probe",
+ "type": "message",
+ "role": "assistant",
+ "model": _CLAUDE_UPLIFT_MODEL,
+ "content": [{"type": "text", "text": "pong"}],
+ "stop_reason": "end_turn",
+ "usage": {"input_tokens": 7, "output_tokens": 1},
+ }
+
+
+def _claude_stream_events() -> list[dict[str, object]]:
+ message_start: Final = {**_claude_message(), "content": [], "usage": {"input_tokens": 7, "output_tokens": 0}}
+ return [
+ {"type": "message_start", "message": message_start},
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "pong"}},
+ {"type": "content_block_stop", "index": 0},
+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 1}},
+ {"type": "message_stop"},
+ ]
+
+
[email protected]("stream", [True, False], ids=["streamed", "non-streamed"])
[email protected]("location, multiplier", [("global", 1.0), ("us-east5", _UPLIFT_MULTIPLIER)])
+def test_claude_raw_predict_spend_follows_the_vertex_location(
+ claude_regional_uplift_rate_card: None, stream: bool, location: str, multiplier: float
+) -> None:
+ method: Final = "streamRawPredict" if stream else "rawPredict"
+ url_route: Final = (
+ f"https://aiplatform.googleapis.com/v1/projects/p/locations/{location}"
+ f"/publishers/anthropic/models/{_CLAUDE_UPLIFT_MODEL}:{method}"
+ )
+ expected: Final = (7 * _CLAUDE_INPUT_RATE + 1 * _CLAUDE_OUTPUT_RATE) * multiplier
+
+ recorded: Final = _cost_the_logger_records_for(
+ url_route, stream=stream, reply=_claude_message(), stream_events=_claude_stream_events()
+ )
+
+ assert recorded == pytest.approx(expected), (location, stream)
+
+
[email protected]("stream", [True, False], ids=["streamed", "non-streamed"])
+def test_claude_raw_predict_spend_uses_the_deployment_custom_price(
+ claude_regional_uplift_rate_card: None, monkeypatch: pytest.MonkeyPatch, stream: bool
+) -> None:
+ custom_rates: Final = {"input_cost_per_token": _CUSTOM_INPUT_RATE, "output_cost_per_token": _CUSTOM_OUTPUT_RATE}
+ monkeypatch.setitem(
+ litellm.model_cost, _CUSTOM_PRICED_DEPLOYMENT, {**custom_rates, "litellm_provider": "vertex_ai", "mode": "chat"}
+ )
+ method: Final = "streamRawPredict" if stream else "rawPredict"
+ url_route: Final = (
+ "https://aiplatform.googleapis.com/v1/projects/p/locations/us-east5"
+ f"/publishers/anthropic/models/{_CLAUDE_UPLIFT_MODEL}:{method}"
+ )
+
+ recorded: Final = _cost_the_logger_records_for(
+ url_route,
+ stream=stream,
+ reply=_claude_message(),
+ stream_events=_claude_stream_events(),
+ model_info={"id": _CUSTOM_PRICED_DEPLOYMENT, **custom_rates},
+ )
+
+ assert recorded == pytest.approx(7 * _CUSTOM_INPUT_RATE + 1 * _CUSTOM_OUTPUT_RATE), stream
+
+
+def test_a_claude_stream_through_a_configured_vertex_gateway_with_a_short_path_bills_the_vertex_price(
+ claude_regional_uplift_rate_card: None, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setitem(
+ litellm.model_cost,
+ f"vertex_ai/{_CLAUDE_UPLIFT_MODEL}",
+ {
+ "input_cost_per_token": _CLAUDE_INPUT_RATE,
+ "output_cost_per_token": _CLAUDE_OUTPUT_RATE,
+ "litellm_provider": "vertex_ai-anthropic_models",
+ "mode": "chat",
+ },
+ )
+ litellm.get_model_info.cache_clear()
+
+ recorded: Final = _cost_the_logger_records_for(
+ f"https://vertex-gateway.internal.example/vxc/models/{_CLAUDE_UPLIFT_MODEL}:streamRawPredict",
+ stream=True,
+ reply=_claude_message(),
+ stream_events=_claude_stream_events(),
+ )
+
+ assert recorded == pytest.approx(7 * _CLAUDE_INPUT_RATE + 1 * _CLAUDE_OUTPUT_RATE)
+
+
def test_build_complete_streaming_response_assembles_stream_generate_content_sse_chunks():
logging_obj: Final = Logging(
model="gemini-2.5-flash",
diff --git a/tests/unit/proxy/pass_through_endpoints/test_pass_through_endpoints.py b/tests/unit/proxy/pass_through_endpoints/test_pass_through_endpoints.py
index eb31797d460..5412ea56ac0 100644
--- a/tests/unit/proxy/pass_through_endpoints/test_pass_through_endpoints.py
+++ b/tests/unit/proxy/pass_through_endpoints/test_pass_through_endpoints.py
@@ -8452,7 +8452,9 @@ _LITELLM_PARAMS: Final = TypeAdapter(dict[str, object])
_PROXY_SERVER_REQUEST: Final = TypeAdapter(dict[str, object])
-def _split_pass_through_body(body: str) -> _PassThroughSplit:
+def _split_pass_through_body(
+ body: str, user_api_key_dict: UserAPIKeyAuth = UserAPIKeyAuth(api_key="hashed-key")
+) -> _PassThroughSplit:
mock_request: Final = MagicMock(spec=Request)
mock_request.method = "POST"
mock_request.url = httpx.URL("http://0.0.0.0:4000/gemini/v1beta/models/gemini-2.5-flash:generateContent")
@@ -8462,7 +8464,7 @@ def _split_pass_through_body(body: str) -> _PassThroughSplit:
init_kwargs_for_pass_through_endpoint: Final = HttpPassThroughEndpointHelpers._init_kwargs_for_pass_through_endpoint # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType] # untyped legacy helper
kwargs: Final = init_kwargs_for_pass_through_endpoint(
request=mock_request,
- user_api_key_dict=UserAPIKeyAuth(api_key="hashed-key"),
+ user_api_key_dict=user_api_key_dict,
passthrough_logging_payload=MagicMock(),
logging_obj=MagicMock(),
_parsed_body=json.loads(body),
@@ -8500,6 +8502,7 @@ def test_passthrough_moves_every_litellm_owned_key_from_the_forwarded_body_into_
assert split.forwarded_body == json.loads(GEMINI_BODY)
+PRICING_MODEL_OVERRIDE_NAMES: Final = frozenset(("base_model",))
PROXY_STAMPED_NAMES: Final = frozenset(
(
"proxy_server_request",
@@ -8515,7 +8518,12 @@ PROXY_STAMPED_NAMES: Final = frozenset(
@pytest.mark.parametrize(
"name",
- sorted(frozenset(litellm.all_litellm_params) - frozenset(("metadata", "litellm_metadata")) - PROXY_STAMPED_NAMES),
+ sorted(
+ frozenset(litellm.all_litellm_params)
+ - frozenset(("metadata", "litellm_metadata"))
+ - PROXY_STAMPED_NAMES
+ - PRICING_MODEL_OVERRIDE_NAMES
+ ),
)
def test_passthrough_keeps_each_registered_litellm_owned_name_out_of_the_forwarded_body(name: str) -> None:
split: Final = _split_pass_through_body(json.dumps({name: "owned", **json.loads(GEMINI_BODY)}))
@@ -8525,6 +8533,41 @@ def test_passthrough_keeps_each_registered_litellm_owned_name_out_of_the_forward
assert split.forwarded_body == json.loads(GEMINI_BODY)
[email protected]("allows_client_pricing", [True, False], ids=["key-allows-client-pricing", "plain-key"])
+def test_passthrough_prices_with_a_client_base_model_only_for_keys_that_allow_client_pricing(
+ allows_client_pricing: bool,
+) -> None:
+ key: Final = UserAPIKeyAuth(
+ api_key="hashed-key", metadata={"allow_client_pricing_override": True} if allows_client_pricing else {}
+ )
+
+ split: Final = _split_pass_through_body(
+ json.dumps({"base_model": "vertex_ai/gemini-2.5-flash-lite", **json.loads(GEMINI_BODY)}), key
+ )
+
+ expected: Final = "vertex_ai/gemini-2.5-flash-lite" if allows_client_pricing else None
+ assert split.litellm_params.get("base_model") == expected
+ assert split.forwarded_body == json.loads(GEMINI_BODY)
+
+
[email protected]("model_info", ["malformed", ["malformed"], 123])
+def test_passthrough_drops_a_client_model_info_that_is_not_an_object(model_info: object) -> None:
+ key: Final = UserAPIKeyAuth(api_key="hashed-key", metadata={"allow_client_pricing_override": True})
+ plain_metadata: Final = _metadata_of(_split_pass_through_body(json.dumps({"metadata": {"tag": "a"}}), key))
+
+ split: Final = _split_pass_through_body(json.dumps({"metadata": {"tag": "a", "model_info": model_info}}), key)
+
+ assert _metadata_of(split) == plain_metadata
+
+
+def test_passthrough_keeps_a_client_model_info_object_for_keys_that_allow_client_pricing() -> None:
+ key: Final = UserAPIKeyAuth(api_key="hashed-key", metadata={"allow_client_pricing_override": True})
+
+ split: Final = _split_pass_through_body(json.dumps({"metadata": {"model_info": {"base_model": "gemini/x"}}}), key)
+
+ assert _metadata_of(split)["model_info"] == {"base_model": "gemini/x"}
+
+
@pytest.mark.parametrize("name", sorted(PROXY_STAMPED_NAMES))
def test_passthrough_drops_a_client_supplied_proxy_stamped_name(name: str) -> None:
split: Final = _split_pass_through_body(json.dumps({name: {"forged": "by-client"}, **json.loads(GEMINI_BODY)}))
diff --git a/tests/unit/proxy/pass_through_endpoints/test_streaming_handler.py b/tests/unit/proxy/pass_through_endpoints/test_streaming_handler.py
index fdd21afbc67..da084146894 100644
--- a/tests/unit/proxy/pass_through_endpoints/test_streaming_handler.py
+++ b/tests/unit/proxy/pass_through_endpoints/test_streaming_handler.py
@@ -2,6 +2,7 @@ import json
import logging
from collections.abc import Iterator
from datetime import datetime
+from typing import Final
from unittest.mock import MagicMock
import pytest
@@ -13,6 +14,7 @@ from litellm.proxy.pass_through_endpoints.llm_provider_handlers.vertex_passthrou
VertexPassthroughLoggingHandler,
)
from litellm.proxy.pass_through_endpoints.streaming_handler import (
+ PassThroughStreamContext,
PassThroughStreamingHandler,
)
from litellm.proxy.pass_through_endpoints.success_handler import (
@@ -235,3 +237,40 @@ async def test_failed_anthropic_stream_records_partial_usage_off_the_event_loop(
partial_usage = logging_obj.record_partial_usage_for_failure.call_args.kwargs["usage"]
assert partial_usage.completion_tokens > 100_000
assert_loop_stayed_free(took, lags)
+
+
+async def test_interrupted_vertex_stream_bills_the_deployment_custom_price(monkeypatch: pytest.MonkeyPatch) -> None:
+ deployment_id: Final = "vertex-custom-priced-deployment"
+ custom_rates: Final = {"input_cost_per_token": 2e-09, "output_cost_per_token": 3e-09}
+ monkeypatch.setitem(
+ litellm.model_cost, deployment_id, {**custom_rates, "litellm_provider": "vertex_ai", "mode": "chat"}
+ )
+ logging_obj: Final = LiteLLMLoggingObj(
+ model="unknown",
+ messages=[{"role": "user", "content": "ping"}],
+ stream=True,
+ call_type="pass_through_endpoint",
+ start_time=datetime.now(),
+ litellm_call_id="interrupted-stream",
+ function_id="interrupted-stream",
+ )
+ logging_obj.optional_params = {}
+ logging_obj.litellm_params = {"metadata": {"model_info": {"id": deployment_id, **custom_rates}}}
+ url_route: Final = (
+ f"https://aiplatform.googleapis.com/v1/projects/p/locations/us"
+ f"/publishers/google/models/{MODEL}:streamGenerateContent?alt=sse"
+ )
+
+ await PassThroughStreamingHandler.schedule_stream_failure_logging(
+ litellm_logging_obj=logging_obj,
+ endpoint_type=EndpointType.VERTEX_AI,
+ request_body={},
+ raw_bytes=[chunk.encode("utf-8") for chunk in _chunks()],
+ exception=RuntimeError("upstream closed the stream"),
+ stream_context=PassThroughStreamContext(PassThroughEndpointLogging(), url_route, datetime.now()),
+ )
+ recorded: Final = logging_obj.model_call_details["response_cost"]
+ await GLOBAL_LOGGING_WORKER.flush()
+
+ assert recorded == pytest.approx(PROMPT_TOKENS * 2e-09 + COMPLETION_TOKENS * 3e-09)
diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py
index b4150aad1c7..69ef2caf8f4 100644
--- a/tests/unit/test_utils.py
+++ b/tests/unit/test_utils.py
@@ -114,10 +114,22 @@ from litellm.utils import (
)
-def test_get_base_model_from_metadata_returns_unvalidated_root_value():
[email protected]("root_base_model", [42, ["gemini-3.5-flash"], {"model": "gemini-3.5-flash"}])
+def test_get_base_model_from_metadata_ignores_a_non_string_root_value(root_base_model: object):
from litellm.utils import get_base_model_from_metadata
- assert get_base_model_from_metadata({"litellm_params": {"base_model": 42}}) == 42
+ assert get_base_model_from_metadata({"litellm_params": {"base_model": root_base_model}}) is None
+ assert (
+ get_base_model_from_metadata(
+ {
+ "litellm_params": {
+ "base_model": root_base_model,
+ "metadata": {"model_info": {"base_model": "vertex_ai/gemini-3.5-flash"}},
+ }
+ }
+ )
+ == "vertex_ai/gemini-3.5-flash"
+ )
def _reject_short_post_call_response(input: str, model: str | None = None) -> dict[str, object]: