From 49633a7ca7a72c324d2d91dcc8fe81dedf5bd88b Mon Sep 17 00:00:00 2001 From: cnpierrepapi Date: Fri, 28 Aug 2026 12:33:08 +0100 Subject: [PATCH 1/3] feat(models): add LlmRequest.to_generate_content_body() LlmRequest.config is one flat GenerateContentConfig namespace, but its fields go to three places on the wire: 8 at the top level, 22 inside generationConfig, and 3 that are client-side only and rejected by the endpoint. Nothing on the type says which is which, and getting it wrong does not raise. A custom BaseLlm that buries tools in generationConfig gets a 200 back with no function call in it, because none was offered. Rather than document the split, delegate to the same converter google-genai uses for its own built-in models, so there is one copy of the mapping and it moves when GenerateContentConfig moves. A hand written list is a second copy that goes stale the moment the type gains a field. Also handles three things that bite anyone calling the converter raw: strips the private "_url" routing key, which is a 400 if sent as body; covers the model_selection_config -> modelConfig rename, the only field that changes name in transit; and re-raises genai's ValueError with the LlmRequest.config field that caused it, so the error points at the line that set it rather than at the converter. Closes #6880 --- .../adk/models/_generate_content_body.py | 131 ++++++++ src/google/adk/models/llm_request.py | 35 +++ .../models/test_generate_content_body.py | 293 ++++++++++++++++++ 3 files changed, 459 insertions(+) create mode 100644 src/google/adk/models/_generate_content_body.py create mode 100644 tests/unittests/models/test_generate_content_body.py diff --git a/src/google/adk/models/_generate_content_body.py b/src/google/adk/models/_generate_content_body.py new file mode 100644 index 00000000000..181e231c441 --- /dev/null +++ b/src/google/adk/models/_generate_content_body.py @@ -0,0 +1,131 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Turn an ``LlmRequest`` into a ``generateContent`` request body. + +``LlmRequest.config`` is a ``types.GenerateContentConfig``: one flat namespace +of 35 fields. On the wire those fields go to three different places. Some sit at +the top level of the request, most belong inside ``generationConfig``, and a few +mean something only to the client library and are rejected by the endpoint. + +Nothing on the type says which is which, and getting it wrong does not raise. +Bury ``tools`` inside ``generationConfig`` and the call still returns 200 with a +well formed response in it. The tools are simply absent, so the model answers +from memory instead of calling anything, and the failure looks like a model that +chose not to call the tool. + +Rather than keep a hand written list of which field goes where, this delegates +to the same converter ``google-genai`` uses for its own built-in models. A hand +written list is a second copy of the mapping and it goes stale the moment +``GenerateContentConfig`` gains a field: every custom ``BaseLlm`` in the wild +then starts silently dropping that field. Delegating means there is one copy and +it moves when the type moves. +""" + +from __future__ import annotations + +from typing import Any + +from google.genai import models as _genai_models +from google.genai import types + +__all__ = ["to_generate_content_body"] + + +class _ApiMode: + """The one thing the genai converters need from an API client. + + ``_GenerateContentParameters_to_vertex`` touches exactly one attribute on the + client it is handed, ``vertexai``, by way of ``t_model``. Passing a real + client works and is preferred when the caller has one. This stands in when the + caller does not, so the helper stays usable from a ``BaseLlm`` that talks REST + directly and never builds a genai client at all. + """ + + __slots__ = ("vertexai",) + + def __init__(self, vertexai: bool): + self.vertexai = vertexai + + +def to_generate_content_body( + llm_request: Any, + *, + vertexai: bool = True, + api_client: Any | None = None, +) -> dict[str, Any]: + """Return the request body for ``llm_request``. + + Args: + llm_request: the ``LlmRequest`` to convert. + vertexai: whether the body is bound for Vertex AI rather than the Gemini + Developer API. The two differ in more than the URL: some config fields + exist on one and not the other, so this is not cosmetic. Ignored when + ``api_client`` is given. + api_client: a genai API client, if the caller has one. Preferred over + ``vertexai`` because it is the real thing rather than a stand-in. + + Returns: + A dict ready to send as the request body. The model name is not in it; the + caller already knows the model, and on Vertex it belongs in the URL. + + Raises: + ValueError: if a config field is not valid for the target API. The message + names the ``GenerateContentConfig`` field so the error points at the line + that set it rather than at the converter. + """ + client = api_client if api_client is not None else _ApiMode(vertexai) + + is_vertex = getattr(client, "vertexai", True) + + params = types._GenerateContentParameters( + model=llm_request.model, + contents=llm_request.contents, + config=llm_request.config, + ) + + convert = ( + _genai_models._GenerateContentParameters_to_vertex + if is_vertex + else _genai_models._GenerateContentParameters_to_mldev + ) + + try: + body = convert(client, params) + except ValueError as exc: + raise ValueError(_annotate(str(exc), vertexai=is_vertex)) from exc + + # The converters return the model under a private "_url" key, because the + # caller is normally the genai client, which uses it to build the path. It is + # routing information, not body content. Sending it is a 400. + body.pop("_url", None) + return body + + +def _annotate(message: str, *, vertexai: bool) -> str: + """Point a genai validation error back at the ADK field that caused it. + + The converters raise messages that start with the offending field name, e.g. + "enable_enhanced_civic_answers parameter is only supported in ...". That is + accurate and still hard to act on from a ``BaseLlm``, because the reader has + no reason to connect it to the config they built several layers up. + """ + first = message.split(" ", 1)[0] + if first in types.GenerateContentConfig.model_fields: + mode = "Vertex AI" if vertexai else "the Gemini Developer API" + return ( + f"{message} (set as LlmRequest.config.{first}; this request targets" + f" {mode}.)" + ) + return message diff --git a/src/google/adk/models/llm_request.py b/src/google/adk/models/llm_request.py index 894d7c40290..f571fae2728 100644 --- a/src/google/adk/models/llm_request.py +++ b/src/google/adk/models/llm_request.py @@ -15,6 +15,7 @@ from __future__ import annotations import logging +from typing import Any from google.genai import types from pydantic import BaseModel @@ -405,3 +406,37 @@ def set_output_schema( self.config.response_schema = schema self.config.response_mime_type = "application/json" + + def to_generate_content_body( + self, + *, + vertexai: bool = True, + api_client: Any | None = None, + ) -> dict[str, Any]: + """Returns this request as a ``generateContent`` request body. + + ``config`` is one flat namespace, but its fields go to three different + places on the wire. Some sit at the top level, most belong inside + ``generationConfig``, and a few are consumed by the client library and + rejected by the endpoint. Getting that split wrong does not raise: bury + ``tools`` in ``generationConfig`` and the call returns 200 with no function + call in it, because none was ever offered. + + Custom ``BaseLlm`` implementations that build their own request body should + use this rather than flattening ``config`` by hand. + + Args: + vertexai: whether the body is bound for Vertex AI rather than the Gemini + Developer API. Ignored when ``api_client`` is given. + api_client: a genai API client, if the caller has one. + + Returns: + A dict ready to send as the request body. + """ + # Imported here rather than at module scope: this pulls in google.genai's + # model converters, which nothing else in this module needs. + from ._generate_content_body import to_generate_content_body + + return to_generate_content_body( + self, vertexai=vertexai, api_client=api_client + ) diff --git a/tests/unittests/models/test_generate_content_body.py b/tests/unittests/models/test_generate_content_body.py new file mode 100644 index 00000000000..f789038bdc1 --- /dev/null +++ b/tests/unittests/models/test_generate_content_body.py @@ -0,0 +1,293 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the LlmRequest -> generateContent body conversion.""" + +import pytest +from google.adk.models.llm_request import LlmRequest +from google.genai import types + +from google.adk.models._generate_content_body import to_generate_content_body + +# Fields that sit at the top level of a Vertex generateContent request, as of +# google-genai 2.18.1. This list exists to be asserted against, not to be used: +# the helper derives the split rather than reading it. If a release moves a +# field, test_every_config_field_is_classified fails first and names it. +TOP_LEVEL = { + "cachedContent", + "labels", + "modelArmorConfig", + "safetySettings", + "serviceTier", + "systemInstruction", + "toolConfig", + "tools", +} + +# Config fields the client library consumes. The endpoint rejects them. +CLIENT_ONLY = { + "httpOptions", + "automaticFunctionCalling", + "shouldReturnHttpResponse", +} + + +def _tool() -> types.Tool: + return types.Tool( + function_declarations=[ + types.FunctionDeclaration( + name="a_tool", + description="Look up the weather in a city.", + parameters=types.Schema( + type=types.Type.OBJECT, + properties={"city": types.Schema(type=types.Type.STRING)}, + ), + ) + ] + ) + + +def _request(**config_kwargs) -> LlmRequest: + return LlmRequest( + model="gemini-3.5-flash", + contents=[types.Content(role="user", parts=[types.Part(text="hi")])], + config=types.GenerateContentConfig(**config_kwargs), + ) + + +def _full_config_kwargs() -> dict: + """Every field that can be set at once on a Vertex-bound request. + + Two of the 35 are left out on purpose. response_json_schema is mutually + exclusive with response_schema, and enable_enhanced_civic_answers is Developer + API only, which test_developer_api_only_field_is_named covers separately. + """ + return dict( + system_instruction="You are a research agent.", + tools=[_tool()], + tool_config=types.ToolConfig( + function_calling_config=types.FunctionCallingConfig(mode="AUTO") + ), + safety_settings=[ + types.SafetySetting( + category="HARM_CATEGORY_HATE_SPEECH", threshold="BLOCK_ONLY_HIGH" + ) + ], + cached_content="projects/p/locations/us-central1/cachedContents/123", + labels={"team": "research"}, + http_options=types.HttpOptions(timeout=60_000), + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True + ), + should_return_http_response=True, + temperature=0.2, + top_p=0.9, + top_k=40, + candidate_count=1, + max_output_tokens=8192, + stop_sequences=["STOP"], + response_logprobs=True, + logprobs=3, + presence_penalty=0.1, + frequency_penalty=0.1, + seed=42, + response_mime_type="application/json", + response_schema=types.Schema( + type=types.Type.OBJECT, + properties={"answer": types.Schema(type=types.Type.STRING)}, + ), + routing_config=types.GenerationConfigRoutingConfig( + auto_mode=types.GenerationConfigRoutingConfigAutoRoutingMode( + model_routing_preference="BALANCED" + ) + ), + model_selection_config=types.ModelSelectionConfig( + feature_selection_preference="BALANCED" + ), + response_modalities=["TEXT"], + media_resolution="MEDIA_RESOLUTION_MEDIUM", + speech_config=types.SpeechConfig( + voice_config=types.VoiceConfig( + prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore") + ) + ), + audio_timestamp=True, + thinking_config=types.ThinkingConfig( + include_thoughts=True, thinking_budget=4096 + ), + image_config=types.ImageConfig(aspect_ratio="1:1"), + model_armor_config=types.ModelArmorConfig( + prompt_template_name="projects/p/locations/us-central1/templates/t" + ), + service_tier="standard", + audio_transcription_config=types.AudioTranscriptionConfig(), + ) + + +# The bug this whole module exists to prevent. +def test_tools_are_top_level_not_buried_in_generation_config(): + body = to_generate_content_body(_request(temperature=0.2, tools=[_tool()])) + + assert "tools" in body + assert "tools" not in body["generationConfig"] + + +def test_temperature_stays_in_generation_config(): + body = to_generate_content_body(_request(temperature=0.2, tools=[_tool()])) + + assert body["generationConfig"]["temperature"] == pytest.approx(0.2) + assert "temperature" not in body + + +def test_client_only_fields_never_reach_the_wire(): + body = to_generate_content_body( + _request( + temperature=0.2, + http_options=types.HttpOptions(timeout=60_000), + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True + ), + should_return_http_response=True, + ) + ) + + emitted = set(body) | set(body.get("generationConfig", {})) + assert not (CLIENT_ONLY & emitted) + + +def test_url_routing_key_is_stripped(): + # The converter returns the model under "_url" for the genai client to build + # a path with. It is not body content and Vertex 400s on it. + body = to_generate_content_body(_request(temperature=0.2)) + + assert "_url" not in body + + +def test_full_field_set_splits_eight_twentytwo_three(): + body = to_generate_content_body(_request(**_full_config_kwargs())) + + top = set(body) - {"contents", "generationConfig"} + generation = set(body["generationConfig"]) + + assert top == TOP_LEVEL + assert not (TOP_LEVEL & generation), "a top-level field was buried" + assert not (CLIENT_ONLY & (top | generation)) + # 33 set, 8 up top, 3 dropped, so 22 sampling settings and nothing lost. + assert len(generation) == 22 + + +def test_model_selection_config_is_renamed_to_model_config(): + # The only field that changes name in transit. Anyone diffing their own config + # keys against the emitted body gets a false miss on this one. + body = to_generate_content_body( + _request( + model_selection_config=types.ModelSelectionConfig( + feature_selection_preference="BALANCED" + ) + ) + ) + + assert "modelConfig" in body["generationConfig"] + assert "modelSelectionConfig" not in body["generationConfig"] + + +def test_developer_api_only_field_is_named_in_the_error(): + request = _request(enable_enhanced_civic_answers=True) + + with pytest.raises(ValueError) as excinfo: + to_generate_content_body(request, vertexai=True) + + message = str(excinfo.value) + assert "enable_enhanced_civic_answers" in message + # The point of the annotation: say where it was set, not just that it is bad. + assert "LlmRequest.config" in message + assert "Vertex AI" in message + + +def test_developer_api_accepts_what_vertex_rejects(): + body = to_generate_content_body( + _request(enable_enhanced_civic_answers=True), vertexai=False + ) + + assert body is not None + + +def test_string_system_instruction_becomes_a_content_block(): + body = to_generate_content_body(_request(system_instruction="Be terse.")) + + assert body["systemInstruction"]["parts"][0]["text"] == "Be terse." + + +def test_no_config_still_produces_a_body(): + request = LlmRequest( + model="gemini-3.5-flash", + contents=[types.Content(role="user", parts=[types.Part(text="hi")])], + ) + + body = to_generate_content_body(request) + + assert body["contents"][0]["parts"][0]["text"] == "hi" + + +# The test that keeps the other tests honest. +def test_every_config_field_is_classified(): + """Fail when GenerateContentConfig gains a field nobody has classified. + + This is the whole argument for the helper. A hand written mapping goes stale + silently: the new field lands in generationConfig, the endpoint ignores it, + and no one finds out until a feature quietly stops working. This turns that + into a red test naming the field. + """ + known = ( + TOP_LEVEL + | CLIENT_ONLY + | {"enableEnhancedCivicAnswers", "responseJsonSchema"} + ) + body = to_generate_content_body(_request(**_full_config_kwargs())) + classified = ( + (set(body) - {"contents", "generationConfig"}) + | set(body["generationConfig"]) + | known + ) + + # Aliases as the wire spells them, which is how the body is keyed. + declared = { + field.alias or name + for name, field in types.GenerateContentConfig.model_fields.items() + } + # modelSelectionConfig is emitted as modelConfig; see the rename test. + declared.discard("modelSelectionConfig") + classified.add("modelSelectionConfig") + + unclassified = declared - classified + assert not unclassified, ( + "GenerateContentConfig gained field(s) with no known destination:" + f" {sorted(unclassified)}. Add them to TOP_LEVEL or CLIENT_ONLY and" + " confirm where the converter puts them." + ) + + +def test_method_matches_function(): + """LlmRequest.to_generate_content_body is a thin delegate, not a fork.""" + request = _request(**_full_config_kwargs()) + + assert request.to_generate_content_body() == to_generate_content_body(request) + + +def test_method_passes_the_api_mode_through(): + request = _request(enable_enhanced_civic_answers=True) + + assert request.to_generate_content_body(vertexai=False) is not None + with pytest.raises(ValueError): + request.to_generate_content_body(vertexai=True) From eb4b58fd9a502113cfb2c8b56904b2eeca467cdd Mon Sep 17 00:00:00 2001 From: cnpierrepapi Date: Wed, 16 Sep 2026 21:18:34 +0100 Subject: [PATCH 2/3] test(models): fail loudly if genai renames the private converters --- .../models/test_generate_content_body.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/unittests/models/test_generate_content_body.py b/tests/unittests/models/test_generate_content_body.py index f789038bdc1..bfafb61272b 100644 --- a/tests/unittests/models/test_generate_content_body.py +++ b/tests/unittests/models/test_generate_content_body.py @@ -16,6 +16,7 @@ import pytest from google.adk.models.llm_request import LlmRequest +from google.genai import models as _genai_models from google.genai import types from google.adk.models._generate_content_body import to_generate_content_body @@ -278,6 +279,27 @@ def test_every_config_field_is_classified(): ) +@pytest.mark.parametrize( + "module, symbol", + [ + (types, "_GenerateContentParameters"), + (_genai_models, "_GenerateContentParameters_to_vertex"), + (_genai_models, "_GenerateContentParameters_to_mldev"), + ], +) +def test_private_genai_symbols_still_exist(module, symbol): + """Fail in CI when a google-genai release renames a converter we call. + + These are underscore prefixed, so they sit outside genai's semver contract + while our pin allows any 2.x. Without this, a rename would surface as an + AttributeError inside someone's BaseLlm at request time. + """ + assert hasattr(module, symbol), ( + f"google-genai no longer exposes {module.__name__}.{symbol}, which" + " to_generate_content_body depends on." + ) + + def test_method_matches_function(): """LlmRequest.to_generate_content_body is a thin delegate, not a fork.""" request = _request(**_full_config_kwargs()) From ecacf48ce63a7584dbdb21fa75b36ed790043fdc Mon Sep 17 00:00:00 2001 From: cnpierrepapi Date: Thu, 5 Nov 2026 01:07:21 +0100 Subject: [PATCH 3/3] fix(models): return a JSON-serializable generateContent body The converters leave pydantic objects and raw bytes in the dict, and genai finishes the job with convert_to_dict and encode_unserializable_types just before it sends. The helper stopped short of that, so json.dumps failed on any body with tools, a schema, safety settings or an inline image, which made the "ready to send" in its docstring wrong. Also strips every underscore key, as the client does, rather than only _url. Classifies the config fields added since this was written: continuationToken is top level, automaticContinuation is client side, store is top level on the Developer API only, and generation_output_config goes out as outputConfig on Vertex only. Adds a test that runs the same request through the real client on both backends and compares against what reaches _request, and adds the two new genai symbols to the guard test. --- .../adk/models/_generate_content_body.py | 19 +- .../models/test_generate_content_body.py | 168 ++++++++++++++++-- 2 files changed, 172 insertions(+), 15 deletions(-) diff --git a/src/google/adk/models/_generate_content_body.py b/src/google/adk/models/_generate_content_body.py index 181e231c441..b39edf7471d 100644 --- a/src/google/adk/models/_generate_content_body.py +++ b/src/google/adk/models/_generate_content_body.py @@ -37,6 +37,7 @@ from typing import Any +from google.genai import _common as _genai_common from google.genai import models as _genai_models from google.genai import types @@ -77,8 +78,9 @@ def to_generate_content_body( ``vertexai`` because it is the real thing rather than a stand-in. Returns: - A dict ready to send as the request body. The model name is not in it; the - caller already knows the model, and on Vertex it belongs in the URL. + A JSON-serializable dict ready to send as the request body. The model name + is not in it; the caller already knows the model, and on Vertex it belongs + in the URL. Raises: ValueError: if a config field is not valid for the target API. The message @@ -108,9 +110,16 @@ def to_generate_content_body( # The converters return the model under a private "_url" key, because the # caller is normally the genai client, which uses it to build the path. It is - # routing information, not body content. Sending it is a 400. - body.pop("_url", None) - return body + # routing information, not body content. Sending it is a 400. The client drops + # every underscore key before sending, so do the same. + body = {key: value for key, value in body.items() if not key.startswith("_")} + # The converters leave pydantic objects and raw bytes in the dict: tools, + # schemas, inline images, thought signatures. genai finishes the job with + # these two calls just before it sends, so a caller doing its own HTTP needs + # them too or json.dumps fails. + return _genai_common.encode_unserializable_types( + _genai_common.convert_to_dict(body) + ) def _annotate(message: str, *, vertexai: bool) -> str: diff --git a/tests/unittests/models/test_generate_content_body.py b/tests/unittests/models/test_generate_content_body.py index bfafb61272b..6fa597c7dc6 100644 --- a/tests/unittests/models/test_generate_content_body.py +++ b/tests/unittests/models/test_generate_content_body.py @@ -14,19 +14,25 @@ """Tests for the LlmRequest -> generateContent body conversion.""" -import pytest +import base64 +import json +from unittest import mock + +from google.adk.models._generate_content_body import to_generate_content_body from google.adk.models.llm_request import LlmRequest +from google.genai import _common as _genai_common +from google.genai import Client from google.genai import models as _genai_models from google.genai import types - -from google.adk.models._generate_content_body import to_generate_content_body +import pytest # Fields that sit at the top level of a Vertex generateContent request, as of -# google-genai 2.18.1. This list exists to be asserted against, not to be used: +# google-genai 2.30, the floor of our pin. This list exists to be asserted against, not to be used: # the helper derives the split rather than reading it. If a release moves a # field, test_every_config_field_is_classified fails first and names it. TOP_LEVEL = { "cachedContent", + "continuationToken", "labels", "modelArmorConfig", "safetySettings", @@ -39,6 +45,7 @@ # Config fields the client library consumes. The endpoint rejects them. CLIENT_ONLY = { "httpOptions", + "automaticContinuation", "automaticFunctionCalling", "shouldReturnHttpResponse", } @@ -70,9 +77,10 @@ def _request(**config_kwargs) -> LlmRequest: def _full_config_kwargs() -> dict: """Every field that can be set at once on a Vertex-bound request. - Two of the 35 are left out on purpose. response_json_schema is mutually - exclusive with response_schema, and enable_enhanced_civic_answers is Developer - API only, which test_developer_api_only_field_is_named covers separately. + Left out on purpose: response_json_schema is mutually exclusive with + response_schema. enable_enhanced_civic_answers and store are Developer API + only, and generation_output_config is newer than our pin's floor; each has its + own test below. """ return dict( system_instruction="You are a research agent.", @@ -92,6 +100,8 @@ def _full_config_kwargs() -> dict: disable=True ), should_return_http_response=True, + automatic_continuation=False, + continuation_token=b"\xb6\x89", temperature=0.2, top_p=0.9, top_k=40, @@ -160,6 +170,7 @@ def test_client_only_fields_never_reach_the_wire(): disable=True ), should_return_http_response=True, + automatic_continuation=False, ) ) @@ -175,7 +186,18 @@ def test_url_routing_key_is_stripped(): assert "_url" not in body -def test_full_field_set_splits_eight_twentytwo_three(): +def test_every_underscore_key_is_stripped(): + with mock.patch.object( + _genai_models, + "_GenerateContentParameters_to_vertex", + return_value={"_url": {}, "_query": {}, "contents": []}, + ): + body = to_generate_content_body(_request(temperature=0.2)) + + assert body == {"contents": []} + + +def test_full_field_set_splits_nine_twentytwo_four(): body = to_generate_content_body(_request(**_full_config_kwargs())) top = set(body) - {"contents", "generationConfig"} @@ -184,7 +206,7 @@ def test_full_field_set_splits_eight_twentytwo_three(): assert top == TOP_LEVEL assert not (TOP_LEVEL & generation), "a top-level field was buried" assert not (CLIENT_ONLY & (top | generation)) - # 33 set, 8 up top, 3 dropped, so 22 sampling settings and nothing lost. + # 35 set, 9 up top, 4 dropped, so 22 sampling settings and nothing lost. assert len(generation) == 22 @@ -224,6 +246,125 @@ def test_developer_api_accepts_what_vertex_rejects(): assert body is not None +def _needs_field(name: str) -> None: + if name not in types.GenerateContentConfig.model_fields: + pytest.skip(f"{name} is newer than this google-genai") + + +def test_store_is_top_level_on_the_developer_api(): + _needs_field("store") + + body = to_generate_content_body(_request(store=True), vertexai=False) + + assert body["store"] is True + assert "store" not in body["generationConfig"] + + +def test_store_is_rejected_on_vertex_and_named(): + _needs_field("store") + + with pytest.raises(ValueError, match="LlmRequest.config.store"): + to_generate_content_body(_request(store=True), vertexai=True) + + +def test_generation_output_config_is_renamed_and_top_level_on_vertex(): + _needs_field("generation_output_config") + + body = to_generate_content_body( + _request( + generation_output_config=types.GenerationOutputConfig( + output_uri_prefix="gs://bucket/prefix" + ) + ), + vertexai=True, + ) + + assert body["outputConfig"] + assert "generationOutputConfig" not in body + assert "outputConfig" not in body["generationConfig"] + + +def _image_request(**config_kwargs) -> LlmRequest: + return LlmRequest( + model="gemini-3.5-flash", + contents=[ + types.Content( + role="user", + parts=[ + types.Part( + text="what is this", thought_signature=b"\x01\x02" + ), + types.Part( + inline_data=types.Blob( + data=b"\x89PNG\x00\xff", mime_type="image/png" + ) + ), + ], + ) + ], + config=types.GenerateContentConfig(**config_kwargs), + ) + + +def test_full_body_is_json_serializable(): + # Tools and schemas come out of the converter as pydantic objects, and bytes as + # bytes. The docstring promises a body you can send, so hold it to that. + body = to_generate_content_body(_image_request(**_full_config_kwargs())) + + assert json.loads(json.dumps(body))["tools"] + + +def test_bytes_are_base64_encoded(): + body = to_generate_content_body( + _image_request(continuation_token=b"\xb6\x89") + ) + + part = body["contents"][0]["parts"][1] + assert base64.urlsafe_b64decode(part["inlineData"]["data"]) == ( + b"\x89PNG\x00\xff" + ) + assert base64.urlsafe_b64decode(body["continuationToken"]) == b"\xb6\x89" + + +@pytest.mark.parametrize( + "client_kwargs, config_kwargs", + [ + ( + {"vertexai": True, "project": "p", "location": "us-central1"}, + _full_config_kwargs(), + ), + ( + {"vertexai": False, "api_key": "k"}, + {"tools": [_tool()], "temperature": 0.2}, + ), + ], + ids=["vertex", "developer_api"], +) +def test_body_matches_what_the_genai_client_sends(client_kwargs, config_kwargs): + """The real check on the helper: same request, same body as genai itself.""" + request = _image_request(**config_kwargs) + client = Client(**client_kwargs) + captured = {} + + # _request sits below all of genai's own request building, so what it receives + # is what goes on the wire. + def capture(http_request, http_options=None, stream=False): + captured.update(http_request.data) + raise InterruptedError + + with mock.patch.object(client._api_client, "_request", side_effect=capture): + with pytest.raises(InterruptedError): + client.models._generate_content( + model=request.model, contents=request.contents, config=request.config + ) + + assert captured + assert ( + to_generate_content_body(request, vertexai=client_kwargs["vertexai"]) + == captured + ) + + def test_string_system_instruction_becomes_a_content_block(): body = to_generate_content_body(_request(system_instruction="Be terse.")) @@ -253,7 +394,12 @@ def test_every_config_field_is_classified(): known = ( TOP_LEVEL | CLIENT_ONLY - | {"enableEnhancedCivicAnswers", "responseJsonSchema"} + | { + "enableEnhancedCivicAnswers", + "generationOutputConfig", + "responseJsonSchema", + "store", + } ) body = to_generate_content_body(_request(**_full_config_kwargs())) classified = ( @@ -285,6 +431,8 @@ def test_every_config_field_is_classified(): (types, "_GenerateContentParameters"), (_genai_models, "_GenerateContentParameters_to_vertex"), (_genai_models, "_GenerateContentParameters_to_mldev"), + (_genai_common, "convert_to_dict"), + (_genai_common, "encode_unserializable_types"), ], ) def test_private_genai_symbols_still_exist(module, symbol):