Repository navigation
fix(py): hydrate output_schema via TypeAdapter across all accepted types - #7136
huangjeff5 wants to merge 1 commit into
Conversation
`ai.generate(output_schema=T)` types `.output` as `T`, but runtime only validated `BaseModel` subclasses. `list[T]`, `Literal`, and `Annotated` raised `ValidationError` on `GenerateCall`; dataclasses, `TypedDict`, `Enum`, `UUID`, `datetime`, and `Decimal` came back as raw JSON. - Drop the `BaseModel`-only gates in `GenerateCall.output_schema`, `Prompt._ensure_resolved`, and `resolve_output_schema`. Any non-dict, non-str schema becomes `schema_type`. - `ModelResponse.output` and `_assert_valid_schema` validate with a cached `TypeAdapter(schema_type)`. - `ModelResponseChunk.output` hydrates through `hydrate_partial`: open JSON is built leniently (lists of models, `RootModel`), closed JSON is validated like the final response. - `construct_partial(closed=True)` raises instead of falling back to `model_construct`, so the closing chunk never carries an object that skipped validators. Nested closed subtrees mid-stream keep the lenient fallback (`build_partial`). - Migration guide note for the three workarounds this breaks. Items: PR2-02, PR2-03, PR2-04 (D2).
There was a problem hiding this comment.
Code Review
This pull request extends output_schema support to hydrate any type that Pydantic validates (such as list[T], dataclasses, TypedDict, Enum, Literal, Decimal, UUID, and datetime), moving beyond the previous restriction of only supporting BaseModel. This is achieved by introducing output_adapter (which wraps Pydantic's TypeAdapter) and updating the validation and partial hydration logic (hydrate_partial) to handle these non-model types. Comprehensive tests and documentation updates have been added to verify and explain this new behavior. There are no review comments to assess, and I have no additional feedback to provide.
|
Closing: migrated to standalone repository genkit-ai/genkit-python (PR #45): genkit-ai/genkit-python#45 |
Hydrates any valid
output_schematype through Pydantic TypeAdapter instead of restricting to BaseModel subclasses.Main Changes
list[T],dict,Literal,Annotated, dataclasses,Enum, andTypedDicthydrate on final response and stream chunks.isinstance(..., type)gates that prevented valid typing constructs in_prompt.py.