Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

feat(gemini): set the long decode budget for requests with no output limit from LITELLM_GEMINI_DEFAULT_MAX_OUTPUT_TOKENS (#47542)

Mateo Wang11b5d1a81711
diff --git a/litellm/llms/vertex_ai/gemini/long_decode.py b/litellm/llms/vertex_ai/gemini/long_decode.py
index 81d6c04d0e8..571fa94d4a5 100644
--- a/litellm/llms/vertex_ai/gemini/long_decode.py
+++ b/litellm/llms/vertex_ai/gemini/long_decode.py
@@ -2,17 +2,20 @@ import json
from collections.abc import Awaitable, Callable, Mapping, Sequence
from dataclasses import dataclass
from itertools import accumulate, chain
-from typing import Final, TypeAlias, TypeVar, cast # noqa: TID251 # sum_usage_metadata casts computed keys
+from typing import Final, Literal, TypeAlias, TypeVar, cast # noqa: TID251 # sum_usage_metadata casts computed keys
import httpx
+from pydantic import TypeAdapter, ValidationError
from litellm._logging import verbose_logger
from litellm.exceptions import Timeout
+from litellm.litellm_core_utils.env_utils import get_env_int_or_none
from litellm.types.llms.vertex_ai import (
Candidates,
Citation,
CitationMetadata,
GenerateContentResponseBody,
+ GenerationConfig,
GroundingMetadata,
GroundingSegment,
GroundingSupport,
@@ -48,8 +51,14 @@ HOP_FAILURES: Final = (VertexAIError, httpx.HTTPError, Timeout)
HOP_END_FINISH_REASON: Final = "CONTINUATION"
CUT_OFF_FINISH_REASONS: Final = frozenset({"MAX_TOKENS", HOP_END_FINISH_REASON})
+DEFAULT_OUTPUT_BUDGET_ENV: Final = "LITELLM_GEMINI_DEFAULT_MAX_OUTPUT_TOKENS"
+_OUTPUT_LIMIT_KEYS: Final = frozenset({"max_output_tokens", "maxOutputTokens"})
+_REQUEST_KEYS_THAT_SKIP_THE_DEFAULT_BUDGET: Final = frozenset({"generation_config", "continuationToken"})
+_TEXT_ONLY_MODALITIES: Final = TypeAdapter(list[Literal["TEXT"]])
+
_VERTEX_V1_PATH: Final = "/v1/projects/"
_VERTEX_PATH_ACCEPTING_CONTINUATION_TOKEN: Final = "/v1beta1/projects/"
+_CANDIDATE_COUNT_KEYS: Final = ("candidate_count", "candidateCount")
LongDecodeHops: TypeAlias = tuple[GenerateContentResponseBody, ...]
AsyncHopPost: TypeAlias = Callable[[RequestBody], Awaitable[httpx.Response]]
@@ -76,15 +85,53 @@ def _int_or_none(value: object) -> int | None:
return value if isinstance(value, int) else None
+def _asks_for_one_candidate(generation_config: Mapping[str, object]) -> bool:
+ return all(
+ _int_or_none(generation_config[key] or 1) == 1 for key in _CANDIDATE_COUNT_KEYS if key in generation_config
+ )
+
+
def continuation_cap_of(request_body: RequestBody) -> int | None:
generation_config: Final = request_body.get("generationConfig")
if generation_config is None or "max_output_tokens" not in generation_config:
return None
- if "candidate_count" in generation_config and _int_or_none(generation_config["candidate_count"]) != 1:
+ if not _asks_for_one_candidate(generation_config):
return None
return _int_or_none(generation_config["max_output_tokens"])
+def _asks_for_text_only(generation_config: Mapping[str, object]) -> bool:
+ if "response_modalities" in generation_config:
+ return False
+ try:
+ _ = _TEXT_ONLY_MODALITIES.validate_python(generation_config.get("responseModalities", []))
+ except ValidationError:
+ return False
+ return True
+
+
+def with_default_output_budget(
+ request_body: RequestBody, model_max_output_tokens: Callable[[], int | None]
+) -> RequestBody:
+ generation_config: Final = request_body.get("generationConfig", GenerationConfig())
+ request_json: Final[Mapping[str, object]] = request_body
+ budget: Final = get_env_int_or_none(DEFAULT_OUTPUT_BUDGET_ENV)
+ if budget is None or budget <= 0:
+ return request_body
+ if not _REQUEST_KEYS_THAT_SKIP_THE_DEFAULT_BUDGET.isdisjoint(request_body):
+ return request_body
+ if not isinstance(request_json.get("generationConfig", {}), dict):
+ return request_body
+ if not _OUTPUT_LIMIT_KEYS.isdisjoint(generation_config):
+ return request_body
+ if not _asks_for_text_only(generation_config):
+ return request_body
+ model_max: Final = model_max_output_tokens()
+ if model_max is None:
+ return request_body
+ return {**request_body, "generationConfig": {**generation_config, "max_output_tokens": min(budget, model_max)}}
+
+
def client_continuation_token(candidate: Candidates) -> str | None:
if candidate.get("finishReason") not in CUT_OFF_FINISH_REASONS:
return None
diff --git a/litellm/llms/vertex_ai/gemini/transformation.py b/litellm/llms/vertex_ai/gemini/transformation.py
index e5ce395031a..71bb05ee155 100644
--- a/litellm/llms/vertex_ai/gemini/transformation.py
+++ b/litellm/llms/vertex_ai/gemini/transformation.py
@@ -7,16 +7,19 @@ Why separate file? Make it easy to see how transformation works
import os
import re
from collections.abc import Callable, Mapping
+from functools import partial
from typing import TYPE_CHECKING, Any, Final, Literal, cast
from urllib.parse import quote
import httpx
-from pydantic import BaseModel, TypeAdapter
+from pydantic import BaseModel, PositiveInt, TypeAdapter, ValidationError
+from typing_extensions import NotRequired, ReadOnly, TypedDict
import litellm
from litellm._logging import verbose_logger
from litellm.litellm_core_utils.asyncify import asyncify
from litellm.litellm_core_utils.core_helpers import drops_unsupported_params
+from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMap
from litellm.litellm_core_utils.prompt_templates.common_utils import (
get_image_mime_type_from_url,
)
@@ -65,6 +68,7 @@ from ..common_utils import (
get_supports_response_schema,
get_supports_system_message,
)
+from .long_decode import with_default_output_budget
# VertexBase is imported only for type checking to avoid introducing a
# module-load-time cyclic import to vertex_llm_base. The instance is lazily
@@ -1304,13 +1308,75 @@ def sync_transform_request_body(
vertex_auth_header=vertex_auth_header,
)
- return transform_request_body(
- messages=messages,
- model=model,
- custom_llm_provider=custom_llm_provider,
- litellm_params=litellm_params,
- cached_content=cached_content,
- optional_params=optional_params,
+ return _with_default_output_budget(
+ transform_request_body(
+ messages=messages,
+ model=model,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ cached_content=cached_content,
+ optional_params=optional_params,
+ ),
+ model,
+ custom_llm_provider,
+ litellm_params.get("model_info"), # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType] # litellm_params is an untyped dict
+ )
+
+
+class _CostMapOutputModalities(TypedDict):
+ supported_output_modalities: NotRequired[ReadOnly[tuple[str, ...]]]
+
+
+_COST_MAP_OUTPUT_MODALITIES: Final = TypeAdapter(_CostMapOutputModalities)
+
+
+def _answers_text(cost_map_key: str) -> bool:
+ try:
+ row: Final = _COST_MAP_OUTPUT_MODALITIES.validate_python(litellm.model_cost.get(cost_map_key)) # pyright: ignore[reportUnknownMemberType] # cost map rows are untyped JSON
+ except ValidationError:
+ return False
+ return "text" in row.get("supported_output_modalities", ("text",))
+
+
+class _OutputLimit(TypedDict):
+ max_output_tokens: NotRequired[ReadOnly[PositiveInt | None]]
+
+
+_OUTPUT_LIMIT: Final = TypeAdapter(_OutputLimit)
+
+
+def _output_limit(fields: object) -> int | None:
+ try:
+ return _OUTPUT_LIMIT.validate_python(fields).get("max_output_tokens")
+ except ValidationError:
+ return None
+
+
+def _catalog_capped_output_limit(cost_map_key: str, override: object) -> int | None:
+ limits: Final = (
+ _output_limit(GetModelCostMap.loaded_model_cost_map().get(cost_map_key)),
+ _output_limit(override),
+ )
+ return min((limit for limit in limits if limit is not None), default=None)
+
+
+def _text_chat_model_max_output_tokens(
+ model: str, custom_llm_provider: str, deployment_model_info: object
+) -> int | None:
+ info: Final = litellm.utils.lookup_model_info_for_registration(model, custom_llm_provider)
+ if isinstance(info, litellm.utils.ModelInfoLookupMiss) or info.get("mode") != "chat":
+ return None
+ if not _answers_text(info["key"]):
+ return None
+ return _catalog_capped_output_limit(info["key"], deployment_model_info or info)
+
+
+def _with_default_output_budget(
+ request_body: RequestBody, model: str, custom_llm_provider: str, deployment_model_info: object
+) -> RequestBody:
+ return with_default_output_budget(
+ request_body,
+ partial(_text_chat_model_max_output_tokens, model, custom_llm_provider, deployment_model_info),
)
@@ -1380,21 +1446,8 @@ async def async_transform_request_body(
messages, should_inline=should_inline_remote_media(custom_llm_provider)
)
- if _openai_messages_may_need_sync_gcs_metadata_fetch(inlined_messages):
- # _transform_request_body may issue a sync httpx.get (up to 5s timeout)
- # via _get_gcs_object_content_type to fetch GCS object metadata. Run the
- # whole sync transformation on a worker thread so it does not block the
- # async event loop.
- return await asyncify(transform_request_body)(
- messages=inlined_messages,
- model=model,
- custom_llm_provider=custom_llm_provider,
- litellm_params=litellm_params,
- cached_content=cached_content,
- optional_params=optional_params,
- )
-
- return transform_request_body(
+ transform: Final = partial(
+ transform_request_body,
messages=inlined_messages,
model=model,
custom_llm_provider=custom_llm_provider,
@@ -1402,6 +1455,21 @@ async def async_transform_request_body(
cached_content=cached_content,
optional_params=optional_params,
)
+ # _transform_request_body may issue a sync httpx.get (up to 5s timeout)
+ # via _get_gcs_object_content_type to fetch GCS object metadata. Run the
+ # whole sync transformation on a worker thread so it does not block the
+ # async event loop.
+ request_body: Final[RequestBody] = (
+ await asyncify(transform)()
+ if _openai_messages_may_need_sync_gcs_metadata_fetch(inlined_messages)
+ else transform()
+ )
+ return _with_default_output_budget(
+ request_body,
+ model,
+ custom_llm_provider,
+ litellm_params.get("model_info"), # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType] # litellm_params is an untyped dict
+ )
def _default_user_message_when_system_message_passed() -> ChatCompletionUserMessage:
diff --git a/tests/unit/llms/vertex_ai/gemini/test_long_decode.py b/tests/unit/llms/vertex_ai/gemini/test_long_decode.py
index 4465ad7f3df..3fe9a5c7a92 100644
--- a/tests/unit/llms/vertex_ai/gemini/test_long_decode.py
+++ b/tests/unit/llms/vertex_ai/gemini/test_long_decode.py
@@ -516,9 +516,16 @@ async def test_unary_answer_cut_at_the_callers_cap_is_returned_with_its_token_in
assert response.choices[0].message.provider_specific_fields["continuation_token"] == "dG9rLTE="
+ "choice_count_request",
+ [{"max_tokens": 100_000, "n": 2}, {"extra_body": {"generationConfig": {"candidateCount": 2}}}],
+)
@pytest.mark.parametrize("is_async", [True, False])
@pytest.mark.asyncio
-async def test_unary_request_for_more_than_one_choice_is_never_continued(is_async: bool):
+async def test_unary_request_for_more_than_one_choice_is_never_continued(
+ monkeypatch: pytest.MonkeyPatch, is_async: bool, choice_count_request: Mapping[str, object]
+):
+ monkeypatch.setenv(BUDGET_ENV, "100000")
sent: Final[list[dict[str, object]]] = []
# Vertex AI answered 400 "Candidate count greater than 1 is not supported when continuation_token is set"
# on 2026-10-13
@@ -526,9 +533,8 @@ async def test_unary_request_for_more_than_one_choice_is_never_continued(is_asyn
kwargs: Final = {
"model": MODEL,
"messages": list(MESSAGES),
- "max_tokens": 100_000,
- "n": 2,
"api_key": "fake-gemini-key",
+ **choice_count_request,
}
response: Final = (
@@ -548,6 +554,42 @@ async def test_unary_request_for_more_than_one_choice_is_never_continued(is_asyn
]
+ "one_choice_request",
+ [
+ {"max_tokens": 100_000, "n": 0},
+ {"extra_body": {"generationConfig": {"candidateCount": None}}},
+ {"extra_body": {"generationConfig": {"candidateCount": 0}}},
+ ],
+)
[email protected]("is_async", [True, False])
+async def test_unary_request_whose_candidate_count_google_reads_as_one_is_continued(
+ monkeypatch: pytest.MonkeyPatch, is_async: bool, one_choice_request: Mapping[str, object]
+):
+ monkeypatch.setenv(BUDGET_ENV, "100000")
+ sent: Final[list[dict[str, object]]] = []
+ hops: Final = (httpx.Response(200, json=HOP_1), httpx.Response(200, json=HOP_2))
+ kwargs: Final = {
+ "model": MODEL,
+ "messages": list(MESSAGES),
+ "api_key": "fake-gemini-key",
+ **one_choice_request,
+ }
+
+ response: Final = (
+ await litellm.acompletion(**kwargs, client=AsyncHTTPHandler(transport=httpx.MockTransport(_replay(hops, sent))))
+ if is_async
+ else litellm.completion(
+ **kwargs, client=HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(_replay(hops, sent))))
+ )
+ )
+
+ assert sent[1] == {**sent[0], "continuationToken": "dG9rLTE="}
+ assert response.choices[0].message.content == "hello world"
+ assert response.choices[0].finish_reason == "stop"
+
+
@pytest.mark.asyncio
async def test_unary_failed_continuation_hop_returns_the_answer_so_far_with_its_token():
sent: Final[list[dict[str, object]]] = []
@@ -1295,6 +1337,468 @@ async def test_vertex_long_decode_keeps_the_callers_own_authorization_header_on_
assert seen == ["Bearer mine", "Bearer mine"]
+BUDGET_ENV: Final = "LITELLM_GEMINI_DEFAULT_MAX_OUTPUT_TOKENS"
+ARGON: Final = "gemini/gemini-4-argon"
+UNMAPPED_GEMINI: Final = "gemini/gemini-99-unreleased"
+OUTPUT_LIMIT_KEYS: Final = ("max_output_tokens", "maxOutputTokens")
+
+
+def _output_limits(request: Mapping[str, object]) -> dict[str, object]:
+ generation_config: Final = request.get("generationConfig", {})
+ assert isinstance(generation_config, dict)
+ return {key: value for key, value in generation_config.items() if key in OUTPUT_LIMIT_KEYS}
+
+
+def _cost_map_max_output_tokens(model: str) -> int:
+ provider, name = model.split("/", 1)
+ max_output_tokens: Final = litellm.get_model_info(model=name, custom_llm_provider=provider)["max_output_tokens"]
+ assert isinstance(max_output_tokens, int)
+ return max_output_tokens
+
+
[email protected]("stream", [False, True])
[email protected]("is_async", [True, False])
+async def test_request_with_no_output_limit_keeps_continuing_until_the_env_budget_is_spent(
+ monkeypatch: pytest.MonkeyPatch, is_async: bool, stream: bool
+):
+ monkeypatch.setenv(BUDGET_ENV, "50")
+ sent: Final[list[dict[str, object]]] = []
+ hops: Final = (
+ (_sse(STREAM_FIRST_CHUNK, STREAM_HOP_1_END), _sse(HOP_2_TRUNCATED), _sse(HOP_2))
+ if stream
+ else (
+ httpx.Response(200, json=HOP_1),
+ httpx.Response(200, json=HOP_2_TRUNCATED),
+ httpx.Response(200, json=HOP_2),
+ )
+ )
+ kwargs: Final = {"model": ARGON, "messages": list(MESSAGES), "stream": stream, "api_key": "fake-gemini-key"}
+ transport: Final = httpx.MockTransport(_replay(hops, sent))
+
+ response: Final = (
+ await litellm.acompletion(**kwargs, client=AsyncHTTPHandler(transport=transport))
+ if is_async
+ else litellm.completion(**kwargs, client=HTTPHandler(client=httpx.Client(transport=transport)))
+ )
+ chunks: Final = ([chunk async for chunk in response] if is_async else list(response)) if stream else []
+
+ assert len(sent) == 2
+ assert _output_limits(sent[0]) == {"max_output_tokens": 50}
+ if stream:
+ assert _stream_text(chunks) == "hello world"
+ assert _stream_finish_reasons(chunks) == ["length"]
+ assert {"continuation_token": "dG9rLTI="} in _delta_fields(chunks)
+ else:
+ assert response.choices[0].message.content == "hello world"
+ assert response.choices[0].finish_reason == "length"
+ assert response.choices[0].message.provider_specific_fields["continuation_token"] == "dG9rLTI="
+
+
+ "budget, model, request_params, expected_limits",
+ [
+ ("50", ARGON, {"max_tokens": 30}, {"max_output_tokens": 30}),
+ ("50", ARGON, {"max_completion_tokens": 30}, {"max_output_tokens": 30}),
+ (
+ "50",
+ ARGON,
+ {"extra_body": {"generationConfig": {"maxOutputTokens": 30}}},
+ {"maxOutputTokens": 30},
+ ),
+ (None, ARGON, {}, {}),
+ ("", ARGON, {}, {}),
+ ("a lot", ARGON, {}, {}),
+ ("0", ARGON, {}, {}),
+ ("-5", ARGON, {}, {}),
+ ("50", UNMAPPED_GEMINI, {}, {}),
+ ],
+)
+async def test_env_budget_applies_only_to_a_request_that_sets_no_output_limit_of_its_own(
+ monkeypatch: pytest.MonkeyPatch,
+ budget: str | None,
+ model: str,
+ request_params: Mapping[str, object],
+ expected_limits: Mapping[str, object],
+):
+ if budget is None:
+ monkeypatch.delenv(BUDGET_ENV, raising=False)
+ else:
+ monkeypatch.setenv(BUDGET_ENV, budget)
+ sent: Final[list[dict[str, object]]] = []
+
+ await litellm.acompletion(
+ model=model,
+ messages=list(MESSAGES),
+ api_key="fake-gemini-key",
+ client=AsyncHTTPHandler(transport=httpx.MockTransport(_replay((httpx.Response(200, json=HOP_2),), sent))),
+ **request_params,
+ )
+
+ assert _output_limits(sent[0]) == expected_limits
+
+
+ "modalities, expected_limits",
+ [
+ (["audio"], {}),
+ (["text", "audio"], {}),
+ (["text", "image"], {}),
+ (["text"], {"max_output_tokens": 50}),
+ ],
+)
+async def test_env_budget_applies_only_to_a_request_asking_for_text_output(
+ monkeypatch: pytest.MonkeyPatch, modalities: list[str], expected_limits: Mapping[str, object]
+):
+ monkeypatch.setenv(BUDGET_ENV, "50")
+ sent: Final[list[dict[str, object]]] = []
+
+ await litellm.acompletion(
+ model=ARGON,
+ messages=list(MESSAGES),
+ modalities=modalities,
+ api_key="fake-gemini-key",
+ client=AsyncHTTPHandler(transport=httpx.MockTransport(_replay((httpx.Response(200, json=HOP_2),), sent))),
+ )
+
+ assert _output_limits(sent[0]) == expected_limits
+
+
+def _ai_studio_model_in_mode(mode: str) -> str:
+ return next(
+ name
+ for name, row in litellm.model_cost.items()
+ if name.startswith("gemini/") and row.get("mode") == mode and row.get("max_output_tokens")
+ )
+
+
[email protected]("mode", ["audio_speech", "image_generation"])
+async def test_env_budget_skips_a_model_the_cost_map_does_not_list_as_a_chat_model(
+ monkeypatch: pytest.MonkeyPatch, mode: str
+):
+ monkeypatch.setenv(BUDGET_ENV, "50")
+ sent: Final[list[dict[str, object]]] = []
+
+ await litellm.acompletion(
+ model=_ai_studio_model_in_mode(mode),
+ messages=list(MESSAGES),
+ api_key="fake-gemini-key",
+ client=AsyncHTTPHandler(transport=httpx.MockTransport(_replay((httpx.Response(200, json=HOP_2),), sent))),
+ )
+
+ assert _output_limits(sent[0]) == {}
+
+
+ "output_modalities, expected_limits",
+ [
+ ({}, {"max_output_tokens": 50}),
+ ({"supported_output_modalities": ["text"]}, {"max_output_tokens": 50}),
+ ({"supported_output_modalities": ["text", "audio"]}, {"max_output_tokens": 50}),
+ ({"supported_output_modalities": ["audio"]}, {}),
+ ({"supported_output_modalities": "audio"}, {}),
+ ],
+)
+async def test_env_budget_applies_only_to_a_chat_model_the_cost_map_lists_as_answering_text(
+ monkeypatch: pytest.MonkeyPatch, output_modalities: Mapping[str, object], expected_limits: Mapping[str, object]
+):
+ monkeypatch.setenv(BUDGET_ENV, "50")
+ litellm.register_model(
+ {
+ UNMAPPED_GEMINI: {
+ "litellm_provider": "gemini",
+ "mode": "chat",
+ "max_output_tokens": 1000,
+ **output_modalities,
+ }
+ }
+ )
+ sent: Final[list[dict[str, object]]] = []
+
+ await litellm.acompletion(
+ model=UNMAPPED_GEMINI,
+ messages=list(MESSAGES),
+ api_key="fake-gemini-key",
+ client=AsyncHTTPHandler(transport=httpx.MockTransport(_replay((httpx.Response(200, json=HOP_2),), sent))),
+ )
+
+ assert _output_limits(sent[0]) == expected_limits
+
+
+ "extra_body",
+ [
+ {"generation_config": {"temperature": 0.1}},
+ {"generation_config": {"max_output_tokens": 30}},
+ {"generationConfig": {"response_modalities": ["AUDIO"]}},
+ ],
+)
+async def test_env_budget_leaves_a_snake_case_generation_config_from_extra_body_alone(
+ monkeypatch: pytest.MonkeyPatch, extra_body: Mapping[str, object]
+):
+ monkeypatch.setenv(BUDGET_ENV, "50")
+ sent: Final[list[dict[str, object]]] = []
+
+ await litellm.acompletion(
+ model=ARGON,
+ messages=list(MESSAGES),
+ extra_body=dict(extra_body),
+ api_key="fake-gemini-key",
+ client=AsyncHTTPHandler(transport=httpx.MockTransport(_replay((httpx.Response(200, json=HOP_2),), sent))),
+ )
+
+ assert _output_limits(sent[0]) == {}
+
+
+def _gemini_chat_models_answering_no_text() -> tuple[str, ...]:
+ rows: Final = (
+ (name, row)
+ for name, row in litellm.model_cost.items()
+ if row.get("mode") == "chat" and "text" not in row.get("supported_output_modalities", ("text",))
+ )
+ return tuple(
+ name if name.startswith("gemini/") else f"vertex_ai/{name}"
+ for name, row in rows
+ if row.get("litellm_provider") in ("gemini", "vertex_ai-language-models")
+ )
+
+
+async def test_env_budget_skips_every_chat_model_the_cost_map_lists_as_answering_no_text(
+ monkeypatch: pytest.MonkeyPatch, token_endpoint: _TokenEndpoint
+):
+ monkeypatch.setenv(BUDGET_ENV, "50")
+ models: Final = _gemini_chat_models_answering_no_text()
+ sent: Final[list[dict[str, object]]] = []
+ replies: Final = tuple(httpx.Response(200, json=HOP_2) for _ in models)
+ client: Final = AsyncHTTPHandler(transport=httpx.MockTransport(_replay(replies, sent)))
+
+ for model in models:
+ await litellm.acompletion(
+ model=model,
+ messages=list(MESSAGES),
+ api_key="fake-gemini-key",
+ vertex_project="p",
+ vertex_location="us-central1",
+ vertex_credentials=token_endpoint.credentials,
+ client=client,
+ )
+
+ assert models
+ assert {model: _output_limits(request) for model, request in zip(models, sent, strict=True)} == dict.fromkeys(
+ models, {}
+ )
+
+
[email protected]("stream", [False, True])
+async def test_env_budget_leaves_a_continuation_token_resume_with_no_limit_alone(
+ monkeypatch: pytest.MonkeyPatch, stream: bool
+):
+ monkeypatch.setenv(BUDGET_ENV, "50")
+ sent: Final[list[dict[str, object]]] = []
+ reply: Final = _sse(HOP_2) if stream else httpx.Response(200, json=HOP_2)
+
+ response: Final = await litellm.acompletion(
+ model=ARGON,
+ messages=list(MESSAGES),
+ continuation_token="dG9rLTE=",
+ stream=stream,
+ api_key="fake-gemini-key",
+ client=AsyncHTTPHandler(transport=httpx.MockTransport(_replay((reply,), sent))),
+ )
+ if stream:
+ _ = [chunk async for chunk in response]
+
+ assert sent[0]["continuationToken"] == "dG9rLTE="
+ assert _output_limits(sent[0]) == {}
+
+
[email protected]("model", ["gemini/gemini-2.5-flash", "vertex_ai/gemini-2.5-flash", ARGON])
+async def test_env_budget_above_a_models_output_limit_sends_that_limit_instead(
+ monkeypatch: pytest.MonkeyPatch, token_endpoint: _TokenEndpoint, model: str
+):
+ budget: Final = 2 * _cost_map_max_output_tokens(model)
+ monkeypatch.setenv(BUDGET_ENV, str(budget))
+ sent: Final[list[dict[str, object]]] = []
+
+ await litellm.acompletion(
+ model=model,
+ messages=list(MESSAGES),
+ api_key="fake-gemini-key",
+ vertex_project="p",
+ vertex_location="us-central1",
+ vertex_credentials=token_endpoint.credentials,
+ client=AsyncHTTPHandler(transport=httpx.MockTransport(_replay((httpx.Response(200, json=HOP_2),), sent))),
+ )
+
+ assert _output_limits(sent[0]) == {"max_output_tokens": _cost_map_max_output_tokens(model)}
+
+
+async def test_env_budget_never_goes_above_the_cost_map_limit_when_a_deployment_overrides_it(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ model: Final = "gemini/gemini-2.5-flash"
+ model_limit: Final = _cost_map_max_output_tokens(model)
+ monkeypatch.setenv(BUDGET_ENV, str(2 * model_limit))
+ router: Final = litellm.Router(
+ model_list=[
+ {"model_name": "plain", "litellm_params": {"model": model, "api_key": "fake-gemini-key"}},
+ {
+ "model_name": "raised",
+ "litellm_params": {"model": model, "api_key": "fake-gemini-key"},
+ "model_info": {"max_output_tokens": 4 * model_limit},
+ },
+ ]
+ )
+ sent: Final[list[dict[str, object]]] = []
+ replies: Final = (httpx.Response(200, json=HOP_2), httpx.Response(200, json=HOP_2))
+ client: Final = AsyncHTTPHandler(transport=httpx.MockTransport(_replay(replies, sent)))
+
+ for model_name in ("plain", "raised"):
+ await router.acompletion(model=model_name, messages=list(MESSAGES), client=client)
+
+ sent_limits: Final = [_output_limits(request).get("max_output_tokens", 0) for request in sent]
+ assert len(sent_limits) == 2
+ assert all(isinstance(limit, int) and limit <= model_limit for limit in sent_limits)
+
+
+async def test_env_budget_caps_each_deployment_at_its_own_model_info_limit_and_never_at_a_siblings(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ model: Final = "gemini/gemini-2.5-flash"
+ budget: Final = _cost_map_max_output_tokens(model) // 2
+ low_limit: Final = budget // 4
+ monkeypatch.setenv(BUDGET_ENV, str(budget))
+ router: Final = litellm.Router(
+ model_list=[
+ {
+ "model_name": "low",
+ "litellm_params": {"model": model, "api_key": "fake-gemini-key"},
+ "model_info": {"max_output_tokens": low_limit},
+ },
+ {"model_name": "plain", "litellm_params": {"model": model, "api_key": "fake-gemini-key"}},
+ ]
+ )
+ sent: Final[list[dict[str, object]]] = []
+ replies: Final = (httpx.Response(200, json=HOP_2), httpx.Response(200, json=HOP_2))
+ client: Final = AsyncHTTPHandler(transport=httpx.MockTransport(_replay(replies, sent)))
+
+ for model_name in ("plain", "low"):
+ await router.acompletion(model=model_name, messages=list(MESSAGES), client=client)
+
+ assert [_output_limits(request) for request in sent] == [
+ {"max_output_tokens": budget},
+ {"max_output_tokens": low_limit},
+ ]
+
+
[email protected]("deployment_limit", [0, -1])
+async def test_env_budget_ignores_a_deployment_model_info_limit_that_is_not_positive(
+ monkeypatch: pytest.MonkeyPatch, deployment_limit: int
+):
+ model: Final = "gemini/gemini-2.5-flash"
+ budget: Final = _cost_map_max_output_tokens(model) // 2
+ monkeypatch.setenv(BUDGET_ENV, str(budget))
+ router: Final = litellm.Router(
+ model_list=[
+ {
+ "model_name": "odd",
+ "litellm_params": {"model": model, "api_key": "fake-gemini-key"},
+ "model_info": {"max_output_tokens": deployment_limit},
+ }
+ ]
+ )
+ sent: Final[list[dict[str, object]]] = []
+
+ await router.acompletion(
+ model="odd",
+ messages=list(MESSAGES),
+ client=AsyncHTTPHandler(transport=httpx.MockTransport(_replay((httpx.Response(200, json=HOP_2),), sent))),
+ )
+
+ assert _output_limits(sent[0]) == {"max_output_tokens": budget}
+
+
+async def test_env_budget_on_a_direct_call_never_goes_above_the_cost_map_limit_after_a_router_raised_it(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ model: Final = "gemini/gemini-2.5-flash"
+ model_limit: Final = _cost_map_max_output_tokens(model)
+ monkeypatch.setenv(BUDGET_ENV, str(2 * model_limit))
+ litellm.Router(
+ model_list=[
+ {
+ "model_name": "raised",
+ "litellm_params": {"model": model, "api_key": "fake-gemini-key"},
+ "model_info": {"max_output_tokens": 4 * model_limit},
+ }
+ ]
+ )
+ sent: Final[list[dict[str, object]]] = []
+
+ await litellm.acompletion(
+ model=model,
+ messages=list(MESSAGES),
+ api_key="fake-gemini-key",
+ client=AsyncHTTPHandler(transport=httpx.MockTransport(_replay((httpx.Response(200, json=HOP_2),), sent))),
+ )
+
+ assert _output_limits(sent[0]) == {"max_output_tokens": model_limit}
+
+
+async def test_env_budget_on_a_direct_call_follows_a_lower_limit_set_with_register_model(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ model: Final = "gemini/gemini-2.5-flash"
+ lowered_limit: Final = _cost_map_max_output_tokens(model) // 4
+ monkeypatch.setenv(BUDGET_ENV, str(2 * lowered_limit))
+ litellm.register_model({model: {"litellm_provider": "gemini", "max_output_tokens": lowered_limit}})
+ sent: Final[list[dict[str, object]]] = []
+
+ await litellm.acompletion(
+ model=model,
+ messages=list(MESSAGES),
+ api_key="fake-gemini-key",
+ client=AsyncHTTPHandler(transport=httpx.MockTransport(_replay((httpx.Response(200, json=HOP_2),), sent))),
+ )
+
+ assert _output_limits(sent[0]) == {"max_output_tokens": lowered_limit}
+
+
+ "generation_config",
+ [None, {"responseModalities": None}, {"responseModalities": {"TEXT": 1}}],
+)
+async def test_env_budget_sends_a_generation_config_of_an_unexpected_shape_as_it_came(
+ monkeypatch: pytest.MonkeyPatch, generation_config: object
+):
+ monkeypatch.setenv(BUDGET_ENV, "50")
+ sent: Final[list[dict[str, object]]] = []
+
+ await litellm.acompletion(
+ model=ARGON,
+ messages=list(MESSAGES),
+ extra_body={"generationConfig": generation_config},
+ api_key="fake-gemini-key",
+ client=AsyncHTTPHandler(transport=httpx.MockTransport(_replay((httpx.Response(200, json=HOP_2),), sent))),
+ )
+
+ assert sent[0]["generationConfig"] == generation_config
+
+
def test_initial_prompt_tokens_is_absent_on_a_single_hop_and_the_first_hops_count_otherwise():
assert initial_prompt_tokens_of((HOP_1,)) is None
assert initial_prompt_tokens_of((HOP_1, HOP_2)) == 10