Repository navigation
fix(py)!: require input on typed actions, type context-only tools as Tool[None, T], and pin ref configs - #46
Conversation
450d099 to
1f087fc
Compare
133492a to
8af18ce
Compare
8af18ce to
227b9fe
Compare
227b9fe to
1ecf3a9
Compare
8fb2195 to
f023c4c
Compare
f023c4c to
0d515ca
Compare
0d515ca to
c528553
Compare
c528553 to
e9ee864
Compare
e9ee864 to
8d16198
Compare
hilariie
left a comment
There was a problem hiding this comment.
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.
# 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.
|
the ref-picked-between-providers case type-checks again without config: generate/embed split overloads on config, config still pinned when passed. ec7d06d |
hilariie
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
approving with the comments above
Typed flows, tools and actions now require
inputat type-check time unless it has a default, context-only tools type asTool[None, T],ModelRef/EmbedderRefpin their config class,embed_manytakes anySequence[str | Document], and tools treat an explicitNoneas a value like flows do.Changes
input:Action.__call__,runandstreamused to declareinput: InputT | None = NO_INPUT, so every checker acceptedawait create_invoice()on aFlow[OrderReq, Invoice]and the call failed at runtime withINVALID_ARGUMENT. Self-typed overloads now keepinputoptional only forAction[None, ...],Any-input actions, and flows and tools whose input has a default (below); everything else needs it.DefaultedFlow[T, O]/DefaultedTool[T, O]:Callablecan't say a parameter is optional, so aProtocolwith a defaulted positional parameter matchesasync def todays_special(cuisine: str = 'italian')first, and@ai.flow/@ai.tool/define_*return an internalFlow/Toolsubclass whose__call__/run/streamtake either no input or aT.await todays_special()andawait todays_special('thai')type-check;await todays_special(None)doesn't, unlessTincludesNone(res_id: str | None = None). The factories build the subclass at runtime too, soisinstanceagrees 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 aFlow[T, O]/Tool[T, O]annotation still works when callers pass aT; calling it with no input through that annotation fails the type check becauseFlow[T, O]requiresT.TypeErrorat 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.DefaultedFlow[str, str]fits aFlow[str, str]annotation, and an explicitFlow[str | None, str]fitsFlow[str, str]orFlow[None, str](same forTool). A no-inputFlow[None, str]still doesn't fitFlow[Order, str].Noneas a value, like flows:await todays_soup(None)used to silently run with the default, andx: Allergens | None = Allergens()could never receiveNone. From Python,Noneis 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".Tool[None, T]:async def whoami(ctx: ToolContext) -> strused to type asTool[Any, str], so passing it an input type-checked even though the function never sees it and runtime dropped it.@ai.tool,define_toolandTool(fn)now returnTool[None, T], matching context-only flows.ModelRef/EmbedderRefconfig is invariant: the config TypeVars were covariant, which let a checker solvegenerate(model=ModelRef[GeminiConfig], config=VeoConfig())by widening toBaseModel. They're invariant now, so the ref pins the config class. They default toAny, so a bareModelRef/EmbedderRefannotation still accepts any typed ref.generate,generate_stream,generate_operation,define_prompt,embed,embed_manyandgenkit.expdefine_agentsplit their overloads on whetherconfigis passed, so a ref picked between providers works without config, and config stays pinned when it's passed.embed_manytakesSequence[str | Document]:list[str] | list[Document]rejected tuples and mixed lists becauselistis invariant. A barestris also aSequence[str], so an explicit check raisesTypeErrorinstead of embedding one vector per character.genkit_mcpexportsMcpServerEntry:mcp_servers=takesMapping[str, McpServerEntry], and a dict literal assigned to a variable infers asdict[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.mdnow spells out when aTypedDictexport like this is justified.typing.get_type_hints()onAction.__call__/run/stream,BackgroundActionandBackgroundModelraisedNameErroron 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.
Action handlers with keyword-only parameters now raise
TypeErrorat definition across every action kind (flows, tools, models, embedders, custom actions), and fail the@ai.flow/Flowtype check when required. Take input and context as regular parameters:ModelRef[BaseModel]/EmbedderRef[BaseModel]no longer accept plugin refs. Invariance meansModelRef[GeminiConfig]isn't aModelRef[BaseModel]. Use the bare type, which isModelRef[Any]:Calling a context-only tool with an input now fails the type check.
async def whoami(ctx: ToolContext) -> strtypes asTool[None, str]instead ofTool[Any, str]:Calling a typed flow, tool or action without
inputnow fails the type check, including a defaulted one called through aFlow[T, O]/Tool[T, O]annotation (sinceFlow[T, O]requiresT):Known limitations
DefaultedFlow[str, O]doesn't fit aFlow[None, O]annotation, since that would accept an explicitNone.DefaultedFlow/DefaultedToolaren't exported, so widening one toFlow[T, O]/Tool[T, O]drops the zero-arg call overload. Exporting them later is additive.Flow(fn)/Tool(fn)built directly stay plainFlow/Tool, so omitting a defaulted input there is a type error. ty doesn't read the self-typed__init__overloads, so it typesTool(fn)asTool[Any, Any].