Skip to content
Open
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
69 changes: 69 additions & 0 deletions google/genai/tests/types/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -3136,3 +3136,72 @@ def test_from_response_malformed_json_parsed_is_none():
)
assert response.text == '{not json'
assert response.parsed is None


class _RecipeModel(pydantic.BaseModel):
name: str
ingredients: list[str]


_RECIPE_JSON = '{"name": "Pancakes", "ingredients": ["flour", "eggs"]}'


def test_from_response_optional_pydantic_schema_parses_model():
"""Optional[Model] parses into the model, not a plain dict."""
response = types.GenerateContentResponse._from_response(
response=_text_response(_RECIPE_JSON),
kwargs={
'config': {'response_schema': typing.Optional[_RecipeModel]}
},
)
assert isinstance(response.parsed, _RecipeModel)
assert response.parsed.name == 'Pancakes'
assert response.parsed.ingredients == ['flour', 'eggs']


@pytest.mark.skipif(
sys.version_info < (3, 10),
reason='| is not supported in Python 3.9',
)
def test_from_response_pydantic_union_type_parses_model():
"""Model | None parses into the model, not a plain dict."""
response = types.GenerateContentResponse._from_response(
response=_text_response(_RECIPE_JSON),
kwargs={'config': {'response_schema': _RecipeModel | None}},
)
assert isinstance(response.parsed, _RecipeModel)
assert response.parsed.name == 'Pancakes'


def test_from_response_union_with_list_member_parses_model():
"""Union[Model, list[Model]] parses an object body into the model."""
response = types.GenerateContentResponse._from_response(
response=_text_response(_RECIPE_JSON),
kwargs={
'config': {
'response_schema': typing.Union[
_RecipeModel, list[_RecipeModel]
]
}
},
)
assert isinstance(response.parsed, _RecipeModel)
assert response.parsed.name == 'Pancakes'


def test_from_response_union_with_list_member_parses_model_list():
"""Union[Model, list[Model]] parses an array body into a list of models."""
response = types.GenerateContentResponse._from_response(
response=_text_response('[' + _RECIPE_JSON + ']'),
kwargs={
'config': {
'response_schema': typing.Union[
_RecipeModel, list[_RecipeModel]
]
}
},
)
assert isinstance(response.parsed, list)
assert len(response.parsed) == 1
assert isinstance(response.parsed[0], _RecipeModel)
assert response.parsed[0].name == 'Pancakes'
26 changes: 17 additions & 9 deletions google/genai/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -9419,8 +9419,11 @@ class Placeholder(pydantic.BaseModel):
elif typing.get_origin(response_schema) in _UNION_TYPES:
# Union schema.
union_types = typing.get_args(response_schema)
parsed_as_model = False
for union_type in union_types:
if issubclass(union_type, pydantic.BaseModel):
if inspect.isclass(union_type) and issubclass(
union_type, pydantic.BaseModel
):
try:
result_text = result._get_text()
if result_text is not None:
Expand All @@ -9431,16 +9434,21 @@ class Placeholder(pydantic.BaseModel): # type: ignore[no-redef]
parsed = {'placeholder': json.loads(result_text)}
placeholder = Placeholder.model_validate(parsed)
result.parsed = placeholder.placeholder
parsed_as_model = True
break
except ValueError:
pass
else:
try:
result_text = result._get_text()
if result_text is not None:
result.parsed = json.loads(result_text)
# may not be a valid json per stream response
except ValueError:
pass
if not parsed_as_model:
# No BaseModel member produced a parsed value (the union has no
# model member, or the model member did not validate), so fall
# back to plain JSON.
try:
result_text = result._get_text()
if result_text is not None:
result.parsed = json.loads(result_text)
# may not be a valid json per stream response
except ValueError:
pass

return result

Expand Down