Skip to content

fix(py): type prompt on_chunk callbacks as ModelResponseChunk - #135

Open
huangjeff5 wants to merge 22 commits into
mainfrom
fix/py-prompt-on-chunk-type
Open

huangjeff5 wants to merge 22 commits into
mainfrom
fix/py-prompt-on-chunk-type

Conversation

@huangjeff5

Copy link
Copy Markdown
Collaborator

Stacked on #46.

await prompt(on_chunk=cb) now hands cb a ModelResponseChunk[OutputT], so a callback reads .text, and with a typed output_schema it reads a typed .output, with no cast.

plate = ai.define_prompt(prompt='Plate the special.', output_schema=Dish)

# before (main): on_chunk was Callable[[object], None]
await plate(on_chunk=lambda c: print(c.text))
# => type error: Cannot access attribute "text" for class "object"

# after
await plate(on_chunk=lambda c: print(c.text))

def on_dish(chunk: ModelResponseChunk[Dish]) -> None:
    print(chunk.output)  # Dish | None

await plate(on_chunk=on_dish)

Changes

  • Prompt.__call__(on_chunk=) takes Callable[[ModelResponseChunk[OutputT]], Any]: on main it was StreamingCallback = 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 to Callable[[ModelResponseChunk], Any]; this PR adds the output type, so the chunk matches what Prompt.stream() already yields (ModelStreamResponse[OutputT]).
    • Runtime always passes a ModelResponseChunk. generate_action builds every chunk and parses its output with the prompt's schema.
    • The one cast now sits at the generate_action call, which isn't generic in the output type, instead of on every stream() chunk.
  • Contract test (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.
    • A prompt with output_schema=Dish accepts a ModelResponseChunk[Dish] callback, and chunk.output is Dish | None.
    • A def log_anything(chunk: object) callback and received.append still fit.
    • A def count_covers(covers: int) callback is rejected.
    • At runtime, every chunk arrives as a 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, already ModelResponseChunk[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.
  • Agents: no public chunk callback. Chats stream through their response objects.

No other public path passes something other than its declared chunk type.

After #46 and #134 both land, #134's cast(ModelResponseChunk, chunk) in prompt_test.py can go. It exists only because main's callback was typed object.

Breaking changes

None. The callback parameter widens what callers can rely on, and existing callbacks typed object (or Any) still type-check, since Callable parameters are contravariant.

# 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.
Base automatically changed from fix/py-1.0-pr2-static-typing to main November 18, 2026 17:29
# 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
@huangjeff5
huangjeff5 requested a review from hilariie December 1, 2026 23:23

@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 description predates #46 landing: main already has Callable[[ModelResponseChunk], Any], so .text type-checks there today, and #134 closed without touching prompt_test.py. Could the body and title be updated to describe what's left, typing the chunk's .output by the prompt's schema?

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,

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.

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)

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.

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

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.

Nit: received.append returns None, so this doesn't exercise the Any return.

This branch has not been deployed

No deployments
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