From 7cf32c634c6eb3a202936264ef24d46f8422df74 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Wed, 11 Nov 2026 14:19:36 -0600 Subject: [PATCH 1/2] fix(py): stop Gemini tool-calling loops and log failed GenkitError turns --- .../genkit_google_genai/_models/_gemini.py | 169 ++---- .../tests/models/googlegenai_gemini_test.py | 529 +++++++++++++++++- packages/genkit/src/genkit/_ai/_generate.py | 12 +- .../tests/genkit/ai/generate_logging_test.py | 79 ++- 4 files changed, 652 insertions(+), 137 deletions(-) diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py index da2d46d13..f468b5ad7 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py @@ -377,6 +377,28 @@ def _tool_config(tool_choice: str, function_tools: list[genai_types.Tool]) -> ge return genai_types.ToolConfig(function_calling_config=calling) +def _effective_tool_choice(request: ModelRequest) -> str | None: + """The request's tool_choice, with 'required' relaxed to 'auto' once tools have answered. + + Gemini's ANY mode only allows a function call, so keeping 'required' on + the turn after the tool responses loops until max_turns and never + produces the final answer. 'required' forces the first call of a user + turn; if any message after the most recent model turn carries a tool + response (even when middleware appended a trailing user message), later + turns may answer. + """ + choice = request.tool_choice + if choice != 'required': + return choice + saw_tool_response = False + for msg in reversed(request.messages): + if msg.role == Role.MODEL: + return 'auto' if saw_tool_response else choice + if msg.role == Role.TOOL or any(p.tool_response is not None for p in msg.content): + saw_tool_response = True + return choice + + def _pop_prefixed(config: dict[str, Any], prefix: str) -> dict[str, Any]: """Pop every ``name`` key from *config*, returned as ``{name: value}``.""" return {key[len(prefix) :]: config.pop(key) for key in [k for k in config if k.startswith(prefix)]} @@ -813,66 +835,37 @@ class GemmaConfig(GeminiConfig): common_field_bounds = {'top_p': (0.0, 1.0)} +# Native JSON mode combined with function declarations causes Gemini to +# re-call tools in a loop; NO_TOOLS keeps native constrained JSON when no +# tools are attached and switches to schema prompt instructions with tools. GEMINI_TEXT_SUPPORTS = ModelSupports( multiturn=True, media=True, tools=True, tool_choice=True, system_role=True, - constrained=ConstrainedSupport.ALL, + constrained=ConstrainedSupport.NO_TOOLS, output=['text', 'json'], ) GEMINI_2_5_PRO_EXP_03_25 = ModelInfo( label='Google AI - Gemini 2.5 Pro Exp 03-25', - supports=ModelSupports( - multiturn=True, - media=True, - tools=True, - tool_choice=True, - system_role=True, - constrained=ConstrainedSupport.ALL, - output=['text', 'json'], - ), + supports=GEMINI_TEXT_SUPPORTS, ) GEMINI_2_5_PRO_PREVIEW_03_25 = ModelInfo( label='Google AI - Gemini 2.5 Pro Preview 03-25', - supports=ModelSupports( - multiturn=True, - media=True, - tools=True, - tool_choice=True, - system_role=True, - constrained=ConstrainedSupport.ALL, - output=['text', 'json'], - ), + supports=GEMINI_TEXT_SUPPORTS, ) GEMINI_2_5_PRO_PREVIEW_05_06 = ModelInfo( label='Google AI - Gemini 2.5 Pro Preview 05-06', - supports=ModelSupports( - multiturn=True, - media=True, - tools=True, - tool_choice=True, - system_role=True, - constrained=ConstrainedSupport.ALL, - output=['text', 'json'], - ), + supports=GEMINI_TEXT_SUPPORTS, ) GEMINI_2_5_FLASH_PREVIEW_04_17 = ModelInfo( label='Google AI - Gemini 2.5 Flash Preview 04-17', - supports=ModelSupports( - multiturn=True, - media=True, - tools=True, - tool_choice=True, - system_role=True, - constrained=ConstrainedSupport.ALL, - output=['text', 'json'], - ), + supports=GEMINI_TEXT_SUPPORTS, ) GEMINI_2_5_PRO = ModelInfo( @@ -887,54 +880,22 @@ class GemmaConfig(GeminiConfig): GEMINI_2_5_FLASH_LITE = ModelInfo( label='Google AI - Gemini 2.5 Flash Lite', - supports=ModelSupports( - multiturn=True, - media=True, - tools=True, - tool_choice=True, - system_role=True, - constrained=ConstrainedSupport.NO_TOOLS, - output=['text', 'json'], - ), + supports=GEMINI_TEXT_SUPPORTS, ) GEMINI_3_FLASH_PREVIEW = ModelInfo( label='Google AI - Gemini 3 Flash Preview', - supports=ModelSupports( - multiturn=True, - media=True, - tools=True, - tool_choice=True, - system_role=True, - constrained=ConstrainedSupport.ALL, - output=['text', 'json'], - ), + supports=GEMINI_TEXT_SUPPORTS, ) GEMINI_3_PRO_PREVIEW = ModelInfo( label='Google AI - Gemini 3 Pro Preview', - supports=ModelSupports( - multiturn=True, - media=True, - tools=True, - tool_choice=True, - system_role=True, - constrained=ConstrainedSupport.ALL, - output=['text', 'json'], - ), + supports=GEMINI_TEXT_SUPPORTS, ) GEMINI_3_5_FLASH = ModelInfo( label='Google AI - Gemini 3.5 Flash', - supports=ModelSupports( - multiturn=True, - media=True, - tools=True, - tool_choice=True, - system_role=True, - constrained=ConstrainedSupport.ALL, - output=['text', 'json'], - ), + supports=GEMINI_TEXT_SUPPORTS, ) GEMINI_3_6_FLASH = ModelInfo( @@ -954,55 +915,23 @@ class GemmaConfig(GeminiConfig): GEMINI_3_1_PRO_PREVIEW = ModelInfo( label='Google AI - Gemini 3.1 Pro Preview', - supports=ModelSupports( - multiturn=True, - media=True, - tools=True, - tool_choice=True, - system_role=True, - constrained=ConstrainedSupport.ALL, - output=['text', 'json'], - ), + supports=GEMINI_TEXT_SUPPORTS, ) # customtools is registered identically to pro-preview (no distinct config in JS). GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS = ModelInfo( label='Google AI - Gemini 3.1 Pro Preview (Custom Tools)', - supports=ModelSupports( - multiturn=True, - media=True, - tools=True, - tool_choice=True, - system_role=True, - constrained=ConstrainedSupport.ALL, - output=['text', 'json'], - ), + supports=GEMINI_TEXT_SUPPORTS, ) GEMINI_3_1_FLASH_LITE_PREVIEW = ModelInfo( label='Google AI - Gemini 3.1 Flash Lite Preview', - supports=ModelSupports( - multiturn=True, - media=True, - tools=True, - tool_choice=True, - system_role=True, - constrained=ConstrainedSupport.ALL, - output=['text', 'json'], - ), + supports=GEMINI_TEXT_SUPPORTS, ) GEMINI_3_1_FLASH_LITE = ModelInfo( label='Google AI - Gemini 3.1 Flash Lite', - supports=ModelSupports( - multiturn=True, - media=True, - tools=True, - tool_choice=True, - system_role=True, - constrained=ConstrainedSupport.ALL, - output=['text', 'json'], - ), + supports=GEMINI_TEXT_SUPPORTS, ) GEMINI_FLASH_LITE_LATEST = ModelInfo( @@ -1106,15 +1035,7 @@ class GemmaConfig(GeminiConfig): GENERIC_GEMINI_MODEL = ModelInfo( label='Google AI - Gemini', - supports=ModelSupports( - multiturn=True, - media=True, - tools=True, - tool_choice=True, - system_role=True, - constrained=ConstrainedSupport.ALL, - output=['text', 'json'], - ), + supports=GEMINI_TEXT_SUPPORTS, ) GENERIC_TTS_MODEL = ModelInfo( @@ -1259,7 +1180,7 @@ def _add_model(model_info: ModelInfo, names: list[str]) -> None: tools=True, tool_choice=True, system_role=True, - constrained=ConstrainedSupport.ALL, + constrained=ConstrainedSupport.NO_TOOLS, ) @@ -2404,6 +2325,7 @@ async def _genkit_to_googleai_cfg( tools.extend(function_tools) has_output = bool(request.output_format or request.output_schema or request.output_content_type) + tool_choice = _effective_tool_choice(request) if function_tools else None if cfg is not None or tools or system_instruction or has_output or leftovers or extra or timeout is not None: if cfg is None: @@ -2426,14 +2348,17 @@ async def _genkit_to_googleai_cfg( supports_constrained = model_supports_constrained == ConstrainedSupport.ALL or ( model_supports_constrained == ConstrainedSupport.NO_TOOLS and not request.tools ) - if supports_constrained: + # In ANY mode the turn can only be a function call, and Gemini + # rejects JSON mode next to it. The schema applies on the + # follow-up turn, where tool_choice is back to 'auto'. + if supports_constrained and tool_choice != 'required': self._apply_output_config(cfg, request) if tools: cfg.tools = cast(genai_types.ToolListUnion, tools) - if request.tool_choice and function_tools: - cfg.tool_config = _tool_config(request.tool_choice, function_tools) + if tool_choice: + cfg.tool_config = _tool_config(tool_choice, function_tools) cfg.system_instruction = genai_types.Content(parts=system_instruction) if system_instruction else None cfg = attach_leftovers(cfg, leftovers, nest='generationConfig') diff --git a/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py b/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py index 366407778..db618b409 100644 --- a/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py +++ b/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py @@ -18,6 +18,7 @@ """Tests for the Gemini model implementation.""" import base64 +import json import math from datetime import date, datetime from enum import Enum @@ -27,6 +28,7 @@ import httpx import pytest +from genkit_google_genai import GoogleAI from genkit_google_genai._models import _gemini, _veo from genkit_google_genai._models._gemini import ( DEFAULT_SUPPORTS_MODEL, @@ -51,7 +53,7 @@ from pydantic import BaseModel, Field, HttpUrl, ValidationError from pytest_mock import MockerFixture -from genkit import FinishReason, GenkitError, Message, ModelResponse, Part, Role +from genkit import FinishReason, Genkit, GenkitError, Message, ModelResponse, Part, Role from genkit.model import ( ConstrainedSupport, ModelContext, @@ -60,6 +62,8 @@ ModelSupports, OutputConfig, ToolDefinition, + ToolRequest, + ToolResponse, ) from genkit.plugin_api import StrEnum, to_json_schema @@ -610,7 +614,7 @@ def test_gemini_3_1_models_register_real_capabilities(model_name: str) -> None: The generic fallback (DEFAULT_SUPPORTS_MODEL) leaves ``output`` unset, so asserting ``output == ['text', 'json']`` alongside tools/constrained proves these names are - registered with real capability metadata matching the JS/Go registries. + registered with real capability metadata. """ model_info = google_model_info(model_name) @@ -619,7 +623,7 @@ def test_gemini_3_1_models_register_real_capabilities(model_name: str) -> None: assert model_info.supports is not None assert model_info.supports.tools is True assert model_info.supports.tool_choice is True - assert model_info.supports.constrained == ConstrainedSupport.ALL + assert model_info.supports.constrained == ConstrainedSupport.NO_TOOLS assert model_info.supports.output == ['text', 'json'] @@ -632,22 +636,23 @@ def test_gemini_3_1_models_register_real_capabilities(model_name: str) -> None: 'gemini-3.6-flash', 'gemini-3.7-flash', 'gemini-3.8-flash', + 'gemini-flash-latest', + 'gemini-pro-latest', ], ) def test_vertexai_gemini_3_x_text_models_register_real_capabilities(model_name: str) -> None: - """VertexAI Gemini 3.1/3.5 text models resolve to explicit ModelInfo, not the generic fallback. + """Gemini 3.x and -latest text models resolve to explicit ModelInfo with NO_TOOLS constrained support. These names are registered in the Gemini catalog. The generic fallback (DEFAULT_SUPPORTS_MODEL) leaves ``output`` unset, so asserting ``output == ['text', 'json']`` - alongside tools/constrained proves they carry real capability metadata matching the JS Vertex - registry, not the fallback. + alongside tools/constrained proves they carry explicit capability metadata. """ model_info = google_model_info(model_name) assert model_info.supports is not None assert model_info.supports.tools is True assert model_info.supports.tool_choice is True - assert model_info.supports.constrained == ConstrainedSupport.ALL + assert model_info.supports.constrained == ConstrainedSupport.NO_TOOLS assert model_info.supports.output == ['text', 'json'] @@ -672,7 +677,7 @@ def test_stable_gemini_text_models_register_real_capabilities(model_name: str, e assert model_info.supports.tools is True assert model_info.supports.tool_choice is True assert model_info.supports.system_role is True - assert model_info.supports.constrained == ConstrainedSupport.ALL + assert model_info.supports.constrained == ConstrainedSupport.NO_TOOLS assert model_info.supports.output == ['text', 'json'] @@ -3359,3 +3364,511 @@ async def single_chunk() -> Any: # noqa: ANN401 assert response.custom == { 'promptFeedback': {'safetyRatings': [{'category': 'HARM_CATEGORY_HARASSMENT', 'probability': 'NEGLIGIBLE'}]} } + + +class _DishRecipe(BaseModel): + title: str + on_sale_ingredients: list[str] + + +class _StoreQuery(BaseModel): + store: str + + +def _mock_googleai_with_client(monkeypatch: pytest.MonkeyPatch, mock_client: MagicMock) -> GoogleAI: + async def _empty_models() -> Any: # noqa: ANN401 + if False: + yield None + + mock_client.aio.models.list = AsyncMock(side_effect=lambda: _empty_models()) + plugin = GoogleAI(api_key='test-key') + monkeypatch.setattr(plugin, '_runtime_client', lambda: mock_client) + return plugin + + +@pytest.mark.asyncio +async def test_gemini_tools_alone_runs_tool_and_returns_text( + monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture +) -> None: + """Tools without output_schema declare function tools with no response_mime_type and complete in two turns.""" + captured_configs: list[genai_types.GenerateContentConfig | None] = [] + tool_calls = 0 + + async def fake_generate_content( + *, + model: str, # noqa: ARG001 + contents: Any, # noqa: ANN401, ARG001 + config: genai_types.GenerateContentConfig | None = None, + ) -> genai_types.GenerateContentResponse: + captured_configs.append(config) + if len(captured_configs) == 1: + return genai_types.GenerateContentResponse( + candidates=[ + genai_types.Candidate( + finish_reason=genai_types.FinishReason.STOP, + content=genai_types.Content( + role='model', + parts=[ + genai_types.Part( + function_call=genai_types.FunctionCall(name='get_sale_items', args={'store': 'dt'}) + ) + ], + ), + ) + ] + ) + return genai_types.GenerateContentResponse( + candidates=[ + genai_types.Candidate( + finish_reason=genai_types.FinishReason.STOP, + content=genai_types.Content(role='model', parts=[genai_types.Part(text='Make tomato bruschetta.')]), + ) + ] + ) + + mock_client = mocker.MagicMock(spec=genai.Client) + mock_client.vertexai = False + mock_client.aio.models.generate_content = AsyncMock(side_effect=fake_generate_content) + ai = Genkit(plugins=[_mock_googleai_with_client(monkeypatch, mock_client)]) + + @ai.tool() + async def get_sale_items(query: _StoreQuery) -> list[str]: + """Look up ingredients on sale.""" + nonlocal tool_calls + tool_calls += 1 + return [f'{query.store}-tomatoes', 'basil'] + + response = await ai.generate( + model=GoogleAI.gemini('gemini-flash-latest'), + prompt='What should I cook?', + tools=[get_sale_items], + ) + + assert tool_calls == 1 + assert response.text == 'Make tomato bruschetta.' + assert len(captured_configs) == 2 + for cfg in captured_configs: + assert cfg is not None + assert cfg.tools is not None + assert cfg.response_mime_type is None + assert cfg.response_json_schema is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize('model_id', ['gemini-flash-latest', 'gemini-9.9-flash-unlisted']) +@pytest.mark.parametrize('empty_tools', [None, []], ids=['tools-none', 'tools-empty-list']) +async def test_gemini_output_schema_without_tools_keeps_native_constrained_json( + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, + model_id: str, + empty_tools: list[Any] | None, +) -> None: + """output_schema with no tools (None or []) still uses native response_mime_type and response_json_schema.""" + captured_calls: list[tuple[Any, genai_types.GenerateContentConfig | None]] = [] + + async def fake_generate_content( + *, + model: str, # noqa: ARG001 + contents: Any, # noqa: ANN401 + config: genai_types.GenerateContentConfig | None = None, + ) -> genai_types.GenerateContentResponse: + captured_calls.append((contents, config)) + return genai_types.GenerateContentResponse( + candidates=[ + genai_types.Candidate( + finish_reason=genai_types.FinishReason.STOP, + content=genai_types.Content( + role='model', + parts=[genai_types.Part(text='{"title":"Tomato Tart","on_sale_ingredients":["tomatoes"]}')], + ), + ) + ] + ) + + mock_client = mocker.MagicMock(spec=genai.Client) + mock_client.vertexai = False + mock_client.aio.models.generate_content = AsyncMock(side_effect=fake_generate_content) + ai = Genkit(plugins=[_mock_googleai_with_client(monkeypatch, mock_client)]) + + try: + response = await ai.generate( + model=GoogleAI.gemini(model_id), + prompt='Suggest a bargain recipe.', + tools=empty_tools, + output_schema=_DishRecipe, + ) + finally: + _gemini.SUPPORTED_MODELS.pop('gemini-9.9-flash-unlisted', None) + + assert response.output == _DishRecipe(title='Tomato Tart', on_sale_ingredients=['tomatoes']) + assert len(captured_calls) == 1 + contents, cfg = captured_calls[0] + assert cfg is not None + assert cfg.response_mime_type == 'application/json' + assert cfg.response_json_schema == to_json_schema(_DishRecipe) + # Native constrained mode sends no prompt-level schema instructions. + sent_texts = [p.text for c in contents for p in (c.parts or []) if p.text] + assert sent_texts == ['Suggest a bargain recipe.'] + + +@pytest.mark.asyncio +@pytest.mark.parametrize('model_id', ['gemini-flash-latest', 'gemini-9.9-flash-unlisted']) +async def test_gemini_tools_plus_output_schema_omits_native_json_mode_and_hydrates_output( + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, + model_id: str, +) -> None: + """tools + output_schema drops native JSON mode on both turns, injects schema instructions, and hydrates output.""" + captured_calls: list[tuple[Any, genai_types.GenerateContentConfig | None]] = [] + tool_calls = 0 + + async def fake_generate_content( + *, + model: str, # noqa: ARG001 + contents: Any, # noqa: ANN401 + config: genai_types.GenerateContentConfig | None = None, + ) -> genai_types.GenerateContentResponse: + captured_calls.append((contents, config)) + if len(captured_calls) == 1: + return genai_types.GenerateContentResponse( + candidates=[ + genai_types.Candidate( + finish_reason=genai_types.FinishReason.STOP, + content=genai_types.Content( + role='model', + parts=[ + genai_types.Part( + function_call=genai_types.FunctionCall(name='get_sale_items', args={'store': 'dt'}) + ) + ], + ), + ) + ] + ) + return genai_types.GenerateContentResponse( + candidates=[ + genai_types.Candidate( + finish_reason=genai_types.FinishReason.STOP, + content=genai_types.Content( + role='model', + parts=[ + genai_types.Part( + text=( + '```json\n{"title":"Caprese Salad","on_sale_ingredients":["tomatoes","basil"]}\n```' + ) + ) + ], + ), + ) + ] + ) + + mock_client = mocker.MagicMock(spec=genai.Client) + mock_client.vertexai = False + mock_client.aio.models.generate_content = AsyncMock(side_effect=fake_generate_content) + ai = Genkit(plugins=[_mock_googleai_with_client(monkeypatch, mock_client)]) + + @ai.tool() + async def get_sale_items(query: _StoreQuery) -> list[str]: + """Look up ingredients on sale.""" + nonlocal tool_calls + tool_calls += 1 + return [f'{query.store}-tomatoes', 'basil'] + + try: + response = await ai.generate( + model=GoogleAI.gemini(model_id), + prompt='Suggest a bargain recipe.', + tools=[get_sale_items], + output_schema=_DishRecipe, + ) + finally: + _gemini.SUPPORTED_MODELS.pop('gemini-9.9-flash-unlisted', None) + + assert tool_calls == 1 + assert response.output == _DishRecipe(title='Caprese Salad', on_sale_ingredients=['tomatoes', 'basil']) + assert len(captured_calls) == 2 + for _contents, cfg in captured_calls: + assert cfg is not None + assert cfg.tools is not None + assert cfg.response_mime_type is None + assert cfg.response_json_schema is None + assert cfg.response_schema is None + turn1_texts = [p.text for c in captured_calls[0][0] for p in (c.parts or []) if p.text] + assert any('Output should be in JSON format' in t for t in turn1_texts) + + +@pytest.mark.asyncio +async def test_gemini_stream_tools_plus_output_schema_streams_partials_and_hydrates_output( + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, +) -> None: + """Streaming tools + output_schema omits native JSON mode, runs tools once, and streams structured partials.""" + captured_configs: list[genai_types.GenerateContentConfig | None] = [] + tool_calls = 0 + + async def fake_generate_content_stream( + *, + model: str, # noqa: ARG001 + contents: Any, # noqa: ANN401, ARG001 + config: genai_types.GenerateContentConfig | None = None, + ) -> Any: # noqa: ANN401 + captured_configs.append(config) + turn = len(captured_configs) + + async def _chunks() -> Any: # noqa: ANN401 + if turn == 1: + yield genai_types.GenerateContentResponse( + candidates=[ + genai_types.Candidate( + finish_reason=genai_types.FinishReason.STOP, + content=genai_types.Content( + role='model', + parts=[ + genai_types.Part( + function_call=genai_types.FunctionCall( + name='get_sale_items', args={'store': 'dt'} + ) + ) + ], + ), + ) + ] + ) + return + yield _text_chunk('{"title":"Basil ') + yield _text_chunk('Pasta","on_sale_ingredients":["basil"]}', genai_types.FinishReason.STOP) + + return _chunks() + + mock_client = mocker.MagicMock(spec=genai.Client) + mock_client.vertexai = False + mock_client.aio.models.generate_content_stream = AsyncMock(side_effect=fake_generate_content_stream) + ai = Genkit(plugins=[_mock_googleai_with_client(monkeypatch, mock_client)]) + + @ai.tool() + async def get_sale_items(query: _StoreQuery) -> list[str]: + """Look up ingredients on sale.""" + nonlocal tool_calls + tool_calls += 1 + return [f'{query.store}-basil'] + + handle = ai.generate_stream( + model=GoogleAI.gemini('gemini-flash-latest'), + prompt='Suggest a bargain recipe.', + tools=[get_sale_items], + output_schema=_DishRecipe, + ) + partial_outputs = [chunk.output async for chunk in handle.stream if chunk.output is not None] + final = await handle.response + + assert tool_calls == 1 + assert len(partial_outputs) >= 1 + assert final.output == _DishRecipe(title='Basil Pasta', on_sale_ingredients=['basil']) + assert len(captured_configs) == 2 + for cfg in captured_configs: + assert cfg is not None + assert cfg.response_mime_type is None + assert cfg.response_json_schema is None + + +class _MenuDish(BaseModel): + dish: str + + +def _required_tool_request(**kwargs: Any) -> ModelRequest: # noqa: ANN401 + return ModelRequest( + messages=kwargs.pop('messages', [Message(role=Role.USER, content=[Part.from_text('Is the pho in stock?')])]), + tools=[ToolDefinition(name='lookup_menu', description='d', input_schema={'type': 'object'})], + **kwargs, + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize('model_id', ['gemini-flash-latest', 'gemma-4-31b-it']) +async def test_required_with_output_schema_omits_json_mode_on_first_turn(model_id: str) -> None: + """ANY mode plus responseMimeType=application/json is a Gemini 400; Turn 1 skips JSON mode even on ALL models.""" + client = MagicMock(spec=genai.Client) + client.vertexai = False + model = GeminiModel(model_id, client) + request = _required_tool_request( + tool_choice='required', + output=OutputConfig(format='json', json_schema=_MenuDish.model_json_schema(), constrained=True), + ) + + cfg = await model._genkit_to_googleai_cfg(request) + + assert cfg is not None + assert cfg.tool_config is not None and cfg.tool_config.function_calling_config is not None + assert cfg.tool_config.function_calling_config.mode == genai_types.FunctionCallingConfigMode.ANY + assert cfg.tool_config.function_calling_config.allowed_function_names == ['lookup_menu'] + assert cfg.response_mime_type is None + assert cfg.response_json_schema is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ('model_id', 'expect_native_json'), + [ + ('gemini-flash-latest', False), + ('gemma-4-31b-it', True), + ], +) +async def test_required_relaxes_to_auto_after_tool_responses(model_id: str, expect_native_json: bool) -> None: + """After tools answer, ANY relaxes to AUTO; ALL models apply native JSON while NO_TOOLS models keep prompt JSON.""" + client = MagicMock(spec=genai.Client) + client.vertexai = False + model = GeminiModel(model_id, client) + messages = [ + Message(role=Role.USER, content=[Part.from_text('Is the pho in stock?')]), + Message(role=Role.MODEL, content=[Part(tool_request=ToolRequest(name='lookup_menu', ref='1', input={}))]), + Message( + role=Role.TOOL, content=[Part(tool_response=ToolResponse(name='lookup_menu', ref='1', output='in stock'))] + ), + ] + request = _required_tool_request( + messages=messages, + tool_choice='required', + output=OutputConfig(format='json', json_schema=_MenuDish.model_json_schema(), constrained=True), + ) + + cfg = await model._genkit_to_googleai_cfg(request) + + assert cfg is not None + assert cfg.tool_config is not None and cfg.tool_config.function_calling_config is not None + assert cfg.tool_config.function_calling_config.mode == genai_types.FunctionCallingConfigMode.AUTO + assert cfg.tool_config.function_calling_config.allowed_function_names is None + if expect_native_json: + assert cfg.response_mime_type == 'application/json' + assert cfg.response_json_schema == _MenuDish.model_json_schema() + else: + assert cfg.response_mime_type is None + assert cfg.response_json_schema is None + + +@pytest.mark.asyncio +async def test_required_relaxes_to_auto_when_middleware_appends_user_message_after_tool() -> None: + """Filesystem.read_file queues a trailing Role.USER message after Role.TOOL; the turn still relaxes to AUTO.""" + client = MagicMock(spec=genai.Client) + client.vertexai = False + model = GeminiModel('gemma-4-31b-it', client) + messages = [ + Message(role=Role.USER, content=[Part.from_text('Read menu.md and tell me what soup is in stock.')]), + Message(role=Role.MODEL, content=[Part(tool_request=ToolRequest(name='lookup_menu', ref='1', input={}))]), + Message( + role=Role.TOOL, + content=[Part(tool_response=ToolResponse(name='lookup_menu', ref='1', output={'ok': True}))], + ), + Message(role=Role.USER, content=[Part.from_text('\npho: in stock\n')]), + ] + request = _required_tool_request( + messages=messages, + tool_choice='required', + output=OutputConfig(format='json', json_schema=_MenuDish.model_json_schema(), constrained=True), + ) + + cfg = await model._genkit_to_googleai_cfg(request) + + assert cfg is not None + assert cfg.tool_config is not None and cfg.tool_config.function_calling_config is not None + assert cfg.tool_config.function_calling_config.mode == genai_types.FunctionCallingConfigMode.AUTO + assert cfg.tool_config.function_calling_config.allowed_function_names is None + assert cfg.response_mime_type == 'application/json' + assert cfg.response_json_schema == _MenuDish.model_json_schema() + + +@pytest.mark.asyncio +@pytest.mark.parametrize('model_id', ['gemini-flash-latest', 'gemma-4-31b-it']) +async def test_required_stays_required_on_fresh_user_followup_turn(model_id: str) -> None: + """A new user question after a completed model text reply has no tool_response after the last MODEL turn.""" + client = MagicMock(spec=genai.Client) + client.vertexai = False + model = GeminiModel(model_id, client) + messages = [ + Message(role=Role.USER, content=[Part.from_text('Is the pho in stock?')]), + Message(role=Role.MODEL, content=[Part(tool_request=ToolRequest(name='lookup_menu', ref='1', input={}))]), + Message( + role=Role.TOOL, content=[Part(tool_response=ToolResponse(name='lookup_menu', ref='1', output='in stock'))] + ), + Message(role=Role.MODEL, content=[Part.from_text('{"dish": "pho"}')]), + Message(role=Role.USER, content=[Part.from_text('What about bun bo hue?')]), + ] + request = _required_tool_request( + messages=messages, + tool_choice='required', + output=OutputConfig(format='json', json_schema=_MenuDish.model_json_schema(), constrained=True), + ) + + cfg = await model._genkit_to_googleai_cfg(request) + + assert cfg is not None + assert cfg.tool_config is not None and cfg.tool_config.function_calling_config is not None + assert cfg.tool_config.function_calling_config.mode == genai_types.FunctionCallingConfigMode.ANY + assert cfg.tool_config.function_calling_config.allowed_function_names == ['lookup_menu'] + assert cfg.response_mime_type is None + assert cfg.response_json_schema is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ('model_ref', 'expect_turn2_native_json'), + [ + ('googleai/gemini-flash-latest', False), + ('googleai/gemma-4-31b-it', True), + ], +) +async def test_required_end_to_end_returns_structured_answer( + monkeypatch: pytest.MonkeyPatch, + model_ref: str, + expect_turn2_native_json: bool, +) -> None: + """required + output_schema: Turn 1 sends ANY without JSON mode; Turn 2 relaxes to AUTO and hydrates output.""" + bodies: list[dict[str, Any]] = [] + + # Like Gemini: ANY mode can only return a function call, so keeping + # 'required' on Turn 2 would loop until max_turns. + async def send(_client: httpx.AsyncClient, request: httpx.Request, **_: object) -> httpx.Response: + if request.method == 'GET': + return httpx.Response(200, json={'models': []}, request=request) + body = json.loads(request.content) + bodies.append(body) + mode = body.get('toolConfig', {}).get('functionCallingConfig', {}).get('mode') + part: dict[str, Any] = ( + # lookup_menu takes a bare str, so its wire args ride under `input`. + {'functionCall': {'id': f'c{len(bodies)}', 'name': 'lookup_menu', 'args': {'input': 'pho'}}} + if mode == 'ANY' + else {'text': '{"dish": "pho"}'} + ) + return httpx.Response( + 200, + json={'candidates': [{'content': {'role': 'model', 'parts': [part]}, 'finishReason': 'STOP'}]}, + request=request, + ) + + monkeypatch.setattr(httpx.AsyncClient, 'send', send) + ai = Genkit(plugins=[GoogleAI(api_key='fake-key')]) + + @ai.tool(name='lookup_menu') + async def lookup_menu(dish: str) -> str: + """Check whether a dish is on today's menu.""" + return f'{dish}: in stock' + + response = await ai.generate( + model=model_ref, + prompt='Is the pho in stock?', + tools=['lookup_menu'], + tool_choice='required', + output_schema=_MenuDish, + ) + + assert response.error is None + assert len(bodies) == 2 + first, second = bodies + assert first['toolConfig']['functionCallingConfig']['mode'] == 'ANY' + assert 'responseMimeType' not in first.get('generationConfig', {}) + assert second['toolConfig']['functionCallingConfig']['mode'] == 'AUTO' + if expect_turn2_native_json: + assert second['generationConfig']['responseMimeType'] == 'application/json' + else: + assert 'responseMimeType' not in second.get('generationConfig', {}) + assert response.output == _MenuDish(dish='pho') diff --git a/packages/genkit/src/genkit/_ai/_generate.py b/packages/genkit/src/genkit/_ai/_generate.py index 4f14dfac4..de03146fe 100644 --- a/packages/genkit/src/genkit/_ai/_generate.py +++ b/packages/genkit/src/genkit/_ai/_generate.py @@ -1374,12 +1374,12 @@ def boxed_finish_message(*, exc: BaseException, pipe_failed: bool) -> str: def log_dropped_failure(exc: BaseException, *, model: str | None = None, tool: str | None = None) -> None: - """Log a failure whose cause boxing hides behind ``internal error``. + """Log an unraised turn failure boxed onto ``ModelResponse``. - The caller only gets ``finish_reason=failed`` with ``internal error``, so - without this line the cause lives only in an exported trace. Failures that - keep their own message (``PublicError``, a ``GenkitError`` without a - foreign cause) are already on ``response.error`` and are not logged. + ``generate()`` returns ``finish_reason=failed`` instead of raising once a + turn has started, so callers reading ``response.text`` would otherwise get + an empty string with no log output. ``PublicError`` is an intentional + caller-facing rejection on ``response.error`` and is not logged. Args: exc: The exception about to be boxed. @@ -1388,7 +1388,7 @@ def log_dropped_failure(exc: BaseException, *, model: str | None = None, tool: s """ if getattr(exc, _LOGGED_ATTR, False): return - if boxed_finish_message(exc=exc, pipe_failed=False) != INTERNAL_FINISH_MESSAGE: + if public_error(exc) is not None: return with contextlib.suppress(AttributeError, TypeError): setattr(exc, _LOGGED_ATTR, True) diff --git a/packages/genkit/tests/genkit/ai/generate_logging_test.py b/packages/genkit/tests/genkit/ai/generate_logging_test.py index db24b2201..0b979626c 100644 --- a/packages/genkit/tests/genkit/ai/generate_logging_test.py +++ b/packages/genkit/tests/genkit/ai/generate_logging_test.py @@ -12,11 +12,12 @@ import structlog from structlog.testing import capture_logs -from genkit import ErrorReason, Genkit, Message, ModelResponse, ModelResponseChunk, Part, PublicError +from genkit import ErrorReason, Genkit, GenkitError, Message, ModelResponse, ModelResponseChunk, Part, PublicError from genkit._ai._generate import CallScope, generate_action, log_dropped_failure from genkit._ai._model import resolve_model_arg from genkit._ai._tools import Interrupt from genkit._core._environment import GENKIT_ENV +from genkit._core._error import StatusName from genkit._core._logger import GENKIT_LOG, get_logger from genkit._core._model import GenerateActionOptions, ModelRequest, Resume from genkit._core._registry import Registry @@ -784,3 +785,79 @@ async def crashing(_request: ModelRequest, _ctx: ModelContext) -> ModelResponse: errors = _errors(entries) assert len(errors) == 1 assert errors[0]['error'] == 'ReadOnlyError: immutable provider failure' + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ('status', 'message'), + [ + ('FAILED_PRECONDITION', '[Genkit] No Gemini API key found.\nSet GEMINI_API_KEY.'), + ('UNAUTHENTICATED', 'API key not valid. Please pass a valid API key.'), + ('NOT_FOUND', 'models/gemini-flash-lates is not found for API version v1beta'), + ('INVALID_ARGUMENT', 'Unable to fetch media from https://example.com/photo.jpg'), + ], +) +async def test_non_public_genkit_error_from_model_logs_one_line_without_traceback( + status: StatusName, + message: str, +) -> None: + """Non-public GenkitErrors boxed into finish_reason=failed log one line naming the model and cause.""" + structlog.reset_defaults() + ai = Genkit() + + async def failing_provider(_request: ModelRequest, _ctx: ModelContext) -> ModelResponse: + raise GenkitError(status=status, message=message) + + ai.define_model(name='googleai/gemini-flash-latest', fn=failing_provider) + + with capture_logs() as entries: + response = await ai.generate(model='googleai/gemini-flash-latest', prompt='secret-prompt-text') + + assert response.finish_reason == FinishReason.FAILED + assert response.text == '' + assert response.error is not None + assert response.error.status == status + assert response.error.message == message + errors = _errors(entries) + assert len(errors) == 1 + assert errors[0]['event'] == "model 'googleai/gemini-flash-latest' raised, returning finish_reason=failed" + assert errors[0]['model'] == 'googleai/gemini-flash-latest' + assert errors[0]['error'] == f'GenkitError: {status}: {message}' + assert str(errors[0]['at']).startswith(f'{__file__}:') + assert 'exc_info' not in errors[0] + + # Rendered console output stays strictly one line and never echoes the prompt. + buf = io.StringIO() + structlog.configure(logger_factory=structlog.PrintLoggerFactory(file=buf)) + _ = await ai.generate(model='googleai/gemini-flash-latest', prompt='secret-prompt-text') + rendered = buf.getvalue() + assert len(rendered.strip().splitlines()) == 1 + assert 'secret-prompt-text' not in rendered + + +@pytest.mark.asyncio +async def test_non_public_genkit_error_from_tool_logs_once() -> None: + """A tool raising a non-public GenkitError logs one line naming the tool, without duplicate outer logging.""" + structlog.reset_defaults() + ai = Genkit() + pm, _ = define_scripted_model(ai) + + @ai.tool(name='check_allergens') + async def check_allergens(_: dict) -> str: # noqa: ARG001 + raise GenkitError(status='UNAVAILABLE', message='allergy service unavailable') + + pm.responses = [_tool_turn('check_allergens')] + + with capture_logs() as entries: + response = await ai.generate(model='scriptedModel', prompt='hi', tools=['check_allergens']) + + assert response.finish_reason == FinishReason.FAILED + assert response.error is not None + assert response.error.status == 'UNAVAILABLE' + errors = _errors(entries) + assert len(errors) == 1 + assert errors[0]['event'] == "tool 'check_allergens' raised, returning finish_reason=failed" + assert errors[0]['tool'] == 'check_allergens' + assert errors[0]['error'] == 'GenkitError: UNAVAILABLE: allergy service unavailable' + assert str(errors[0]['at']).startswith(f'{__file__}:') + assert 'exc_info' not in errors[0] From 712e389b032db2266bb2ec7ce8418350d52603ae Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Wed, 11 Nov 2026 19:44:02 -0600 Subject: [PATCH 2/2] fix(google-genai): keep native constrained JSON with tools on supporting Gemini models --- .../src/genkit_google_genai/_google.py | 2 +- .../genkit_google_genai/_models/_gemini.py | 111 ++++- .../tests/models/googlegenai_gemini_test.py | 405 ++++++++++++++++-- .../tests/tuned_gemini_test.py | 19 + 4 files changed, 469 insertions(+), 68 deletions(-) diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_google.py b/packages/genkit-google-genai/src/genkit_google_genai/_google.py index 68a6da3c2..ab4a4bb11 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_google.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_google.py @@ -1338,7 +1338,7 @@ async def _run_try_on(request: ModelRequest[VirtualTryOnConfig], ctx: ModelConte if is_tuned_gemini_name(name): model_info = ModelInfo( label=f'{PLUGIN_DISPLAY_NAME[VERTEXAI_PLUGIN_NAME]} - {name}', - supports=google_model_info('gemini').supports, + supports=google_model_info(name).supports, ) async def _run_tuned(request: ModelRequest[GeminiConfig], ctx: ModelContext) -> ModelResponse: diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py index f468b5ad7..18fc402a1 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py @@ -835,52 +835,56 @@ class GemmaConfig(GeminiConfig): common_field_bounds = {'top_p': (0.0, 1.0)} -# Native JSON mode combined with function declarations causes Gemini to -# re-call tools in a loop; NO_TOOLS keeps native constrained JSON when no -# tools are attached and switches to schema prompt instructions with tools. GEMINI_TEXT_SUPPORTS = ModelSupports( multiturn=True, media=True, tools=True, tool_choice=True, system_role=True, - constrained=ConstrainedSupport.NO_TOOLS, + constrained=ConstrainedSupport.ALL, output=['text', 'json'], ) +# Gemini 2.5 HTTP-400s on response_mime_type='application/json' alongside tools, +# and gemini-3.7/3.8-flash (including gemini-flash-latest) loops tool calls or +# 504s when response_json_schema is sent next to function declarations. +GEMINI_NO_TOOLS_CONSTRAINED_SUPPORTS = GEMINI_TEXT_SUPPORTS.model_copy( + update={'constrained': ConstrainedSupport.NO_TOOLS} +) + GEMINI_2_5_PRO_EXP_03_25 = ModelInfo( label='Google AI - Gemini 2.5 Pro Exp 03-25', - supports=GEMINI_TEXT_SUPPORTS, + supports=GEMINI_NO_TOOLS_CONSTRAINED_SUPPORTS, ) GEMINI_2_5_PRO_PREVIEW_03_25 = ModelInfo( label='Google AI - Gemini 2.5 Pro Preview 03-25', - supports=GEMINI_TEXT_SUPPORTS, + supports=GEMINI_NO_TOOLS_CONSTRAINED_SUPPORTS, ) GEMINI_2_5_PRO_PREVIEW_05_06 = ModelInfo( label='Google AI - Gemini 2.5 Pro Preview 05-06', - supports=GEMINI_TEXT_SUPPORTS, + supports=GEMINI_NO_TOOLS_CONSTRAINED_SUPPORTS, ) GEMINI_2_5_FLASH_PREVIEW_04_17 = ModelInfo( label='Google AI - Gemini 2.5 Flash Preview 04-17', - supports=GEMINI_TEXT_SUPPORTS, + supports=GEMINI_NO_TOOLS_CONSTRAINED_SUPPORTS, ) GEMINI_2_5_PRO = ModelInfo( label='Google AI - Gemini 2.5 Pro', - supports=GEMINI_TEXT_SUPPORTS, + supports=GEMINI_NO_TOOLS_CONSTRAINED_SUPPORTS, ) GEMINI_2_5_FLASH = ModelInfo( label='Google AI - Gemini 2.5 Flash', - supports=GEMINI_TEXT_SUPPORTS, + supports=GEMINI_NO_TOOLS_CONSTRAINED_SUPPORTS, ) GEMINI_2_5_FLASH_LITE = ModelInfo( label='Google AI - Gemini 2.5 Flash Lite', - supports=GEMINI_TEXT_SUPPORTS, + supports=GEMINI_NO_TOOLS_CONSTRAINED_SUPPORTS, ) GEMINI_3_FLASH_PREVIEW = ModelInfo( @@ -905,12 +909,17 @@ class GemmaConfig(GeminiConfig): GEMINI_3_7_FLASH = ModelInfo( label='Google AI - Gemini 3.7 Flash', - supports=GEMINI_TEXT_SUPPORTS, + supports=GEMINI_NO_TOOLS_CONSTRAINED_SUPPORTS, ) GEMINI_3_8_FLASH = ModelInfo( label='Google AI - Gemini 3.8 Flash', - supports=GEMINI_TEXT_SUPPORTS, + supports=GEMINI_NO_TOOLS_CONSTRAINED_SUPPORTS, +) + +GEMINI_FLASH_LATEST = ModelInfo( + label='Google AI - Gemini Flash Latest', + supports=GEMINI_NO_TOOLS_CONSTRAINED_SUPPORTS, ) GEMINI_3_1_PRO_PREVIEW = ModelInfo( @@ -1013,13 +1022,15 @@ class GemmaConfig(GeminiConfig): supports=GEMINI_TTS_SUPPORTS, ) +# Gemma 4 504s or skips tool calls when native JSON mode is sent alongside +# function declarations; NO_TOOLS uses prompt-instructed JSON when tools are attached. GEMMA_SUPPORTS = ModelSupports( multiturn=True, media=True, tools=True, tool_choice=True, system_role=True, - constrained=ConstrainedSupport.ALL, + constrained=ConstrainedSupport.NO_TOOLS, output=['text', 'json'], ) @@ -1131,7 +1142,8 @@ def _add_model(model_info: ModelInfo, names: list[str]) -> None: _add_model(GEMINI_FLASH_LITE_LATEST, ['gemini-flash-lite-latest']) _add_model(GEMINI_3_FLASH_PREVIEW, ['gemini-3-flash-preview']) _add_model(GEMINI_3_PRO_PREVIEW, ['gemini-3-pro-preview', 'gemini-pro-latest']) -_add_model(GEMINI_3_5_FLASH, ['gemini-3.5-flash', 'gemini-flash-latest']) +_add_model(GEMINI_3_5_FLASH, ['gemini-3.5-flash']) +_add_model(GEMINI_FLASH_LATEST, ['gemini-flash-latest']) _add_model(GEMINI_3_6_FLASH, ['gemini-3.6-flash']) _add_model(GEMINI_3_7_FLASH, ['gemini-3.7-flash']) _add_model(GEMINI_3_8_FLASH, ['gemini-3.8-flash']) @@ -1180,7 +1192,7 @@ def _add_model(model_info: ModelInfo, names: list[str]) -> None: tools=True, tool_choice=True, system_role=True, - constrained=ConstrainedSupport.NO_TOOLS, + constrained=ConstrainedSupport.ALL, ) @@ -1349,6 +1361,29 @@ def get_model_config_schema(name: str) -> type[GeminiConfig]: return GeminiConfig +_LEGACY_NO_TOOLS_GEMINI_PREFIXES = ('gemini-1.', 'gemini-2.0-', 'gemini-2.5-') + + +def _json_schema_instruction(schema: Mapping[str, Any]) -> str: + """Prompt instruction matching JsonFormat when native constrained output is unavailable.""" + return ( + 'Output should be in JSON format and conform to the following schema:\n\n' + f'```\n{json.dumps(schema, indent=2)}\n```\n' + ) + + +def _has_instruction_text( + messages: Iterable[Message], + system_parts: Iterable[genai_types.Part], + instruction: str, +) -> bool: + """Whether *instruction* already appears in request messages or system parts.""" + needle = instruction.strip() + if any(part.text and needle in part.text for msg in messages for part in msg.content): + return True + return any(part.text and needle in part.text for part in system_parts) + + def google_model_info( version: str, ) -> ModelInfo: @@ -1365,6 +1400,9 @@ def google_model_info( """ if version in SUPPORTED_MODELS: return SUPPORTED_MODELS[version] + local = version.split('/')[-1] + if local in SUPPORTED_MODELS: + return SUPPORTED_MODELS[local] if is_tts_model(version): return GENERIC_TTS_MODEL @@ -1373,6 +1411,12 @@ def google_model_info( if is_gemma_model(version): return GENERIC_GEMMA_MODEL + if local.lower().startswith(_LEGACY_NO_TOOLS_GEMINI_PREFIXES): + return ModelInfo( + label=f'Google AI - {version}', + supports=DEFAULT_SUPPORTS_MODEL.model_copy(update={'constrained': ConstrainedSupport.NO_TOOLS}), + ) + return ModelInfo( label=f'Google AI - {version}', supports=DEFAULT_SUPPORTS_MODEL, @@ -1822,8 +1866,12 @@ async def generate(self, request: ModelRequest, ctx: ModelContext) -> ModelRespo """ model_name = self._version if request.config: - version = getattr(request.config, 'version', None) - if version: + version = ( + cast(Mapping[str, Any], request.config).get('version') + if isinstance(request.config, Mapping) + else getattr(request.config, 'version', None) + ) + if isinstance(version, str) and version: model_name = version declared_tools, tool_table = self._declare_tools(request) @@ -2334,8 +2382,12 @@ async def _genkit_to_googleai_cfg( if has_output: model_name = self._version if request.config: - version = getattr(request.config, 'version', None) - if version: + version = ( + cast(Mapping[str, Any], request.config).get('version') + if isinstance(request.config, Mapping) + else getattr(request.config, 'version', None) + ) + if isinstance(version, str) and version: model_name = version # Check if the model supports constrained generation with this configuration @@ -2353,6 +2405,17 @@ async def _genkit_to_googleai_cfg( # follow-up turn, where tool_choice is back to 'auto'. if supports_constrained and tool_choice != 'required': self._apply_output_config(cfg, request) + elif ( + not supports_constrained + and request.output_constrained + and request.output_schema + and request.output_format in (None, 'json') + and (request.output_format == 'json' or request.output_content_type == 'application/json') + and (model_info.supports is None or model_info.supports.system_role is not False) + ): + fallback_instruction = _json_schema_instruction(request.output_schema) + if not _has_instruction_text(request.messages, system_instruction, fallback_instruction): + system_instruction.append(genai_types.Part(text=fallback_instruction)) if tools: cfg.tools = cast(genai_types.ToolListUnion, tools) @@ -2402,7 +2465,10 @@ def _apply_output_config(self, cfg: genai_types.GenerateContentConfig, request: JSON output turns on JSON mode, and constrained JSON output also sends the schema verbatim as ``response_json_schema``, or as a converted - ``response_schema`` when ``legacy_response_schema`` is set. Constrained + ``response_schema`` when ``legacy_response_schema`` is set. When tools + are attached and a schema was explicitly marked unconstrained + (``output_constrained=False``), JSON mode is omitted so prompt-instructed + schema generation does not collide with function calling. Constrained enum output sends ``text/x.enum`` with a converted ``response_schema``; enum output without a constrained schema sends neither. """ @@ -2411,7 +2477,8 @@ def _apply_output_config(self, cfg: genai_types.GenerateContentConfig, request: enum_mode = request.output_format == 'enum' or request.output_content_type == 'text/enum' if json_mode: - cfg.response_mime_type = 'application/json' + if not (schema and not request.output_constrained and request.tools): + cfg.response_mime_type = 'application/json' if schema and request.output_constrained: if self._legacy_response_schema: cfg.response_schema = self._output_response_schema(schema) diff --git a/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py b/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py index db618b409..3fe425051 100644 --- a/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py +++ b/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py @@ -610,7 +610,7 @@ def test_google_model_info(input: str, expected: ModelInfo) -> None: ], ) def test_gemini_3_1_models_register_real_capabilities(model_name: str) -> None: - """Gemini 3.1 text models resolve to explicit ModelInfo, not the generic fallback. + """Gemini 3.1 text models resolve to explicit ModelInfo with ALL constrained support. The generic fallback (DEFAULT_SUPPORTS_MODEL) leaves ``output`` unset, so asserting ``output == ['text', 'json']`` alongside tools/constrained proves these names are @@ -623,25 +623,28 @@ def test_gemini_3_1_models_register_real_capabilities(model_name: str) -> None: assert model_info.supports is not None assert model_info.supports.tools is True assert model_info.supports.tool_choice is True - assert model_info.supports.constrained == ConstrainedSupport.NO_TOOLS + assert model_info.supports.constrained == ConstrainedSupport.ALL assert model_info.supports.output == ['text', 'json'] @pytest.mark.parametrize( - 'model_name', + ('model_name', 'expected_constrained'), [ - 'gemini-3.1-pro-preview', - 'gemini-3.1-flash-lite', - 'gemini-3.5-flash', - 'gemini-3.6-flash', - 'gemini-3.7-flash', - 'gemini-3.8-flash', - 'gemini-flash-latest', - 'gemini-pro-latest', + ('gemini-3-flash-preview', ConstrainedSupport.ALL), + ('gemini-3.1-pro-preview', ConstrainedSupport.ALL), + ('gemini-3.1-flash-lite', ConstrainedSupport.ALL), + ('gemini-3.5-flash', ConstrainedSupport.ALL), + ('gemini-3.6-flash', ConstrainedSupport.ALL), + ('gemini-pro-latest', ConstrainedSupport.ALL), + ('gemini-3.7-flash', ConstrainedSupport.NO_TOOLS), + ('gemini-3.8-flash', ConstrainedSupport.NO_TOOLS), + ('gemini-flash-latest', ConstrainedSupport.NO_TOOLS), ], ) -def test_vertexai_gemini_3_x_text_models_register_real_capabilities(model_name: str) -> None: - """Gemini 3.x and -latest text models resolve to explicit ModelInfo with NO_TOOLS constrained support. +def test_vertexai_gemini_3_x_text_models_register_real_capabilities( + model_name: str, expected_constrained: ConstrainedSupport +) -> None: + """Gemini 3.x and -latest text models resolve to explicit ModelInfo with per-model constrained support. These names are registered in the Gemini catalog. The generic fallback (DEFAULT_SUPPORTS_MODEL) leaves ``output`` unset, so asserting ``output == ['text', 'json']`` @@ -652,19 +655,23 @@ def test_vertexai_gemini_3_x_text_models_register_real_capabilities(model_name: assert model_info.supports is not None assert model_info.supports.tools is True assert model_info.supports.tool_choice is True - assert model_info.supports.constrained == ConstrainedSupport.NO_TOOLS + assert model_info.supports.constrained == expected_constrained assert model_info.supports.output == ['text', 'json'] @pytest.mark.parametrize( - ('model_name', 'expected_label'), + ('model_name', 'expected_label', 'expected_constrained'), [ - ('gemini-2.5-pro', 'Google AI - Gemini 2.5 Pro'), - ('gemini-2.5-flash', 'Google AI - Gemini 2.5 Flash'), - ('gemini-flash-lite-latest', 'Google AI - Gemini Flash Lite Latest'), + ('gemini-2.5-pro', 'Google AI - Gemini 2.5 Pro', ConstrainedSupport.NO_TOOLS), + ('gemini-2.5-flash', 'Google AI - Gemini 2.5 Flash', ConstrainedSupport.NO_TOOLS), + ('gemini-2.5-flash-lite', 'Google AI - Gemini 2.5 Flash Lite', ConstrainedSupport.NO_TOOLS), + ('gemini-flash-latest', 'Google AI - Gemini Flash Latest', ConstrainedSupport.NO_TOOLS), + ('gemini-flash-lite-latest', 'Google AI - Gemini Flash Lite Latest', ConstrainedSupport.ALL), ], ) -def test_stable_gemini_text_models_register_real_capabilities(model_name: str, expected_label: str) -> None: +def test_stable_gemini_text_models_register_real_capabilities( + model_name: str, expected_label: str, expected_constrained: ConstrainedSupport +) -> None: """Stable text ids resolve to their own ModelInfo, not the generic fallback. The fallback (DEFAULT_SUPPORTS_MODEL) leaves ``output`` unset and labels the id verbatim, @@ -677,10 +684,38 @@ def test_stable_gemini_text_models_register_real_capabilities(model_name: str, e assert model_info.supports.tools is True assert model_info.supports.tool_choice is True assert model_info.supports.system_role is True - assert model_info.supports.constrained == ConstrainedSupport.NO_TOOLS + assert model_info.supports.constrained == expected_constrained assert model_info.supports.output == ['text', 'json'] +@pytest.mark.parametrize( + ('version', 'expected_constrained', 'expected_output'), + [ + ('models/gemini-2.5-flash-lite', ConstrainedSupport.NO_TOOLS, ['text', 'json']), + ('publishers/google/models/gemini-3.8-flash', ConstrainedSupport.NO_TOOLS, ['text', 'json']), + ('models/gemini-3.1-pro-preview', ConstrainedSupport.ALL, ['text', 'json']), + ('gemini-2.5-flash-001', ConstrainedSupport.NO_TOOLS, None), + ('models/gemini-2.0-flash-001', ConstrainedSupport.NO_TOOLS, None), + ('gemini-1.5-pro-002', ConstrainedSupport.NO_TOOLS, None), + ('gemini-3.5-flash-lite', ConstrainedSupport.ALL, None), + ('gemini-4-carbon', ConstrainedSupport.ALL, None), + ('gemini-4-argon', ConstrainedSupport.ALL, None), + ('endpoints/1234567890', ConstrainedSupport.ALL, None), + ], +) +def test_google_model_info_prefix_stripping_and_legacy_fallback( + version: str, + expected_constrained: ConstrainedSupport, + expected_output: list[str] | None, +) -> None: + """Prefixed catalog ids match SUPPORTED_MODELS; unlisted 1.x/2.0/2.5 get NO_TOOLS while 3.x+/4.x+ get ALL.""" + model_info = google_model_info(version) + + assert model_info.supports is not None + assert model_info.supports.constrained == expected_constrained + assert model_info.supports.output == expected_output + + @pytest.mark.parametrize( ('model_name', 'expected_label'), [ @@ -732,10 +767,11 @@ def test_tts_models_do_not_advertise_system_role(model_name: str) -> None: [ ('gemma-4-26b-a4b-it', 'Google AI - Gemma 4 26B A4B IT'), ('gemma-4-31b-it', 'Google AI - Gemma 4 31B IT'), + ('gemma-3-27b-it', 'Google AI - Gemma'), ], ) def test_gemma_4_models_register_per_name_capabilities(model_name: str, expected_label: str) -> None: - """Each gemma-4 id carries its own label instead of sharing the generic Gemma entry.""" + """Gemma ids advertise NO_TOOLS constrained support and route to GemmaConfig.""" model_info = google_model_info(model_name) assert model_info.label == expected_label @@ -745,7 +781,7 @@ def test_gemma_4_models_register_per_name_capabilities(model_name: str, expected tools=True, tool_choice=True, system_role=True, - constrained=ConstrainedSupport.ALL, + constrained=ConstrainedSupport.NO_TOOLS, output=['text', 'json'], ) assert get_model_config_schema(model_name) is GemmaConfig @@ -3455,15 +3491,23 @@ async def get_sale_items(query: _StoreQuery) -> list[str]: @pytest.mark.asyncio -@pytest.mark.parametrize('model_id', ['gemini-flash-latest', 'gemini-9.9-flash-unlisted']) +@pytest.mark.parametrize( + 'model_ref', + [ + 'googleai/gemini-flash-latest', + 'googleai/gemini-2.5-flash-lite', + 'googleai/gemini-4-carbon', + 'googleai/gemma-4-31b-it', + ], +) @pytest.mark.parametrize('empty_tools', [None, []], ids=['tools-none', 'tools-empty-list']) async def test_gemini_output_schema_without_tools_keeps_native_constrained_json( monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture, - model_id: str, + model_ref: str, empty_tools: list[Any] | None, ) -> None: - """output_schema with no tools (None or []) still uses native response_mime_type and response_json_schema.""" + """output_schema with no tools (None or []) keeps native response_mime_type and response_json_schema.""" captured_calls: list[tuple[Any, genai_types.GenerateContentConfig | None]] = [] async def fake_generate_content( @@ -3492,13 +3536,13 @@ async def fake_generate_content( try: response = await ai.generate( - model=GoogleAI.gemini(model_id), + model=model_ref, prompt='Suggest a bargain recipe.', tools=empty_tools, output_schema=_DishRecipe, ) finally: - _gemini.SUPPORTED_MODELS.pop('gemini-9.9-flash-unlisted', None) + _gemini.SUPPORTED_MODELS.pop('gemini-4-carbon', None) assert response.output == _DishRecipe(title='Tomato Tart', on_sale_ingredients=['tomatoes']) assert len(captured_calls) == 1 @@ -3512,13 +3556,117 @@ async def fake_generate_content( @pytest.mark.asyncio -@pytest.mark.parametrize('model_id', ['gemini-flash-latest', 'gemini-9.9-flash-unlisted']) +@pytest.mark.parametrize( + 'model_ref', + [ + 'googleai/gemini-4-carbon', + 'googleai/gemini-4-argon', + 'googleai/gemini-3.1-pro-preview', + 'googleai/gemini-3.6-flash', + ], +) +async def test_gemini_tools_plus_output_schema_keeps_native_constrained_json_on_supporting_models( + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, + model_ref: str, +) -> None: + """Supporting Gemini models keep native response_json_schema alongside tools with zero prompt schema text.""" + captured_calls: list[tuple[Any, genai_types.GenerateContentConfig | None]] = [] + tool_calls = 0 + + async def fake_generate_content( + *, + model: str, # noqa: ARG001 + contents: Any, # noqa: ANN401 + config: genai_types.GenerateContentConfig | None = None, + ) -> genai_types.GenerateContentResponse: + captured_calls.append((contents, config)) + if len(captured_calls) == 1: + return genai_types.GenerateContentResponse( + candidates=[ + genai_types.Candidate( + finish_reason=genai_types.FinishReason.STOP, + content=genai_types.Content( + role='model', + parts=[ + genai_types.Part( + function_call=genai_types.FunctionCall(name='get_sale_items', args={'store': 'dt'}) + ) + ], + ), + ) + ] + ) + return genai_types.GenerateContentResponse( + candidates=[ + genai_types.Candidate( + finish_reason=genai_types.FinishReason.STOP, + content=genai_types.Content( + role='model', + parts=[ + genai_types.Part( + text='{"title":"Caprese Salad","on_sale_ingredients":["tomatoes","basil"]}' + ) + ], + ), + ) + ] + ) + + mock_client = mocker.MagicMock(spec=genai.Client) + mock_client.vertexai = False + mock_client.aio.models.generate_content = AsyncMock(side_effect=fake_generate_content) + ai = Genkit(plugins=[_mock_googleai_with_client(monkeypatch, mock_client)]) + + @ai.tool() + async def get_sale_items(query: _StoreQuery) -> list[str]: + """Look up ingredients on sale.""" + nonlocal tool_calls + tool_calls += 1 + return [f'{query.store}-tomatoes', 'basil'] + + try: + response = await ai.generate( + model=model_ref, + prompt='Suggest a bargain recipe.', + tools=[get_sale_items], + output_schema=_DishRecipe, + ) + finally: + _gemini.SUPPORTED_MODELS.pop('gemini-4-carbon', None) + _gemini.SUPPORTED_MODELS.pop('gemini-4-argon', None) + + assert tool_calls == 1 + assert response.output == _DishRecipe(title='Caprese Salad', on_sale_ingredients=['tomatoes', 'basil']) + assert len(captured_calls) == 2 + expected_schema = to_json_schema(_DishRecipe) + for _contents, cfg in captured_calls: + assert cfg is not None + assert cfg.tools is not None + assert cfg.response_mime_type == 'application/json' + assert cfg.response_json_schema == expected_schema + assert cfg.response_schema is None + turn1_texts = [p.text for c in captured_calls[0][0] for p in (c.parts or []) if p.text] + assert turn1_texts == ['Suggest a bargain recipe.'] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + 'model_ref', + [ + 'googleai/gemini-flash-latest', + 'googleai/gemini-3.8-flash', + 'googleai/gemini-2.5-flash-lite', + 'googleai/gemini-2.5-flash-001', + 'googleai/gemma-4-31b-it', + ], +) async def test_gemini_tools_plus_output_schema_omits_native_json_mode_and_hydrates_output( monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture, - model_id: str, + model_ref: str, ) -> None: - """tools + output_schema drops native JSON mode on both turns, injects schema instructions, and hydrates output.""" + """NO_TOOLS models drop native JSON mode on both turns, inject schema instructions, and hydrate output.""" captured_calls: list[tuple[Any, genai_types.GenerateContentConfig | None]] = [] tool_calls = 0 @@ -3577,13 +3725,13 @@ async def get_sale_items(query: _StoreQuery) -> list[str]: try: response = await ai.generate( - model=GoogleAI.gemini(model_id), + model=model_ref, prompt='Suggest a bargain recipe.', tools=[get_sale_items], output_schema=_DishRecipe, ) finally: - _gemini.SUPPORTED_MODELS.pop('gemini-9.9-flash-unlisted', None) + _gemini.SUPPORTED_MODELS.pop('gemini-2.5-flash-001', None) assert tool_calls == 1 assert response.output == _DishRecipe(title='Caprese Salad', on_sale_ingredients=['tomatoes', 'basil']) @@ -3598,6 +3746,162 @@ async def get_sale_items(query: _StoreQuery) -> list[str]: assert any('Output should be in JSON format' in t for t in turn1_texts) +@pytest.mark.asyncio +async def test_version_override_from_all_to_no_tools_injects_fallback_schema_instruction( + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, +) -> None: + """Overriding config.version from an ALL model to a NO_TOOLS model injects fallback schema instructions.""" + captured_configs: list[genai_types.GenerateContentConfig | None] = [] + tool_calls = 0 + + async def fake_generate_content( + *, + model: str, + contents: Any, # noqa: ANN401, ARG001 + config: genai_types.GenerateContentConfig | None = None, + ) -> genai_types.GenerateContentResponse: + assert model == 'gemini-2.5-flash-lite' + captured_configs.append(config) + if len(captured_configs) == 1: + return genai_types.GenerateContentResponse( + candidates=[ + genai_types.Candidate( + finish_reason=genai_types.FinishReason.STOP, + content=genai_types.Content( + role='model', + parts=[ + genai_types.Part( + function_call=genai_types.FunctionCall(name='get_sale_items', args={'store': 'dt'}) + ) + ], + ), + ) + ] + ) + return genai_types.GenerateContentResponse( + candidates=[ + genai_types.Candidate( + finish_reason=genai_types.FinishReason.STOP, + content=genai_types.Content( + role='model', + parts=[genai_types.Part(text='{"title":"Pesto Pasta","on_sale_ingredients":["basil"]}')], + ), + ) + ] + ) + + mock_client = mocker.MagicMock(spec=genai.Client) + mock_client.vertexai = False + mock_client.aio.models.generate_content = AsyncMock(side_effect=fake_generate_content) + ai = Genkit(plugins=[_mock_googleai_with_client(monkeypatch, mock_client)]) + + @ai.tool() + async def get_sale_items(query: _StoreQuery) -> list[str]: + """Look up ingredients on sale.""" + nonlocal tool_calls + tool_calls += 1 + return [f'{query.store}-basil'] + + response = await ai.generate( + model=GoogleAI.gemini('gemini-3.1-pro-preview'), + config={'version': 'gemini-2.5-flash-lite'}, + prompt='Suggest a bargain recipe.', + tools=[get_sale_items], + output_schema=_DishRecipe, + ) + + assert tool_calls == 1 + assert response.output == _DishRecipe(title='Pesto Pasta', on_sale_ingredients=['basil']) + assert len(captured_configs) == 2 + for cfg in captured_configs: + assert cfg is not None + assert cfg.response_mime_type is None + assert cfg.response_json_schema is None + assert isinstance(cfg.system_instruction, genai_types.Content) + sys_texts = [p.text for p in (cfg.system_instruction.parts or []) if p.text] + assert any('Output should be in JSON format' in t and 'on_sale_ingredients' in t for t in sys_texts) + + +@pytest.mark.asyncio +async def test_output_constrained_false_with_tools_omits_native_json_mode_on_all_model( + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, +) -> None: + """output_constrained=False + tools + output_schema omits native JSON mode on ALL models.""" + captured_calls: list[tuple[Any, genai_types.GenerateContentConfig | None]] = [] + tool_calls = 0 + + async def fake_generate_content( + *, + model: str, # noqa: ARG001 + contents: Any, # noqa: ANN401 + config: genai_types.GenerateContentConfig | None = None, + ) -> genai_types.GenerateContentResponse: + captured_calls.append((contents, config)) + if len(captured_calls) == 1: + return genai_types.GenerateContentResponse( + candidates=[ + genai_types.Candidate( + finish_reason=genai_types.FinishReason.STOP, + content=genai_types.Content( + role='model', + parts=[ + genai_types.Part( + function_call=genai_types.FunctionCall(name='get_sale_items', args={'store': 'dt'}) + ) + ], + ), + ) + ] + ) + return genai_types.GenerateContentResponse( + candidates=[ + genai_types.Candidate( + finish_reason=genai_types.FinishReason.STOP, + content=genai_types.Content( + role='model', + parts=[ + genai_types.Part( + text='```json\n{"title":"Bruschetta","on_sale_ingredients":["tomato"]}\n```' + ) + ], + ), + ) + ] + ) + + mock_client = mocker.MagicMock(spec=genai.Client) + mock_client.vertexai = False + mock_client.aio.models.generate_content = AsyncMock(side_effect=fake_generate_content) + ai = Genkit(plugins=[_mock_googleai_with_client(monkeypatch, mock_client)]) + + @ai.tool() + async def get_sale_items(query: _StoreQuery) -> list[str]: + """Look up ingredients on sale.""" + nonlocal tool_calls + tool_calls += 1 + return [f'{query.store}-tomato'] + + response = await ai.generate( + model=GoogleAI.gemini('gemini-3.1-pro-preview'), + prompt='Suggest a bargain recipe.', + tools=[get_sale_items], + output_schema=_DishRecipe, + output_constrained=False, + ) + + assert tool_calls == 1 + assert response.output == _DishRecipe(title='Bruschetta', on_sale_ingredients=['tomato']) + assert len(captured_calls) == 2 + for _contents, cfg in captured_calls: + assert cfg is not None + assert cfg.response_mime_type is None + assert cfg.response_json_schema is None + turn1_texts = [p.text for c in captured_calls[0][0] for p in (c.parts or []) if p.text] + assert any('Output should be in JSON format' in t for t in turn1_texts) + + @pytest.mark.asyncio async def test_gemini_stream_tools_plus_output_schema_streams_partials_and_hydrates_output( monkeypatch: pytest.MonkeyPatch, @@ -3685,7 +3989,10 @@ def _required_tool_request(**kwargs: Any) -> ModelRequest: # noqa: ANN401 @pytest.mark.asyncio -@pytest.mark.parametrize('model_id', ['gemini-flash-latest', 'gemma-4-31b-it']) +@pytest.mark.parametrize( + 'model_id', + ['gemini-3.1-pro-preview', 'gemini-4-argon', 'gemini-flash-latest', 'gemma-4-31b-it'], +) async def test_required_with_output_schema_omits_json_mode_on_first_turn(model_id: str) -> None: """ANY mode plus responseMimeType=application/json is a Gemini 400; Turn 1 skips JSON mode even on ALL models.""" client = MagicMock(spec=genai.Client) @@ -3710,8 +4017,10 @@ async def test_required_with_output_schema_omits_json_mode_on_first_turn(model_i @pytest.mark.parametrize( ('model_id', 'expect_native_json'), [ + ('gemini-3.1-pro-preview', True), + ('gemini-4-argon', True), ('gemini-flash-latest', False), - ('gemma-4-31b-it', True), + ('gemma-4-31b-it', False), ], ) async def test_required_relaxes_to_auto_after_tool_responses(model_id: str, expect_native_json: bool) -> None: @@ -3729,7 +4038,7 @@ async def test_required_relaxes_to_auto_after_tool_responses(model_id: str, expe request = _required_tool_request( messages=messages, tool_choice='required', - output=OutputConfig(format='json', json_schema=_MenuDish.model_json_schema(), constrained=True), + output=OutputConfig(format='json', json_schema=_MenuDish.model_json_schema(), constrained=expect_native_json), ) cfg = await model._genkit_to_googleai_cfg(request) @@ -3751,7 +4060,7 @@ async def test_required_relaxes_to_auto_when_middleware_appends_user_message_aft """Filesystem.read_file queues a trailing Role.USER message after Role.TOOL; the turn still relaxes to AUTO.""" client = MagicMock(spec=genai.Client) client.vertexai = False - model = GeminiModel('gemma-4-31b-it', client) + model = GeminiModel('gemini-3.1-pro-preview', client) messages = [ Message(role=Role.USER, content=[Part.from_text('Read menu.md and tell me what soup is in stock.')]), Message(role=Role.MODEL, content=[Part(tool_request=ToolRequest(name='lookup_menu', ref='1', input={}))]), @@ -3778,7 +4087,7 @@ async def test_required_relaxes_to_auto_when_middleware_appends_user_message_aft @pytest.mark.asyncio -@pytest.mark.parametrize('model_id', ['gemini-flash-latest', 'gemma-4-31b-it']) +@pytest.mark.parametrize('model_id', ['gemini-3.1-pro-preview', 'gemini-flash-latest', 'gemma-4-31b-it']) async def test_required_stays_required_on_fresh_user_followup_turn(model_id: str) -> None: """A new user question after a completed model text reply has no tool_response after the last MODEL turn.""" client = MagicMock(spec=genai.Client) @@ -3813,8 +4122,10 @@ async def test_required_stays_required_on_fresh_user_followup_turn(model_id: str @pytest.mark.parametrize( ('model_ref', 'expect_turn2_native_json'), [ + ('googleai/gemini-3.1-pro-preview', True), + ('googleai/gemini-4-argon', True), ('googleai/gemini-flash-latest', False), - ('googleai/gemma-4-31b-it', True), + ('googleai/gemma-4-31b-it', False), ], ) async def test_required_end_to_end_returns_structured_answer( @@ -3853,13 +4164,16 @@ async def lookup_menu(dish: str) -> str: """Check whether a dish is on today's menu.""" return f'{dish}: in stock' - response = await ai.generate( - model=model_ref, - prompt='Is the pho in stock?', - tools=['lookup_menu'], - tool_choice='required', - output_schema=_MenuDish, - ) + try: + response = await ai.generate( + model=model_ref, + prompt='Is the pho in stock?', + tools=['lookup_menu'], + tool_choice='required', + output_schema=_MenuDish, + ) + finally: + _gemini.SUPPORTED_MODELS.pop('gemini-4-argon', None) assert response.error is None assert len(bodies) == 2 @@ -3869,6 +4183,7 @@ async def lookup_menu(dish: str) -> str: assert second['toolConfig']['functionCallingConfig']['mode'] == 'AUTO' if expect_turn2_native_json: assert second['generationConfig']['responseMimeType'] == 'application/json' + assert second['generationConfig']['responseJsonSchema'] == _MenuDish.model_json_schema() else: assert 'responseMimeType' not in second.get('generationConfig', {}) assert response.output == _MenuDish(dish='pho') diff --git a/packages/genkit-google-genai/tests/tuned_gemini_test.py b/packages/genkit-google-genai/tests/tuned_gemini_test.py index 21cbfdd61..b8275dd66 100644 --- a/packages/genkit-google-genai/tests/tuned_gemini_test.py +++ b/packages/genkit-google-genai/tests/tuned_gemini_test.py @@ -17,13 +17,18 @@ """Tests for Vertex AI tuned Gemini endpoint routing helpers.""" from types import SimpleNamespace +from typing import Any, cast import pytest +from genkit_google_genai import VertexAI from genkit_google_genai._models._gemini import ( + google_model_info, is_tuned_gemini_name, resolve_vertex_model_name, ) +from genkit.model import ConstrainedSupport + @pytest.mark.parametrize( 'name,expected', @@ -80,3 +85,17 @@ def test_resolve_without_project_or_location_leaves_name() -> None: """If the client lacks project/location, defer to the SDK rather than building a bad path.""" client = _vertex_client(project='', location='') assert resolve_vertex_model_name(client, 'endpoints/1') == 'endpoints/1' + + +def test_tuned_endpoint_action_metadata_matches_google_model_info() -> None: + """Vertex tuned endpoints resolve capabilities through google_model_info(name) (ConstrainedSupport.ALL).""" + plugin = VertexAI(project='my-proj', location='us-central1') + action = plugin._resolve_model('endpoints/1234567890') + + assert action is not None + model_meta = cast(dict[str, Any], action.metadata['model']) + supports = cast(dict[str, Any], model_meta['supports']) + assert supports['constrained'] == ConstrainedSupport.ALL + info = google_model_info('endpoints/1234567890') + assert info.supports is not None + assert info.supports.constrained == ConstrainedSupport.ALL