Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions src/google/adk/models/apigee_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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'}
Expand Down
177 changes: 173 additions & 4 deletions tests/unittests/models/test_completions_http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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'}},
},
},
},
),
Expand All @@ -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'}},
},
},
},
),
Expand All @@ -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(
Expand Down Expand Up @@ -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
Expand Down
Loading