Skip to content

fix(py)!: accept model and embedder handlers with context in either position - #133

Merged
huangjeff5 merged 28 commits into
mainfrom
fix/py-model-embedder-handler-shapes
Nov 18, 2026
Merged

huangjeff5 merged 28 commits into
mainfrom
fix/py-model-embedder-handler-shapes

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Model, embedder and background-model handlers now follow the same rule as flows and tools: one request plus an optional context, with the context in either position. Every one of these shapes type-checks in pyright, pyrefly and ty, and runs.

# 1. A model that doesn't stream can drop the context
async def house_chef(req: ModelRequest[SpiceConfig]) -> ModelResponse: ...

ai.define_model(name='bistro/house-chef', fn=house_chef)
# before: type error in all three checkers (ModelFn required (req, ctx)); ran fine
# after:  type-checks

# 2. Context first, like a flow can
async def line_cook(ctx: ModelContext, req: ModelRequest[SpiceConfig]) -> ModelResponse: ...

ai.define_model(name='bistro/line-cook', fn=line_cook)
# before: type error, then GenkitError at definition:
#         "the request parameter must be annotated as ModelRequest ..., got ModelContext"
# after:  type-checks, runs, and req.config arrives as SpiceConfig

# 3. Embedders and background models take the same shapes
async def embed_menu(ctx: EmbedContext, req: EmbedRequest) -> EmbedResponse: ...
async def start_reel(ctx: ModelContext, req: ModelRequest) -> Operation: ...

# 4. Two inputs or a keyword-only parameter still fail both ways
async def chef(req: ModelRequest, table: str) -> ModelResponse: ...
ai.define_model(name='bistro/chef', fn=chef)
# => type error, and TypeError: model 'bistro/chef' takes one input, but 'table' is a second parameter. ...

Changes

  • Model handlers accept (req), (req, ctx) and (ctx, req): ModelFn was Callable[[ModelRequest, ModelContext], ...], so a model with no context parameter failed every checker even though Genkit passes the request and context by name and runs it. ModelFn is now (req) | (req, ctx), and define_model / Model take (ctx, req) through a second overload. A third arm in the union would make pyright and pyrefly infer lambda req: ... as (req: ModelContext). ModelRequest[Cfg] still types the config, because Callable parameters are contravariant.
  • A context-first model runs: define_model checked the request annotation on the first parameter, so (ctx: ModelContext, req: ModelRequest) raised INVALID_ARGUMENT naming ModelContext as the request. It now asks find_input_and_context which parameter is the input, as flows, tools and embedders already do. Config class resolution already read the input parameter, so ModelRequest[SpiceConfig] keeps SpiceConfig in both orders.
  • Embedders take (ctx, req) too: EmbedderFn stays (req) | (req, ctx), and define_embedder / Embedder add (ctx, req) as a second overload, so lambda req: ... keeps type-checking. Runtime already ran the reversed order.
  • Background model start / check / cancel take the same three shapes: StartModelOpFn, CheckModelOpFn and CancelModelOpFn required (input, ctx). Runtime already ran all three shapes for start, check and cancel, so this is types only. CancelModelOpFn is now the same alias as CheckModelOpFn; both take an Operation[ModelResponse].
  • *args and **kwargs on a handler raise at definition: Genkit passes only the input and context, by name, so these never received anything; find_input_and_context dropped them. A decorator without functools.wraps leaves (*args, **kwargs), and that handler ran with no input. Every handler Genkit calls by name now raises TypeError at definition, next to the / and * checks: flows, tools, models, embedders, background start / check / cancel, batch evaluators and custom actions. Bidi fns and per-row evaluators are called positionally and keep their own shapes.
  • Contract tests: tests/typecheck/model_embedder_shapes_contract_test.py checks every supported shape at ai.define_*, the plugin-level Model / Embedder / BackgroundModel constructors and the registry-level define_*, runs each one, and pins two-input and keyword-only handlers as errors in all three checkers plus TypeError at definition. It also pins lambda req: ... at every model and embedder entry point.

Breaking changes

  • A handler with *args or **kwargs raises TypeError at definition. They never received a value. Remove them, or apply functools.wraps in the decorator that added them:

    # before: defined fine, extras was always empty
    @ai.flow
    async def plate(dish: str, **extras) -> str: ...
    # => TypeError: flow 'plate' takes **extras, but Genkit passes only the input and context. ...
    
    # after
    @ai.flow
    async def plate(dish: str) -> str: ...

Every other shape that type-checked or ran before still does. ModelFn, EmbedderFn and the background aliases stay unexported.

# 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.
…sition

Model, embedder and background-model handlers now follow the flow/tool
rule: one request plus an optional context, in either order.

ModelFn only allowed (req, ctx), so a model with no context failed every
checker though it ran. EmbedderFn lacked (ctx, req), and the background
start/check/cancel aliases required (input, ctx). All four are now unions
of the (input, ctx), (ctx, input) and (input) Callable shapes.

define_model checked the request annotation on the first parameter, so a
context-first model raised INVALID_ARGUMENT naming ModelContext. It now
finds the request with find_input_and_context, like the other kinds.
ModelRequest[Cfg] keeps its config class in both orders.

model_embedder_shapes_contract_test.py pins every shape at ai.define_*,
the plugin-level constructors and registry-level define_*, runs each, and
pins two-input and keyword-only handlers as errors.
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.
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/tests/typecheck/flow_tool_shapes_contract_test.py
…ignature-less wrappers

ModelFn and EmbedderFn go back to (req) | (req, ctx). The ctx-first shape
is a second overload on define_model, Model, define_embedder and Embedder:
as a third union arm it made pyright and pyrefly infer `lambda req: ...`
as (req: ModelContext).

A model fn that only takes *args / **kwargs (a decorator without
functools.wraps) raises INVALID_ARGUMENT at define_model instead of
failing every generate(). Tests pin the ctx-first request check too.
Genkit passes only the input and context, by name, so *args and **kwargs
never received anything: find_input_and_context dropped them. A wrapper
without functools.wraps, (*args, **kwargs), ran with no input at all.

Every handler Genkit calls by name (flows, tools, models, embedders,
background start/check/cancel, batch evaluators, custom actions) now
raises TypeError at definition, next to the '/' and '*' checks. This
replaces the model-only check from the previous commit. Bidi fns and
per-row evaluators are called positionally and keep their own shapes.
@huangjeff5 huangjeff5 changed the title fix(py): accept model and embedder handlers with context in either position fix(py)!: accept model and embedder handlers with context in either position Nov 18, 2026
@huangjeff5
huangjeff5 merged commit 5020b4d into main Nov 18, 2026
22 checks passed
@huangjeff5
huangjeff5 deleted the fix/py-model-embedder-handler-shapes branch November 18, 2026 22:34
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