Repository navigation
fix(py)!: accept model and embedder handlers with context in either position - #133
Merged
Merged
Conversation
… and pin ref configs
# 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.
hilariie
reviewed
Nov 18, 2026
hilariie
approved these changes
Nov 18, 2026
# 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.
Merged
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.
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.
Changes
(req),(req, ctx)and(ctx, req):ModelFnwasCallable[[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.ModelFnis now(req) | (req, ctx), anddefine_model/Modeltake(ctx, req)through a second overload. A third arm in the union would make pyright and pyrefly inferlambda req: ...as(req: ModelContext).ModelRequest[Cfg]still types the config, becauseCallableparameters are contravariant.define_modelchecked the request annotation on the first parameter, so(ctx: ModelContext, req: ModelRequest)raisedINVALID_ARGUMENTnamingModelContextas the request. It now asksfind_input_and_contextwhich parameter is the input, as flows, tools and embedders already do. Config class resolution already read the input parameter, soModelRequest[SpiceConfig]keepsSpiceConfigin both orders.(ctx, req)too:EmbedderFnstays(req) | (req, ctx), anddefine_embedder/Embedderadd(ctx, req)as a second overload, solambda req: ...keeps type-checking. Runtime already ran the reversed order.start/check/canceltake the same three shapes:StartModelOpFn,CheckModelOpFnandCancelModelOpFnrequired(input, ctx). Runtime already ran all three shapes for start, check and cancel, so this is types only.CancelModelOpFnis now the same alias asCheckModelOpFn; both take anOperation[ModelResponse].*argsand**kwargson a handler raise at definition: Genkit passes only the input and context, by name, so these never received anything;find_input_and_contextdropped them. A decorator withoutfunctools.wrapsleaves(*args, **kwargs), and that handler ran with no input. Every handler Genkit calls by name now raisesTypeErrorat 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.tests/typecheck/model_embedder_shapes_contract_test.pychecks every supported shape atai.define_*, the plugin-levelModel/Embedder/BackgroundModelconstructors and the registry-leveldefine_*, runs each one, and pins two-input and keyword-only handlers as errors in all three checkers plusTypeErrorat definition. It also pinslambda req: ...at every model and embedder entry point.Breaking changes
A handler with
*argsor**kwargsraisesTypeErrorat definition. They never received a value. Remove them, or applyfunctools.wrapsin the decorator that added them:Every other shape that type-checked or ran before still does.
ModelFn,EmbedderFnand the background aliases stay unexported.