Repository navigation
fix(py/exp): type SessionSnapshot by state_schema and export missing agent types - #119
Open
huangjeff5 wants to merge 23 commits into
Open
huangjeff5 wants to merge 23 commits into
huangjeff5 wants to merge 23 commits into
Conversation
huangjeff5
force-pushed
the
fix/py-exp-agent-snapshot-typing
branch
from
November 12, 2026 08:31
d67be1b to
1c902bc
Compare
… and pin ref configs
huangjeff5
force-pushed
the
fix/py-exp-agent-snapshot-typing
branch
from
November 12, 2026 09:24
1c902bc to
fec5037
Compare
# Conflicts: # packages/genkit/src/genkit/_core/_action.py # packages/genkit/src/genkit/_core/_background.py # packages/genkit/src/genkit/_core/_model.py
copy.copy, copy.deepcopy and Tool subclasses with their own __init__ args raised TypeError through the overloaded __new__. ty inferred no better types with them. Context-only tools are Tool[None, T]; assert that.
Both only name a shape a parameter already accepts (define_model's fn, define_mcp_host's entries), so per plugins.md they stay private.
Sequence[object] dropped argument checking on a public classmethod and rebuilt every message per call. Back to Sequence[Message]/Message.
…able A dict literal assigned to a variable infers as dict[str, dict[str, str]] and fails pyright, pyrefly and ty against Mapping[str, McpServerEntry]. The TypedDict is the only typed way to build it away from the call, so it stays public. plugins.md now says when a TypedDict export is justified.
A Protocol with a defaulted positional parameter matches 'async def greet(name: str = "world")', so @ai.flow / @ai.tool / define_* / Flow(...) / Tool(...) type it Flow[str | None, str]. A third self-typed overload on __call__/run/stream makes input optional when InputT includes None. Required inputs still fail at check time.
Flow[str | None, str] (a defaulted input) now fits a Flow[str, str] or Flow[None, str] annotation, and Tool likewise. Private helpers that returned InputT return Any, Action.input_type is TypeAdapter[Any], and Tool.from_action casts after isinstance so ty keeps the type params.
From Python, await todays_soup(None) passed NO_INPUT, so a tool with 'day: str = "monday"' silently used the default and 'x: Foo | None = Foo()' could never receive None. None is now validated like any value; omit the input to use the default. JSON null still means omitted: the reflection and web boundaries already used input_from_json, and the generate tool loop now does too, so a model's no-input tool request still gets the default.
…Tool A flow or tool whose input has a default was typed Flow[T | None, O], so `await todays_special(None)` type-checked and then failed input validation at runtime. @ai.flow / @ai.tool / define_* now return an internal DefaultedFlow[T, O] / DefaultedTool[T, O] subclass whose __call__ / run / stream take either no input or a T. None is rejected statically unless T includes it. The factories build the subclass at runtime when the input has a default, so isinstance agrees with the static type. Flow(fn) / Tool(fn) built directly stay plain. The Action-level `T | None` overload is gone.
`async def special(cuisine: str = 'thai', ctx: FlowContext | None = None)` matched the (input, ctx) overload and typed Flow[str, str], so `special()` failed all three checkers though it runs. A DefaultInputCtxFn Protocol, `(input = ..., ctx = ..., /)`, matches it by position whatever the context is named, ahead of (input, ctx), and returns DefaultedFlow / DefaultedTool.
…racts Shapes the overloads can't model, like a keyword-only context (`(cuisine: str = 'thai', *, ctx: FlowContext)`), failed at the decorator with no-matching-overload. Each flow and tool overload set now ends in `Callable[..., Awaitable[O]] -> Flow[Any, O]` / `Tool[Any, O]`: output stays typed, input is unchecked for those shapes only. flow_tool_shapes_contract_test.py pins the exact type of every supported shape for @ai.flow, @ai.flow(), define_flow, @ai.tool, @ai.tool() and define_tool, so a shape that falls through to the catch-all fails CI as Flow[Any, ...]. It also checks call-level errors, assignability, and that the runtime class matches the static type.
…erload Flows and tools take at most one input and one context. A keyword-only parameter (`(cuisine: str = 'thai', *, ctx: FlowContext)`) was never a supported shape, but runtime accepted it silently. find_input_and_context now raises TypeError for it, next to the positional-only check. With that, the Callable[..., Awaitable[O]] catch-all on every flow and tool overload set (and Flow.__init__) has nothing left to cover, so it's gone. Keyword-only and two-input handlers fail at the decorator in pyright, pyrefly and ty, and raise TypeError at definition. The contract tests pin both.
With invariant ModelRef / EmbedderRef config, one signature `model: ModelRef[C] | str, config: C | dict | None = None` made pyright solve a single C even when config was omitted, so `GoogleAI.gemini(...) if x else OpenAI.gpt(...)` failed generate. generate, generate_stream, generate_operation, define_prompt, embed, embed_many and exp define_agent now split their overloads on config: - no config: `model: ModelRef[Any] | ...`, `config: None = None` - config passed: `model: ModelRef[C]`, `config: C | Mapping | None` (required), so another family's config still fails. The typed output_schema arms are kept in both. ref_config_contract_test.py pins union-no-config, pinned, dict, wrong-family and union-plus-typed-config per entry point, with typed output in both arms.
…to HEAD # Conflicts: # packages/genkit/tests/genkit/core/public_types_runtime_test.py
# Conflicts: # packages/genkit/src/genkit/_core/_action.py # packages/genkit/src/genkit/web/_sse.py # packages/genkit/tests/genkit/core/public_types_runtime_test.py # packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py
This branch has not been deployed
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.
Stacked on #46. Parameterizes
SessionSnapshot[StateT]andSessionState[StateT]soAgentClient.get_snapshot()andAgentChat.get_snapshot()hydratestate.customfromstate_schema, and exports missing types used ingenkit.expsignatures.Main Changes
SessionSnapshot[StateT]and hydratestate.customonget_snapshot(): Previously,SessionSnapshotwas non-generic andAgentClient.get_snapshot()/AgentChat.get_snapshot()returnedstate.customas a rawdicteven whenstate_schemawas configured.SessionSnapshotandSessionStateare now generic (defaulting toAny) and validate settled snapshot state againststate_schema, matchingDetachedTask.BidiConnectionandselect_leaffromgenkit.exp.agent: Previously, implementing a customAgentTransportor store helper required importingBidiConnectionorselect_leaffrom private_modules. Both are now exported fromgenkit.exp.agent.genkit.exp.current_session()with publicSession[Any] | None: Previously,current_session()was annotated with private_core._protocols.SessionLike. ReturningSession[Any] | Nonematches the concreteSessionexported fromgenkit.exp.agent.