GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — response.parsed is a plain dict, not the model, when response_schema is Optional[Model] or Model | None · Issue #3437 · googleapis/python-genai

response.parsed is a plain dict, not the model, when response_schema is Optional[Model] or Model | None #3437

New issue
Copy link
New issue
Copy link
Backlog
#3439
Backlog
response.parsed is a plain dict, not the model, when response_schema is Optional[Model] or Model | None#3437
#3439
Copy link

Description

@chaitanya0305
chaitanya0305
opened on Nov 28, 2026
Issue body actions

Environment details

  • Programming language: Python
  • OS: macOS (not OS specific)
  • Language runtime version: 3.12
  • Package version: google-genai 3.6.1, main at 36e2970

Description

With response_schema=Optional[Recipe] (or Recipe | None, or Union[Recipe, None]), the request is sent correctly as a nullable object schema, and the model returns valid JSON. But response.parsed is a plain dict, not a Recipe instance. Code like response.parsed.name then fails with AttributeError: 'dict' object has no attribute 'name'.

The same happens for any union where a non-model member comes after a model member, for example Union[Recipe, list[Recipe]]. With Recipe alone, parsed is a Recipe as expected.

This affects models.generate_content, generate_content_stream, chats, and the async versions, since they all build the response through GenerateContentResponse._from_response.

Steps to reproduce

Runs offline. It uses an httpx.MockTransport in place of the API.

from typing import Optional
import httpx
import pydantic
from google import genai
from google.genai import types


class Recipe(pydantic.BaseModel):
  name: str
  minutes: int


def handler(request):
  return httpx.Response(200, json={'candidates': [{
      'content': {'role': 'model',
                  'parts': [{'text': '{"name": "soup", "minutes": 20}'}]},
      'finishReason': 'STOP'}]})


client = genai.Client(
    api_key='test-key',
    http_options=types.HttpOptions(
        httpx_client=httpx.Client(transport=httpx.MockTransport(handler))
    ),
)
for schema in [Recipe, Optional[Recipe]]:
  response = client.models.generate_content(
      model='gemini-2.5-flash',
      contents='Give me a recipe',
      config=types.GenerateContentConfig(
          response_mime_type='application/json', response_schema=schema
      ),
  )
  print(schema, '->', repr(response.parsed))

Expected:

<class '__main__.Recipe'> -> Recipe(name='soup', minutes=20)
typing.Optional[__main__.Recipe] -> Recipe(name='soup', minutes=20)

Actual:

<class '__main__.Recipe'> -> Recipe(name='soup', minutes=20)
typing.Optional[__main__.Recipe] -> {'name': 'soup', 'minutes': 20}

Root cause

google/genai/types.py:9419-9443, the union branch of GenerateContentResponse._from_response:

union_types = typing.get_args(response_schema)
for union_type in union_types:
  if issubclass(union_type, pydantic.BaseModel):
    ...
    result.parsed = placeholder.placeholder   # Recipe instance
  else:
    ...
    result.parsed = json.loads(result_text)   # plain dict

The loop handles each union member in turn and assigns result.parsed every time. For Optional[Recipe] the members are (Recipe, NoneType). The first pass sets parsed to the validated Recipe. The second pass (NoneType is not a model) overwrites it with the raw json.loads result. So the result depends on member order: Union[None, Recipe] happens to work, and Optional[Recipe] does not.

Suggested fix

Validate once against the whole union when any member is a model, and keep the plain json.loads path only for unions without a model:

union_types = typing.get_args(response_schema)
if any(
    inspect.isclass(union_type)
    and issubclass(union_type, pydantic.BaseModel)
    for union_type in union_types
):
  # validate json.loads(result_text) against `placeholder: response_schema`
  # once, as the model branch does today
  ...
else:
  # unchanged: result.parsed = json.loads(result_text)
  ...

Pydantic already handles None and generic members inside the union, so Optional[Recipe] gives a Recipe (or None for a null response), and Union[int, Recipe] keeps working. The inspect.isclass guard also avoids calling issubclass on generic aliases such as list[Recipe].

A tested fix is ready on branch chaitanya0305:fix/parsed-optional-union-model. It adds regression tests to google/genai/tests/types/test_types.py (Optional[Model], Union[Model, None], Union[None, Model], Union[Model, list[Model]], and a null response). Before the fix 3 of them fail. After the fix all pass, and google/genai/tests/types passes (207 passed, 7 skipped).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402775 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.