Repository navigation
fix(py): statically narrow response.output to OutputT - #56
Closed
huangjeff5 wants to merge 22 commits into
Closed
huangjeff5 wants to merge 22 commits into
huangjeff5 wants to merge 22 commits into
Conversation
huangjeff5
force-pushed
the
fix/py-1.0-pr2-output-hydration
branch
from
November 9, 2026 19:08
291e086 to
c93be6c
Compare
huangjeff5
force-pushed
the
fix/py-1.0-pr2-output-narrowing
branch
from
November 9, 2026 19:08
0404016 to
658039f
Compare
huangjeff5
force-pushed
the
fix/py-1.0-pr2-output-hydration
branch
from
November 9, 2026 19:49
c93be6c to
5a290b5
Compare
huangjeff5
force-pushed
the
fix/py-1.0-pr2-output-narrowing
branch
from
November 9, 2026 19:49
658039f to
20fbccd
Compare
huangjeff5
force-pushed
the
fix/py-1.0-pr2-output-hydration
branch
from
November 9, 2026 20:01
5a290b5 to
db96b31
Compare
huangjeff5
force-pushed
the
fix/py-1.0-pr2-output-narrowing
branch
from
November 9, 2026 20:02
20fbccd to
3fc6a0a
Compare
huangjeff5
force-pushed
the
fix/py-1.0-pr2-output-hydration
branch
from
November 9, 2026 20:19
db96b31 to
c831aef
Compare
huangjeff5
force-pushed
the
fix/py-1.0-pr2-output-narrowing
branch
from
November 9, 2026 20:20
3fc6a0a to
3fa2777
Compare
huangjeff5
force-pushed
the
fix/py-1.0-pr2-output-hydration
branch
from
November 9, 2026 21:25
c831aef to
24f0bae
Compare
huangjeff5
force-pushed
the
fix/py-1.0-pr2-output-narrowing
branch
from
November 9, 2026 21:25
3fa2777 to
fe53dfd
Compare
huangjeff5
force-pushed
the
fix/py-1.0-pr2-output-hydration
branch
from
November 9, 2026 22:03
24f0bae to
af2b347
Compare
huangjeff5
force-pushed
the
fix/py-1.0-pr2-output-narrowing
branch
from
November 9, 2026 22:03
fe53dfd to
3b1face
Compare
huangjeff5
force-pushed
the
fix/py-1.0-pr2-output-hydration
branch
from
November 9, 2026 23:12
af2b347 to
2148558
Compare
huangjeff5
force-pushed
the
fix/py-1.0-pr2-output-narrowing
branch
from
November 9, 2026 23:12
3b1face to
d2f9992
Compare
…ne_helper, plugin error)
…ngo 5.0 requirement
…d image/Veo ids in docstrings
…results, close streams in fastapi README
…mini rejects the combination)
…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
force-pushed
the
fix/py-1.0-pr2-output-hydration
branch
from
November 10, 2026 07:44
2148558 to
1ea19dc
Compare
huangjeff5
force-pushed
the
fix/py-1.0-pr2-output-narrowing
branch
from
November 10, 2026 07:44
d2f9992 to
6b6f15e
Compare
huangjeff5
force-pushed
the
fix/py-1.0-pr2-output-hydration
branch
from
November 10, 2026 18:14
1ea19dc to
7edc1a1
Compare
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.
Collaborator
Author
|
Closing. |
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
With
output_schema=T,response.outputnow types asTinstead ofT | None, so callers drop thecast(). The type does not modelNone. At runtimeoutputis stillNonewhen the reply has no output.Main changes
ModelResponse.output: returnsOutputT, with onecastat the parser boundary. No schema or a JSON-schema dict types asAny. A bareModelResponsetypes asobject.ModelResponseChunk.output: staysOutputT | 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 acached_propertyreturn type. Parsing still runs once per chunk.tests/typecheck/output_narrowing_contract_test.pycoversgenerate, theconfig={...}overload,list[T], dataclass,Enum, no schema, a dict schema, streams,define_prompt,ai.prompt, and bareModelResponse. pyright, pyrefly, and ty all check it. Reverting the return type gives 20+ errors in each.output" section.Decisions
T, notT | None, on the final response. This trades soundness for the happy path. With the defaultraise_on_error=False, a reply that doesn't match the schema still returnsNone(witherrorset). The guide and docstring say so, and recommendraise_on_error=Trueor a guard onerror/finish_reason/interrupts.None, so narrowing them would be wrong most of the time.Breaking changes
if res.output is None:on a typed response now reportsreportUnnecessaryComparison. Guard onres.errororres.finish_reasoninstead. No runtime behavior change.