Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
1caceff
fix(py): export missing public types, require input on typed actions,…
huangjeff5 Nov 12, 2026
1363fb4
fix(py): keep ActionResponse out of genkit.plugin_api
huangjeff5 Nov 12, 2026
0df3bdc
docs(py): clarify why ref config TypeVars default to Any
huangjeff5 Nov 12, 2026
18cff5d
chore(py): remove unused CheckOpFn and CancelOpFn aliases
huangjeff5 Nov 12, 2026
43c4f81
Merge remote-tracking branch 'origin/main' into HEAD
huangjeff5 Nov 16, 2026
0d36862
chore(py): unquote ActionContext annotation after merge
huangjeff5 Nov 16, 2026
3bdcf41
fix(py): drop Tool.__new__ overloads so copy and subclassing work again
huangjeff5 Nov 16, 2026
047575f
fix(py): keep ModelFn and McpServerEntry out of the public exports
huangjeff5 Nov 16, 2026
74676ca
fix(py): restore typed GenerationUsage.from_messages signature
huangjeff5 Nov 16, 2026
fd66387
fix(py): keep McpServerEntry exported for mcp_servers built in a vari…
huangjeff5 Nov 16, 2026
756770e
fix(py): let flows and tools with a defaulted input run with no input
huangjeff5 Nov 16, 2026
2d3806a
fix(py): make action input contravariant
huangjeff5 Nov 16, 2026
c31cc69
fix(py)!: tools treat an explicit None as a value, like flows
huangjeff5 Nov 16, 2026
848b91d
fix(py)!: type defaulted flows and tools as DefaultedFlow / Defaulted…
huangjeff5 Nov 16, 2026
62ac92f
fix(py): type a defaulted input followed by a context
huangjeff5 Nov 16, 2026
fbcbdee
fix(py): add a catch-all handler overload and pin every shape in cont…
huangjeff5 Nov 16, 2026
d4f9c0c
fix(py): reject keyword-only handler params and drop the catch-all ov…
huangjeff5 Nov 16, 2026
54115f8
test(py): separate an omitted input from an explicit None in the shap…
huangjeff5 Nov 16, 2026
ec7d06d
fix(py): accept a ref picked between providers when no config is passed
huangjeff5 Nov 16, 2026
d784714
test(py): note the ty overload-order bug behind the define_prompt pin
huangjeff5 Nov 16, 2026
2ff7959
fix(py): type prompt on_chunk callbacks as ModelResponseChunk
huangjeff5 Nov 16, 2026
a96a08b
Merge remote-tracking branch 'origin/main' into HEAD
huangjeff5 Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions packages/genkit/src/genkit/_ai/_prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,7 @@ async def __call__(
resume_respond: Part | list[Part] | None = None,
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.

) -> ModelResponse[OutputT]:
"""Render the prompt with ``input`` as template variables, run it, and return the response.

Expand Down Expand Up @@ -482,15 +482,17 @@ async def _run(
*,
input: InputT | dict[str, Any] | None,
opts: PromptGenerateOptions,
on_chunk: Callable[[ModelResponseChunk], Any] | None,
on_chunk: Callable[[ModelResponseChunk[OutputT]], Any] | None,
caller_stopped: asyncio.Event | None,
) -> ModelResponse[OutputT]:
async def run() -> ModelResponse:
prepared = await render_prompt(prompt=self, input=input, opts=opts)
return await generate_action(
prepared.scope,
prepared.options,
on_chunk=on_chunk,
# generate_action isn't generic in the output type; it parses chunk
# output with this prompt's schema, so chunks are ModelResponseChunk[OutputT].
on_chunk=cast('Callable[[ModelResponseChunk], None] | None', on_chunk),
# Same context the template already rendered, so {{@auth}} and tools agree.
context=prepared.context,
caller_stopped=caller_stopped,
Expand Down Expand Up @@ -562,7 +564,7 @@ async def run(
return await self._run(
input=input,
opts=opts,
on_chunk=lambda c: send_chunk(cast('ModelResponseChunk[OutputT]', c)),
on_chunk=send_chunk,
caller_stopped=caller_stopped,
)

Expand Down
103 changes: 103 additions & 0 deletions packages/genkit/tests/typecheck/prompt_on_chunk_contract_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0

# pyright: reportUnnecessaryTypeIgnoreComment=true

"""Type-checker contract for ``Prompt.__call__(on_chunk=...)``.

The callback receives ``ModelResponseChunk[OutputT]``: ``.text`` reads with no
cast, a prompt with a typed ``output_schema`` types the chunk's output, a
callback that takes ``object`` still fits, and one that takes an unrelated
type is rejected.
"""

import pytest
from pydantic import BaseModel
from typing_extensions import assert_type

from genkit import Genkit, Message, ModelResponse, ModelResponseChunk, Part, Role
from genkit.model import ModelContext, ModelRequest


class Dish(BaseModel):
name: str


def _app() -> Genkit:
ai = Genkit()

async def line_cook(req: ModelRequest, ctx: ModelContext) -> ModelResponse:
del req
ctx.send_chunk(ModelResponseChunk(content=[Part.from_text('{"name": ')]))
ctx.send_chunk(ModelResponseChunk(content=[Part.from_text('"tartine"}')]))
return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('{"name": "tartine"}')]))

ai.define_model(name='bistro/line-cook', fn=line_cook)
return ai


@pytest.mark.asyncio
async def test_on_chunk_reads_text_without_a_cast() -> None:
"""``on_chunk=lambda c: ...`` sees a ModelResponseChunk, so ``.text`` type-checks."""
ai = _app()
special = ai.define_prompt(name='special', model='bistro/line-cook', prompt="Today's special?")
seen: list[str] = []

await special(on_chunk=lambda c: seen.append(c.text))

assert seen == ['{"name": ', '"tartine"}']


@pytest.mark.asyncio
async def test_on_chunk_is_typed_by_the_output_schema() -> None:
"""A prompt with ``output_schema=Dish`` hands the callback ``ModelResponseChunk[Dish]``."""
ai = _app()
plate = ai.define_prompt(name='plate', model='bistro/line-cook', prompt='Plate it.', output_schema=Dish)
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.

chunks.append(chunk)

await plate(on_chunk=on_dish)

assert len(chunks) == 2
assert all(isinstance(c, ModelResponseChunk) for c in chunks)


@pytest.mark.asyncio
async def test_object_callbacks_still_fit_and_unrelated_ones_do_not() -> None:
"""A callback taking ``object`` still fits; one taking an unrelated type doesn't."""
ai = _app()
special = ai.define_prompt(name='special', model='bistro/line-cook', prompt="Today's special?")
received: list[object] = []

# 1. Callable params are contravariant: object accepts every chunk
def log_anything(chunk: object) -> None:
received.append(chunk)

await special(on_chunk=log_anything)
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.

await special(on_chunk=received.append)

# 3. A callback for some other type doesn't
def count_covers(covers: int) -> None:
del covers

await special(on_chunk=count_covers) # pyright: ignore[reportArgumentType] # pyrefly: ignore[bad-argument-type] # ty: ignore[invalid-argument-type]
Loading