Skip to content

Fix response.parsed returning a dict for Optional and union schemas - #3439

Open
Sun-Wukhan wants to merge 1 commit into
googleapis:mainfrom
Sun-Wukhan:fix/parsed-union-schemas
Open

Sun-Wukhan wants to merge 1 commit into
googleapis:mainfrom
Sun-Wukhan:fix/parsed-union-schemas

Conversation

@Sun-Wukhan

Copy link
Copy Markdown

Fixes #3437

With a union response schema such as Optional[Recipe] or Union[Recipe, list[Recipe]], GenerateContentResponse._from_response validated the JSON against the model member and set response.parsed to the model instance, but then kept iterating over the remaining union members. The trailing non-model member (NoneType, or the parameterized list[Recipe]) fell into the plain-JSON branch and overwrote result.parsed with json.loads(...), so callers received a plain dict and response.parsed.name raised AttributeError.

This change makes the union branch stop once a BaseModel member has produced a parsed value, and only falls back to json.loads when no model member produced one. It also guards the issubclass check with inspect.isclass(...) so parameterized members such as list[Recipe] are skipped safely. The ValueError handling for partial streaming JSON is unchanged.

Tests: added four regression tests in google/genai/tests/types/test_types.py covering Optional[Model], Model | None, and Union[Model, list[Model]] with both object and array bodies; they fail before this change and pass after. The full test_types.py file passes (118 passed, 6 skipped) and the transformers tests pass (196 passed).

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

1 participant