Skip to content

feat(py): support list[T], TypedDict, and @dataclass in output_schema - #45

Open
huangjeff5 wants to merge 6 commits into
mainfrom
fix/py-1.0-pr2-output-hydration
Open

huangjeff5 wants to merge 6 commits into
mainfrom
fix/py-1.0-pr2-output-hydration

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Adds output_schema support for non-BaseModel Python types backed by Pydantic's TypeAdapter: list[T], stdlib @dataclass, TypedDict, RootModel, Enum, Literal, Annotated, Decimal, UUID, and datetime.

Previously, only Pydantic BaseModel subclasses (and raw JSON Schema dicts) were supported—passing list[LineItem] crashed with ValidationError, TypedDict skipped validation, and stdlib @dataclass returned an unvalidated dict instead of constructing the dataclass (BaseModel behavior is unchanged).

from dataclasses import dataclass
from typing import TypedDict
from pydantic import BaseModel


# Existing supported path (Pydantic BaseModel) — unchanged
class LineItem(BaseModel):
    sku: str
    qty: int


# Python stdlib @dataclass (new)
@dataclass
class Vendor:
    name: str
    risk_score: int


# Python TypedDict (new)
class Address(TypedDict):
    city: str
    postal_code: str


# --- BEFORE ---
await ai.generate(prompt='List 2 line items.', output_schema=list[LineItem])
# => pydantic.ValidationError (GenerateCall.output_schema only accepted a class)

res = await ai.generate(prompt='Assess Acme Corp.', output_schema=Vendor)
print(res.output)
# => {'name': 'Acme Corp', 'risk_score': 12}  (plain dict; res.output.name raised AttributeError)

res = await ai.generate(prompt='Extract shipping city.', output_schema=Address)
print(res.output)
# => {'city': 'Austin'}  (missing required postal_code, never validated)

# --- AFTER ---
items = await ai.generate(prompt='List 2 line items.', output_schema=list[LineItem])
print(items.output)
# => [LineItem(sku='CH-1', qty=2), LineItem(sku='DK-2', qty=5)]

vendor = await ai.generate(prompt='Assess Acme Corp.', output_schema=Vendor)
print(vendor.output)
# => Vendor(name='Acme Corp', risk_score=12)  (real Vendor @dataclass instance)
print(vendor.output.name)
# => 'Acme Corp'

addr = await ai.generate(prompt='Extract shipping city.', output_schema=Address)
print(addr.output)
# => {'city': 'Austin', 'postal_code': '78701'}  (validated against Address keys)

Main Changes

  • Every output_schema validates through TypeAdapter: GenerateCall.output_schema was typed type, which rejected generic aliases like list[LineItem] or Vendor | None, and ModelResponse only called .model_validate() on BaseModel subclasses. Validation now goes through a cached TypeAdapter, so runtime .output matches the static OutputT. Types Pydantic cannot build a schema for raise InvalidOutputSchemaError (non-retryable).
  • The closing stream chunk validates instead of constructing: ModelResponseChunk.output built the last chunk with model_construct, skipping validation. The chunk that closes the JSON now runs full validation and is None if validation fails, matching (await stream.response).output. array and jsonl formats validate each emitted item.
  • Partial dataclasses, TypedDicts, and enums stay safe mid-stream: Open dataclasses and TypedDicts remain raw dicts until their JSON closes, and an enum chunk that is a prefix of multiple members stays None until disambiguated.
  • Public signatures keep type[OutputT]: Widening to Any would lose .output type inference for every caller. Literal, Annotated, and union schemas work at runtime; static inference for non-type forms waits on PEP 747 TypeForm.

Decisions

  • Additive feature, not a breaking change: Genkit only documented Pydantic BaseModel and JSON Schema dict for output_schema (BaseModel behavior is unchanged). Passing an unsupported @dataclass previously happened not to throw and returned a raw dict; constructing the @dataclass instance brings runtime behavior in line with the declared ModelResponse[OutputT] type.

Breaking changes

None.

@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-hydration branch from 291e086 to c93be6c Compare November 9, 2026 19:08
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-hydration branch from c93be6c to 5a290b5 Compare November 9, 2026 19:49
@huangjeff5
huangjeff5 changed the base branch from main to fix/py-1.0-pr1-docs-quickstart November 9, 2026 19:49
@huangjeff5
huangjeff5 added this pull request to stack #59 November 9, 2026 19:58
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr1-docs-quickstart branch from 5ee7a6e to c0ce853 Compare November 9, 2026 19:59
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-hydration branch 2 times, most recently from db96b31 to c831aef Compare November 9, 2026 20:19
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr1-docs-quickstart branch from c0ce853 to 9df2ab7 Compare November 9, 2026 21:24
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-hydration branch 2 times, most recently from 24f0bae to af2b347 Compare November 9, 2026 22:03
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr1-docs-quickstart branch 2 times, most recently from aa37fb2 to 4ac9ef3 Compare November 9, 2026 23:12
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-hydration branch from af2b347 to 2148558 Compare November 9, 2026 23:12
@huangjeff5 huangjeff5 changed the title fix(py): hydrate output_schema via TypeAdapter across all accepted types feat(py): hydrate output_schema for TypedDict, list, and dataclasses Nov 10, 2026
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr1-docs-quickstart branch from 4ac9ef3 to 65453be Compare November 10, 2026 07:44
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-hydration branch from 2148558 to 1ea19dc Compare November 10, 2026 07:44
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr1-docs-quickstart branch from 65453be to 9f7cb68 Compare November 10, 2026 18:14
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-hydration branch from 1ea19dc to 7edc1a1 Compare November 10, 2026 18:14
@huangjeff5
huangjeff5 removed this pull request from stack #59 November 10, 2026 18:16
@huangjeff5
huangjeff5 added this pull request to stack #75 November 10, 2026 18:16
@huangjeff5
huangjeff5 removed this pull request from stack #75 November 10, 2026 18:16
@huangjeff5
huangjeff5 added this pull request to stack #76 November 10, 2026 18:16
@huangjeff5
huangjeff5 removed this pull request from stack #76 November 10, 2026 18:38
@huangjeff5
huangjeff5 added this pull request to stack #77 November 10, 2026 18:38
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr1-docs-quickstart branch from d3c6672 to 8854224 Compare November 10, 2026 21:50
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-hydration branch from 7edc1a1 to a5eb59e Compare November 10, 2026 21:51
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr1-docs-quickstart branch 2 times, most recently from d3c6672 to 8854224 Compare November 10, 2026 22:05
@huangjeff5
huangjeff5 removed this pull request from stack #77 November 10, 2026 22:09
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-hydration branch from a5eb59e to 75288da Compare November 10, 2026 22:16
@huangjeff5
huangjeff5 added this pull request to stack #82 November 10, 2026 22:24
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-hydration branch 2 times, most recently from 4d82180 to 33b6a5a Compare November 11, 2026 02:35
@huangjeff5
huangjeff5 removed this pull request from stack #82 November 11, 2026 02:36
@huangjeff5
huangjeff5 added this pull request to stack #88 November 11, 2026 02:37
@huangjeff5 huangjeff5 changed the title feat(py): hydrate output_schema for TypedDict, list, and dataclasses feat(py)!: hydrate output_schema for TypedDict, list, and dataclasses Nov 11, 2026
@huangjeff5
huangjeff5 removed this pull request from stack #88 November 11, 2026 06:22
@huangjeff5
huangjeff5 changed the base branch from fix/py-1.0-pr1-docs-quickstart to main November 11, 2026 06:22
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-hydration branch from 33b6a5a to 278fc9b Compare November 11, 2026 06:22
@huangjeff5
huangjeff5 added this pull request to stack #89 November 11, 2026 06:23
`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).
Pins the shapes most likely to regress: InvoiceItem | None, a union of
models picking the matching member, a dataclass nesting a dataclass,
and a stream of a model that nests a dataclass and a TypedDict (open
chunk keeps the TypedDict raw, closing chunk matches the final output).
…igration guide

The guide covers 0.12 -> 0.13. The 1.0 note goes to the release notes.
@huangjeff5
huangjeff5 removed this pull request from stack #89 November 11, 2026 18:06
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-hydration branch from 278fc9b to 94b4a28 Compare November 11, 2026 18:38
@huangjeff5
huangjeff5 added this pull request to stack #104 November 11, 2026 19:43
@huangjeff5 huangjeff5 changed the title feat(py)!: hydrate output_schema for TypedDict, list, and dataclasses feat(py): support list[T], TypedDict, and @dataclass in output_schema Nov 11, 2026
@huangjeff5
huangjeff5 removed this pull request from stack #104 November 12, 2026 06:39
# Conflicts:
#	packages/genkit/src/genkit/_core/_model.py
@huangjeff5
huangjeff5 requested a review from cabljac December 1, 2026 23:23

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.

1 participant