Skip to content

fix(py)!: require input on typed actions, type context-only tools as Tool[None, T], and pin ref configs - #46

Merged
huangjeff5 merged 21 commits into
mainfrom
fix/py-1.0-pr2-static-typing
Nov 18, 2026
Merged

huangjeff5 merged 21 commits into
mainfrom
fix/py-1.0-pr2-static-typing

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Typed flows, tools and actions now require input at type-check time unless it has a default, context-only tools type as Tool[None, T], ModelRef / EmbedderRef pin their config class, embed_many takes any Sequence[str | Document], and tools treat an explicit None as a value like flows do.

# 1. Calling a typed flow with no input fails the type check instead of at runtime
@ai.flow
async def create_invoice(order: OrderReq) -> Invoice: ...

await create_invoice()
# before: passed pyright/pyrefly/ty; raised GenkitError INVALID_ARGUMENT at runtime
# after:  type error, missing argument "input"

# 2. A config from another model family fails the type check
await ai.generate(model=GoogleAI.gemini('gemini-2.5-flash'), config=VeoConfig())
# before: passed every type checker (ModelRef[GeminiConfig] widened to ModelRef[BaseModel])
# after:  type error, VeoConfig is not assignable to GeminiConfig

# 3. embed_many takes tuples and mixed sequences, and rejects a bare str up front
await ai.embed_many(embedder='googleai/gemini-embedding-001', content=('tartine', Document.from_text('soup')))
await ai.embed_many(embedder='googleai/gemini-embedding-001', content='tartine')
# => TypeError: embed_many() takes a sequence of strings or Documents, not a str; use embed() for one.

Changes

  • Fix: typed actions require input: Action.__call__, run and stream used to declare input: InputT | None = NO_INPUT, so every checker accepted await create_invoice() on a Flow[OrderReq, Invoice] and the call failed at runtime with INVALID_ARGUMENT. Self-typed overloads now keep input optional only for Action[None, ...], Any-input actions, and flows and tools whose input has a default (below); everything else needs it.
  • A defaulted input gives DefaultedFlow[T, O] / DefaultedTool[T, O]: Callable can't say a parameter is optional, so a Protocol with a defaulted positional parameter matches async def todays_special(cuisine: str = 'italian') first, and @ai.flow / @ai.tool / define_* return an internal Flow / Tool subclass whose __call__ / run / stream take either no input or a T. await todays_special() and await todays_special('thai') type-check; await todays_special(None) doesn't, unless T includes None (res_id: str | None = None). The factories build the subclass at runtime too, so isinstance agrees with the type. A context after the defaulted input (cuisine: str = 'thai', ctx: FlowContext | None = None) matches by position, whatever it's named. Assigning or passing one to a Flow[T, O] / Tool[T, O] annotation still works when callers pass a T; calling it with no input through that annotation fails the type check because Flow[T, O] requires T.
  • Keyword-only handler parameters are rejected at definition: any action handler (flow, tool, model, embedder, custom action, ...) with a keyword-only parameter now raises TypeError at definition, like positional-only parameters already did. Every action takes at most one input and one context as regular parameters; flows and tools also fail the decorator type check unless the keyword-only parameter has a default.
  • Action input is contravariant: an action that accepts more inputs can stand in where fewer are expected, so DefaultedFlow[str, str] fits a Flow[str, str] annotation, and an explicit Flow[str | None, str] fits Flow[str, str] or Flow[None, str] (same for Tool). A no-input Flow[None, str] still doesn't fit Flow[Order, str].
  • Tools treat an explicit None as a value, like flows: await todays_soup(None) used to silently run with the default, and x: Allergens | None = Allergens() could never receive None. From Python, None is now validated like any value. JSON can't tell null from omitted, so the reflection server, web adapters and the generate tool loop still turn null into "no input".
  • Fix: context-only tools are Tool[None, T]: async def whoami(ctx: ToolContext) -> str used to type as Tool[Any, str], so passing it an input type-checked even though the function never sees it and runtime dropped it. @ai.tool, define_tool and Tool(fn) now return Tool[None, T], matching context-only flows.
  • ModelRef / EmbedderRef config is invariant: the config TypeVars were covariant, which let a checker solve generate(model=ModelRef[GeminiConfig], config=VeoConfig()) by widening to BaseModel. They're invariant now, so the ref pins the config class. They default to Any, so a bare ModelRef / EmbedderRef annotation still accepts any typed ref. generate, generate_stream, generate_operation, define_prompt, embed, embed_many and genkit.exp define_agent split their overloads on whether config is passed, so a ref picked between providers works without config, and config stays pinned when it's passed.
  • embed_many takes Sequence[str | Document]: list[str] | list[Document] rejected tuples and mixed lists because list is invariant. A bare str is also a Sequence[str], so an explicit check raises TypeError instead of embedding one vector per character.
  • genkit_mcp exports McpServerEntry: mcp_servers= takes Mapping[str, McpServerEntry], and a dict literal assigned to a variable infers as dict[str, dict[str, str]], which fails pyright, pyrefly and ty. With the name exported, servers: dict[str, McpServerEntry] = {...} type-checks when the block is built away from the call (from settings, say). skills/.../plugins.md now spells out when a TypedDict export like this is justified.
  • Public annotations resolve at runtime: typing.get_type_hints() on Action.__call__ / run / stream, BackgroundAction and BackgroundModel raised NameError on names only imported for type checking. FastAPI and Pydantic introspect these, so they resolve now.

Breaking changes

The first two are runtime changes; the rest are static type-check changes.

  • Calling a tool with an explicit None now passes None (validated like any value) instead of using the parameter's default. Omit the input to use the default. Tool requests from a model with no input still use the default.

    @ai.tool
    async def todays_soup(day: str = 'monday') -> str: ...
    
    # before
    await todays_soup(None)
    # => 'monday: bouillabaisse'
    # after
    await todays_soup(None)
    # => GenkitError: INVALID_ARGUMENT
    await todays_soup()
    # => 'monday: bouillabaisse'
  • Action handlers with keyword-only parameters now raise TypeError at definition across every action kind (flows, tools, models, embedders, custom actions), and fail the @ai.flow / Flow type check when required. Take input and context as regular parameters:

    # before
    @ai.flow
    async def plate(dish: str, *, ctx: FlowContext) -> str: ...
    # after: TypeError at definition (and type error at @ai.flow)
    @ai.flow
    async def plate(dish: str, ctx: FlowContext) -> str: ...
  • ModelRef[BaseModel] / EmbedderRef[BaseModel] no longer accept plugin refs. Invariance means ModelRef[GeminiConfig] isn't a ModelRef[BaseModel]. Use the bare type, which is ModelRef[Any]:

    # before
    ref: ModelRef[BaseModel] = GoogleAI.gemini('gemini-flash-latest')
    # after
    ref: ModelRef = GoogleAI.gemini('gemini-flash-latest')
  • Calling a context-only tool with an input now fails the type check. async def whoami(ctx: ToolContext) -> str types as Tool[None, str] instead of Tool[Any, str]:

    @ai.tool
    async def whoami(ctx: ToolContext) -> str: ...
    
    # before
    await whoami('ignored')
    # after: type error, expected None
    await whoami()
  • Calling a typed flow, tool or action without input now fails the type check, including a defaulted one called through a Flow[T, O] / Tool[T, O] annotation (since Flow[T, O] requires T):

    # before
    async def run_default(f: Flow[str, str]) -> str:
        return await f()
    # after: type error, missing argument "input" — pass a str, or call todays_special() directly

Known limitations

  • DefaultedFlow[str, O] doesn't fit a Flow[None, O] annotation, since that would accept an explicit None.
  • DefaultedFlow / DefaultedTool aren't exported, so widening one to Flow[T, O] / Tool[T, O] drops the zero-arg call overload. Exporting them later is additive.
  • Flow(fn) / Tool(fn) built directly stay plain Flow / Tool, so omitting a defaulted input there is a type error. ty doesn't read the self-typed __init__ overloads, so it types Tool(fn) as Tool[Any, Any].
  • Calling a no-input flow with an input is a type error, but the input is ignored at runtime.

@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-static-typing branch 2 times, most recently from 450d099 to 1f087fc Compare November 9, 2026 19:25
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-static-typing branch from 133492a to 8af18ce Compare November 9, 2026 19:51
@huangjeff5
huangjeff5 changed the base branch from main to fix/py-1.0-pr2-output-narrowing November 9, 2026 19:51
@huangjeff5
huangjeff5 added this pull request to stack #59 November 9, 2026 19:58
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-static-typing branch from 8af18ce to 227b9fe Compare November 9, 2026 20:02
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-static-typing branch from 227b9fe to 1ecf3a9 Compare November 9, 2026 20:20
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-static-typing branch 2 times, most recently from 8fb2195 to f023c4c Compare November 9, 2026 22:03
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-static-typing branch from f023c4c to 0d515ca Compare November 9, 2026 23:18
@huangjeff5 huangjeff5 changed the title fix(py): static typing overloads and public signature exports fix(py): complete public type exports and clean generate typing overloads Nov 10, 2026
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-static-typing branch from 0d515ca to c528553 Compare November 10, 2026 07:44
@huangjeff5
huangjeff5 marked this pull request as draft November 10, 2026 18:01
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-static-typing branch from c528553 to e9ee864 Compare November 10, 2026 18:14
@huangjeff5
huangjeff5 removed this pull request from stack #59 November 10, 2026 18:16
@huangjeff5
huangjeff5 changed the base branch from fix/py-1.0-pr2-output-narrowing to fix/py-1.0-pr2-output-hydration 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-pr2-static-typing branch from e9ee864 to 8d16198 Compare November 10, 2026 21:57

@hilariie hilariie left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some code that type-checked before doesn't now, so this needs a Breaking changes section. The ones I hit: ModelRef[BaseModel] and EmbedderRef[BaseModel] annotations no longer accept plugin refs, a context-only tool called with an input is an error, and a ref picked between two providers fails pyright when no config is passed.

Comment thread scripts/schema_to_typing.py Resolved
# 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.
@huangjeff5 huangjeff5 changed the title fix(py): export missing public types, require input on typed actions, and pin ref configs fix(py)!: require input on typed actions, type context-only tools as Tool[None, T], and pin ref configs Nov 16, 2026
…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.
@huangjeff5
huangjeff5 requested a review from hilariie November 16, 2026 17:51
…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.
@huangjeff5

Copy link
Copy Markdown
Collaborator Author

the ref-picked-between-providers case type-checks again without config: generate/embed split overloads on config, config still pinned when passed. ec7d06d

@hilariie hilariie left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Breaking changes section says everything except the tool None change is static, but the keyword-only check is a runtime break for handlers that work today. A context-only tool called with an input is also still missing there, and "annotating one as Flow[T, O] still works" reads as if calling it with no input through that annotation works too, which now fails all three checkers.

@hilariie hilariie left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

approving with the comments above

@huangjeff5
huangjeff5 merged commit a7d302c into main Nov 18, 2026
21 checks passed
@huangjeff5
huangjeff5 deleted the fix/py-1.0-pr2-static-typing branch November 18, 2026 17:29
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.

2 participants