From e7399048956be104878b102977a71b40f4c50337 Mon Sep 17 00:00:00 2001 From: "Navid Khan (Ali)" <60997541+Sun-Wukhan@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:35:01 -0500 Subject: [PATCH] Fix response.parsed returning a dict for Optional and union schemas --- google/genai/tests/types/test_types.py | 69 ++++++++++++++++++++++++++ google/genai/types.py | 26 ++++++---- 2 files changed, 86 insertions(+), 9 deletions(-) diff --git a/google/genai/tests/types/test_types.py b/google/genai/tests/types/test_types.py index 7da592a38..1b9197383 100644 --- a/google/genai/tests/types/test_types.py +++ b/google/genai/tests/types/test_types.py @@ -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' diff --git a/google/genai/types.py b/google/genai/types.py index 63c10f68d..db850c795 100644 --- a/google/genai/types.py +++ b/google/genai/types.py @@ -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: @@ -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