Skip to content

fix(py): statically narrow response.output to OutputT - #56

Closed
huangjeff5 wants to merge 22 commits into
fix/py-1.0-pr2-output-hydrationfrom
fix/py-1.0-pr2-output-narrowing
Closed

huangjeff5 wants to merge 22 commits into
fix/py-1.0-pr2-output-hydrationfrom
fix/py-1.0-pr2-output-narrowing

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

With output_schema=T, response.output now types as T instead of T | None, so callers drop the cast(). The type does not model None. At runtime output is still None when the reply has no output.

class Recipe(BaseModel):
    title: str

# 1. Ask for a schema and opt into raising on a non-matching reply
res = await ai.generate(prompt='Suggest a soup.', output_schema=Recipe, raise_on_error=True)

# 2. Read the typed output
reveal_type(res.output)
# => Type of "res.output" is "Recipe"
print(res.output.title)
# => French Onion Soup

Main changes

  • ModelResponse.output: returns OutputT, with one cast at the parser boundary. No schema or a JSON-schema dict types as Any. A bare ModelResponse types as object.
  • ModelResponseChunk.output: stays OutputT | None, because early chunks have nothing to parse. Now a plain property over a cached _partial_output, since ty drops the class type param from a cached_property return type. Parsing still runs once per chunk.
  • Contract tests: tests/typecheck/output_narrowing_contract_test.py covers generate, the config={...} overload, list[T], dataclass, Enum, no schema, a dict schema, streams, define_prompt, ai.prompt, and bare ModelResponse. pyright, pyrefly, and ty all check it. Reverting the return type gives 20+ errors in each.
  • Migration guide: new "Typed output" section.

Decisions

  • T, not T | None, on the final response. This trades soundness for the happy path. With the default raise_on_error=False, a reply that doesn't match the schema still returns None (with error set). The guide and docstring say so, and recommend raise_on_error=True or a guard on error / finish_reason / interrupts.
  • Chunks stay optional. Partial parses are routinely None, so narrowing them would be wrong most of the time.

Breaking changes

  • Strict pyright only: if res.output is None: on a typed response now reports reportUnnecessaryComparison. Guard on res.error or res.finish_reason instead. No runtime behavior change.

@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-narrowing branch from 0404016 to 658039f 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 force-pushed the fix/py-1.0-pr2-output-narrowing branch from 658039f to 20fbccd Compare 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-pr2-output-hydration branch from 5a290b5 to db96b31 Compare November 9, 2026 20:01
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-narrowing branch from 20fbccd to 3fc6a0a Compare November 9, 2026 20:02
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-hydration branch from db96b31 to c831aef Compare November 9, 2026 20:19
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-narrowing branch from 3fc6a0a to 3fa2777 Compare November 9, 2026 20:20
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-hydration branch from c831aef to 24f0bae Compare November 9, 2026 21:25
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-narrowing branch from 3fa2777 to fe53dfd Compare November 9, 2026 21:25
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-hydration branch from 24f0bae to af2b347 Compare November 9, 2026 22:03
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-narrowing branch from fe53dfd to 3b1face Compare November 9, 2026 22:03
@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 force-pushed the fix/py-1.0-pr2-output-narrowing branch from 3b1face to d2f9992 Compare November 9, 2026 23:12
@huangjeff5 huangjeff5 changed the title fix(py): statically narrow response.output as OutputT fix(py): statically narrow response.output to OutputT Nov 10, 2026
@huangjeff5
huangjeff5 requested a review from hilariie November 10, 2026 04:08
…efault

The middleware resume note and the google-genai incompatible-settings list
read as if generate raises. Under the default, a bad resume and the
request-time Gemini checks return finish_reason='failed' with error set;
only config validators (thinking_level/thinking_budget, voice/speakers)
raise.
`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).
680991669 replayed a stale copy of the lower PR's README fix and undid
eadf19090: it put google_search back next to a function tool, which
Gemini rejects, and dropped tool_choice from the 'GeminiConfig and
tool_choice' example. Restore the base version; the README is not part
of this PR.
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).
With output_schema=T, ModelResponse[T].output was typed T | None, so every
caller needed a None guard or cast() before reading a field. It now types
as T for generate(), generate_stream()'s final response, and prompts.
With no schema or a JSON-schema dict it types as Any (was Any | None,
which made pyright, mypy, pyrefly and ty all reject res.output['key']).
Bare ModelResponse keeps OutputT's default, object.

ModelResponseChunk.output stays OutputT | None: early chunks routinely
have nothing to parse. It moves from a cached_property to a property over
a cached helper because ty drops the class type parameter from a
cached_property's return type and inferred chunk.output as None.

Runtime is unchanged. output is still None when the reply carries no
output (interrupted / blocked / other finish, a stream stopped early, or
a boxed failure); the docstring lists those. Pairs with raise_on_error
(PR0), which makes failed turns and INVALID_OUTPUT raise instead.

Typing contract: tests/typecheck/output_narrowing_contract_test.py
(pyright, pyrefly, ty, and pytest).
@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-pr2-output-narrowing branch from d2f9992 to 6b6f15e Compare November 10, 2026 07:44
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-output-hydration branch from 1ea19dc to 7edc1a1 Compare November 10, 2026 18:14
huangjeff5 added a commit that referenced this pull request Nov 10, 2026
cached_property drops the class type parameter under ty, so every
chunk.output typed as None. output is now a plain property over a cached
_partial_output; it still parses once per chunk.

Salvaged from #56.
huangjeff5 added a commit that referenced this pull request Nov 10, 2026
generate boxes failures by default, so a reply that doesn't match the
schema is None at runtime; the static type says so. pyright, pyrefly,
and ty check the file. Salvaged from #56 with the assertions flipped.
@huangjeff5

Copy link
Copy Markdown
Collaborator Author

Closing. raise_on_error stays False on generate, so a reply that misses the schema is None at runtime, and typing response.output as OutputT is unsound. JS types it O | null. Two pieces moved to #46: the ModelResponseChunk.output fix (plain property over a cached parse, since ty drops the class type param on cached_property), and output_narrowing_contract_test.py with the assertions flipped to T | None. The OutputT narrowing, the _parse_output split, the migration-guide section, and the flipped generate_test.py assertion are dropped.

@huangjeff5 huangjeff5 closed this Nov 10, 2026
@huangjeff5
huangjeff5 removed this pull request from stack #59 November 10, 2026 18:16
huangjeff5 added a commit that referenced this pull request Nov 10, 2026
cached_property drops the class type parameter under ty, so every
chunk.output typed as None. output is now a plain property over a cached
_partial_output; it still parses once per chunk.

Salvaged from #56.
huangjeff5 added a commit that referenced this pull request Nov 10, 2026
generate boxes failures by default, so a reply that doesn't match the
schema is None at runtime; the static type says so. pyright, pyrefly,
and ty check the file. Salvaged from #56 with the assertions flipped.
huangjeff5 added a commit that referenced this pull request Nov 10, 2026
cached_property drops the class type parameter under ty, so every
chunk.output typed as None. output is now a plain property over a cached
_partial_output; it still parses once per chunk.

Salvaged from #56.
huangjeff5 added a commit that referenced this pull request Nov 10, 2026
generate boxes failures by default, so a reply that doesn't match the
schema is None at runtime; the static type says so. pyright, pyrefly,
and ty check the file. Salvaged from #56 with the assertions flipped.
huangjeff5 added a commit that referenced this pull request Nov 11, 2026
cached_property drops the class type parameter under ty, so every
chunk.output typed as None. output is now a plain property over a cached
_partial_output; it still parses once per chunk.

Salvaged from #56.
huangjeff5 added a commit that referenced this pull request Nov 11, 2026
generate boxes failures by default, so a reply that doesn't match the
schema is None at runtime; the static type says so. pyright, pyrefly,
and ty check the file. Salvaged from #56 with the assertions flipped.
huangjeff5 added a commit that referenced this pull request Nov 11, 2026
cached_property drops the class type parameter under ty, so every
chunk.output typed as None. output is now a plain property over a cached
_partial_output; it still parses once per chunk.

Salvaged from #56.
huangjeff5 added a commit that referenced this pull request Nov 11, 2026
generate boxes failures by default, so a reply that doesn't match the
schema is None at runtime; the static type says so. pyright, pyrefly,
and ty check the file. Salvaged from #56 with the assertions flipped.
huangjeff5 added a commit that referenced this pull request Nov 11, 2026
cached_property drops the class type parameter under ty, so every
chunk.output typed as None. output is now a plain property over a cached
_partial_output; it still parses once per chunk.

Salvaged from #56.
huangjeff5 added a commit that referenced this pull request Nov 11, 2026
generate boxes failures by default, so a reply that doesn't match the
schema is None at runtime; the static type says so. pyright, pyrefly,
and ty check the file. Salvaged from #56 with the assertions flipped.
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