From 11116d20d70af7c23b701eb1e3332278a2447648 Mon Sep 17 00:00:00 2001 From: samecho Date: Sun, 1 Nov 2026 10:09:06 -0500 Subject: [PATCH] fix(apigee): send structured output schemas --- src/google/adk/models/apigee_llm.py | 29 ++- .../models/test_completions_http_client.py | 177 +++++++++++++++++- 2 files changed, 200 insertions(+), 6 deletions(-) diff --git a/src/google/adk/models/apigee_llm.py b/src/google/adk/models/apigee_llm.py index 485a0df8410..638dd7c67ed 100644 --- a/src/google/adk/models/apigee_llm.py +++ b/src/google/adk/models/apigee_llm.py @@ -18,12 +18,14 @@ import atexit import base64 import collections.abc +import copy import enum from functools import cached_property from functools import partial import json import logging import os +import re from typing import Any from typing import AsyncGenerator from typing import Generator @@ -42,6 +44,8 @@ from ..utils import streaming_utils from ..utils._event_loop_cache import PerLoopCachedProperty from ..utils._google_client_headers import merge_tracking_headers +from ..utils._schema_utils import lowercase_schema_types +from ..utils._schema_utils import schema_to_json_schema from ..utils.env_utils import is_enterprise_mode_enabled from .google_llm import Gemini from .llm_response import LlmResponse @@ -755,10 +759,31 @@ def _map_config_parameters( if config.logprobs is not None: payload['top_logprobs'] = config.logprobs - if config.response_json_schema: + response_schema = config.response_json_schema + if response_schema is None: + response_schema = config.response_schema + if response_schema is not None: + if ( + isinstance(response_schema, dict) + and isinstance(response_schema.get('name'), str) + and isinstance(response_schema.get('schema'), dict) + ): + json_schema = response_schema + else: + if isinstance(response_schema, types.Schema): + schema_dict = response_schema.model_dump( + by_alias=True, exclude_none=True, mode='json' + ) + else: + schema_dict = copy.deepcopy(schema_to_json_schema(response_schema)) + lowercase_schema_types(schema_dict) + title = schema_dict.get('title') + name = title if isinstance(title, str) and title else 'response' + name = re.sub(r'[^a-zA-Z0-9_-]', '_', name)[:64] or 'response' + json_schema = {'name': name, 'schema': schema_dict} payload['response_format'] = { 'type': 'json_schema', - 'json_schema': config.response_json_schema, + 'json_schema': json_schema, } elif config.response_mime_type == 'application/json': payload['response_format'] = {'type': 'json_object'} diff --git a/tests/unittests/models/test_completions_http_client.py b/tests/unittests/models/test_completions_http_client.py index 1a8ca348102..17abe517683 100644 --- a/tests/unittests/models/test_completions_http_client.py +++ b/tests/unittests/models/test_completions_http_client.py @@ -28,6 +28,7 @@ from google.adk.models.llm_response import LlmResponse from google.genai import types import httpx +from pydantic import BaseModel import pytest @@ -325,8 +326,11 @@ async def test_generate_content_async_function_call_response( { 'type': 'json_schema', 'json_schema': { - 'type': 'object', - 'properties': {'name': {'type': 'string'}}, + 'name': 'response', + 'schema': { + 'type': 'object', + 'properties': {'name': {'type': 'string'}}, + }, }, }, ), @@ -337,8 +341,11 @@ async def test_generate_content_async_function_call_response( { 'type': 'json_schema', 'json_schema': { - 'type': 'object', - 'properties': {'name': {'type': 'string'}}, + 'name': 'response', + 'schema': { + 'type': 'object', + 'properties': {'name': {'type': 'string'}}, + }, }, }, ), @@ -348,6 +355,58 @@ async def test_generate_content_async_function_call_response( 'application/json', {'type': 'json_object'}, ), + ( + { + 'name': 'weather', + 'description': 'Forecast', + 'strict': True, + 'schema': {'type': 'object', 'properties': {}}, + }, + None, + { + 'type': 'json_schema', + 'json_schema': { + 'name': 'weather', + 'description': 'Forecast', + 'strict': True, + 'schema': {'type': 'object', 'properties': {}}, + }, + }, + ), + ( + {'title': 'Daily weather!', 'type': 'object', 'properties': {}}, + None, + { + 'type': 'json_schema', + 'json_schema': { + 'name': 'Daily_weather_', + 'schema': { + 'title': 'Daily weather!', + 'type': 'object', + 'properties': {}, + }, + }, + }, + ), + ( + {}, + 'application/json', + { + 'type': 'json_schema', + 'json_schema': {'name': 'response', 'schema': {}}, + }, + ), + ( + {'title': 'a' * 70, 'type': 'object'}, + None, + { + 'type': 'json_schema', + 'json_schema': { + 'name': 'a' * 64, + 'schema': {'title': 'a' * 70, 'type': 'object'}, + }, + }, + ), ], ) async def test_construct_payload_response_format( @@ -381,6 +440,116 @@ async def test_construct_payload_response_format( assert payload['response_format'] == expected_response_format +@pytest.mark.asyncio +async def test_output_schema_model_is_sent_to_chat_completions( + client, llm_request +): + class Weather(BaseModel): + city: str + + llm_request.set_output_schema(Weather) + mock_response = AsyncMock(spec=httpx.Response) + mock_response.json.return_value = { + 'choices': [{'message': {'role': 'assistant', 'content': '{}'}}] + } + mock_response.status_code = 200 + + with mock.patch.object( + httpx.AsyncClient, 'post', return_value=mock_response + ) as mock_post: + _ = [ + r + async for r in client.generate_content_async(llm_request, stream=False) + ] + + assert mock_post.call_args[1]['json']['response_format'] == { + 'type': 'json_schema', + 'json_schema': {'name': 'Weather', 'schema': Weather.model_json_schema()}, + } + + +@pytest.mark.asyncio +async def test_response_json_schema_takes_precedence_over_output_schema( + client, llm_request +): + llm_request.config = types.GenerateContentConfig( + response_schema={'type': 'object', 'title': 'Ignored'}, + response_json_schema={}, + response_mime_type='application/json', + ) + mock_response = AsyncMock(spec=httpx.Response) + mock_response.json.return_value = { + 'choices': [{'message': {'role': 'assistant', 'content': '{}'}}] + } + mock_response.status_code = 200 + + with mock.patch.object( + httpx.AsyncClient, 'post', return_value=mock_response + ) as mock_post: + _ = [ + r + async for r in client.generate_content_async(llm_request, stream=False) + ] + + assert mock_post.call_args[1]['json']['response_format'] == { + 'type': 'json_schema', + 'json_schema': {'name': 'response', 'schema': {}}, + } + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ('schema', 'expected_schema'), + [ + ( + types.Schema( + type=types.Type.OBJECT, + properties={'city': types.Schema(type=types.Type.STRING)}, + ), + {'type': 'object', 'properties': {'city': {'type': 'string'}}}, + ), + ( + { + 'type': 'OBJECT', + 'properties': {'city': {'type': 'STRING'}}, + 'default': {'type': 'EXAMPLE'}, + }, + { + 'type': 'object', + 'properties': {'city': {'type': 'string'}}, + 'default': {'type': 'EXAMPLE'}, + }, + ), + (list[str], {'items': {'type': 'string'}, 'type': 'array'}), + ], +) +async def test_output_schema_formats_supported_types( + client, llm_request, schema, expected_schema +): + llm_request.set_output_schema(schema) + mock_response = AsyncMock(spec=httpx.Response) + mock_response.json.return_value = { + 'choices': [{'message': {'role': 'assistant', 'content': '{}'}}] + } + mock_response.status_code = 200 + + with mock.patch.object( + httpx.AsyncClient, 'post', return_value=mock_response + ) as mock_post: + _ = [ + r + async for r in client.generate_content_async(llm_request, stream=False) + ] + + assert mock_post.call_args[1]['json']['response_format'] == { + 'type': 'json_schema', + 'json_schema': {'name': 'response', 'schema': expected_schema}, + } + if isinstance(schema, dict): + assert schema['type'] == 'OBJECT' + assert schema['properties']['city']['type'] == 'STRING' + + @pytest.mark.asyncio async def test_generate_content_async_invalid_tool_call_type_raises_error( client, llm_request