Skip to content

fix(py/exp): type SessionSnapshot by state_schema and export missing agent types - #119

Open
huangjeff5 wants to merge 23 commits into
mainfrom
fix/py-exp-agent-snapshot-typing
Open

huangjeff5 wants to merge 23 commits into
mainfrom
fix/py-exp-agent-snapshot-typing

Conversation

@huangjeff5

Copy link
Copy Markdown
Collaborator

Stacked on #46. Parameterizes SessionSnapshot[StateT] and SessionState[StateT] so AgentClient.get_snapshot() and AgentChat.get_snapshot() hydrate state.custom from state_schema, and exports missing types used in genkit.exp signatures.

# --- BEFORE ---
# 1. Annotating custom AgentTransport or session store helpers required private imports
from genkit._core._action import BidiConnection  # => pyright: reportPrivateImportUsage

# 2. SessionSnapshot was non-generic and get_snapshot() returned an unhydrated dict
snap = await client.get_snapshot(session_id='order-42')
snap.state.custom
# => {'items': ['tartine']}  (dict, even when state_schema=CartState was set)


# --- AFTER ---
# 1. Public exports on genkit.exp.agent and public Session return type on current_session()
from genkit.exp.agent import BidiConnection, select_leaf

# 2. SessionSnapshot[CartState] hydrates state.custom from state_schema
snap: SessionSnapshot[CartState] | None = await client.get_snapshot(session_id='order-42')
print(snap.state.custom.items)
# => ['tartine']

Main Changes

  • Parameterize SessionSnapshot[StateT] and hydrate state.custom on get_snapshot(): Previously, SessionSnapshot was non-generic and AgentClient.get_snapshot() / AgentChat.get_snapshot() returned state.custom as a raw dict even when state_schema was configured. SessionSnapshot and SessionState are now generic (defaulting to Any) and validate settled snapshot state against state_schema, matching DetachedTask.
  • Export BidiConnection and select_leaf from genkit.exp.agent: Previously, implementing a custom AgentTransport or store helper required importing BidiConnection or select_leaf from private _ modules. Both are now exported from genkit.exp.agent.
  • Annotate genkit.exp.current_session() with public Session[Any] | None: Previously, current_session() was annotated with private _core._protocols.SessionLike. Returning Session[Any] | None matches the concrete Session exported from genkit.exp.agent.

@huangjeff5
huangjeff5 force-pushed the fix/py-exp-agent-snapshot-typing branch from d67be1b to 1c902bc Compare November 12, 2026 08:31
@huangjeff5
huangjeff5 force-pushed the fix/py-exp-agent-snapshot-typing branch from 1c902bc to fec5037 Compare November 12, 2026 09:24
@huangjeff5
huangjeff5 added this pull request to stack #122 November 12, 2026 16:11
# 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
Base automatically changed from fix/py-1.0-pr2-static-typing to main November 18, 2026 17:29
# 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
@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