Repository navigation
fix(py): type prompt on_chunk callbacks as ModelResponseChunk - #135
huangjeff5 wants to merge 22 commits into
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.
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.
`await prompt(on_chunk=cb)` now passes `ModelResponseChunk[OutputT]`, matching what Prompt.stream() yields. Callbacks read `.text` and, with a typed output_schema, a typed `.output`, with no cast. Callbacks typed `object` still fit; ones for an unrelated type are rejected. The cast moves to the generate_action call, which isn't generic in the output type, instead of wrapping every stream() chunk.
# Conflicts: # packages/genkit/src/genkit/_ai/_prompt.py # packages/genkit/src/genkit/_core/_action.py # packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py
| resume_restart: Part | list[Part] | None = None, | ||
| resume_metadata: dict[str, Any] | None = None, | ||
| on_chunk: Callable[[ModelResponseChunk], Any] | None = None, | ||
| on_chunk: Callable[[ModelResponseChunk[OutputT]], Any] | None = None, |
There was a problem hiding this comment.
Since ModelResponseChunk is invariant in its output type, a callback typed with bare ModelResponseChunk (main's own signature) no longer type-checks on a prompt with an output_schema. Forwarding ctx.send_chunk from a FlowContext[ModelResponseChunk] breaks the same way, in both pyright and ty. So this is breaking for those callers, which the body currently says it isn't.
| chunks: list[ModelResponseChunk[Dish]] = [] | ||
|
|
||
| def on_dish(chunk: ModelResponseChunk[Dish]) -> None: | ||
| assert_type(chunk.output, Dish | None) |
There was a problem hiding this comment.
This checks on_dish's own annotation rather than what the prompt passes in, so widening on_chunk to ModelResponseChunk[Any] still passes every test here. Nothing checks at runtime that the chunk output is actually a Dish either.
| assert len(received) == 2 | ||
| assert all(isinstance(c, ModelResponseChunk) for c in received) | ||
|
|
||
| # 2. A callback returning a value fits too |
There was a problem hiding this comment.
Nit: received.append returns None, so this doesn't exercise the Any return.
Stacked on #46.
await prompt(on_chunk=cb)now handscbaModelResponseChunk[OutputT], so a callback reads.text, and with a typedoutput_schemait reads a typed.output, with no cast.Changes
Prompt.__call__(on_chunk=)takesCallable[[ModelResponseChunk[OutputT]], Any]: on main it wasStreamingCallback = Callable[[object], None]. fix(py)!: require input on typed actions, type context-only tools as Tool[None, T], and pin ref configs #46 already widened it toCallable[[ModelResponseChunk], Any]; this PR adds the output type, so the chunk matches whatPrompt.stream()already yields (ModelStreamResponse[OutputT]).ModelResponseChunk.generate_actionbuilds every chunk and parses its output with the prompt's schema.generate_actioncall, which isn't generic in the output type, instead of on everystream()chunk.tests/typecheck/prompt_on_chunk_contract_test.py), clean in pyright, pyrefly and ty:on_chunk=lambda c: seen.append(c.text)type-checks with no cast.output_schema=Dishaccepts aModelResponseChunk[Dish]callback, andchunk.outputisDish | None.def log_anything(chunk: object)callback andreceived.appendstill fit.def count_covers(covers: int)callback is rejected.ModelResponseChunk.Audit of public chunk callbacks in genkit core
Prompt.__call__(on_chunk=): loose on main (object). Fixed here; fix(py)!: require input on typed actions, type context-only tools as Tool[None, T], and pin ref configs #46 had started it.Prompt.stream()/ai.generate_stream(): no callback. Chunks come from.stream, alreadyModelResponseChunk[OutputT].Prompt.render()/ai.generate(): no chunk callback.Action.run(on_chunk=)/Flow.run/Tool.run:Callable[[ChunkT], None], typed by the action's chunk type.FlowContext.send_chunk/ToolContext.send_chunk:ChunkT.MiddlewareContext.on_chunk/send_chunk:ModelResponseChunk.No other public path passes something other than its declared chunk type.
After #46 and #134 both land, #134's
cast(ModelResponseChunk, chunk)inprompt_test.pycan go. It exists only because main's callback was typedobject.Breaking changes
None. The callback parameter widens what callers can rely on, and existing callbacks typed
object(orAny) still type-check, since Callable parameters are contravariant.