From 1caceff6c4e1f2f5e538eef0beb7c010e1ad06ae Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 12 Nov 2026 00:36:10 -0600 Subject: [PATCH 01/20] fix(py): export missing public types, require input on typed actions, and pin ref configs --- .../genkit-mcp/src/genkit_mcp/__init__.py | 3 +- packages/genkit-mcp/tests/mcp_exports_test.py | 2 +- packages/genkit/src/genkit/_ai/_aio.py | 45 ++-- packages/genkit/src/genkit/_ai/_decorators.py | 5 +- packages/genkit/src/genkit/_ai/_embedding.py | 6 +- packages/genkit/src/genkit/_ai/_model.py | 13 +- packages/genkit/src/genkit/_ai/_prompt.py | 9 +- packages/genkit/src/genkit/_ai/_tools.py | 6 +- packages/genkit/src/genkit/_core/_action.py | 72 ++++++- .../genkit/src/genkit/_core/_background.py | 4 +- packages/genkit/src/genkit/_core/_flow.py | 9 - packages/genkit/src/genkit/_core/_model.py | 32 ++- packages/genkit/src/genkit/_core/_registry.py | 7 + packages/genkit/src/genkit/_core/_tool.py | 93 ++++++++- packages/genkit/src/genkit/_core/_typing.py | 14 +- packages/genkit/src/genkit/model/__init__.py | 2 + .../genkit/src/genkit/plugin_api/__init__.py | 3 +- .../genkit/tests/genkit/ai/embedding_test.py | 33 +++ .../genkit/tests/genkit/ai/model_ref_test.py | 9 +- .../genkit/ai/tool_response_contract_test.py | 6 +- .../tests/genkit/ai/tool_signature_test.py | 2 +- .../genkit/core/action_run_signature_test.py | 8 +- .../genkit/tests/genkit/core/action_test.py | 4 +- .../genkit/core/public_types_runtime_test.py | 107 ++++++++++ .../typecheck/action_and_ref_contract_test.py | 192 ++++++++++++++++++ .../output_narrowing_contract_test.py | 151 ++++++++++++++ .../typecheck/prompt_input_contract_test.py | 66 ++++++ scripts/schema_to_typing.py | 20 +- 28 files changed, 818 insertions(+), 105 deletions(-) create mode 100644 packages/genkit/tests/genkit/core/public_types_runtime_test.py create mode 100644 packages/genkit/tests/typecheck/action_and_ref_contract_test.py create mode 100644 packages/genkit/tests/typecheck/output_narrowing_contract_test.py create mode 100644 packages/genkit/tests/typecheck/prompt_input_contract_test.py diff --git a/packages/genkit-mcp/src/genkit_mcp/__init__.py b/packages/genkit-mcp/src/genkit_mcp/__init__.py index 23ff50d55..3560a5479 100644 --- a/packages/genkit-mcp/src/genkit_mcp/__init__.py +++ b/packages/genkit-mcp/src/genkit_mcp/__init__.py @@ -20,6 +20,7 @@ """ from genkit_mcp._client import McpClient, define_mcp_client +from genkit_mcp._config import McpServerEntry from genkit_mcp._host import McpHost, define_mcp_host -__all__ = ['McpClient', 'McpHost', 'define_mcp_client', 'define_mcp_host'] +__all__ = ['McpClient', 'McpHost', 'McpServerEntry', 'define_mcp_client', 'define_mcp_host'] diff --git a/packages/genkit-mcp/tests/mcp_exports_test.py b/packages/genkit-mcp/tests/mcp_exports_test.py index 9d758e5be..c665a7579 100644 --- a/packages/genkit-mcp/tests/mcp_exports_test.py +++ b/packages/genkit-mcp/tests/mcp_exports_test.py @@ -20,6 +20,6 @@ def test_the_package_exports_exactly_its_public_surface() -> None: - assert genkit_mcp.__all__ == ['McpClient', 'McpHost', 'define_mcp_client', 'define_mcp_host'] + assert genkit_mcp.__all__ == ['McpClient', 'McpHost', 'McpServerEntry', 'define_mcp_client', 'define_mcp_host'] for name in genkit_mcp.__all__: assert getattr(genkit_mcp, name) is not None diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 0a64b5aff..b34da9d35 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -103,7 +103,6 @@ EmbedRequest, ModelConfigDict, ModelRef, - ModelRefConfigT, ModelRequest, Part, ToolChoice, @@ -139,6 +138,7 @@ InputT = TypeVar('InputT') OutputT = TypeVar('OutputT') ChunkT = TypeVar('ChunkT') +ModelRefConfigT = TypeVar('ModelRefConfigT', bound=BaseModel) R = TypeVar('R') T = TypeVar('T') @@ -358,13 +358,6 @@ def flow( /, ) -> Flow[None, OutputT]: ... - @overload - def flow( - self, - func: Callable[..., Awaitable[OutputT]], - /, - ) -> Flow[Any, OutputT, Any]: ... - def flow( self, name: str | Callable[..., Awaitable[Any]] | None = None, @@ -516,7 +509,7 @@ def tool( self, func: Callable[[ToolContext[ChunkT]], Awaitable[OutputT]], /, - ) -> Tool[Any, OutputT, ChunkT]: ... + ) -> Tool[None, OutputT, ChunkT]: ... @overload def tool( @@ -988,7 +981,7 @@ def define_prompt( name: str | None = None, *, variant: str | None = None, - model: str | ModelRef[BaseModel] | Action | None = None, + model: str | ModelRef[Any] | Action | None = None, config: Mapping[str, Any] | BaseModel | ModelConfigDict | None = None, description: str | None = None, system: str | list[Part] | None = None, @@ -1440,7 +1433,7 @@ def _resolve_embedder_name(self, embedder: str | EmbedderRef | None) -> str: async def _embedder_and_options( self, *, - embedder: str | EmbedderRef[BaseModel] | None, + embedder: str | EmbedderRef[Any] | None, config: object, ) -> tuple[Action[EmbedRequest, EmbedResponse, Never], dict[str, Any]]: """Resolve the embedder, check the call config, and layer the options. @@ -1459,10 +1452,11 @@ async def _embedder_and_options( reason=ErrorReason.ACTION_NOT_FOUND, ) ref = embedder if isinstance(embedder, EmbedderRef) else None + ref_schema = cast('type[BaseModel] | None', ref.config_schema) if ref else None schema = call_config_class( name=name, kind='embedder', - ref_schema=ref.config_schema if ref else None, + ref_schema=ref_schema, action_schema=python_config_schema(action.config_schema), ) check_call_config(config=config, schema=schema, model=name) @@ -1546,7 +1540,7 @@ async def generate( config: ModelConfigDict, max_turns: int | None = None, context: dict[str, object] | None = None, - output_schema: type | dict | None = None, + output_schema: type[Any] | dict[str, Any] | str | None = None, output_format: str | None = None, output_content_type: str | None = None, output_instructions: bool | str | None = None, @@ -1573,7 +1567,7 @@ async def generate( config: ModelRefConfigT | Mapping[str, Any] | None = None, max_turns: int | None = None, context: dict[str, object] | None = None, - output_schema: type | dict | None = None, + output_schema: type[Any] | dict[str, Any] | str | None = None, output_format: str | None = None, output_content_type: str | None = None, output_instructions: bool | str | None = None, @@ -1585,7 +1579,7 @@ async def generate( async def generate( self, *, - model: str | ModelRef[BaseModel] | Action | None = None, + model: str | ModelRef[Any] | Action | None = None, prompt: str | list[Part] | None = None, system: str | list[Part] | None = None, messages: list[Message] | None = None, @@ -1598,7 +1592,7 @@ async def generate( config: BaseModel | ModelConfigDict | Mapping[str, Any] | None = None, max_turns: int | None = None, context: dict[str, object] | None = None, - output_schema: type | dict | None = None, + output_schema: type[Any] | dict[str, Any] | str | None = None, output_format: str | None = None, output_content_type: str | None = None, output_instructions: bool | str | None = None, @@ -1742,7 +1736,7 @@ def generate_stream( config: ModelConfigDict, max_turns: int | None = None, context: dict[str, object] | None = None, - output_schema: type | dict | None = None, + output_schema: type[Any] | dict[str, Any] | str | None = None, output_format: str | None = None, output_content_type: str | None = None, output_instructions: bool | str | None = None, @@ -1769,7 +1763,7 @@ def generate_stream( config: ModelRefConfigT | Mapping[str, Any] | None = None, max_turns: int | None = None, context: dict[str, object] | None = None, - output_schema: type | dict | None = None, + output_schema: type[Any] | dict[str, Any] | str | None = None, output_format: str | None = None, output_content_type: str | None = None, output_instructions: bool | str | None = None, @@ -1781,7 +1775,7 @@ def generate_stream( def generate_stream( self, *, - model: str | ModelRef[BaseModel] | Action | None = None, + model: str | ModelRef[Any] | Action | None = None, prompt: str | list[Part] | None = None, system: str | list[Part] | None = None, messages: list[Message] | None = None, @@ -1794,7 +1788,7 @@ def generate_stream( config: BaseModel | ModelConfigDict | Mapping[str, Any] | None = None, max_turns: int | None = None, context: dict[str, object] | None = None, - output_schema: type | dict | None = None, + output_schema: type[Any] | dict[str, Any] | str | None = None, output_format: str | None = None, output_content_type: str | None = None, output_instructions: bool | str | None = None, @@ -1882,7 +1876,7 @@ async def _run_generate( async def _generate( self, *, - model: str | ModelRef[BaseModel] | Action | None = None, + model: str | ModelRef[Any] | Action | None = None, prompt: str | list[Part] | None = None, system: str | list[Part] | None = None, messages: list[Message] | None = None, @@ -1895,7 +1889,7 @@ async def _generate( config: BaseModel | ModelConfigDict | Mapping[str, Any] | None = None, max_turns: int | None = None, context: dict[str, object] | None = None, - output_schema: type | dict | None = None, + output_schema: type[Any] | dict[str, Any] | str | None = None, output_format: str | None = None, output_content_type: str | None = None, output_instructions: bool | str | None = None, @@ -2019,15 +2013,20 @@ async def embed_many( self, *, embedder: str | EmbedderRef[EmbedderRefConfigT], - content: list[str] | list[Document], + content: Sequence[str | Document], metadata: dict[str, object] | None = None, config: EmbedderRefConfigT | Mapping[str, Any] | None = None, context: dict[str, Any] | None = None, ) -> list[Embedding]: """Generate vector embeddings for multiple documents in a single batch call. + ``content`` is any sequence (list, tuple, ...) of strings or + ``Document``s; one embedding comes back per item, in order. A bare + ``str`` raises ``TypeError``; use ``embed`` for one item. ``config``, ``metadata`` and ``context`` work the same as on ``embed``. """ + if isinstance(content, str): + raise TypeError('embed_many() takes a sequence of strings or Documents, not a str; use embed() for one.') if metadata is not None and any(isinstance(item, Document) for item in content): raise TypeError(_DOCUMENT_METADATA_CONFLICT) diff --git a/packages/genkit/src/genkit/_ai/_decorators.py b/packages/genkit/src/genkit/_ai/_decorators.py index 2c87be6cb..d16399632 100644 --- a/packages/genkit/src/genkit/_ai/_decorators.py +++ b/packages/genkit/src/genkit/_ai/_decorators.py @@ -82,9 +82,6 @@ def __call__(self, func: Callable[[InputT], Awaitable[OutputT]]) -> Flow[InputT, @overload def __call__(self, func: Callable[[], Awaitable[OutputT]]) -> Flow[None, OutputT]: ... - @overload - def __call__(self, func: Callable[..., Awaitable[OutputT]]) -> Flow[Any, OutputT, Any]: ... - def __call__(self, func: Callable[..., Awaitable[Any]]) -> Flow[Any, Any, Any]: return define_flow(self._registry, func, self._name, self._description) @@ -125,7 +122,7 @@ def __call__( def __call__(self, func: Callable[[object], Awaitable[OutputT]]) -> Tool[Any, OutputT]: ... @overload - def __call__(self, func: Callable[[ToolContext[ChunkT]], Awaitable[OutputT]]) -> Tool[Any, OutputT, ChunkT]: ... + def __call__(self, func: Callable[[ToolContext[ChunkT]], Awaitable[OutputT]]) -> Tool[None, OutputT, ChunkT]: ... @overload def __call__(self, func: Callable[[InputT], Awaitable[OutputT]]) -> Tool[InputT, OutputT]: ... diff --git a/packages/genkit/src/genkit/_ai/_embedding.py b/packages/genkit/src/genkit/_ai/_embedding.py index b3214f678..67f41c188 100644 --- a/packages/genkit/src/genkit/_ai/_embedding.py +++ b/packages/genkit/src/genkit/_ai/_embedding.py @@ -51,8 +51,10 @@ class EmbedderInfo(BaseModel): dimensions: int | None = None -# Covariant so EmbedderRef[CrmEmbedConfig] is assignable to EmbedderRef[BaseModel]. -EmbedderRefConfigT = TypeVar('EmbedderRefConfigT', bound=BaseModel, covariant=True, default=BaseModel) +# Invariant for the same reason as ModelRefConfigT: embed(embedder=EmbedderRef[T], +# config=T) must not widen T to BaseModel. Defaults to Any so a bare +# EmbedderRef annotation still accepts any typed ref. +EmbedderRefConfigT = TypeVar('EmbedderRefConfigT', bound=BaseModel, default=Any) @dataclass(frozen=True, kw_only=True) diff --git a/packages/genkit/src/genkit/_ai/_model.py b/packages/genkit/src/genkit/_ai/_model.py index 1d12d8388..9cb4c19f2 100644 --- a/packages/genkit/src/genkit/_ai/_model.py +++ b/packages/genkit/src/genkit/_ai/_model.py @@ -71,13 +71,18 @@ # Type alias for model functions (must be async) # Use ctx.send_chunk() for streaming ModelFn = Callable[[ModelRequest, ModelContext], Awaitable[ModelResponse[Any]]] +"""Signature of the function passed to ``define_model``. + +An async function taking the ``ModelRequest`` and a ``ModelContext``; stream +with ``ctx.send_chunk(...)`` and return the final ``ModelResponse``. +""" logger = get_logger(__name__) # Veneer-facing argument shapes. Internals resolve these into ResolvedModel. # ModelArg is also the constructor default, stored as a registry value the # Dev UI lists as JSON, so it stays a name or ModelRef. -ModelArg: TypeAlias = str | ModelRef[BaseModel] +ModelArg: TypeAlias = str | ModelRef[Any] @dataclass(frozen=True, kw_only=True) @@ -101,10 +106,10 @@ def annotated_config_class(action: object | None) -> type[BaseModel] | None: return declared_config_type(input_class) if isinstance(input_class, type) else None -def _name_or_ref(model: object) -> str | ModelRef[BaseModel] | None: +def _name_or_ref(model: object) -> str | ModelRef[Any] | None: """Unwrap a name or ModelRef. Other values stay None.""" if isinstance(model, ModelRef): - return cast(ModelRef[BaseModel], model) + return model if isinstance(model, str) and model: return model return None @@ -157,7 +162,7 @@ def resolve_model_arg( model: object | None, registry: Registry, message: str = 'No model configured.', -) -> str | ModelRef[BaseModel]: +) -> str | ModelRef[Any]: """Return the explicit model or the registry default (name or ModelRef). An empty string is treated as omitted so ``model=os.getenv('MODEL')`` diff --git a/packages/genkit/src/genkit/_ai/_prompt.py b/packages/genkit/src/genkit/_ai/_prompt.py index 0cd9da8a1..1dbe2e9f6 100644 --- a/packages/genkit/src/genkit/_ai/_prompt.py +++ b/packages/genkit/src/genkit/_ai/_prompt.py @@ -66,7 +66,6 @@ from genkit._core._action import ( Action, ActionKind, - StreamingCallback, StreamResponse, create_action_key, get_current_context, @@ -95,8 +94,6 @@ Role, ) -ModelStreamingCallback = StreamingCallback - logger = get_logger(__name__) # TypeVars for generic input/output typing @@ -283,7 +280,7 @@ def __init__( metadata: dict[str, Any] | None = None, tools: Sequence[str | Tool] | None = None, tool_choice: ToolChoice | None = None, - use: Sequence[Middleware | MiddlewareRef] | None = None, + use: Sequence[Middleware] | None = None, docs: list[Document] | None = None, name: str | None = None, ns: str | None = None, @@ -434,7 +431,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: ModelStreamingCallback | None = None, + on_chunk: Callable[[ModelResponseChunk], Any] | None = None, ) -> ModelResponse[OutputT]: """Render the prompt with ``input`` as template variables, run it, and return the response. @@ -464,7 +461,7 @@ async def _run( *, input: InputT | dict[str, Any] | None, opts: PromptGenerateOptions, - on_chunk: ModelStreamingCallback | None, + on_chunk: Callable[[ModelResponseChunk], Any] | None, caller_stopped: asyncio.Event | None, ) -> ModelResponse[OutputT]: async def run() -> ModelResponse: diff --git a/packages/genkit/src/genkit/_ai/_tools.py b/packages/genkit/src/genkit/_ai/_tools.py index de02596b0..71556042c 100644 --- a/packages/genkit/src/genkit/_ai/_tools.py +++ b/packages/genkit/src/genkit/_ai/_tools.py @@ -284,8 +284,8 @@ def _define_tool( # shapes come first and catch them; a real ``ToolContext`` param can't take # an ``object``, so it skips them. # - The context-only shape comes before input-only because a ``ctx`` function -# also fits ``[InputT]``. It still returns ``Tool[Any, ...]`` so that shape -# keeps accepting an input. +# also fits ``[InputT]``. It returns ``Tool[None, ...]``, like a context-only +# flow: the function takes no input, so a direct call passes none. # - ty types ``(ctx, x: Any)`` as Unknown: the typing spec's overload rule for # Any arguments makes it ambiguous, and no order fixes that. @overload @@ -340,7 +340,7 @@ def define_tool( description: str | None = None, *, input_schema: type[BaseModel] | dict[str, object] | None = None, -) -> _Tool[Any, ToolOutputT, ToolChunkT]: ... +) -> _Tool[None, ToolOutputT, ToolChunkT]: ... @overload diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index 5c77db936..3d4ac7379 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -16,6 +16,8 @@ """Action module for defining and managing remotely callable functions.""" +from __future__ import annotations + import asyncio import functools import inspect @@ -37,6 +39,7 @@ get_args, get_origin, get_type_hints, + overload, ) from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError @@ -371,7 +374,7 @@ def call( self, fn: Callable[..., _CallT], input: object, # noqa: A002 - ctx: 'ActionRunContext', + ctx: ActionRunContext, ) -> _CallT: """Call ``fn`` with ``input`` and ``ctx`` passed by parameter name. @@ -1161,12 +1164,55 @@ def _override_input_schema( else: self._input_type = cast(TypeAdapter[InputT], TypeAdapter(input_schema)) - async def __call__(self, input: InputT | None = NO_INPUT, *, context: dict[str, Any] | None = None) -> OutputT: + @overload + async def __call__( + self: Action[None, OutputT, ChunkT, InitT], + input: None = None, + *, + context: dict[str, Any] | None = None, + ) -> OutputT: ... + + @overload + async def __call__( + self, + input: InputT, + *, + context: dict[str, Any] | None = None, + ) -> OutputT: ... + + async def __call__( + self: Action[Any, OutputT, ChunkT, InitT], + input: InputT | None = NO_INPUT, + *, + context: dict[str, Any] | None = None, + ) -> OutputT: """Call the action directly, returning just the response value.""" - return (await self.run(input, context=context)).response + return (await self._run(input, context=context)).response + + @overload + async def run( + self: Action[None, OutputT, ChunkT, InitT], + input: None = None, + *, + on_chunk: Callable[[ChunkT], None] | None = None, + context: dict[str, Any] | None = None, + telemetry_labels: dict[str, object] | None = None, + init: InitT | None = None, + ) -> ActionResponse[OutputT]: ... + @overload async def run( self, + input: InputT, + *, + on_chunk: Callable[[ChunkT], None] | None = None, + context: dict[str, Any] | None = None, + telemetry_labels: dict[str, object] | None = None, + init: InitT | None = None, + ) -> ActionResponse[OutputT]: ... + + async def run( + self: Action[Any, OutputT, ChunkT, InitT], input: InputT | None = NO_INPUT, *, on_chunk: Callable[[ChunkT], None] | None = None, @@ -1262,8 +1308,28 @@ async def _run( if token is not None: _action_context.reset(token) + @overload + def stream( + self: Action[None, OutputT, ChunkT, InitT], + input: None = None, + *, + context: dict[str, Any] | None = None, + telemetry_labels: dict[str, object] | None = None, + init: InitT | None = None, + ) -> StreamResponse[ChunkT, OutputT]: ... + + @overload def stream( self, + input: InputT, + *, + context: dict[str, Any] | None = None, + telemetry_labels: dict[str, object] | None = None, + init: InitT | None = None, + ) -> StreamResponse[ChunkT, OutputT]: ... + + def stream( + self: Action[Any, OutputT, ChunkT, InitT], input: InputT | None = NO_INPUT, *, context: dict[str, Any] | None = None, diff --git a/packages/genkit/src/genkit/_core/_background.py b/packages/genkit/src/genkit/_core/_background.py index 3bc1e0970..5f5be8b6a 100644 --- a/packages/genkit/src/genkit/_core/_background.py +++ b/packages/genkit/src/genkit/_core/_background.py @@ -252,10 +252,10 @@ def __init__( self, name: str, start: StartOpFn[InT], - check: CheckOpFn[OutT], + check: Callable[[Operation[OutT], FlowContext], Awaitable[Operation]], *, kind: ActionKind, - cancel: CancelOpFn[OutT] | None = None, + cancel: Callable[[Operation[OutT], FlowContext], Awaitable[Operation]] | None = None, metadata: dict[str, Any] | None = None, description: str | None = None, ) -> None: diff --git a/packages/genkit/src/genkit/_core/_flow.py b/packages/genkit/src/genkit/_core/_flow.py index 882bc6135..7d6dfd9e3 100644 --- a/packages/genkit/src/genkit/_core/_flow.py +++ b/packages/genkit/src/genkit/_core/_flow.py @@ -103,15 +103,6 @@ def __init__( description: str | None = None, ) -> None: ... - @overload - def __init__( - self, - func: Callable[..., Awaitable[OutputT]], - *, - name: str | None = None, - description: str | None = None, - ) -> None: ... - def __init__( self, func: Callable[..., Awaitable[Any]], diff --git a/packages/genkit/src/genkit/_core/_model.py b/packages/genkit/src/genkit/_core/_model.py index 2001cdf67..f077ad22e 100644 --- a/packages/genkit/src/genkit/_core/_model.py +++ b/packages/genkit/src/genkit/_core/_model.py @@ -312,8 +312,10 @@ def reject_config_api_key(config: object) -> None: OutputT = TypeVar('OutputT', default=object) ConfigT = TypeVar('ConfigT', bound=ModelConfig, default=ModelConfig) # Bound to BaseModel so ModelRef is always parameterized with a concrete Pydantic config schema. -# Covariant so ModelRef[GeminiConfig] is assignable to ModelRef[BaseModel] or ModelRef[Any]. -ModelRefConfigT = TypeVar('ModelRefConfigT', bound=BaseModel, covariant=True) +# Invariant: generate(model=ModelRef[T], config=T) solves T from the ref. A +# covariant T let checkers widen ModelRef[GeminiConfig] to ModelRef[BaseModel] +# and accept any config class. Defaults to Any so bare ModelRef means ModelRef[Any]. +ModelRefConfigT = TypeVar('ModelRefConfigT', bound=BaseModel, default=Any) # ModelRequest[X], EmbedRequest[X] and the evaluator requests take a pydantic # model class; __class_getitem__ rejects the rest. Not bound to BaseModel: type # checkers would then reject the common bare ModelRequest(config={...}), where @@ -1803,6 +1805,11 @@ class ModelResponseChunk(GenkitModel, Generic[OutputT]): _previous_chunks: list[Any] = PrivateAttr(default_factory=list) _chunk_parser: Callable[..., object] | None = PrivateAttr(default=None) _schema_type: type[BaseModel] | None = PrivateAttr(default=None) + # .output is parsed once per chunk. A plain @property over a private cache + # rather than @cached_property: ty loses OutputT through cached_property on + # a generic model and types every chunk.output as None. + _output_parsed: bool = PrivateAttr(default=False) + _output_cache: Any = PrivateAttr(default=None) @field_validator('content', mode='before') @classmethod @@ -1847,7 +1854,7 @@ def tool_responses(self) -> list[Part]: """All tool response parts in this chunk.""" return [p for p in self.content if p.tool_response is not None] - @cached_property + @property def output(self) -> OutputT | None: """The reply so far, parsed as far as it goes. Never raises. @@ -1875,6 +1882,12 @@ def output(self) -> OutputT | None: or scalar). It's ``None`` before an object starts or while the text can't be parsed. """ + if not self._output_parsed: + self._output_cache = self._parse_output() + self._output_parsed = True + return cast('OutputT | None', self._output_cache) + + def _parse_output(self) -> object: if self.role is not None and self.role != Role.MODEL: return None try: @@ -1885,15 +1898,12 @@ def output(self) -> OutputT | None: and isinstance(parsed, dict) and not issubclass(self._schema_type, RootModel) ): - return cast( - 'OutputT | None', - construct_partial( - schema_type=self._schema_type, - data=parsed, - closed=is_complete_json(text), - ), + return construct_partial( + schema_type=self._schema_type, + data=parsed, + closed=is_complete_json(text), ) - return cast('OutputT | None', parsed) + return parsed except Exception: # one odd chunk shouldn't end a stream whose final reply may still parse. logger.debug('chunk.output could not be parsed; returning None', exc_info=True) diff --git a/packages/genkit/src/genkit/_core/_registry.py b/packages/genkit/src/genkit/_core/_registry.py index 439df8af6..99631c2f9 100644 --- a/packages/genkit/src/genkit/_core/_registry.py +++ b/packages/genkit/src/genkit/_core/_registry.py @@ -28,6 +28,7 @@ from pydantic import BaseModel from typing_extensions import Never, TypeVar +from genkit._core import _background from genkit._core._action import ( GENKIT_DYNAMIC_ACTION_PROVIDER_ATTR, Action, @@ -950,3 +951,9 @@ async def dap_action(input: DapMetadata) -> DapMetadata: # DynamicActionProvider stamps itself on ``action``. return DynamicActionProvider(action, fn, cache_ttl_millis) + + +# _background imports Registry only for type checking (this module imports it at +# runtime). Bind the name there so typing.get_type_hints() can resolve +# BackgroundAction.lookup's `registry: Registry` (FastAPI/Pydantic introspection). +_background.Registry = Registry diff --git a/packages/genkit/src/genkit/_core/_tool.py b/packages/genkit/src/genkit/_core/_tool.py index c65749d1f..d916d1790 100644 --- a/packages/genkit/src/genkit/_core/_tool.py +++ b/packages/genkit/src/genkit/_core/_tool.py @@ -26,7 +26,7 @@ from typing import Any, Union, cast, get_args, get_origin, overload from pydantic import BaseModel, TypeAdapter -from typing_extensions import TypeVar +from typing_extensions import Self, TypeVar from genkit._core._action import ( Action, @@ -348,6 +348,90 @@ class Tool(Action[InputT, OutputT, ChunkT, None]): # One overload per handler shape, same as ``ai.tool`` / ``define_tool``, so # ``Tool(place_order)`` infers ``Tool[Order, Receipt, Step]`` from the function. + # ty reads the ``__new__`` overloads; pyright, mypy and pyrefly read the + # self-typed ``__init__`` overloads. Keep the two lists in step. + @overload + def __new__( + cls, + func: Callable[[ToolContext[_C], object], Awaitable[_O]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> Tool[Any, _O, _C]: ... + + @overload + def __new__( + cls, + func: Callable[[_I, ToolContext[_C]], Awaitable[_O]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> Tool[_I, _O, _C]: ... + + @overload + def __new__( + cls, + func: Callable[[ToolContext[_C], _I], Awaitable[_O]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> Tool[_I, _O, _C]: ... + + @overload + def __new__( + cls, + func: Callable[[object], Awaitable[_O]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> Tool[Any, _O, Any]: ... + + @overload + def __new__( + cls, + func: Callable[[ToolContext[_C]], Awaitable[_O]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> Tool[None, _O, _C]: ... + + @overload + def __new__( + cls, + func: Callable[[_I], Awaitable[_O]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> Tool[_I, _O, Any]: ... + + @overload + def __new__( + cls, + func: Callable[[], Awaitable[_O]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> Tool[None, _O, Any]: ... + + def __new__( + cls, + func: Callable[..., Awaitable[Any]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> Tool[Any, Any, Any]: + """Allocate the tool; ``__init__`` does the work.""" + del func, name, description, input_schema + return super().__new__(cls) + @overload def __init__( self: Tool[Any, _O, _C], @@ -390,7 +474,7 @@ def __init__( @overload def __init__( - self: Tool[Any, _O, _C], + self: Tool[None, _O, _C], func: Callable[[ToolContext[_C]], Awaitable[_O]], *, name: str | None = None, @@ -555,6 +639,11 @@ async def _invoke(self, input: object | None, ctx: ActionRunContext) -> OutputT: class _ActionTool(Tool[InputT, OutputT, ChunkT]): """A ``Tool`` view over a plain ``Action`` with no ``tool.v2`` companion.""" + def __new__(cls, action: Action[InputT, OutputT, ChunkT, Any]) -> Self: + """Allocate the view; skips ``Tool.__new__``'s function overloads.""" + del action + return object.__new__(cls) + def __init__(self, action: Action[InputT, OutputT, ChunkT, Any]) -> None: self._wire_action = None Action.__init__( diff --git a/packages/genkit/src/genkit/_core/_typing.py b/packages/genkit/src/genkit/_core/_typing.py index ebf4f3d84..c8b276753 100644 --- a/packages/genkit/src/genkit/_core/_typing.py +++ b/packages/genkit/src/genkit/_core/_typing.py @@ -20,7 +20,8 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, ClassVar, Literal +from collections.abc import Sequence # noqa: TC003 - get_type_hints(GenerationUsage.from_messages) needs it +from typing import Any, ClassVar, Literal from pydantic import ConfigDict, Field, RootModel from pydantic.alias_generators import to_camel @@ -28,11 +29,6 @@ from genkit._core._base import GenkitConfig, GenkitModel from genkit._core._compat import StrEnum -if TYPE_CHECKING: - from collections.abc import Sequence - - from genkit._core import _model - class AgentFinishReason(StrEnum): """AgentFinishReason data type class.""" @@ -485,11 +481,11 @@ class GenerationUsage(GenkitModel): cache_write_tokens: float | None = None @classmethod - def from_messages(cls, messages: Sequence[_model.Message], response: _model.Message) -> GenerationUsage: + def from_messages(cls, messages: Sequence[object], response: object) -> GenerationUsage: """Character and media counts for the request messages and the model reply.""" - from genkit._core._model import count_message_usage # noqa: PLC0415 - _model imports this module + from genkit._core._model import as_message, count_message_usage # noqa: PLC0415 - _model imports this module - return cls.model_validate(count_message_usage(messages, response)) + return cls.model_validate(count_message_usage([as_message(m) for m in messages], as_message(response))) class MediaPart(GenkitModel): diff --git a/packages/genkit/src/genkit/model/__init__.py b/packages/genkit/src/genkit/model/__init__.py index 72046a9e4..003a952a5 100644 --- a/packages/genkit/src/genkit/model/__init__.py +++ b/packages/genkit/src/genkit/model/__init__.py @@ -19,6 +19,7 @@ from genkit._ai._background_model import BackgroundModel from genkit._ai._model import ( Model, + ModelFn, ) from genkit._core._action import ModelContext from genkit._core._model import ( @@ -42,6 +43,7 @@ __all__ = [ # Models, request and context types 'Model', + 'ModelFn', 'BackgroundModel', 'GenerateActionOptions', 'ModelContext', diff --git a/packages/genkit/src/genkit/plugin_api/__init__.py b/packages/genkit/src/genkit/plugin_api/__init__.py index 5e7fea6d9..48fb8a137 100644 --- a/packages/genkit/src/genkit/plugin_api/__init__.py +++ b/packages/genkit/src/genkit/plugin_api/__init__.py @@ -17,7 +17,7 @@ """Framework primitives for plugin authors.""" # Base class and framework primitives -from genkit._core._action import Action, ActionKind +from genkit._core._action import Action, ActionKind, ActionResponse from genkit._core._background import BackgroundAction from genkit._core._base import GenkitConfig from genkit._core._compat import StrEnum @@ -34,6 +34,7 @@ 'Plugin', 'GenkitConfig', 'Action', + 'ActionResponse', 'BackgroundAction', 'ActionKind', 'DynamicActionProvider', diff --git a/packages/genkit/tests/genkit/ai/embedding_test.py b/packages/genkit/tests/genkit/ai/embedding_test.py index 5bd1c2e2a..d32a5f04c 100644 --- a/packages/genkit/tests/genkit/ai/embedding_test.py +++ b/packages/genkit/tests/genkit/ai/embedding_test.py @@ -362,6 +362,39 @@ async def fake_embedder_fn(request: EmbedRequest) -> EmbedResponse: assert called_request.input == [Document.from_text('text1'), Document.from_text('text2')] +@pytest.mark.asyncio +async def test_embed_many_accepts_a_tuple_of_documents(mock_genkit_instance: tuple[Genkit, MockGenkitRegistry]) -> None: + """content takes any sequence; a tuple of Documents reaches the embedder in order.""" + genkit_instance, registry = mock_genkit_instance + + async def fake_embedder_fn(request: EmbedRequest) -> EmbedResponse: + return EmbedResponse(embeddings=[Embedding(embedding=[1.0]), Embedding(embedding=[2.0])]) + + registry.register_action( + name='menu-embedder', + kind='embedder', + fn=fake_embedder_fn, + metadata=Embedder('menu-embedder', fake_embedder_fn).metadata, + description='Embeds menu items', + ) + + menu = (Document.from_text('Smoked salmon'), Document.from_text('Tartine')) + response = await genkit_instance.embed_many(embedder='menu-embedder', content=menu) + + assert [e.embedding for e in response] == [[1.0], [2.0]] + embed_action = await registry.resolve_action('embedder', 'menu-embedder') + assert embed_action.run.call_args[0][0].input == list(menu) + + +@pytest.mark.asyncio +async def test_embed_many_rejects_a_bare_string(mock_genkit_instance: tuple[Genkit, MockGenkitRegistry]) -> None: + """A str is a Sequence[str] to the checker; embed_many raises instead of embedding each character.""" + genkit_instance, _ = mock_genkit_instance + + with pytest.raises(TypeError, match='use embed'): + await genkit_instance.embed_many(embedder='menu-embedder', content='Smoked salmon') + + @pytest.mark.asyncio async def test_embed_many_strings_with_metadata_attach_it_to_every_document( mock_genkit_instance: tuple[Genkit, MockGenkitRegistry], diff --git a/packages/genkit/tests/genkit/ai/model_ref_test.py b/packages/genkit/tests/genkit/ai/model_ref_test.py index 6698265f8..a2dc94d0a 100644 --- a/packages/genkit/tests/genkit/ai/model_ref_test.py +++ b/packages/genkit/tests/genkit/ai/model_ref_test.py @@ -6,6 +6,7 @@ """Unit tests for ModelRef.""" from dataclasses import FrozenInstanceError +from typing import Any import pytest from pydantic import BaseModel, ValidationError @@ -45,11 +46,11 @@ def test_model_ref_with_custom_pydantic_schema() -> None: assert ref.config.top_p == 0.9 -def test_typed_ref_assignable_to_model_ref_base_model() -> None: - """A ref built with a plugin config class is still usable as ModelRef[BaseModel].""" +def test_typed_ref_assignable_to_model_ref_any() -> None: + """A ref built with a plugin config class is still usable as ModelRef[Any].""" ref = ModelRef(name='echo', config_schema=CustomConfig) - as_base: ModelRef[BaseModel] = ref - assert as_base is ref + as_any: ModelRef[Any] = ref + assert as_any is ref def test_model_ref_with_bare_base_model_schema() -> None: diff --git a/packages/genkit/tests/genkit/ai/tool_response_contract_test.py b/packages/genkit/tests/genkit/ai/tool_response_contract_test.py index 1f84a8a06..026d65742 100644 --- a/packages/genkit/tests/genkit/ai/tool_response_contract_test.py +++ b/packages/genkit/tests/genkit/ai/tool_response_contract_test.py @@ -715,9 +715,9 @@ async def specials() -> str: # ty types `(ctx, x: Any)` as Unknown: it matches overloads with different # returns, and the typing spec's overload rule for Any makes that # ambiguous. No arrangement fixes it without breaking `(ctx: ToolContext)`. - assert_type(ai.tool(echo_any), Tool[Any, str]) + assert_type(ai.tool(echo_any), Tool[Any, str]) # ty: ignore[type-assertion-failure] assert_type(ai.tool(echo_object), Tool[Any, str]) - assert_type(ai.tool(whoami), Tool[Any, str]) + assert_type(ai.tool(whoami), Tool[Any, str]) # ty: ignore[type-assertion-failure] assert_type(ai.tool(ctx_then_any), Tool[Any, str]) # ty: ignore[type-assertion-failure] assert_type(ai.tool()(ctx_then_any), Tool[Any, str]) # ty: ignore[type-assertion-failure] assert_type(ai.tool()(echo_object), Tool[Any, str]) @@ -729,7 +729,7 @@ async def specials() -> str: # 2. define_tool. assert_type(define_tool(Registry(), ctx_then_any), Tool[Any, str]) # ty: ignore[type-assertion-failure] assert_type(define_tool(Registry(), echo_object), Tool[Any, str]) - assert_type(define_tool(Registry(), echo_any), Tool[Any, str]) + assert_type(define_tool(Registry(), echo_any), Tool[Any, str]) # ty: ignore[type-assertion-failure] # 3. Tool(fn). ty doesn't solve overloaded generic constructors yet (see # test_tool_constructor_infers_types_from_function). diff --git a/packages/genkit/tests/genkit/ai/tool_signature_test.py b/packages/genkit/tests/genkit/ai/tool_signature_test.py index 4ce321735..fcb09141b 100644 --- a/packages/genkit/tests/genkit/ai/tool_signature_test.py +++ b/packages/genkit/tests/genkit/ai/tool_signature_test.py @@ -575,7 +575,7 @@ async def forecast(f: Forecast) -> str: assert seen == [{'city': 'Paris', 'days': 3}] assert _tool_output(response) == '3 days in Paris' with pytest.raises(GenkitError) as exc: - await forecast({'city': 'Paris'}) # ty: ignore[missing-typed-dict-key] + await forecast({'city': 'Paris'}) assert exc.value.status == 'INVALID_ARGUMENT' diff --git a/packages/genkit/tests/genkit/core/action_run_signature_test.py b/packages/genkit/tests/genkit/core/action_run_signature_test.py index e1fc042ad..e70c78499 100644 --- a/packages/genkit/tests/genkit/core/action_run_signature_test.py +++ b/packages/genkit/tests/genkit/core/action_run_signature_test.py @@ -28,13 +28,13 @@ async def test_run_with_positional_on_chunk_raises_type_error() -> None: chunks: list[str] = [] with pytest.raises(TypeError, match='positional argument'): - await _kitchen().run('salmon', chunks.append) # pyright: ignore[reportCallIssue] # ty: ignore[too-many-positional-arguments] # pyrefly: ignore[bad-argument-count] + await _kitchen().run('salmon', chunks.append) # pyright: ignore[reportCallIssue] # pyrefly: ignore[bad-argument-count] def test_stream_with_positional_context_raises_type_error() -> None: """`stream(input, context)` raises TypeError; context is keyword-only.""" with pytest.raises(TypeError, match='positional argument'): - _kitchen().stream('salmon', {'table': 4}) # pyright: ignore[reportCallIssue] # ty: ignore[too-many-positional-arguments] # pyrefly: ignore[bad-argument-count] + _kitchen().stream('salmon', {'table': 4}) # pyright: ignore[reportCallIssue] # pyrefly: ignore[bad-argument-count] async def _table_echo(init: str, inputs: AsyncIterator[str], send_chunk: Callable[[str], None]) -> dict[str, Any]: @@ -71,7 +71,7 @@ async def test_run_rejects_public_abort_signal_kwarg() -> None: abort = asyncio.Event() with pytest.raises(TypeError, match='abort_signal'): - await _kitchen().run('salmon', abort_signal=abort) # pyright: ignore[reportCallIssue] # ty: ignore[unknown-argument] # pyrefly: ignore[unexpected-keyword] + await _kitchen().run('salmon', abort_signal=abort) # pyright: ignore[reportCallIssue] # pyrefly: ignore[unexpected-keyword] def test_stream_rejects_public_abort_signal_kwarg() -> None: @@ -79,7 +79,7 @@ def test_stream_rejects_public_abort_signal_kwarg() -> None: abort = asyncio.Event() with pytest.raises(TypeError, match='abort_signal'): - _kitchen().stream('salmon', abort_signal=abort) # pyright: ignore[reportCallIssue] # ty: ignore[unknown-argument] # pyrefly: ignore[unexpected-keyword] + _kitchen().stream('salmon', abort_signal=abort) # pyright: ignore[reportCallIssue] # pyrefly: ignore[unexpected-keyword] @pytest.mark.asyncio diff --git a/packages/genkit/tests/genkit/core/action_test.py b/packages/genkit/tests/genkit/core/action_test.py index 94c386023..cd5d17257 100644 --- a/packages/genkit/tests/genkit/core/action_test.py +++ b/packages/genkit/tests/genkit/core/action_test.py @@ -901,10 +901,10 @@ async def echo(x: str) -> str: signal = asyncio.Event() with pytest.raises(TypeError, match='abort_signal'): - await action.run('hi', abort_signal=signal) # pyright: ignore[reportCallIssue] # ty: ignore[unknown-argument] # pyrefly: ignore[unexpected-keyword] + await action.run('hi', abort_signal=signal) # pyright: ignore[reportCallIssue] # pyrefly: ignore[unexpected-keyword] with pytest.raises(TypeError, match='abort_signal'): - action.stream('hi', abort_signal=signal) # pyright: ignore[reportCallIssue] # ty: ignore[unknown-argument] # pyrefly: ignore[unexpected-keyword] + action.stream('hi', abort_signal=signal) # pyright: ignore[reportCallIssue] # pyrefly: ignore[unexpected-keyword] @pytest.mark.asyncio diff --git a/packages/genkit/tests/genkit/core/public_types_runtime_test.py b/packages/genkit/tests/genkit/core/public_types_runtime_test.py new file mode 100644 index 000000000..0c97c555b --- /dev/null +++ b/packages/genkit/tests/genkit/core/public_types_runtime_test.py @@ -0,0 +1,107 @@ +# 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 + +"""Runtime side of the public type contract. + +Annotations on public classes resolve with ``typing.get_type_hints`` (FastAPI +and Pydantic introspect them), and the generic session types parametrize. +""" + +import importlib +import typing + +import pytest + +from genkit import Message, Part, Role +from genkit._ai._background_model import BackgroundModel +from genkit._core._background import BackgroundAction +from genkit.model import GenerationUsage +from genkit.plugin_api import Action + + +@pytest.mark.parametrize( + 'target', + [ + Action.__call__, + Action.run, + Action.stream, + BackgroundAction.__init__, + BackgroundAction.lookup, + BackgroundModel.__init__, + BackgroundModel.lookup, + GenerationUsage.from_messages, + ], + ids=lambda t: t.__qualname__, +) +def test_public_annotations_resolve_at_runtime(target: object) -> None: + """get_type_hints() resolves every annotation instead of raising NameError/TypeError.""" + assert typing.get_type_hints(target) + + +def test_generation_usage_from_messages_counts_characters() -> None: + """from_messages still counts the request and reply after the signature change.""" + usage = GenerationUsage.from_messages( + [Message(role=Role.USER, content=[Part.from_text('Table for two')])], + Message(role=Role.MODEL, content=[Part.from_text('Booked')]), + ) + + assert usage.input_characters == len('Table for two') + assert usage.output_characters == len('Booked') + + +@pytest.mark.parametrize( + ('module', 'names'), + [ + ('genkit.model', ['ModelFn']), + ('genkit.plugin_api', ['ActionResponse']), + ('genkit_mcp', ['McpServerEntry']), + ], +) +def test_signature_types_are_exported(module: str, names: list[str]) -> None: + """Types that appear in public signatures import from their canonical module.""" + mod = importlib.import_module(module) + for name in names: + assert name in mod.__all__, f'{module}.{name}' + assert hasattr(mod, name) + + +@pytest.mark.parametrize( + ('module', 'names'), + [ + ( + 'genkit', + [ + 'ActionResponse', + 'ModelConfig', + 'ModelConfigDict', + 'ModelStreamingCallback', + 'Resource', + 'StatusName', + 'StoppableStream', + 'ToolRequest', + 'ToolResponse', + ], + ), + ('genkit.middleware', ['MiddlewareRef']), + ('genkit.plugin_api', ['ActionMetadata', 'custom_options_schema']), + ], +) +def test_non_app_and_wire_types_stay_out_of_genkit_and_middleware_exports(module: str, names: list[str]) -> None: + """Internal wire/reflection types do not leak into ``genkit``, ``genkit.middleware``, or ``genkit.plugin_api``.""" + mod = importlib.import_module(module) + for name in names: + assert name not in mod.__all__, f'{module}.{name}' + assert not hasattr(mod, name), f'{module}.{name}' diff --git a/packages/genkit/tests/typecheck/action_and_ref_contract_test.py b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py new file mode 100644 index 000000000..fce557deb --- /dev/null +++ b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py @@ -0,0 +1,192 @@ +# 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 Action input overloads, Ref invariance, and public exports. + +Checked by pyright, pyrefly, and ty with unused-ignore errors enabled so every +negative assertion below must fail all three type checkers. +""" + +from typing import Any + +import pytest +from genkit_mcp import McpServerEntry +from pydantic import BaseModel +from typing_extensions import assert_type + +from genkit import ( + Document, + Embedding, + FlowContext, + Genkit, + GenkitError, + Message, + ModelResponse, + Part, + Role, + StreamResponse, + ToolContext, +) +from genkit.embedder import EmbedderRef, EmbedRequest, EmbedResponse +from genkit.model import ModelConfig, ModelContext, ModelFn, ModelRef, ModelRequest +from genkit.plugin_api import Action, ActionKind, ActionResponse + + +class OrderReq(BaseModel): + dish: str + + +class Invoice(BaseModel): + total_cents: int + + +class BistroConfig(ModelConfig): + spice_level: int = 1 + + +class OtherModelConfig(ModelConfig): + frames: int = 24 + + +class MenuEmbedConfig(BaseModel): + dimensions: int = 256 + + +class OtherEmbedConfig(BaseModel): + task_type: str = 'search' + + +@pytest.mark.asyncio +async def test_public_signature_exports_and_action_response() -> None: + """``ModelFn``, ``ActionResponse``, and ``McpServerEntry`` import cleanly and type ``action.run``.""" + ai = Genkit() + + async def bistro_model(req: ModelRequest, ctx: ModelContext) -> ModelResponse[Any]: + del req, ctx + return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('Smoked Salmon Tartine')])) + + fn: ModelFn = bistro_model + ai.define_model(name='bistro/chef', fn=fn) + + entry: McpServerEntry = {'command': 'npx'} + assert entry['command'] == 'npx' + + async def bill_order(order: OrderReq) -> Invoice: + return Invoice(total_cents=1800 if order.dish == 'tartine' else 1200) + + action: Action[OrderReq, Invoice] = Action(ActionKind.CUSTOM, 'bill_order', bill_order) + + async def run_traced(act: Action[OrderReq, Invoice], req: OrderReq) -> ActionResponse[Invoice]: + return await act.run(req) + + traced = await run_traced(action, OrderReq(dish='tartine')) + assert_type(traced, ActionResponse[Invoice]) + assert_type(traced.response, Invoice) + assert_type(traced.trace_id, str) + assert traced.response.total_cents == 1800 + assert isinstance(traced.trace_id, str) + + +@pytest.mark.asyncio +async def test_typed_actions_require_input_while_unit_actions_omit_it() -> None: + """Typed flows, tools, and actions reject missing ``input``; ``None``-input ones allow ``()``.""" + ai = Genkit() + + @ai.flow + async def create_invoice(order: OrderReq, ctx: FlowContext[str]) -> Invoice: + ctx.send_chunk(f'billing {order.dish}') + return Invoice(total_cents=1800) + + @ai.flow + async def kitchen_status(ctx: FlowContext[str]) -> str: + ctx.send_chunk('checking') + return 'open' + + @ai.tool + async def lookup_allergens(order: OrderReq) -> str: + return f'{order.dish}: gluten' + + @ai.tool + async def list_specials(ctx: ToolContext) -> list[str]: + del ctx + return ['tartine'] + + invoice = await create_invoice(OrderReq(dish='tartine')) + assert_type(invoice, Invoice) + assert invoice.total_cents == 1800 + + run_res = await create_invoice.run(OrderReq(dish='tartine')) + assert_type(run_res, ActionResponse[Invoice]) + + stream_res = create_invoice.stream(OrderReq(dish='tartine')) + assert_type(stream_res, StreamResponse[str, Invoice]) + assert (await stream_res.response).total_cents == 1800 + + assert_type(await kitchen_status(), str) + assert_type(await list_specials(), list[str]) + + with pytest.raises(GenkitError): + await create_invoice() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] + + with pytest.raises(GenkitError): + await create_invoice.run() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] + + with pytest.raises(GenkitError): + await lookup_allergens() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] + + +@pytest.mark.asyncio +async def test_model_and_embedder_refs_are_invariant_and_default_to_any() -> None: + """Typed refs reject mismatched configs while bare ``ModelRef`` / ``EmbedderRef`` accept any ref.""" + ai = Genkit() + + async def chef(req: ModelRequest[BistroConfig], ctx: ModelContext) -> ModelResponse[Any]: + del ctx + level = req.config.spice_level if isinstance(req.config, BistroConfig) else 1 + return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text(f'spice={level}')])) + + async def embed_menu(req: EmbedRequest[MenuEmbedConfig]) -> EmbedResponse: + return EmbedResponse(embeddings=[Embedding(embedding=[0.25]) for _ in req.input]) + + ai.define_model(name='bistro/chef', fn=chef, config_schema=BistroConfig) + ai.define_embedder(name='bistro/embed', fn=embed_menu, config_schema=MenuEmbedConfig) + + bistro_ref = ModelRef(name='bistro/chef', config_schema=BistroConfig) + embed_ref = EmbedderRef(name='bistro/embed', config_schema=MenuEmbedConfig) + + # Bare ModelRef and EmbedderRef default their config parameter to Any. + any_model_ref: ModelRef = bistro_ref + any_embed_ref: EmbedderRef = embed_ref + assert any_model_ref.name == 'bistro/chef' + assert any_embed_ref.name == 'bistro/embed' + + reply = await ai.generate(model=bistro_ref, prompt='dish', config=BistroConfig(spice_level=3)) + assert reply.text == 'spice=3' + + vecs = await ai.embed_many( + embedder=embed_ref, + content=('tartine', Document.from_text('bouillabaisse')), + config=MenuEmbedConfig(dimensions=128), + ) + assert len(vecs) == 2 + + with pytest.raises(GenkitError): + await ai.generate(model=bistro_ref, prompt='dish', config=OtherModelConfig()) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + + with pytest.raises(GenkitError): + await ai.embed(embedder=embed_ref, content='tartine', config=OtherEmbedConfig()) # pyright: ignore[reportArgumentType] # pyrefly: ignore[bad-argument-type] # ty: ignore[invalid-argument-type] diff --git a/packages/genkit/tests/typecheck/output_narrowing_contract_test.py b/packages/genkit/tests/typecheck/output_narrowing_contract_test.py new file mode 100644 index 000000000..92b435def --- /dev/null +++ b/packages/genkit/tests/typecheck/output_narrowing_contract_test.py @@ -0,0 +1,151 @@ +# 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 + +"""Type-checker contract for ``.output``. + +With ``output_schema=T``, ``response.output`` types as ``T | None``: +``generate`` boxes failures, so a reply +that doesn't match the schema is ``None`` at runtime. JS types it ``O | null``. +Stream chunks are ``T | None`` too. With no schema or a JSON-schema dict, +``.output`` types as ``Any | None``. + +pyright, pyrefly, and ty check this file (see ``[tool.pyright]``); the tests +also run so each static type matches the runtime value. +""" + +from typing import Any + +import pytest +from pydantic import BaseModel +from typing_extensions import assert_type + +from genkit import Genkit, Message, ModelResponse, ModelResponseChunk, Part, Role +from genkit.testing import define_scripted_model, define_static_response_model + + +class Order(BaseModel): + dish: str + quantity: int + + +def _scripted(ai: Genkit, text: str, chunks: list[str] | None = None) -> None: + define_scripted_model( + ai, + name='kitchen', + responses=[ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text(text)]))], + chunks=[[ModelResponseChunk(role=Role.MODEL, content=[Part.from_text(c)]) for c in chunks]] if chunks else None, + ) + + +@pytest.mark.asyncio +async def test_generate_output_is_schema_type() -> None: + """``output_schema=Order`` gives ``Order | None``; a guard narrows it.""" + ai = Genkit() + _scripted(ai, '{"dish": "tartine", "quantity": 2}') + + res = await ai.generate(model='kitchen', prompt='order', output_schema=Order) + + assert_type(res, ModelResponse[Order]) + assert_type(res.output, Order | None) + assert res.output is not None + total: int = res.output.quantity * 3 + assert total == 6 + + +@pytest.mark.asyncio +async def test_generate_output_with_config_dict_is_schema_type() -> None: + """The ``config={...}`` overload narrows the same way.""" + ai = Genkit() + _scripted(ai, '{"dish": "soup", "quantity": 1}') + + res = await ai.generate(model='kitchen', prompt='order', config={'temperature': 0.1}, output_schema=Order) + + assert_type(res.output, Order | None) + assert res.output is not None + assert res.output.dish == 'soup' + + +@pytest.mark.asyncio +async def test_untyped_output_is_any() -> None: + """No schema or a dict schema types as ``Any | None``; a guard makes it indexable.""" + ai = Genkit() + _, _ = define_static_response_model(ai, '{"dish": "tartine"}', name='menu') + + res = await ai.generate(model='menu', prompt='x') + assert_type(res.output, Any | None) + + res_dict = await ai.generate(model='menu', prompt='x', output_schema={'type': 'object'}) + assert_type(res_dict.output, Any | None) + assert res_dict.output is not None + assert res_dict.output['dish'] == 'tartine' + + +@pytest.mark.asyncio +async def test_stream_chunk_and_final_output_are_optional() -> None: + """Chunks and the awaited response are both ``Order | None``.""" + ai = Genkit() + _scripted(ai, '{"dish": "tartine", "quantity": 2}', chunks=['{"dish": "tar', 'tine", "quantity": 2}']) + + stream = ai.generate_stream(model='kitchen', prompt='order', output_schema=Order) + seen: list[Order | None] = [] + async for chunk in stream.stream: + assert_type(chunk, ModelResponseChunk[Order]) + assert_type(chunk.output, Order | None) + seen.append(chunk.output) + final = await stream.response + + assert_type(final.output, Order | None) + assert final.output is not None + assert final.output.quantity == 2 + last = seen[-1] + assert last is not None and last.dish == 'tartine' + + +@pytest.mark.asyncio +async def test_prompt_output_is_optional() -> None: + """``define_prompt`` / ``ai.prompt`` with ``output_schema`` type ``.output`` as ``Order | None``.""" + ai = Genkit() + _, _ = define_static_response_model(ai, '{"dish": "tartine", "quantity": 2}', name='kitchen') + order_prompt = ai.define_prompt(name='order', model='kitchen', prompt='order', output_schema=Order) + + res = await order_prompt() + assert_type(res.output, Order | None) + assert res.output is not None + assert res.output.dish == 'tartine' + + looked_up = ai.prompt('order', output_schema=Order) + looked_up_res = await looked_up() + assert_type(looked_up_res.output, Order | None) + assert looked_up_res.output is not None + assert looked_up_res.output.quantity == 2 + + stream = order_prompt.stream() + async for chunk in stream.stream: + assert_type(chunk.output, Order | None) + final = await stream.response + assert_type(final.output, Order | None) + assert final.output is not None + assert final.output.dish == 'tartine' + + +def test_bare_model_response_output_is_object() -> None: + """Unparameterized ``ModelResponse`` defaults ``OutputT`` to ``object``, so ``.output`` is ``object | None``.""" + + def read(res: ModelResponse) -> object: + assert_type(res.output, object | None) + return res.output + + assert read(ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('hi')]))) is None diff --git a/packages/genkit/tests/typecheck/prompt_input_contract_test.py b/packages/genkit/tests/typecheck/prompt_input_contract_test.py new file mode 100644 index 000000000..82e82072c --- /dev/null +++ b/packages/genkit/tests/typecheck/prompt_input_contract_test.py @@ -0,0 +1,66 @@ +# 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 + +"""Type-checker contract for Prompt.__call__ / Prompt.stream input. + +A prompt's input stays optional, typed or not: the template can fill in +defaults, so ``await order()`` runs. Typed prompts also take a dict of +template variables. pyright, pyrefly, and ty check this directory. +""" + +from typing import Any + +import pytest +from pydantic import BaseModel +from typing_extensions import assert_type + +from genkit import Genkit, ModelResponse, ModelStreamResponse +from genkit.testing import define_echo_model + + +class Order(BaseModel): + dish: str = 'pad thai' + + +@pytest.mark.asyncio +async def test_prompt_input_is_optional_and_accepts_model_or_dict() -> None: + """Untyped and typed prompts accept no input, the model, or a dict, with every keyword.""" + # 1. One prompt without input_schema, one with + ai = Genkit() + define_echo_model(ai) + greeting = ai.define_prompt(name='greeting', model='echoModel', prompt='Welcome to the bistro.') + order = ai.define_prompt(name='order', model='echoModel', prompt='Order {{dish}}.', input_schema=Order) + + # 2. No input: the model's defaults fill the template + reply = await order() + assert_type(reply, ModelResponse[Any]) + assert 'pad thai' in reply.text + + # 3. Model or dict input, with the full keyword set + reply = await greeting(max_turns=1, context={}, resume_metadata=None, on_chunk=None) + assert_type(reply, ModelResponse[Any]) + reply = await order(Order(dish='curry'), max_turns=1, resume_metadata=None) + assert_type(reply, ModelResponse[Any]) + reply = await order({'dish': 'ramen'}) + assert 'ramen' in reply.text + + # 4. stream takes the same input shapes + stream = greeting.stream(max_turns=1, context={}, resume_metadata=None) + assert_type(stream, ModelStreamResponse[Any]) + stream = order.stream(resume_metadata=None) + assert_type(stream, ModelStreamResponse[Any]) + stream = order.stream({'dish': 'tartine'}) + assert 'tartine' in (await stream.response).text diff --git a/scripts/schema_to_typing.py b/scripts/schema_to_typing.py index ce69fefb1..d3ab07f8d 100644 --- a/scripts/schema_to_typing.py +++ b/scripts/schema_to_typing.py @@ -137,7 +137,8 @@ def _output_name(name: str) -> str: from __future__ import annotations -from typing import TYPE_CHECKING, Any, ClassVar, Literal +from collections.abc import Sequence # noqa: TC003 - get_type_hints(GenerationUsage.from_messages) needs it +from typing import Any, ClassVar, Literal from pydantic import ConfigDict, Field, RootModel from pydantic.alias_generators import to_camel @@ -145,11 +146,6 @@ def _output_name(name: str) -> str: from genkit._core._base import GenkitConfig, GenkitModel from genkit._core._compat import StrEnum -if TYPE_CHECKING: - from collections.abc import Sequence - - from genkit._core import _model - ''' @@ -438,11 +434,15 @@ def _emit_model( lines.extend([ '', ' @classmethod', - ' def from_messages(cls, messages: Sequence[_model.Message], response: _model.Message) -> GenerationUsage:', + # Annotated as object, not _model.Message: _model imports this + # module, so its names can't resolve here and + # typing.get_type_hints() would raise NameError. as_message + # normalizes wire MessageData and dicts at runtime. + ' def from_messages(cls, messages: Sequence[object], response: object) -> GenerationUsage:', ' """Character and media counts for the request messages and the model reply."""', - ' from genkit._core._model import count_message_usage # noqa: PLC0415 - _model imports this module', + ' from genkit._core._model import as_message, count_message_usage # noqa: PLC0415 - _model imports this module', '', - ' return cls.model_validate(count_message_usage(messages, response))', + ' return cls.model_validate(count_message_usage([as_message(m) for m in messages], as_message(response)))', ]) return lines + [''] @@ -575,7 +575,7 @@ def generate(schema_path: Path, _out: Path) -> str: ]) content = '\n'.join(out) - # _model.Message is the public Message (GenerationUsage.from_messages), not the wire type. + # Schema refs to Message are the wire MessageData; the public Message lives in _model. content = re.sub(r'(? Date: Thu, 12 Nov 2026 02:24:28 -0600 Subject: [PATCH 02/20] fix(py/exp): type SessionSnapshot by state_schema and export missing agent types --- .../genkit/src/genkit/_ai/_agents/_client.py | 77 +++++++++---------- packages/genkit/src/genkit/_core/_model.py | 24 ++++-- packages/genkit/src/genkit/exp/_api.py | 5 +- .../genkit/src/genkit/exp/agent/__init__.py | 4 + packages/genkit/src/genkit/web/_sse.py | 7 +- .../tests/genkit/ai/agent_snapshot_test.py | 36 +++++++++ .../genkit/core/public_types_runtime_test.py | 1 + 7 files changed, 101 insertions(+), 53 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_agents/_client.py b/packages/genkit/src/genkit/_ai/_agents/_client.py index eafe6e82c..792945072 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_client.py +++ b/packages/genkit/src/genkit/_ai/_agents/_client.py @@ -25,7 +25,7 @@ from dataclasses import dataclass, field from typing import Any, Generic, Protocol, TypeVar, cast -from pydantic import BaseModel, ValidationError, field_validator +from pydantic import BaseModel, ValidationError from typing_extensions import TypeVar as TypeVarExt from genkit._ai._agents._runtime import AgentInitError, seeded_init_fields @@ -51,11 +51,10 @@ Message, Part, Resume, - SessionSnapshot as SessionSnapshotVeneer, - SessionState as SessionStateVeneer, + SessionSnapshot, + SessionState, as_message, as_part, - as_session_state, resume_options_to_resume, ) from genkit._core._typing import ( @@ -98,25 +97,25 @@ class _TurnCheckpoint: resume_snapshot_id: str | None -class SessionState(SessionStateVeneer, Generic[StateT]): - """Session state generic over custom state.""" +def _typed_snapshot( + raw: SessionSnapshot | None, + state_schema: type[StateT] | None, +) -> SessionSnapshot[StateT] | None: + """Re-read a stored snapshot with ``state.custom`` validated as ``state_schema``. - custom: StateT | None = None - - -class SessionSnapshot(SessionSnapshotVeneer, Generic[StateT]): - """Session snapshot generic over custom state.""" - - # Narrows the wire model's plain SessionState to the typed one so snap.state.custom - # reads as the declared model; the runtime shape is identical (same JSON fields). - state: SessionState[StateT] | None = None # pyright: ignore[reportIncompatibleVariableOverride] # pyrefly: ignore[bad-override] - - @field_validator('state', mode='before') - @classmethod - def _wrap_state(cls, v: object) -> object: - if v is None: - return v - return SessionState.model_validate(as_session_state(v).model_dump(mode='json', by_alias=True)) + A settled snapshot whose state doesn't fit raises; a pending one keeps the + raw value, since the turn may still be writing it. + """ + if raw is None: + return None + snap = SessionSnapshot[StateT].model_validate_json(raw.model_dump_json(by_alias=True)) + if snap.state is not None and snap.state.custom is not None and state_schema is not None: + try: + snap.state.custom = state_schema.model_validate(snap.state.custom) + except Exception: + if snap.status is not None and snap.status in TERMINAL_SNAPSHOT_STATUSES: + raise + return snap # =========================================================================== @@ -158,7 +157,7 @@ async def get_snapshot( *, snapshot_id: str | None = None, session_id: str | None = None, - ) -> SessionSnapshotVeneer | None: + ) -> SessionSnapshot | None: """Retrieves a session snapshot from the server store.""" ... @@ -559,7 +558,7 @@ async def get_snapshot( *, snapshot_id: str | None = None, session_id: str | None = None, - ) -> SessionSnapshotVeneer | None: + ) -> SessionSnapshot[StateT] | None: """Reads a stored snapshot without starting a session. Pass exactly one of ``snapshot_id`` or ``session_id``. A session @@ -669,15 +668,17 @@ async def get_snapshot( *, snapshot_id: str | None = None, session_id: str | None = None, - ) -> SessionSnapshotVeneer | None: + ) -> SessionSnapshot[StateT] | None: """Reads a stored snapshot without starting a session. Pass exactly one of ``snapshot_id`` or ``session_id``. A session lookup returns the newest row even when that turn failed or was aborted. ``chat(session_id=)`` is how you continue from the last - good turn. + good turn. With ``state_schema``, ``state.custom`` comes back as + that model. """ - return await self._transport.get_snapshot(snapshot_id=snapshot_id, session_id=session_id) + raw = await self._transport.get_snapshot(snapshot_id=snapshot_id, session_id=session_id) + return _typed_snapshot(raw, self._state_schema) async def abort(self, snapshot_id: str) -> SnapshotStatus | None: """Aborts a running snapshot on the server. @@ -1231,11 +1232,12 @@ def resume_stream( wire = resume_options_to_resume(resume_respond=respond, resume_restart=restart, resume_metadata=metadata) return self.send_stream(AgentInput(resume=wire or Resume(metadata=metadata))) - async def get_snapshot(self) -> SessionSnapshotVeneer | None: + async def get_snapshot(self) -> SessionSnapshot[StateT] | None: """Reads the current snapshot from the server store, if store-backed.""" if not self._snapshot_id: return None - return await self._transport.get_snapshot(snapshot_id=self._snapshot_id) + raw = await self._transport.get_snapshot(snapshot_id=self._snapshot_id) + return _typed_snapshot(raw, self._state_schema) async def detach(self, input: str | AgentInput) -> DetachedTask[StateT]: # noqa: A002 """Runs a turn in the background on the server and returns a poll handle.""" @@ -1306,13 +1308,13 @@ async def abort(self) -> SnapshotStatus | None: # Internal (transport / runtime wiring) # ------------------------------------------------------------------ - def _load_from_snapshot(self, snapshot: SessionSnapshotVeneer) -> None: + def _load_from_snapshot(self, snapshot: SessionSnapshot) -> None: self._snapshot_id = snapshot.snapshot_id self._resume_snapshot_id = snapshot.snapshot_id if snapshot.state is not None: self._set_state(snapshot.state) - def _set_state(self, state: SessionStateVeneer) -> None: + def _set_state(self, state: SessionState) -> None: snapshot = state.model_copy(deep=True) self._session_id = snapshot.session_id self._messages = list(snapshot.messages or []) @@ -1561,17 +1563,8 @@ def __init__( self._transport = transport self._state_schema = state_schema - def _parse_snapshot(self, raw: SessionSnapshotVeneer | None) -> SessionSnapshot[StateT] | None: - if raw is None: - return None - snap = SessionSnapshot[StateT].model_validate_json(raw.model_dump_json(by_alias=True)) - if snap.state is not None and snap.state.custom is not None and self._state_schema is not None: - try: - snap.state.custom = self._state_schema.model_validate(snap.state.custom) - except Exception: - if snap.status is not None and snap.status in TERMINAL_SNAPSHOT_STATUSES: - raise - return snap + def _parse_snapshot(self, raw: SessionSnapshot | None) -> SessionSnapshot[StateT] | None: + return _typed_snapshot(raw, self._state_schema) async def poll(self, interval: float = 1.0) -> AsyncIterator[SessionSnapshot[StateT]]: """Yields the task's snapshot every ``interval`` seconds until it settles. diff --git a/packages/genkit/src/genkit/_core/_model.py b/packages/genkit/src/genkit/_core/_model.py index f077ad22e..da871136e 100644 --- a/packages/genkit/src/genkit/_core/_model.py +++ b/packages/genkit/src/genkit/_core/_model.py @@ -1193,12 +1193,21 @@ def count_parts(parts: Sequence[Part]) -> tuple[int, int, int, int]: } -class SessionState(GenkitModel): - """Session state whose conversation uses Message and Artifact.""" +# Custom session state type. Defaults to Any so a bare SessionState / +# SessionSnapshot is the untyped wire shape. +SessionStateT = TypeVar('SessionStateT', default=Any) + + +class SessionState(GenkitModel, Generic[SessionStateT]): + """Session state whose conversation uses Message and Artifact. + + ``SessionState[CartState]`` validates ``custom`` as ``CartState``; a bare + ``SessionState`` leaves it as the stored JSON value. + """ session_id: str | None = None messages: list[Message] | None = None - custom: Any | None = Field(default=None) + custom: SessionStateT | None = Field(default=None) artifacts: list[Artifact] | None = None usage: GenerationUsage | None = None @@ -1229,8 +1238,11 @@ def as_session_state(value: object) -> SessionState: return SessionState.model_validate(value) -class SessionSnapshot(GenkitModel): - """Snapshot whose state uses the public SessionState type.""" +class SessionSnapshot(GenkitModel, Generic[SessionStateT]): + """Snapshot whose state uses the public SessionState type. + + ``SessionSnapshot[CartState]`` types ``state.custom`` as ``CartState``. + """ snapshot_id: str session_id: str | None = None @@ -1241,7 +1253,7 @@ class SessionSnapshot(GenkitModel): status: SnapshotStatus | None = None finish_reason: AgentFinishReason | None = None error: Failure | None = None - state: SessionState | None = None + state: SessionState[SessionStateT] | None = None @field_validator('state', mode='before') @classmethod diff --git a/packages/genkit/src/genkit/exp/_api.py b/packages/genkit/src/genkit/exp/_api.py index 2ad3fe87b..44100a296 100644 --- a/packages/genkit/src/genkit/exp/_api.py +++ b/packages/genkit/src/genkit/exp/_api.py @@ -30,18 +30,17 @@ define_prompt_agent, ) from genkit._ai._agents._runtime import AgentFn -from genkit._ai._agents._session import SessionStore, StateT, get_current_session +from genkit._ai._agents._session import Session, SessionStore, StateT, get_current_session from genkit._ai._agents._types import ChunkTransform, StateTransform from genkit._ai._aio import Genkit as StableGenkit from genkit._core._action import Action, ActionKind from genkit._core._error import ErrorReason, GenkitError from genkit._core._middleware import Middleware from genkit._core._model import ModelConfigDict, ModelRef, ModelRefConfigT, Part -from genkit._core._protocols import SessionLike from genkit._core._tool import Tool -def current_session() -> SessionLike | None: +def current_session() -> Session[Any] | None: """Return the active agent session, or None if not inside a session.""" return get_current_session() diff --git a/packages/genkit/src/genkit/exp/agent/__init__.py b/packages/genkit/src/genkit/exp/agent/__init__.py index fc82acc45..b7ec07a19 100644 --- a/packages/genkit/src/genkit/exp/agent/__init__.py +++ b/packages/genkit/src/genkit/exp/agent/__init__.py @@ -58,6 +58,7 @@ apply_save, iterate_statuses, require_one_selector, + select_leaf, session_id_of, ) from genkit._ai._agents._transports._http import HttpAgentTransport, remote_agent @@ -68,6 +69,7 @@ TurnResult, ) from genkit._ai._json_patch import apply_json_patch, diff_json +from genkit._core._action import BidiConnection from genkit._core._model import ( AgentInit, AgentInput, @@ -99,6 +101,7 @@ 'AgentResponse', 'DetachedTask', 'AgentTransport', + 'BidiConnection', 'HttpAgentTransport', 'remote_agent', # Agent function protocol @@ -121,6 +124,7 @@ 'apply_save', 'iterate_statuses', 'require_one_selector', + 'select_leaf', 'session_id_of', # JSON Patch helpers 'apply_json_patch', diff --git a/packages/genkit/src/genkit/web/_sse.py b/packages/genkit/src/genkit/web/_sse.py index ae55665e8..d3b4fde57 100644 --- a/packages/genkit/src/genkit/web/_sse.py +++ b/packages/genkit/src/genkit/web/_sse.py @@ -19,7 +19,7 @@ import json import logging from collections.abc import AsyncGenerator, AsyncIterator, Awaitable -from typing import Protocol +from typing import Any, Protocol from pydantic_core import to_jsonable_python @@ -71,7 +71,10 @@ def _frame_value(obj: object) -> object: # A failed turn is a 200 with the failure as data, so error_body never # sees it. Apply the same rule here: only a PublicError's text leaves. if isinstance(obj, (AgentOutput, SessionSnapshot)) and obj.error is not None: - obj = obj.model_copy(update={'error': client_safe_failure(obj.error)}) + # Typed as Any-valued: ty narrows to Top[SessionSnapshot[Any]], whose + # model_copy(update=) would otherwise only accept Mapping[str, Never]. + update: dict[str, Any] = {'error': client_safe_failure(obj.error)} + obj = obj.model_copy(update=update) return to_jsonable_python(obj, by_alias=True, exclude_none=True) diff --git a/packages/genkit/tests/genkit/ai/agent_snapshot_test.py b/packages/genkit/tests/genkit/ai/agent_snapshot_test.py index 48f6cd902..9baf8d841 100644 --- a/packages/genkit/tests/genkit/ai/agent_snapshot_test.py +++ b/packages/genkit/tests/genkit/ai/agent_snapshot_test.py @@ -18,6 +18,7 @@ from datetime import datetime, timedelta, timezone import pytest +from pydantic import BaseModel from genkit import Genkit, Part from genkit._ai._agents._base import define_custom_agent @@ -365,3 +366,38 @@ async def handle_turn(inp: AgentInput, _: TurnContext) -> TurnResult | None: out = await resumed.send('still there?') assert out.finish_reason == AgentFinishReason.STOP assert resumed.snapshot_id not in (None, task.snapshot_id) + + +class _CartState(BaseModel): + items: list[str] + + +@pytest.mark.asyncio +async def test_get_snapshot_hydrates_state_schema() -> None: + """With state_schema set, agent.get_snapshot and chat.get_snapshot validate state.custom.""" + ai = Genkit() + store = InMemorySessionStore() + + async def fn(session_runner: SessionRunner[_CartState], _: AgentContext) -> AgentResult: + async def handle_turn(_inp: AgentInput, _tc: TurnContext) -> TurnResult | None: + await session_runner.update_custom(lambda _: _CartState(items=['tartine'])) + await session_runner.add_messages([Message(role='model', content=[Part.from_text('added')])]) + return TurnResult(finish_reason=AgentFinishReason.STOP) + + await session_runner.run(handle_turn) + return await session_runner.result() + + agent = define_custom_agent(ai, 'cartAgent', fn, store=store, state_schema=_CartState) + chat = agent.chat() + await chat.send('add tartine') + assert chat.session_id is not None + + from_chat: SessionSnapshot[_CartState] | None = await chat.get_snapshot() + assert from_chat is not None and from_chat.state is not None + assert isinstance(from_chat.state.custom, _CartState) + assert from_chat.state.custom.items == ['tartine'] + + from_client: SessionSnapshot[_CartState] | None = await agent.get_snapshot(session_id=chat.session_id) + assert from_client is not None and from_client.state is not None + assert isinstance(from_client.state.custom, _CartState) + assert from_client.state.custom.items == ['tartine'] diff --git a/packages/genkit/tests/genkit/core/public_types_runtime_test.py b/packages/genkit/tests/genkit/core/public_types_runtime_test.py index 0c97c555b..7253e81c9 100644 --- a/packages/genkit/tests/genkit/core/public_types_runtime_test.py +++ b/packages/genkit/tests/genkit/core/public_types_runtime_test.py @@ -67,6 +67,7 @@ def test_generation_usage_from_messages_counts_characters() -> None: [ ('genkit.model', ['ModelFn']), ('genkit.plugin_api', ['ActionResponse']), + ('genkit.exp.agent', ['BidiConnection', 'DetachedTask', 'AgentInitError', 'select_leaf']), ('genkit_mcp', ['McpServerEntry']), ], ) From 1363fb443926580dc5d097cc5775cfe417cc70c5 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 12 Nov 2026 11:40:05 -0600 Subject: [PATCH 03/20] fix(py): keep ActionResponse out of genkit.plugin_api --- packages/genkit/src/genkit/plugin_api/__init__.py | 3 +-- .../genkit/tests/genkit/core/public_types_runtime_test.py | 3 +-- .../genkit/tests/typecheck/action_and_ref_contract_test.py | 5 +++-- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/packages/genkit/src/genkit/plugin_api/__init__.py b/packages/genkit/src/genkit/plugin_api/__init__.py index 48fb8a137..5e7fea6d9 100644 --- a/packages/genkit/src/genkit/plugin_api/__init__.py +++ b/packages/genkit/src/genkit/plugin_api/__init__.py @@ -17,7 +17,7 @@ """Framework primitives for plugin authors.""" # Base class and framework primitives -from genkit._core._action import Action, ActionKind, ActionResponse +from genkit._core._action import Action, ActionKind from genkit._core._background import BackgroundAction from genkit._core._base import GenkitConfig from genkit._core._compat import StrEnum @@ -34,7 +34,6 @@ 'Plugin', 'GenkitConfig', 'Action', - 'ActionResponse', 'BackgroundAction', 'ActionKind', 'DynamicActionProvider', diff --git a/packages/genkit/tests/genkit/core/public_types_runtime_test.py b/packages/genkit/tests/genkit/core/public_types_runtime_test.py index 0c97c555b..614f000bf 100644 --- a/packages/genkit/tests/genkit/core/public_types_runtime_test.py +++ b/packages/genkit/tests/genkit/core/public_types_runtime_test.py @@ -66,7 +66,6 @@ def test_generation_usage_from_messages_counts_characters() -> None: ('module', 'names'), [ ('genkit.model', ['ModelFn']), - ('genkit.plugin_api', ['ActionResponse']), ('genkit_mcp', ['McpServerEntry']), ], ) @@ -96,7 +95,7 @@ def test_signature_types_are_exported(module: str, names: list[str]) -> None: ], ), ('genkit.middleware', ['MiddlewareRef']), - ('genkit.plugin_api', ['ActionMetadata', 'custom_options_schema']), + ('genkit.plugin_api', ['ActionMetadata', 'ActionResponse', 'custom_options_schema']), ], ) def test_non_app_and_wire_types_stay_out_of_genkit_and_middleware_exports(module: str, names: list[str]) -> None: diff --git a/packages/genkit/tests/typecheck/action_and_ref_contract_test.py b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py index fce557deb..e253bafbf 100644 --- a/packages/genkit/tests/typecheck/action_and_ref_contract_test.py +++ b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py @@ -42,9 +42,10 @@ StreamResponse, ToolContext, ) +from genkit._core._action import ActionResponse from genkit.embedder import EmbedderRef, EmbedRequest, EmbedResponse from genkit.model import ModelConfig, ModelContext, ModelFn, ModelRef, ModelRequest -from genkit.plugin_api import Action, ActionKind, ActionResponse +from genkit.plugin_api import Action, ActionKind class OrderReq(BaseModel): @@ -73,7 +74,7 @@ class OtherEmbedConfig(BaseModel): @pytest.mark.asyncio async def test_public_signature_exports_and_action_response() -> None: - """``ModelFn``, ``ActionResponse``, and ``McpServerEntry`` import cleanly and type ``action.run``.""" + """``ModelFn`` and ``McpServerEntry`` import cleanly and ``action.run`` preserves ``ActionResponse[T]``.""" ai = Genkit() async def bistro_model(req: ModelRequest, ctx: ModelContext) -> ModelResponse[Any]: From 0df3bdc00368b5abb427b3a713a0a94ece35412d Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 12 Nov 2026 11:50:10 -0600 Subject: [PATCH 04/20] docs(py): clarify why ref config TypeVars default to Any --- packages/genkit/src/genkit/_ai/_embedding.py | 7 ++++--- packages/genkit/src/genkit/_core/_model.py | 9 +++++---- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_embedding.py b/packages/genkit/src/genkit/_ai/_embedding.py index 67f41c188..32712d19b 100644 --- a/packages/genkit/src/genkit/_ai/_embedding.py +++ b/packages/genkit/src/genkit/_ai/_embedding.py @@ -51,9 +51,10 @@ class EmbedderInfo(BaseModel): dimensions: int | None = None -# Invariant for the same reason as ModelRefConfigT: embed(embedder=EmbedderRef[T], -# config=T) must not widen T to BaseModel. Defaults to Any so a bare -# EmbedderRef annotation still accepts any typed ref. +# Invariant so embed(embedder=EmbedderRef[T], config=T) pins T to the ref's +# config class. Defaults to Any (not BaseModel) because invariant generics +# forbid subtyping on the type parameter, so bare EmbedderRef must mean +# EmbedderRef[Any] to accept any typed ref. EmbedderRefConfigT = TypeVar('EmbedderRefConfigT', bound=BaseModel, default=Any) diff --git a/packages/genkit/src/genkit/_core/_model.py b/packages/genkit/src/genkit/_core/_model.py index f077ad22e..b70691aec 100644 --- a/packages/genkit/src/genkit/_core/_model.py +++ b/packages/genkit/src/genkit/_core/_model.py @@ -311,10 +311,11 @@ def reject_config_api_key(config: object) -> None: # TypeVars for generic types OutputT = TypeVar('OutputT', default=object) ConfigT = TypeVar('ConfigT', bound=ModelConfig, default=ModelConfig) -# Bound to BaseModel so ModelRef is always parameterized with a concrete Pydantic config schema. -# Invariant: generate(model=ModelRef[T], config=T) solves T from the ref. A -# covariant T let checkers widen ModelRef[GeminiConfig] to ModelRef[BaseModel] -# and accept any config class. Defaults to Any so bare ModelRef means ModelRef[Any]. +# Bound to BaseModel so ModelRef only accepts Pydantic config schemas. +# Invariant so generate(model=ModelRef[T], config=T) pins T to the ref's config +# class rather than widening to BaseModel. Defaults to Any (not BaseModel) +# because invariant generics forbid subtyping on the type parameter: bare +# ModelRef must mean ModelRef[Any] to accept any typed ref. ModelRefConfigT = TypeVar('ModelRefConfigT', bound=BaseModel, default=Any) # ModelRequest[X], EmbedRequest[X] and the evaluator requests take a pydantic # model class; __class_getitem__ rejects the rest. Not bound to BaseModel: type From 18cff5d40e77ae832ef1d87d075faaff59b0698c Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 12 Nov 2026 12:17:45 -0600 Subject: [PATCH 05/20] chore(py): remove unused CheckOpFn and CancelOpFn aliases --- packages/genkit/src/genkit/_ai/_background_model.py | 2 -- packages/genkit/src/genkit/_core/_background.py | 5 ----- 2 files changed, 7 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_background_model.py b/packages/genkit/src/genkit/_ai/_background_model.py index 2d7afa664..ec59c093f 100644 --- a/packages/genkit/src/genkit/_ai/_background_model.py +++ b/packages/genkit/src/genkit/_ai/_background_model.py @@ -46,8 +46,6 @@ from genkit._core._schema import custom_options_schema from genkit._core._typing import ModelInfo -# Spelled out, not CheckOpFn[ModelResponse]: Operation[ModelResponse] is a -# concrete pydantic class at runtime, so the generic alias can't be subscripted. # A fn may return a plain Operation; its output is validated as a ModelResponse. StartModelOpFn = Callable[[ModelRequest, ModelContext], Awaitable[Operation]] CheckModelOpFn = Callable[[Operation[ModelResponse], ModelContext], Awaitable[Operation]] diff --git a/packages/genkit/src/genkit/_core/_background.py b/packages/genkit/src/genkit/_core/_background.py index 5f5be8b6a..d121b2d24 100644 --- a/packages/genkit/src/genkit/_core/_background.py +++ b/packages/genkit/src/genkit/_core/_background.py @@ -50,12 +50,7 @@ InT = TypeVar('InT') OutT = TypeVar('OutT') -# Annotation-only aliases. Operation[OutT] is a concrete pydantic class at -# runtime, so CheckOpFn[X] can't be subscripted outside an annotation; spell -# the Callable out when you need a runtime alias. StartOpFn = Callable[[InT, FlowContext], Awaitable[Operation]] -CheckOpFn = Callable[[Operation[OutT], FlowContext], Awaitable[Operation]] -CancelOpFn = Callable[[Operation[OutT], FlowContext], Awaitable[Operation]] def _make_action_key(action_type: ActionKind | str, name: str) -> str: From 0d36862c27778b2f4cfc6926f39bcba3288ca89e Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 16 Nov 2026 10:34:54 -0600 Subject: [PATCH 06/20] chore(py): unquote ActionContext annotation after merge --- packages/genkit/src/genkit/_core/_action.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index 7ab24bd44..9db9d8113 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -375,7 +375,7 @@ def call( self, fn: Callable[..., _CallT], input: object, # noqa: A002 - ctx: 'ActionContext', + ctx: ActionContext, ) -> _CallT: """Call ``fn`` with ``input`` and ``ctx`` passed by parameter name. From 3bdcf41a3c3a85d6bf70fa8765f5176ce1a6ad14 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 16 Nov 2026 10:34:54 -0600 Subject: [PATCH 07/20] fix(py): drop Tool.__new__ overloads so copy and subclassing work again 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. --- packages/genkit/src/genkit/_core/_tool.py | 91 +------------------ .../genkit/ai/tool_response_contract_test.py | 4 +- 2 files changed, 3 insertions(+), 92 deletions(-) diff --git a/packages/genkit/src/genkit/_core/_tool.py b/packages/genkit/src/genkit/_core/_tool.py index 776438d56..559dab4c2 100644 --- a/packages/genkit/src/genkit/_core/_tool.py +++ b/packages/genkit/src/genkit/_core/_tool.py @@ -26,7 +26,7 @@ from typing import Any, Union, cast, get_args, get_origin, overload from pydantic import BaseModel, TypeAdapter -from typing_extensions import Self, TypeVar +from typing_extensions import TypeVar from genkit._core._action import ( Action, @@ -349,90 +349,6 @@ class Tool(Action[InputT, OutputT, ChunkT, None]): # One overload per handler shape, same as ``ai.tool`` / ``define_tool``, so # ``Tool(place_order)`` infers ``Tool[Order, Receipt, Step]`` from the function. - # ty reads the ``__new__`` overloads; pyright, mypy and pyrefly read the - # self-typed ``__init__`` overloads. Keep the two lists in step. - @overload - def __new__( - cls, - func: Callable[[ToolContext[_C], object], Awaitable[_O]], - *, - name: str | None = None, - description: str | None = None, - input_schema: type[BaseModel] | dict[str, object] | None = None, - ) -> Tool[Any, _O, _C]: ... - - @overload - def __new__( - cls, - func: Callable[[_I, ToolContext[_C]], Awaitable[_O]], - *, - name: str | None = None, - description: str | None = None, - input_schema: type[BaseModel] | dict[str, object] | None = None, - ) -> Tool[_I, _O, _C]: ... - - @overload - def __new__( - cls, - func: Callable[[ToolContext[_C], _I], Awaitable[_O]], - *, - name: str | None = None, - description: str | None = None, - input_schema: type[BaseModel] | dict[str, object] | None = None, - ) -> Tool[_I, _O, _C]: ... - - @overload - def __new__( - cls, - func: Callable[[object], Awaitable[_O]], - *, - name: str | None = None, - description: str | None = None, - input_schema: type[BaseModel] | dict[str, object] | None = None, - ) -> Tool[Any, _O, Any]: ... - - @overload - def __new__( - cls, - func: Callable[[ToolContext[_C]], Awaitable[_O]], - *, - name: str | None = None, - description: str | None = None, - input_schema: type[BaseModel] | dict[str, object] | None = None, - ) -> Tool[None, _O, _C]: ... - - @overload - def __new__( - cls, - func: Callable[[_I], Awaitable[_O]], - *, - name: str | None = None, - description: str | None = None, - input_schema: type[BaseModel] | dict[str, object] | None = None, - ) -> Tool[_I, _O, Any]: ... - - @overload - def __new__( - cls, - func: Callable[[], Awaitable[_O]], - *, - name: str | None = None, - description: str | None = None, - input_schema: type[BaseModel] | dict[str, object] | None = None, - ) -> Tool[None, _O, Any]: ... - - def __new__( - cls, - func: Callable[..., Awaitable[Any]], - *, - name: str | None = None, - description: str | None = None, - input_schema: type[BaseModel] | dict[str, object] | None = None, - ) -> Tool[Any, Any, Any]: - """Allocate the tool; ``__init__`` does the work.""" - del func, name, description, input_schema - return super().__new__(cls) - @overload def __init__( self: Tool[Any, _O, _C], @@ -641,11 +557,6 @@ async def _invoke(self, input: object | None, ctx: ActionContext) -> OutputT: class _ActionTool(Tool[InputT, OutputT, ChunkT]): """A ``Tool`` view over a plain ``Action`` with no ``tool.v2`` companion.""" - def __new__(cls, action: Action[InputT, OutputT, ChunkT, Any]) -> Self: - """Allocate the view; skips ``Tool.__new__``'s function overloads.""" - del action - return object.__new__(cls) - def __init__(self, action: Action[InputT, OutputT, ChunkT, Any]) -> None: self._wire_action = None Action.__init__( diff --git a/packages/genkit/tests/genkit/ai/tool_response_contract_test.py b/packages/genkit/tests/genkit/ai/tool_response_contract_test.py index 026d65742..1137e187b 100644 --- a/packages/genkit/tests/genkit/ai/tool_response_contract_test.py +++ b/packages/genkit/tests/genkit/ai/tool_response_contract_test.py @@ -569,7 +569,7 @@ async def shot() -> ShotOut: # constructors yet and infers Tool[Any, Any]; @ai.tool() is typed for it. assert_type(Tool(add_pair), Tool[Pair, int]) # ty: ignore[type-assertion-failure] assert_type(Tool(add_pair_ctx_first), Tool[Pair, int]) # ty: ignore[type-assertion-failure] - assert_type(Tool(whoami), Tool[Any, str]) # ty: ignore[type-assertion-failure] + assert_type(Tool(whoami), Tool[None, str]) # ty: ignore[type-assertion-failure] assert_type(Tool(double), Tool[int, int]) # ty: ignore[type-assertion-failure] assert_type(Tool(shot, name='shot'), Tool[None, ShotOut]) # ty: ignore[type-assertion-failure] @@ -717,7 +717,7 @@ async def specials() -> str: # ambiguous. No arrangement fixes it without breaking `(ctx: ToolContext)`. assert_type(ai.tool(echo_any), Tool[Any, str]) # ty: ignore[type-assertion-failure] assert_type(ai.tool(echo_object), Tool[Any, str]) - assert_type(ai.tool(whoami), Tool[Any, str]) # ty: ignore[type-assertion-failure] + assert_type(ai.tool(whoami), Tool[None, str]) assert_type(ai.tool(ctx_then_any), Tool[Any, str]) # ty: ignore[type-assertion-failure] assert_type(ai.tool()(ctx_then_any), Tool[Any, str]) # ty: ignore[type-assertion-failure] assert_type(ai.tool()(echo_object), Tool[Any, str]) From 047575fdb8e7917a804f89c614b53164cc919428 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 16 Nov 2026 10:35:04 -0600 Subject: [PATCH 08/20] fix(py): keep ModelFn and McpServerEntry out of the public exports 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. --- .../genkit-mcp/src/genkit_mcp/__init__.py | 3 +-- packages/genkit-mcp/tests/mcp_exports_test.py | 2 +- packages/genkit/src/genkit/_ai/_model.py | 5 ----- packages/genkit/src/genkit/model/__init__.py | 2 -- .../genkit/core/public_types_runtime_test.py | 15 -------------- .../typecheck/action_and_ref_contract_test.py | 20 ++++--------------- 6 files changed, 6 insertions(+), 41 deletions(-) diff --git a/packages/genkit-mcp/src/genkit_mcp/__init__.py b/packages/genkit-mcp/src/genkit_mcp/__init__.py index 3560a5479..23ff50d55 100644 --- a/packages/genkit-mcp/src/genkit_mcp/__init__.py +++ b/packages/genkit-mcp/src/genkit_mcp/__init__.py @@ -20,7 +20,6 @@ """ from genkit_mcp._client import McpClient, define_mcp_client -from genkit_mcp._config import McpServerEntry from genkit_mcp._host import McpHost, define_mcp_host -__all__ = ['McpClient', 'McpHost', 'McpServerEntry', 'define_mcp_client', 'define_mcp_host'] +__all__ = ['McpClient', 'McpHost', 'define_mcp_client', 'define_mcp_host'] diff --git a/packages/genkit-mcp/tests/mcp_exports_test.py b/packages/genkit-mcp/tests/mcp_exports_test.py index c665a7579..9d758e5be 100644 --- a/packages/genkit-mcp/tests/mcp_exports_test.py +++ b/packages/genkit-mcp/tests/mcp_exports_test.py @@ -20,6 +20,6 @@ def test_the_package_exports_exactly_its_public_surface() -> None: - assert genkit_mcp.__all__ == ['McpClient', 'McpHost', 'McpServerEntry', 'define_mcp_client', 'define_mcp_host'] + assert genkit_mcp.__all__ == ['McpClient', 'McpHost', 'define_mcp_client', 'define_mcp_host'] for name in genkit_mcp.__all__: assert getattr(genkit_mcp, name) is not None diff --git a/packages/genkit/src/genkit/_ai/_model.py b/packages/genkit/src/genkit/_ai/_model.py index 9cb4c19f2..69a587dc4 100644 --- a/packages/genkit/src/genkit/_ai/_model.py +++ b/packages/genkit/src/genkit/_ai/_model.py @@ -71,11 +71,6 @@ # Type alias for model functions (must be async) # Use ctx.send_chunk() for streaming ModelFn = Callable[[ModelRequest, ModelContext], Awaitable[ModelResponse[Any]]] -"""Signature of the function passed to ``define_model``. - -An async function taking the ``ModelRequest`` and a ``ModelContext``; stream -with ``ctx.send_chunk(...)`` and return the final ``ModelResponse``. -""" logger = get_logger(__name__) diff --git a/packages/genkit/src/genkit/model/__init__.py b/packages/genkit/src/genkit/model/__init__.py index 003a952a5..72046a9e4 100644 --- a/packages/genkit/src/genkit/model/__init__.py +++ b/packages/genkit/src/genkit/model/__init__.py @@ -19,7 +19,6 @@ from genkit._ai._background_model import BackgroundModel from genkit._ai._model import ( Model, - ModelFn, ) from genkit._core._action import ModelContext from genkit._core._model import ( @@ -43,7 +42,6 @@ __all__ = [ # Models, request and context types 'Model', - 'ModelFn', 'BackgroundModel', 'GenerateActionOptions', 'ModelContext', diff --git a/packages/genkit/tests/genkit/core/public_types_runtime_test.py b/packages/genkit/tests/genkit/core/public_types_runtime_test.py index 614f000bf..53e06dbd1 100644 --- a/packages/genkit/tests/genkit/core/public_types_runtime_test.py +++ b/packages/genkit/tests/genkit/core/public_types_runtime_test.py @@ -62,21 +62,6 @@ def test_generation_usage_from_messages_counts_characters() -> None: assert usage.output_characters == len('Booked') -@pytest.mark.parametrize( - ('module', 'names'), - [ - ('genkit.model', ['ModelFn']), - ('genkit_mcp', ['McpServerEntry']), - ], -) -def test_signature_types_are_exported(module: str, names: list[str]) -> None: - """Types that appear in public signatures import from their canonical module.""" - mod = importlib.import_module(module) - for name in names: - assert name in mod.__all__, f'{module}.{name}' - assert hasattr(mod, name) - - @pytest.mark.parametrize( ('module', 'names'), [ diff --git a/packages/genkit/tests/typecheck/action_and_ref_contract_test.py b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py index e253bafbf..0e67e5ea0 100644 --- a/packages/genkit/tests/typecheck/action_and_ref_contract_test.py +++ b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py @@ -16,7 +16,7 @@ # pyright: reportUnnecessaryTypeIgnoreComment=true -"""Type-checker contract for Action input overloads, Ref invariance, and public exports. +"""Type-checker contract for Action input overloads and Ref invariance. Checked by pyright, pyrefly, and ty with unused-ignore errors enabled so every negative assertion below must fail all three type checkers. @@ -25,7 +25,6 @@ from typing import Any import pytest -from genkit_mcp import McpServerEntry from pydantic import BaseModel from typing_extensions import assert_type @@ -44,7 +43,7 @@ ) from genkit._core._action import ActionResponse from genkit.embedder import EmbedderRef, EmbedRequest, EmbedResponse -from genkit.model import ModelConfig, ModelContext, ModelFn, ModelRef, ModelRequest +from genkit.model import ModelConfig, ModelContext, ModelRef, ModelRequest from genkit.plugin_api import Action, ActionKind @@ -73,19 +72,8 @@ class OtherEmbedConfig(BaseModel): @pytest.mark.asyncio -async def test_public_signature_exports_and_action_response() -> None: - """``ModelFn`` and ``McpServerEntry`` import cleanly and ``action.run`` preserves ``ActionResponse[T]``.""" - ai = Genkit() - - async def bistro_model(req: ModelRequest, ctx: ModelContext) -> ModelResponse[Any]: - del req, ctx - return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('Smoked Salmon Tartine')])) - - fn: ModelFn = bistro_model - ai.define_model(name='bistro/chef', fn=fn) - - entry: McpServerEntry = {'command': 'npx'} - assert entry['command'] == 'npx' +async def test_action_run_preserves_action_response() -> None: + """``action.run`` preserves ``ActionResponse[T]``.""" async def bill_order(order: OrderReq) -> Invoice: return Invoice(total_cents=1800 if order.dish == 'tartine' else 1200) From 74676ca79482d76145b1f5cd05c2ce4eca52b08e Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 16 Nov 2026 10:35:04 -0600 Subject: [PATCH 09/20] fix(py): restore typed GenerationUsage.from_messages signature Sequence[object] dropped argument checking on a public classmethod and rebuilt every message per call. Back to Sequence[Message]/Message. --- packages/genkit/src/genkit/_core/_typing.py | 14 ++++++++----- .../genkit/core/public_types_runtime_test.py | 3 +-- scripts/schema_to_typing.py | 20 +++++++++---------- 3 files changed, 20 insertions(+), 17 deletions(-) diff --git a/packages/genkit/src/genkit/_core/_typing.py b/packages/genkit/src/genkit/_core/_typing.py index c8b276753..ebf4f3d84 100644 --- a/packages/genkit/src/genkit/_core/_typing.py +++ b/packages/genkit/src/genkit/_core/_typing.py @@ -20,8 +20,7 @@ from __future__ import annotations -from collections.abc import Sequence # noqa: TC003 - get_type_hints(GenerationUsage.from_messages) needs it -from typing import Any, ClassVar, Literal +from typing import TYPE_CHECKING, Any, ClassVar, Literal from pydantic import ConfigDict, Field, RootModel from pydantic.alias_generators import to_camel @@ -29,6 +28,11 @@ from genkit._core._base import GenkitConfig, GenkitModel from genkit._core._compat import StrEnum +if TYPE_CHECKING: + from collections.abc import Sequence + + from genkit._core import _model + class AgentFinishReason(StrEnum): """AgentFinishReason data type class.""" @@ -481,11 +485,11 @@ class GenerationUsage(GenkitModel): cache_write_tokens: float | None = None @classmethod - def from_messages(cls, messages: Sequence[object], response: object) -> GenerationUsage: + def from_messages(cls, messages: Sequence[_model.Message], response: _model.Message) -> GenerationUsage: """Character and media counts for the request messages and the model reply.""" - from genkit._core._model import as_message, count_message_usage # noqa: PLC0415 - _model imports this module + from genkit._core._model import count_message_usage # noqa: PLC0415 - _model imports this module - return cls.model_validate(count_message_usage([as_message(m) for m in messages], as_message(response))) + return cls.model_validate(count_message_usage(messages, response)) class MediaPart(GenkitModel): diff --git a/packages/genkit/tests/genkit/core/public_types_runtime_test.py b/packages/genkit/tests/genkit/core/public_types_runtime_test.py index 53e06dbd1..6ceffd996 100644 --- a/packages/genkit/tests/genkit/core/public_types_runtime_test.py +++ b/packages/genkit/tests/genkit/core/public_types_runtime_test.py @@ -42,7 +42,6 @@ BackgroundAction.lookup, BackgroundModel.__init__, BackgroundModel.lookup, - GenerationUsage.from_messages, ], ids=lambda t: t.__qualname__, ) @@ -52,7 +51,7 @@ def test_public_annotations_resolve_at_runtime(target: object) -> None: def test_generation_usage_from_messages_counts_characters() -> None: - """from_messages still counts the request and reply after the signature change.""" + """from_messages counts characters in the request messages and the reply.""" usage = GenerationUsage.from_messages( [Message(role=Role.USER, content=[Part.from_text('Table for two')])], Message(role=Role.MODEL, content=[Part.from_text('Booked')]), diff --git a/scripts/schema_to_typing.py b/scripts/schema_to_typing.py index d3ab07f8d..ce69fefb1 100644 --- a/scripts/schema_to_typing.py +++ b/scripts/schema_to_typing.py @@ -137,8 +137,7 @@ def _output_name(name: str) -> str: from __future__ import annotations -from collections.abc import Sequence # noqa: TC003 - get_type_hints(GenerationUsage.from_messages) needs it -from typing import Any, ClassVar, Literal +from typing import TYPE_CHECKING, Any, ClassVar, Literal from pydantic import ConfigDict, Field, RootModel from pydantic.alias_generators import to_camel @@ -146,6 +145,11 @@ def _output_name(name: str) -> str: from genkit._core._base import GenkitConfig, GenkitModel from genkit._core._compat import StrEnum +if TYPE_CHECKING: + from collections.abc import Sequence + + from genkit._core import _model + ''' @@ -434,15 +438,11 @@ def _emit_model( lines.extend([ '', ' @classmethod', - # Annotated as object, not _model.Message: _model imports this - # module, so its names can't resolve here and - # typing.get_type_hints() would raise NameError. as_message - # normalizes wire MessageData and dicts at runtime. - ' def from_messages(cls, messages: Sequence[object], response: object) -> GenerationUsage:', + ' def from_messages(cls, messages: Sequence[_model.Message], response: _model.Message) -> GenerationUsage:', ' """Character and media counts for the request messages and the model reply."""', - ' from genkit._core._model import as_message, count_message_usage # noqa: PLC0415 - _model imports this module', + ' from genkit._core._model import count_message_usage # noqa: PLC0415 - _model imports this module', '', - ' return cls.model_validate(count_message_usage([as_message(m) for m in messages], as_message(response)))', + ' return cls.model_validate(count_message_usage(messages, response))', ]) return lines + [''] @@ -575,7 +575,7 @@ def generate(schema_path: Path, _out: Path) -> str: ]) content = '\n'.join(out) - # Schema refs to Message are the wire MessageData; the public Message lives in _model. + # _model.Message is the public Message (GenerationUsage.from_messages), not the wire type. content = re.sub(r'(? Date: Mon, 16 Nov 2026 11:30:12 -0600 Subject: [PATCH 10/20] fix(py): keep McpServerEntry exported for mcp_servers built in a variable 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. --- .../genkit-mcp/src/genkit_mcp/__init__.py | 3 +- packages/genkit-mcp/tests/mcp_exports_test.py | 2 +- .../typecheck/mcp_host_entry_contract_test.py | 42 +++++++++++++++++++ .../references/plugins.md | 5 ++- 4 files changed, 48 insertions(+), 4 deletions(-) create mode 100644 packages/genkit-mcp/tests/typecheck/mcp_host_entry_contract_test.py diff --git a/packages/genkit-mcp/src/genkit_mcp/__init__.py b/packages/genkit-mcp/src/genkit_mcp/__init__.py index 23ff50d55..3560a5479 100644 --- a/packages/genkit-mcp/src/genkit_mcp/__init__.py +++ b/packages/genkit-mcp/src/genkit_mcp/__init__.py @@ -20,6 +20,7 @@ """ from genkit_mcp._client import McpClient, define_mcp_client +from genkit_mcp._config import McpServerEntry from genkit_mcp._host import McpHost, define_mcp_host -__all__ = ['McpClient', 'McpHost', 'define_mcp_client', 'define_mcp_host'] +__all__ = ['McpClient', 'McpHost', 'McpServerEntry', 'define_mcp_client', 'define_mcp_host'] diff --git a/packages/genkit-mcp/tests/mcp_exports_test.py b/packages/genkit-mcp/tests/mcp_exports_test.py index 9d758e5be..c665a7579 100644 --- a/packages/genkit-mcp/tests/mcp_exports_test.py +++ b/packages/genkit-mcp/tests/mcp_exports_test.py @@ -20,6 +20,6 @@ def test_the_package_exports_exactly_its_public_surface() -> None: - assert genkit_mcp.__all__ == ['McpClient', 'McpHost', 'define_mcp_client', 'define_mcp_host'] + assert genkit_mcp.__all__ == ['McpClient', 'McpHost', 'McpServerEntry', 'define_mcp_client', 'define_mcp_host'] for name in genkit_mcp.__all__: assert getattr(genkit_mcp, name) is not None diff --git a/packages/genkit-mcp/tests/typecheck/mcp_host_entry_contract_test.py b/packages/genkit-mcp/tests/typecheck/mcp_host_entry_contract_test.py new file mode 100644 index 000000000..3b87895a1 --- /dev/null +++ b/packages/genkit-mcp/tests/typecheck/mcp_host_entry_contract_test.py @@ -0,0 +1,42 @@ +# 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 + +"""Type-checker contract for building ``mcp_servers`` away from the call. + +A dict literal assigned to a variable infers as ``dict[str, dict[str, str]]`` +and fails every checker against ``Mapping[str, McpServerEntry]``. Annotating +the variable with the exported ``McpServerEntry`` is the typed way to do it. +""" + +from genkit_mcp import McpHost, McpServerEntry, define_mcp_host +from typing_extensions import assert_type + +from genkit import Genkit + + +def test_servers_built_in_a_variable_pass_define_mcp_host() -> None: + """``dict[str, McpServerEntry]`` built ahead of the call type-checks and registers.""" + ai = Genkit() + + # 1. Build the servers block once, e.g. from app settings + servers: dict[str, McpServerEntry] = { + 'menu': {'command': 'uvx', 'args': ['menu-mcp-server']}, + 'orders': {'command': 'npx', 'args': ['orders-mcp'], 'env': {'REGION': 'us'}}, + } + + # 2. Pass it to the host; connection is lazy, so nothing starts here + host = define_mcp_host(ai, 'bistro', mcp_servers=servers) + assert_type(host, McpHost) diff --git a/skills/contributing-to-genkit-python/references/plugins.md b/skills/contributing-to-genkit-python/references/plugins.md index d92817d9a..dbe110bce 100644 --- a/skills/contributing-to-genkit-python/references/plugins.md +++ b/skills/contributing-to-genkit-python/references/plugins.md @@ -8,7 +8,7 @@ The package root `__init__.py` is the only file that exports anything, and its ` ```text genkit_mcp/ - __init__.py # McpClient, McpHost, define_mcp_client, define_mcp_host + __init__.py # McpClient, McpHost, McpServerEntry, define_mcp_client, define_mcp_host _client.py _config.py # McpStdioServerConfig: not exported _connection.py @@ -20,7 +20,8 @@ genkit_mcp/ A name goes in `__all__` only if a user constructs it, calls it, or writes it in an annotation, and there's no simpler way to do that. Leave it out if: -- it only names a shape a parameter already accepts. A `TypedDict` for a dict argument or an alias for a callback type adds an import and nothing else. +- it only names a shape a parameter already accepts and the user has a better typed path. An alias for a callback type adds an import and nothing else, since a `def` keeps its signature wherever it's written. A `TypedDict` that mirrors a typed config class (the user should import the family config instead) is the same. + - Exception: export a `TypedDict` when it's the only typed way to build the argument away from the call. A dict literal assigned to a variable infers as `dict[str, ...]` and fails pyright, pyrefly and ty against the `TypedDict` parameter, so without the name the user can only write it inline. `genkit_mcp.McpServerEntry` for `mcp_servers=` is the example. - it belongs to a request or response the user never makes directly. - it declares no fields of its own. A config class that accepts anything does nothing a dict doesn't. - it's a nested config class the user would have to build by hand. See the next section. From 756770e754c9b4d41e1ef00d5a3a9bd75e2ae9b7 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 16 Nov 2026 11:45:09 -0600 Subject: [PATCH 11/20] fix(py): let flows and tools with a defaulted input run with no input 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. --- packages/genkit/src/genkit/_ai/_aio.py | 37 ++++++++++- packages/genkit/src/genkit/_ai/_decorators.py | 18 ++++- packages/genkit/src/genkit/_ai/_tools.py | 24 ++++++- packages/genkit/src/genkit/_core/_action.py | 66 ++++++++++++++++++- packages/genkit/src/genkit/_core/_flow.py | 41 ++++++++++++ packages/genkit/src/genkit/_core/_tool.py | 22 +++++++ .../tests/genkit/ai/flow_signature_test.py | 4 +- .../typecheck/action_and_ref_contract_test.py | 40 ++++++++++- 8 files changed, 241 insertions(+), 11 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index c418057df..3c92593bb 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -83,7 +83,14 @@ to_generate_options, ) from genkit._ai._tools import define_interrupt -from genkit._core._action import Action, ActionKind, FlowContext, get_current_context +from genkit._core._action import ( + Action, + ActionKind, + CtxDefaultInputFn, + DefaultInputFn, + FlowContext, + get_current_context, +) from genkit._core._background import missing_operation_error from genkit._core._channel import run_loop from genkit._core._config_check import layer_call_config @@ -325,6 +332,13 @@ def flow( /, ) -> Flow[InputT, OutputT, ChunkT]: ... + @overload + def flow( + self, + func: CtxDefaultInputFn[FlowContext[ChunkT], InputT, OutputT], + /, + ) -> Flow[InputT | None, OutputT, ChunkT]: ... + @overload def flow( self, @@ -346,6 +360,13 @@ def flow( /, ) -> Flow[None, OutputT, ChunkT]: ... + @overload + def flow( + self, + func: DefaultInputFn[InputT, OutputT], + /, + ) -> Flow[InputT | None, OutputT]: ... + @overload def flow( self, @@ -492,6 +513,13 @@ def tool( /, ) -> Tool[InputT, OutputT, ChunkT]: ... + @overload + def tool( + self, + func: CtxDefaultInputFn[ToolContext[ChunkT], InputT, OutputT], + /, + ) -> Tool[InputT | None, OutputT, ChunkT]: ... + @overload def tool( self, @@ -513,6 +541,13 @@ def tool( /, ) -> Tool[None, OutputT, ChunkT]: ... + @overload + def tool( + self, + func: DefaultInputFn[InputT, OutputT], + /, + ) -> Tool[InputT | None, OutputT]: ... + @overload def tool( self, diff --git a/packages/genkit/src/genkit/_ai/_decorators.py b/packages/genkit/src/genkit/_ai/_decorators.py index d16399632..023055543 100644 --- a/packages/genkit/src/genkit/_ai/_decorators.py +++ b/packages/genkit/src/genkit/_ai/_decorators.py @@ -24,7 +24,7 @@ from pydantic import BaseModel from genkit._ai._tools import define_tool -from genkit._core._action import FlowContext +from genkit._core._action import CtxDefaultInputFn, DefaultInputFn, FlowContext from genkit._core._flow import Flow, define_flow from genkit._core._registry import Registry from genkit._core._tool import Tool, ToolContext @@ -65,6 +65,11 @@ def __call__( self, func: Callable[[InputT, FlowContext[ChunkT]], Awaitable[OutputT]] ) -> Flow[InputT, OutputT, ChunkT]: ... + @overload + def __call__( + self, func: CtxDefaultInputFn[FlowContext[ChunkT], InputT, OutputT] + ) -> Flow[InputT | None, OutputT, ChunkT]: ... + @overload def __call__( self, func: Callable[[FlowContext[ChunkT], InputT], Awaitable[OutputT]] @@ -76,6 +81,9 @@ def __call__(self, func: Callable[[object], Awaitable[OutputT]]) -> Flow[Any, Ou @overload def __call__(self, func: Callable[[FlowContext[ChunkT]], Awaitable[OutputT]]) -> Flow[None, OutputT, ChunkT]: ... + @overload + def __call__(self, func: DefaultInputFn[InputT, OutputT]) -> Flow[InputT | None, OutputT]: ... + @overload def __call__(self, func: Callable[[InputT], Awaitable[OutputT]]) -> Flow[InputT, OutputT]: ... @@ -113,6 +121,11 @@ def __call__( self, func: Callable[[InputT, ToolContext[ChunkT]], Awaitable[OutputT]] ) -> Tool[InputT, OutputT, ChunkT]: ... + @overload + def __call__( + self, func: CtxDefaultInputFn[ToolContext[ChunkT], InputT, OutputT] + ) -> Tool[InputT | None, OutputT, ChunkT]: ... + @overload def __call__( self, func: Callable[[ToolContext[ChunkT], InputT], Awaitable[OutputT]] @@ -124,6 +137,9 @@ def __call__(self, func: Callable[[object], Awaitable[OutputT]]) -> Tool[Any, Ou @overload def __call__(self, func: Callable[[ToolContext[ChunkT]], Awaitable[OutputT]]) -> Tool[None, OutputT, ChunkT]: ... + @overload + def __call__(self, func: DefaultInputFn[InputT, OutputT]) -> Tool[InputT | None, OutputT]: ... + @overload def __call__(self, func: Callable[[InputT], Awaitable[OutputT]]) -> Tool[InputT, OutputT]: ... diff --git a/packages/genkit/src/genkit/_ai/_tools.py b/packages/genkit/src/genkit/_ai/_tools.py index fc471a131..3c1080291 100644 --- a/packages/genkit/src/genkit/_ai/_tools.py +++ b/packages/genkit/src/genkit/_ai/_tools.py @@ -21,7 +21,7 @@ from pydantic import BaseModel, ValidationError -from genkit._core._action import Action +from genkit._core._action import Action, CtxDefaultInputFn, DefaultInputFn from genkit._core._error import ErrorReason, GenkitError, Interrupt as Interrupt from genkit._core._logger import get_logger from genkit._core._middleware import MiddlewareContext @@ -310,6 +310,17 @@ def define_tool( ) -> _Tool[ToolInputT, ToolOutputT, ToolChunkT]: ... +@overload +def define_tool( + registry: Registry, + func: CtxDefaultInputFn[ToolContext[ToolChunkT], ToolInputT, ToolOutputT], + name: str | None = None, + description: str | None = None, + *, + input_schema: type[BaseModel] | dict[str, object] | None = None, +) -> _Tool[ToolInputT | None, ToolOutputT, ToolChunkT]: ... + + @overload def define_tool( registry: Registry, @@ -343,6 +354,17 @@ def define_tool( ) -> _Tool[None, ToolOutputT, ToolChunkT]: ... +@overload +def define_tool( + registry: Registry, + func: DefaultInputFn[ToolInputT, ToolOutputT], + name: str | None = None, + description: str | None = None, + *, + input_schema: type[BaseModel] | dict[str, object] | None = None, +) -> _Tool[ToolInputT | None, ToolOutputT]: ... + + @overload def define_tool( registry: Registry, diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index 9db9d8113..0590b46f5 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -34,6 +34,7 @@ ClassVar, Generic, NamedTuple, + Protocol, Union, cast, get_args, @@ -840,6 +841,35 @@ def create_action_key(kind: ActionKind | str, name: str) -> str: OutputT = TypeVar('OutputT', default=Any) ChunkT = TypeVar('ChunkT', default=Any) InitT = TypeVar('InitT', default=Any) +# Solves the T in Action[T | None, ...]: an action whose input has a default. +_OptInputT = TypeVar('_OptInputT') +_FnInputT_contra = TypeVar('_FnInputT_contra', contravariant=True) +_FnCtxT_contra = TypeVar('_FnCtxT_contra', contravariant=True) +_FnOutputT_co = TypeVar('_FnOutputT_co', covariant=True) + + +class DefaultInputFn(Protocol[_FnInputT_contra, _FnOutputT_co]): + """An action function whose one input has a default: ``async def greet(name: str = 'world')``. + + ``Callable`` can't say a parameter is optional, so the flow and tool + overloads match this first and type the action ``Flow[str | None, ...]``. + That's what lets ``await greet()`` type-check while ``await + create_invoice()`` on a required input doesn't. + """ + + def __call__(self, input: _FnInputT_contra = ..., /) -> Awaitable[_FnOutputT_co]: ... # noqa: A002 + + +class CtxDefaultInputFn(Protocol[_FnCtxT_contra, _FnInputT_contra, _FnOutputT_co]): + """``DefaultInputFn`` with the context first: ``async def greet(ctx: FlowContext, name: str = 'world')``.""" + + def __call__( + self, + ctx: _FnCtxT_contra, + input: _FnInputT_contra = ..., # noqa: A002 + /, + ) -> Awaitable[_FnOutputT_co]: ... + # Generic streaming callback - use Callable[[ChunkT], None] for typed chunks # This untyped version is for internal use where chunk type is unknown @@ -1228,6 +1258,14 @@ async def __call__( context: dict[str, Any] | None = None, ) -> OutputT: ... + @overload + async def __call__( + self: Action[_OptInputT | None, OutputT, ChunkT, InitT], + input: _OptInputT | None = None, + *, + context: dict[str, Any] | None = None, + ) -> OutputT: ... + @overload async def __call__( self, @@ -1256,6 +1294,17 @@ async def run( init: InitT | None = None, ) -> ActionResponse[OutputT]: ... + @overload + async def run( + self: Action[_OptInputT | None, OutputT, ChunkT, InitT], + input: _OptInputT | None = None, + *, + on_chunk: Callable[[ChunkT], None] | None = None, + context: dict[str, Any] | None = None, + telemetry_labels: dict[str, object] | None = None, + init: InitT | None = None, + ) -> ActionResponse[OutputT]: ... + @overload async def run( self, @@ -1279,9 +1328,10 @@ async def run( """Run the action and return its result with trace ids. Args: - input: The input, validated against the input schema. Omit it to use - the function's own default. On a flow, an explicit None is a - value and is validated like any other. + input: The input, validated against the input schema. Required + unless the action takes no input or its function gives the + input a default; omit it to use that default. On a flow, an + explicit None is a value and is validated like any other. on_chunk: Called with each chunk the action streams. context: Request context (auth, headers, ...), read as ``ctx.context``. telemetry_labels: Custom labels set as span attributes. @@ -1380,6 +1430,16 @@ def stream( init: InitT | None = None, ) -> StreamResponse[ChunkT, OutputT]: ... + @overload + def stream( + self: Action[_OptInputT | None, OutputT, ChunkT, InitT], + input: _OptInputT | None = None, + *, + context: dict[str, Any] | None = None, + telemetry_labels: dict[str, object] | None = None, + init: InitT | None = None, + ) -> StreamResponse[ChunkT, OutputT]: ... + @overload def stream( self, diff --git a/packages/genkit/src/genkit/_core/_flow.py b/packages/genkit/src/genkit/_core/_flow.py index 7d6dfd9e3..17230228b 100644 --- a/packages/genkit/src/genkit/_core/_flow.py +++ b/packages/genkit/src/genkit/_core/_flow.py @@ -28,6 +28,8 @@ Action, ActionKind, ChunkT, + CtxDefaultInputFn, + DefaultInputFn, FlowContext, InputT, OutputT, @@ -67,6 +69,18 @@ def __init__( description: str | None = None, ) -> None: ... + # A defaulted input types the flow Flow[T | None, ...] so a no-input call + # type-checks. These two are self-typed: the class TypeVars can't say + # `InputT | None`. + @overload + def __init__( + self: Flow[_FlowInputT | None, _FlowOutputT, _FlowChunkT], + func: CtxDefaultInputFn[FlowContext[_FlowChunkT], _FlowInputT, _FlowOutputT], + *, + name: str | None = None, + description: str | None = None, + ) -> None: ... + @overload def __init__( self, @@ -85,6 +99,15 @@ def __init__( description: str | None = None, ) -> None: ... + @overload + def __init__( + self: Flow[_FlowInputT | None, _FlowOutputT, Any], + func: DefaultInputFn[_FlowInputT, _FlowOutputT], + *, + name: str | None = None, + description: str | None = None, + ) -> None: ... + @overload def __init__( self, @@ -152,6 +175,15 @@ def define_flow( ) -> Flow[_FlowInputT, _FlowOutputT, _FlowChunkT]: ... +@overload +def define_flow( + registry: Registry, + func: CtxDefaultInputFn[FlowContext[_FlowChunkT], _FlowInputT, _FlowOutputT], + name: str | None = None, + description: str | None = None, +) -> Flow[_FlowInputT | None, _FlowOutputT, _FlowChunkT]: ... + + @overload def define_flow( registry: Registry, @@ -179,6 +211,15 @@ def define_flow( ) -> Flow[None, _FlowOutputT, _FlowChunkT]: ... +@overload +def define_flow( + registry: Registry, + func: DefaultInputFn[_FlowInputT, _FlowOutputT], + name: str | None = None, + description: str | None = None, +) -> Flow[_FlowInputT | None, _FlowOutputT]: ... + + @overload def define_flow( registry: Registry, diff --git a/packages/genkit/src/genkit/_core/_tool.py b/packages/genkit/src/genkit/_core/_tool.py index 559dab4c2..2d1f44f91 100644 --- a/packages/genkit/src/genkit/_core/_tool.py +++ b/packages/genkit/src/genkit/_core/_tool.py @@ -32,6 +32,8 @@ Action, ActionContext, ActionKind, + CtxDefaultInputFn, + DefaultInputFn, get_func_description, resolve_type_hints, ) @@ -369,6 +371,16 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... + @overload + def __init__( + self: Tool[_I | None, _O, _C], + func: CtxDefaultInputFn[ToolContext[_C], _I, _O], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> None: ... + @overload def __init__( self: Tool[_I, _O, _C], @@ -399,6 +411,16 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... + @overload + def __init__( + self: Tool[_I | None, _O, Any], + func: DefaultInputFn[_I, _O], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> None: ... + @overload def __init__( self: Tool[_I, _O, Any], diff --git a/packages/genkit/tests/genkit/ai/flow_signature_test.py b/packages/genkit/tests/genkit/ai/flow_signature_test.py index 30e758756..56d89a126 100644 --- a/packages/genkit/tests/genkit/ai/flow_signature_test.py +++ b/packages/genkit/tests/genkit/ai/flow_signature_test.py @@ -404,7 +404,7 @@ async def with_default(dish: str = 'soup') -> str: assert_type(ai.flow(stream_order), Flow[_Order, str, str]) assert_type(ai.flow(stream_any), Flow[Any, str, str]) # ty: ignore[type-assertion-failure] assert_type(ai.flow(specials), Flow[None, str]) - assert_type(ai.flow(with_default), Flow[str, str]) + assert_type(ai.flow(with_default), Flow[str | None, str]) # 2. Standalone Flow(fn). An __init__ overload can't pin InputT to None, # so ctx-only and no-arg flows leave it at its Any default. @@ -416,7 +416,7 @@ async def with_default(dish: str = 'soup') -> str: assert_type(Flow(stream_order), Flow[_Order, str, str]) assert_type(Flow(stream_any), Flow[Any, str, str]) assert_type(Flow(specials), Flow[Any, str]) - assert_type(Flow(with_default), Flow[str, str]) + assert_type(Flow(with_default), Flow[str | None, str]) # ty: ignore[type-assertion-failure] # 3. An Any/object flow takes any input at the call site. echo = Flow(echo_object) diff --git a/packages/genkit/tests/typecheck/action_and_ref_contract_test.py b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py index 0e67e5ea0..5709da958 100644 --- a/packages/genkit/tests/typecheck/action_and_ref_contract_test.py +++ b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py @@ -31,6 +31,7 @@ from genkit import ( Document, Embedding, + Flow, FlowContext, Genkit, GenkitError, @@ -39,6 +40,7 @@ Part, Role, StreamResponse, + Tool, ToolContext, ) from genkit._core._action import ActionResponse @@ -130,13 +132,45 @@ async def list_specials(ctx: ToolContext) -> list[str]: assert_type(await list_specials(), list[str]) with pytest.raises(GenkitError): - await create_invoice() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] + await create_invoice() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] with pytest.raises(GenkitError): - await create_invoice.run() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] + await create_invoice.run() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] with pytest.raises(GenkitError): - await lookup_allergens() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] + await lookup_allergens() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + + +@pytest.mark.asyncio +async def test_defaulted_inputs_can_be_omitted() -> None: + """A flow or tool whose input has a default types as ``[T | None, ...]`` and runs with no input.""" + ai = Genkit() + + @ai.flow + async def suggest_dish(cuisine: str = 'french') -> str: + return f'{cuisine}: tartine' + + @ai.flow + async def reprint_receipt(order: OrderReq | None = None) -> str: + return order.dish if order else 'last order' + + @ai.tool + async def todays_soup(day: str = 'monday') -> str: + return f'{day}: bouillabaisse' + + assert_type(suggest_dish, Flow[str | None, str]) + assert_type(reprint_receipt, Flow[OrderReq | None, str]) + assert_type(todays_soup, Tool[str | None, str]) + + assert await suggest_dish() == 'french: tartine' + assert await suggest_dish('thai') == 'thai: tartine' + assert (await suggest_dish.run()).response == 'french: tartine' + assert await suggest_dish.stream().response == 'french: tartine' + assert await reprint_receipt() == 'last order' + assert await todays_soup() == 'monday: bouillabaisse' + + with pytest.raises(GenkitError): + await suggest_dish(3) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] @pytest.mark.asyncio From 2d3806a4496faf768455b0756e2e2acd40c2f8c2 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 16 Nov 2026 11:45:52 -0600 Subject: [PATCH 12/20] fix(py): make action input contravariant 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. --- .../src/genkit_fastapi/_handler.py | 2 +- packages/genkit/src/genkit/_core/_action.py | 11 ++++--- packages/genkit/src/genkit/_core/_tool.py | 5 +-- .../typecheck/action_and_ref_contract_test.py | 32 +++++++++++++++++++ 4 files changed, 43 insertions(+), 7 deletions(-) diff --git a/packages/genkit-fastapi/src/genkit_fastapi/_handler.py b/packages/genkit-fastapi/src/genkit_fastapi/_handler.py index 2df58502c..ccee6d0e4 100644 --- a/packages/genkit-fastapi/src/genkit_fastapi/_handler.py +++ b/packages/genkit-fastapi/src/genkit_fastapi/_handler.py @@ -309,7 +309,7 @@ async def handler(request: Request) -> Response: return await handle_genkit_request( request, - action=cast(Action[InputT, OutputT, ChunkT, InitT], action), # ty: ignore[redundant-cast] + action=cast(Action[InputT, OutputT, ChunkT, InitT], action), context=action_context, ) diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index 0590b46f5..2654ce1af 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -837,7 +837,10 @@ def create_action_key(kind: ActionKind | str, name: str) -> str: # Action core # ============================================================================= -InputT = TypeVar('InputT', default=Any) +# Contravariant: an action that accepts more inputs can stand in where fewer +# are expected, so Flow[str | None, str] (a defaulted input) still fits a +# Flow[str, str] or Flow[None, str] annotation. +InputT = TypeVar('InputT', default=Any, contravariant=True) OutputT = TypeVar('OutputT', default=Any) ChunkT = TypeVar('ChunkT', default=Any) InitT = TypeVar('InitT', default=Any) @@ -1206,7 +1209,7 @@ def _action_metadata(self) -> ActionMetadata: ) @property - def input_type(self) -> TypeAdapter[InputT] | None: + def input_type(self) -> TypeAdapter[Any] | None: return self._input_type @property @@ -1676,7 +1679,7 @@ def _validate_init(self, init: InitT | None) -> InitT | None: ) ) from e - def _layer_config_defaults(self, input: InputT | None) -> InputT | None: + def _layer_config_defaults(self, input: InputT | None) -> Any: # noqa: ANN401 - InputT is contravariant """Normalize the request's config against the definition-time class. Every caller (ai.* by name or ref, the Dev UI, the CLI) reaches the fn @@ -1755,7 +1758,7 @@ def _normalized_config(self, current: object, *, schema: type[BaseModel] | dict[ validate_whole_config(config=merged, schema=schema, model=self.name) return merged - def _validate_input(self, input: InputT | None) -> InputT | None: + def _validate_input(self, input: InputT | None) -> Any: # noqa: ANN401 - InputT is contravariant """Validate caller input against the action schema when one is registered.""" omitted = input is NO_INPUT # Skip validation when the caller passed nothing AND the wrapped diff --git a/packages/genkit/src/genkit/_core/_tool.py b/packages/genkit/src/genkit/_core/_tool.py index 2d1f44f91..85c738814 100644 --- a/packages/genkit/src/genkit/_core/_tool.py +++ b/packages/genkit/src/genkit/_core/_tool.py @@ -43,7 +43,8 @@ from genkit._core._telemetry._instrumentation import set_custom_metadata_attributes from genkit._core._typing import MultipartToolResponse as MultipartToolResponseData, ToolDefinition -InputT = TypeVar('InputT', default=Any) +# Contravariant, like Action's InputT. +InputT = TypeVar('InputT', default=Any, contravariant=True) OutputT = TypeVar('OutputT', default=Any) ChunkT = TypeVar('ChunkT', default=Any) @@ -523,7 +524,7 @@ def from_action(cls, action: Action[InputT, OutputT, ChunkT, Any]) -> Tool[Input Shares the action's function and metadata; there is no ``tool.v2`` companion. """ if isinstance(action, Tool): - return action + return cast(Tool[InputT, OutputT, ChunkT], action) # pyrefly: ignore[redundant-cast] - ty needs it return _ActionTool(action) @property diff --git a/packages/genkit/tests/typecheck/action_and_ref_contract_test.py b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py index 5709da958..8f74bcd67 100644 --- a/packages/genkit/tests/typecheck/action_and_ref_contract_test.py +++ b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py @@ -173,6 +173,38 @@ async def todays_soup(day: str = 'monday') -> str: await suggest_dish(3) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] +def test_input_is_contravariant() -> None: + """A flow or tool with a defaulted input fits a required-input or no-input annotation.""" + ai = Genkit() + + @ai.flow + async def suggest_dish(cuisine: str = 'french') -> str: + return f'{cuisine}: tartine' + + @ai.tool + async def todays_soup(day: str = 'monday') -> str: + return f'{day}: bouillabaisse' + + @ai.flow + async def kitchen_status() -> str: + return 'open' + + # 1. Flow[str | None, str] accepts everything Flow[str, str] and Flow[None, str] do + by_cuisine: Flow[str, str] = suggest_dish + house_pick: Flow[None, str] = suggest_dish + + # 2. Same for tools + soup_for_day: Tool[str, str] = todays_soup + soup_today: Tool[None, str] = todays_soup + + # 3. A no-input flow can't stand in for one that needs an order + needs_order: Flow[OrderReq, str] = kitchen_status # pyright: ignore[reportAssignmentType] # pyrefly: ignore[bad-assignment] # ty: ignore[invalid-assignment] + + assert by_cuisine is house_pick + assert soup_for_day is soup_today + assert needs_order is kitchen_status + + @pytest.mark.asyncio async def test_model_and_embedder_refs_are_invariant_and_default_to_any() -> None: """Typed refs reject mismatched configs while bare ``ModelRef`` / ``EmbedderRef`` accept any ref.""" From c31cc69ab48cd06c09ecc11dfa676d39b6dff4d7 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 16 Nov 2026 11:48:26 -0600 Subject: [PATCH 13/20] fix(py)!: tools treat an explicit None as a value, like flows 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. --- packages/genkit/src/genkit/_ai/_tools.py | 6 +- packages/genkit/src/genkit/_core/_action.py | 25 ++-- .../tests/genkit/ai/tool_none_input_test.py | 122 ++++++++++++++++++ 3 files changed, 141 insertions(+), 12 deletions(-) create mode 100644 packages/genkit/tests/genkit/ai/tool_none_input_test.py diff --git a/packages/genkit/src/genkit/_ai/_tools.py b/packages/genkit/src/genkit/_ai/_tools.py index 3c1080291..e9464d461 100644 --- a/packages/genkit/src/genkit/_ai/_tools.py +++ b/packages/genkit/src/genkit/_ai/_tools.py @@ -21,7 +21,7 @@ from pydantic import BaseModel, ValidationError -from genkit._core._action import Action, CtxDefaultInputFn, DefaultInputFn +from genkit._core._action import Action, CtxDefaultInputFn, DefaultInputFn, input_from_json from genkit._core._error import ErrorReason, GenkitError, Interrupt as Interrupt from genkit._core._logger import get_logger from genkit._core._middleware import MiddlewareContext @@ -167,7 +167,9 @@ async def run_tool_request( try: return ( await tool._run( - tool_req.input, + # The model's JSON can't tell null from omitted; both mean no + # input, so a no-arg call still gets the function's default. + input_from_json(tool_req.input), on_chunk=sink, context=run_context, telemetry_labels=telemetry_labels, diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index 2654ce1af..e8120cd8b 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -381,8 +381,8 @@ def call( """Call ``fn`` with ``input`` and ``ctx`` passed by parameter name. A missing input (``NO_INPUT``) is left out when the parameter has a - default, so the default applies. An explicit None on a flow is passed - through as a value. + default, so the default applies. An explicit None on a flow or tool + is passed through as a value. """ kwargs: dict[str, object] = {} if self.input is not None: @@ -1092,8 +1092,8 @@ def __init__( context_kind = _context_kind if _context_kind is not None else kind self._context_cls: type[ActionContext[Any]] = _context_cls_for_kind(context_kind) # Flows treat None as a real value and check the return against the - # annotation. Other actions still treat a missing/None input as omitted - # and leave the return unchecked. + # annotation. Tools take None as a value too (see _run) but check + # their own return. Other actions treat None as omitted. self._strict_io: bool = _strict_io self._metadata: dict[str, object] = metadata if metadata is not None else {} self._description: str | None = description @@ -1333,8 +1333,9 @@ async def run( Args: input: The input, validated against the input schema. Required unless the action takes no input or its function gives the - input a default; omit it to use that default. On a flow, an - explicit None is a value and is validated like any other. + input a default; omit it to use that default. On a flow or + tool, an explicit None is a value and is validated like any + other. on_chunk: Called with each chunk the action streams. context: Request context (auth, headers, ...), read as ``ctx.context``. telemetry_labels: Custom labels set as span attributes. @@ -1375,9 +1376,13 @@ async def _run( omitted, a one-shot run is exactly the single ``input``. Stored on ``ctx._input_stream``; only bidi actions read it. """ - # Only a flow treats an explicit None as a value; for every other action - # None still means "no input". - if input is None and not self._strict_io: + # From Python, None is a value for flows and tools; omit the input to + # use the function's default. JSON can't tell null from omitted, so the + # wire boundaries (reflection, web adapters, a model's tool request) + # turn null into NO_INPUT with input_from_json before calling here. + # Models, embedders and the rest take a request object, where None + # still means no input. + if input is None and not (self._strict_io or self._kind in (ActionKind.TOOL, ActionKind.TOOL_V2)): input = NO_INPUT # With a live input_stream, `input` isn't the payload — the stream # carries the per-turn inputs — so there's nothing to validate up front. @@ -1931,7 +1936,7 @@ async def _invoke(self, input: object | None, ctx: ActionContext) -> OutputT: """Call ``self._fn`` with the input and context. A missing input stays ``NO_INPUT`` so a defaulted parameter gets its - default. An explicit None on a flow is passed through as a value. + default. An explicit None on a flow or tool is passed through as a value. """ if self._fn_is_wrapper: # The wrapper takes (input, ctx) and forwards to the user's diff --git a/packages/genkit/tests/genkit/ai/tool_none_input_test.py b/packages/genkit/tests/genkit/ai/tool_none_input_test.py new file mode 100644 index 000000000..e05f3fcad --- /dev/null +++ b/packages/genkit/tests/genkit/ai/tool_none_input_test.py @@ -0,0 +1,122 @@ +# Copyright 2026 Google LLC +# SPDX-License-Identifier: Apache-2.0 + +"""Tool input: an explicit None from Python is a value; null from JSON means omitted.""" + +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager + +import pytest +from httpx import ASGITransport, AsyncClient +from pydantic import BaseModel + +from genkit import Genkit, GenkitError, Message, ModelResponse, Part +from genkit._core._reflection import create_reflection_asgi_app +from genkit._core._typing import FinishReason, Role, ToolRequest +from genkit.testing import define_scripted_model + + +class Allergens(BaseModel): + nuts: bool = False + + +@pytest.mark.asyncio +async def test_tool_with_explicit_none_on_non_optional_default_raises_invalid_argument() -> None: + """`await todays_soup(None)` on `day: str = 'monday'` validates None and fails.""" + ai = Genkit() + + @ai.tool + async def todays_soup(day: str = 'monday') -> str: + return f'{day}: bouillabaisse' + + with pytest.raises(GenkitError) as exc: + await todays_soup(None) + + assert exc.value.status == 'INVALID_ARGUMENT' + + +@pytest.mark.asyncio +async def test_tool_with_no_input_uses_python_default() -> None: + """`await todays_soup()` runs with the function's default.""" + ai = Genkit() + + @ai.tool + async def todays_soup(day: str = 'monday') -> str: + return f'{day}: bouillabaisse' + + assert await todays_soup() == 'monday: bouillabaisse' + + +@pytest.mark.asyncio +async def test_tool_with_optional_input_receives_explicit_none() -> None: + """`x: Allergens | None = Allergens()` gets None when the caller passes None, the default when omitted.""" + ai = Genkit() + seen: list[Allergens | None] = [] + + @ai.tool + async def check_order(allergens: Allergens | None = Allergens(nuts=True)) -> str: # noqa: B008 + seen.append(allergens) + return 'checked' + + await check_order(None) + await check_order() + + assert seen == [None, Allergens(nuts=True)] + + +@pytest.mark.asyncio +async def test_model_tool_request_with_null_input_uses_python_default() -> None: + """A model's tool request with `input: null` runs the tool with its default.""" + ai = Genkit() + pm, _ = define_scripted_model(ai) + + @ai.tool + async def todays_soup(day: str = 'monday') -> str: + return f'{day}: bouillabaisse' + + # 1. The model calls the tool with no input, then answers + pm.responses.append( + ModelResponse( + message=Message( + role=Role.MODEL, + content=[Part(tool_request=ToolRequest(name='todays_soup', input=None, ref='r1'))], + ) + ) + ) + pm.responses.append( + ModelResponse( + finish_reason=FinishReason.STOP, + message=Message(role=Role.MODEL, content=[Part.from_text('done')]), + ) + ) + + # 2. The tool response carries the default-day soup + response = await ai.generate(model='scriptedModel', prompt="What's the soup?", tools=['todays_soup']) + part = response.messages[2].content[0] + assert part.tool_response is not None + assert part.tool_response.output == 'monday: bouillabaisse' + + +@asynccontextmanager +async def _dev_ui_client(ai: Genkit) -> AsyncIterator[AsyncClient]: + client = AsyncClient(transport=ASGITransport(app=create_reflection_asgi_app(ai._registry)), base_url='http://test') + try: + yield client + finally: + await client.aclose() + + +@pytest.mark.asyncio +async def test_dev_ui_run_tool_with_null_input_uses_python_default() -> None: + """A Dev UI runAction on a tool with `"input": null` behaves like no input.""" + ai = Genkit() + + @ai.tool + async def todays_soup(day: str = 'monday') -> str: + return f'{day}: bouillabaisse' + + async with _dev_ui_client(ai) as client: + response = await client.post('/api/runAction', json={'key': '/tool/todays_soup', 'input': None}) + + assert response.status_code == 200 + assert response.json()['result'] == 'monday: bouillabaisse' From 848b91d0e7d38381cd0a3d34d4b7e5edd1252674 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 16 Nov 2026 13:32:48 -0600 Subject: [PATCH 14/20] fix(py)!: type defaulted flows and tools as DefaultedFlow / DefaultedTool 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. --- packages/genkit/src/genkit/_ai/_aio.py | 12 +- packages/genkit/src/genkit/_ai/_decorators.py | 18 +- packages/genkit/src/genkit/_ai/_tools.py | 20 ++- packages/genkit/src/genkit/_core/_action.py | 168 ++++++++++++++---- packages/genkit/src/genkit/_core/_flow.py | 34 +++- packages/genkit/src/genkit/_core/_tool.py | 18 +- .../tests/genkit/ai/flow_signature_test.py | 5 +- .../typecheck/action_and_ref_contract_test.py | 32 ++-- 8 files changed, 225 insertions(+), 82 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 3c92593bb..d4a483d5c 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -97,7 +97,7 @@ from genkit._core._dap import DapFn, DynamicActionProvider from genkit._core._environment import is_dev_environment from genkit._core._error import ErrorReason, GenkitError, PublicError -from genkit._core._flow import Flow +from genkit._core._flow import DefaultedFlow, Flow from genkit._core._logger import ( REFLECTION_THREAD_NAME, configure_logging, @@ -130,7 +130,7 @@ from genkit._core._telemetry._attrs import metadata_key from genkit._core._telemetry._http import mark_already_sourced, maybe_inject_dev_instrumentation from genkit._core._telemetry._instrumentation import run_in_new_span -from genkit._core._tool import Tool, ToolContext +from genkit._core._tool import DefaultedTool, Tool, ToolContext from genkit._core._typing import ( Embedding, EmbedResponse, @@ -337,7 +337,7 @@ def flow( self, func: CtxDefaultInputFn[FlowContext[ChunkT], InputT, OutputT], /, - ) -> Flow[InputT | None, OutputT, ChunkT]: ... + ) -> DefaultedFlow[InputT, OutputT, ChunkT]: ... @overload def flow( @@ -365,7 +365,7 @@ def flow( self, func: DefaultInputFn[InputT, OutputT], /, - ) -> Flow[InputT | None, OutputT]: ... + ) -> DefaultedFlow[InputT, OutputT]: ... @overload def flow( @@ -518,7 +518,7 @@ def tool( self, func: CtxDefaultInputFn[ToolContext[ChunkT], InputT, OutputT], /, - ) -> Tool[InputT | None, OutputT, ChunkT]: ... + ) -> DefaultedTool[InputT, OutputT, ChunkT]: ... @overload def tool( @@ -546,7 +546,7 @@ def tool( self, func: DefaultInputFn[InputT, OutputT], /, - ) -> Tool[InputT | None, OutputT]: ... + ) -> DefaultedTool[InputT, OutputT]: ... @overload def tool( diff --git a/packages/genkit/src/genkit/_ai/_decorators.py b/packages/genkit/src/genkit/_ai/_decorators.py index 023055543..c957ea85e 100644 --- a/packages/genkit/src/genkit/_ai/_decorators.py +++ b/packages/genkit/src/genkit/_ai/_decorators.py @@ -25,9 +25,9 @@ from genkit._ai._tools import define_tool from genkit._core._action import CtxDefaultInputFn, DefaultInputFn, FlowContext -from genkit._core._flow import Flow, define_flow +from genkit._core._flow import DefaultedFlow, Flow, define_flow from genkit._core._registry import Registry -from genkit._core._tool import Tool, ToolContext +from genkit._core._tool import DefaultedTool, Tool, ToolContext # TypeVars for generic input/output typing InputT = TypeVar('InputT') @@ -45,9 +45,9 @@ def __init__(self, registry: Registry, name: str | None, description: str | None # Overload order matters: checkers pick the first matching overload. # - # - A flow with a defaulted input (`async def f(x: str = '...')`) is - # callable as both 1-arg and 0-arg, so the 1-arg shapes come first and - # the input type stays as written instead of collapsing to `None`. + # - A defaulted input (`async def f(x: str = '...')`) matches the + # Default*Fn Protocols and returns DefaultedFlow[str, ...]: the input may + # be omitted, but None isn't a str. # - `(x: Any)` and `(x: object)` also accept a FlowContext, so they'd match # the ctx-only shape and type as Flow[None, ...]. The `object` shapes # come first and catch them as Flow[Any, ...]. A real `(ctx: FlowContext)` @@ -68,7 +68,7 @@ def __call__( @overload def __call__( self, func: CtxDefaultInputFn[FlowContext[ChunkT], InputT, OutputT] - ) -> Flow[InputT | None, OutputT, ChunkT]: ... + ) -> DefaultedFlow[InputT, OutputT, ChunkT]: ... @overload def __call__( @@ -82,7 +82,7 @@ def __call__(self, func: Callable[[object], Awaitable[OutputT]]) -> Flow[Any, Ou def __call__(self, func: Callable[[FlowContext[ChunkT]], Awaitable[OutputT]]) -> Flow[None, OutputT, ChunkT]: ... @overload - def __call__(self, func: DefaultInputFn[InputT, OutputT]) -> Flow[InputT | None, OutputT]: ... + def __call__(self, func: DefaultInputFn[InputT, OutputT]) -> DefaultedFlow[InputT, OutputT]: ... @overload def __call__(self, func: Callable[[InputT], Awaitable[OutputT]]) -> Flow[InputT, OutputT]: ... @@ -124,7 +124,7 @@ def __call__( @overload def __call__( self, func: CtxDefaultInputFn[ToolContext[ChunkT], InputT, OutputT] - ) -> Tool[InputT | None, OutputT, ChunkT]: ... + ) -> DefaultedTool[InputT, OutputT, ChunkT]: ... @overload def __call__( @@ -138,7 +138,7 @@ def __call__(self, func: Callable[[object], Awaitable[OutputT]]) -> Tool[Any, Ou def __call__(self, func: Callable[[ToolContext[ChunkT]], Awaitable[OutputT]]) -> Tool[None, OutputT, ChunkT]: ... @overload - def __call__(self, func: DefaultInputFn[InputT, OutputT]) -> Tool[InputT | None, OutputT]: ... + def __call__(self, func: DefaultInputFn[InputT, OutputT]) -> DefaultedTool[InputT, OutputT]: ... @overload def __call__(self, func: Callable[[InputT], Awaitable[OutputT]]) -> Tool[InputT, OutputT]: ... diff --git a/packages/genkit/src/genkit/_ai/_tools.py b/packages/genkit/src/genkit/_ai/_tools.py index e9464d461..76b75c188 100644 --- a/packages/genkit/src/genkit/_ai/_tools.py +++ b/packages/genkit/src/genkit/_ai/_tools.py @@ -21,7 +21,14 @@ from pydantic import BaseModel, ValidationError -from genkit._core._action import Action, CtxDefaultInputFn, DefaultInputFn, input_from_json +from genkit._core._action import ( + Action, + ActionKind, + CtxDefaultInputFn, + DefaultInputFn, + input_from_json, + input_has_default, +) from genkit._core._error import ErrorReason, GenkitError, Interrupt as Interrupt from genkit._core._logger import get_logger from genkit._core._middleware import MiddlewareContext @@ -29,6 +36,7 @@ from genkit._core._registry import Registry from genkit._core._tool import ( ORIGINAL_OUTPUT_SCHEMA_KEY as ORIGINAL_OUTPUT_SCHEMA_KEY, + DefaultedTool, Tool as _Tool, ToolContext as ToolContext, _tool_original_input as _tool_original_input, @@ -275,7 +283,10 @@ def _define_tool( cases like define_interrupt where the handler signature cannot express the input shape. """ - built: _Tool[Any, Any, Any] = _Tool(func, name=name, description=description, input_schema=input_schema) + # A defaulted input builds a DefaultedTool, so isinstance agrees with + # what define_tool's overloads promise. + cls = DefaultedTool if input_has_default(func, ActionKind.TOOL) else _Tool + built: _Tool[Any, Any, Any] = cls(func, name=name, description=description, input_schema=input_schema) registry.register_action_from_instance(built) return built @@ -290,6 +301,7 @@ def _define_tool( # flow: the function takes no input, so a direct call passes none. # - ty types ``(ctx, x: Any)`` as Unknown: the typing spec's overload rule for # Any arguments makes it ambiguous, and no order fixes that. +# - A defaulted input returns ``DefaultedTool``. @overload def define_tool( registry: Registry, @@ -320,7 +332,7 @@ def define_tool( description: str | None = None, *, input_schema: type[BaseModel] | dict[str, object] | None = None, -) -> _Tool[ToolInputT | None, ToolOutputT, ToolChunkT]: ... +) -> DefaultedTool[ToolInputT, ToolOutputT, ToolChunkT]: ... @overload @@ -364,7 +376,7 @@ def define_tool( description: str | None = None, *, input_schema: type[BaseModel] | dict[str, object] | None = None, -) -> _Tool[ToolInputT | None, ToolOutputT]: ... +) -> DefaultedTool[ToolInputT, ToolOutputT]: ... @overload diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index e8120cd8b..41eb34c77 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -500,6 +500,20 @@ def find_input_and_context( return ActionParams(input=input_param, context=context_param) +def input_has_default(fn: Callable[..., object], kind: ActionKind) -> bool: + """True if ``fn``'s input parameter has a default, so the action can run with no input. + + The flow and tool factories read this to build a ``DefaultedFlow`` / + ``DefaultedTool``. A signature ``find_input_and_context`` rejects returns + False here; the action's constructor raises the real error. + """ + try: + hints = resolve_type_hints(fn, known_annotation_names(kind)) + return find_input_and_context(fn, hints, kind=kind, name='').input_optional + except (TypeError, ValueError): + return False + + def known_annotation_names(kind: ActionKind, *, context_kind: ActionKind | None = None) -> dict[str, object]: """Genkit types a handler of this kind always takes or returns, by name. @@ -838,14 +852,12 @@ def create_action_key(kind: ActionKind | str, name: str) -> str: # ============================================================================= # Contravariant: an action that accepts more inputs can stand in where fewer -# are expected, so Flow[str | None, str] (a defaulted input) still fits a -# Flow[str, str] or Flow[None, str] annotation. +# are expected, so DefaultedFlow[str, str] still fits a Flow[str, str] +# annotation, and Flow[str | None, str] fits one too. InputT = TypeVar('InputT', default=Any, contravariant=True) OutputT = TypeVar('OutputT', default=Any) ChunkT = TypeVar('ChunkT', default=Any) InitT = TypeVar('InitT', default=Any) -# Solves the T in Action[T | None, ...]: an action whose input has a default. -_OptInputT = TypeVar('_OptInputT') _FnInputT_contra = TypeVar('_FnInputT_contra', contravariant=True) _FnCtxT_contra = TypeVar('_FnCtxT_contra', contravariant=True) _FnOutputT_co = TypeVar('_FnOutputT_co', covariant=True) @@ -855,9 +867,9 @@ class DefaultInputFn(Protocol[_FnInputT_contra, _FnOutputT_co]): """An action function whose one input has a default: ``async def greet(name: str = 'world')``. ``Callable`` can't say a parameter is optional, so the flow and tool - overloads match this first and type the action ``Flow[str | None, ...]``. - That's what lets ``await greet()`` type-check while ``await - create_invoice()`` on a required input doesn't. + overloads match this first and type the action ``DefaultedFlow[str, ...]`` + / ``DefaultedTool[str, ...]``. That's what lets ``await greet()`` + type-check while ``await create_invoice()`` on a required input doesn't. """ def __call__(self, input: _FnInputT_contra = ..., /) -> Awaitable[_FnOutputT_co]: ... # noqa: A002 @@ -1261,14 +1273,6 @@ async def __call__( context: dict[str, Any] | None = None, ) -> OutputT: ... - @overload - async def __call__( - self: Action[_OptInputT | None, OutputT, ChunkT, InitT], - input: _OptInputT | None = None, - *, - context: dict[str, Any] | None = None, - ) -> OutputT: ... - @overload async def __call__( self, @@ -1297,17 +1301,6 @@ async def run( init: InitT | None = None, ) -> ActionResponse[OutputT]: ... - @overload - async def run( - self: Action[_OptInputT | None, OutputT, ChunkT, InitT], - input: _OptInputT | None = None, - *, - on_chunk: Callable[[ChunkT], None] | None = None, - context: dict[str, Any] | None = None, - telemetry_labels: dict[str, object] | None = None, - init: InitT | None = None, - ) -> ActionResponse[OutputT]: ... - @overload async def run( self, @@ -1438,16 +1431,6 @@ def stream( init: InitT | None = None, ) -> StreamResponse[ChunkT, OutputT]: ... - @overload - def stream( - self: Action[_OptInputT | None, OutputT, ChunkT, InitT], - input: _OptInputT | None = None, - *, - context: dict[str, Any] | None = None, - telemetry_labels: dict[str, object] | None = None, - init: InitT | None = None, - ) -> StreamResponse[ChunkT, OutputT]: ... - @overload def stream( self, @@ -1948,6 +1931,119 @@ async def _invoke(self, input: object | None, ctx: ActionContext) -> OutputT: return await coro +class DefaultedAction(Action[InputT, OutputT, ChunkT, InitT]): + """Call overloads for an action whose function gives the input a default. + + ``DefaultedFlow`` and ``DefaultedTool`` mix this in. The input may be + omitted, so the function's default applies. A passed input must be + ``InputT``: for ``async def todays_special(cuisine: str = 'italian')``, + ``await todays_special(None)`` is a type error, like the runtime + INVALID_ARGUMENT it would raise. + """ + + # ty (all three) and pyrefly (run, stream) flag these as bad overrides of + # Action's overloads. They aren't: Action's `self: Action[None, ...]` + # overload only applies when InputT accepts None, and then + # `input: InputT` here takes the same call. + @overload + async def __call__( + self, + *, + context: dict[str, Any] | None = None, + ) -> OutputT: ... + + @overload + async def __call__( + self, + input: InputT, + *, + context: dict[str, Any] | None = None, + ) -> OutputT: ... + + async def __call__( # ty: ignore[invalid-method-override] + self, + input: Any = NO_INPUT, # noqa: ANN401 - NO_INPUT or InputT + *, + context: dict[str, Any] | None = None, + ) -> OutputT: + """Call the action directly, returning just the response value.""" + return (await self._run(input, context=context)).response + + @overload + async def run( # pyrefly: ignore[bad-override] + self, + *, + on_chunk: Callable[[ChunkT], None] | None = None, + context: dict[str, Any] | None = None, + telemetry_labels: dict[str, object] | None = None, + init: InitT | None = None, + ) -> ActionResponse[OutputT]: ... + + @overload + async def run( + self, + input: InputT, + *, + on_chunk: Callable[[ChunkT], None] | None = None, + context: dict[str, Any] | None = None, + telemetry_labels: dict[str, object] | None = None, + init: InitT | None = None, + ) -> ActionResponse[OutputT]: ... + + async def run( # ty: ignore[invalid-method-override] + self, + input: Any = NO_INPUT, # noqa: ANN401 - NO_INPUT or InputT + *, + on_chunk: Callable[[ChunkT], None] | None = None, + context: dict[str, Any] | None = None, + telemetry_labels: dict[str, object] | None = None, + init: InitT | None = None, + ) -> ActionResponse[OutputT]: + """Run the action and return its result with trace ids. See ``Action.run``.""" + return await self._run( + input, + on_chunk=on_chunk, + context=context, + telemetry_labels=telemetry_labels, + init=init, + ) + + @overload + def stream( # pyrefly: ignore[bad-override] + self, + *, + context: dict[str, Any] | None = None, + telemetry_labels: dict[str, object] | None = None, + init: InitT | None = None, + ) -> StreamResponse[ChunkT, OutputT]: ... + + @overload + def stream( + self, + input: InputT, + *, + context: dict[str, Any] | None = None, + telemetry_labels: dict[str, object] | None = None, + init: InitT | None = None, + ) -> StreamResponse[ChunkT, OutputT]: ... + + def stream( # ty: ignore[invalid-method-override] + self, + input: Any = NO_INPUT, # noqa: ANN401 - NO_INPUT or InputT + *, + context: dict[str, Any] | None = None, + telemetry_labels: dict[str, object] | None = None, + init: InitT | None = None, + ) -> StreamResponse[ChunkT, OutputT]: + """Return a ``StreamResponse`` for chunks and the result. See ``Action.stream``.""" + return self._stream( + input, + context=context, + telemetry_labels=telemetry_labels, + init=init, + ) + + async def single_item_stream(item: InputT) -> AsyncIterator[InputT]: """Present a one-shot input as a one-item stream (no item ⇒ no turns). diff --git a/packages/genkit/src/genkit/_core/_flow.py b/packages/genkit/src/genkit/_core/_flow.py index 17230228b..3ad094644 100644 --- a/packages/genkit/src/genkit/_core/_flow.py +++ b/packages/genkit/src/genkit/_core/_flow.py @@ -29,11 +29,13 @@ ActionKind, ChunkT, CtxDefaultInputFn, + DefaultedAction, DefaultInputFn, FlowContext, InputT, OutputT, get_func_description, + input_has_default, ) from genkit._core._registry import Registry @@ -69,12 +71,12 @@ def __init__( description: str | None = None, ) -> None: ... - # A defaulted input types the flow Flow[T | None, ...] so a no-input call - # type-checks. These two are self-typed: the class TypeVars can't say - # `InputT | None`. + # The defaulted-input shapes are self-typed to DefaultedFlow, so they + # apply when define_flow builds one. Flow(fn) itself stays a Flow and + # skips them. @overload def __init__( - self: Flow[_FlowInputT | None, _FlowOutputT, _FlowChunkT], + self: DefaultedFlow[_FlowInputT, _FlowOutputT, _FlowChunkT], func: CtxDefaultInputFn[FlowContext[_FlowChunkT], _FlowInputT, _FlowOutputT], *, name: str | None = None, @@ -101,7 +103,7 @@ def __init__( @overload def __init__( - self: Flow[_FlowInputT | None, _FlowOutputT, Any], + self: DefaultedFlow[_FlowInputT, _FlowOutputT, Any], func: DefaultInputFn[_FlowInputT, _FlowOutputT], *, name: str | None = None, @@ -155,6 +157,16 @@ def __init__( ) +class DefaultedFlow(DefaultedAction[InputT, OutputT, ChunkT, None], Flow[InputT, OutputT, ChunkT]): + """A ``Flow`` whose function gives the input a default. + + ``@ai.flow`` and ``define_flow`` return one for ``async def + todays_special(cuisine: str = 'italian')``. ``await todays_special()`` + runs with the default; ``await todays_special(None)`` is a type error. + It's still a ``Flow``, so a ``Flow[str, str]`` annotation accepts it. + """ + + # Same order as _FlowDecorator.__call__; the `object` shapes catch # `(x: Any)` / `(x: object)` before the ctx-only shape can. @overload @@ -181,7 +193,7 @@ def define_flow( func: CtxDefaultInputFn[FlowContext[_FlowChunkT], _FlowInputT, _FlowOutputT], name: str | None = None, description: str | None = None, -) -> Flow[_FlowInputT | None, _FlowOutputT, _FlowChunkT]: ... +) -> DefaultedFlow[_FlowInputT, _FlowOutputT, _FlowChunkT]: ... @overload @@ -217,7 +229,7 @@ def define_flow( func: DefaultInputFn[_FlowInputT, _FlowOutputT], name: str | None = None, description: str | None = None, -) -> Flow[_FlowInputT | None, _FlowOutputT]: ... +) -> DefaultedFlow[_FlowInputT, _FlowOutputT]: ... @overload @@ -244,7 +256,11 @@ def define_flow( name: str | None = None, description: str | None = None, ) -> Flow[Any, Any, Any]: - """Register an async function as a flow action.""" - flow = Flow(func, name=name, description=description) + """Register an async function as a flow action. + + A function whose input has a default becomes a ``DefaultedFlow``. + """ + cls = DefaultedFlow if input_has_default(func, ActionKind.FLOW) else Flow + flow = cls(func, name=name, description=description) registry.register_action_from_instance(flow) return flow diff --git a/packages/genkit/src/genkit/_core/_tool.py b/packages/genkit/src/genkit/_core/_tool.py index 85c738814..ab3722ff4 100644 --- a/packages/genkit/src/genkit/_core/_tool.py +++ b/packages/genkit/src/genkit/_core/_tool.py @@ -33,6 +33,7 @@ ActionContext, ActionKind, CtxDefaultInputFn, + DefaultedAction, DefaultInputFn, get_func_description, resolve_type_hints, @@ -372,9 +373,12 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... + # The defaulted-input shapes are self-typed to DefaultedTool, so they + # apply when define_tool builds one. Tool(fn) itself stays a Tool and + # skips them. @overload def __init__( - self: Tool[_I | None, _O, _C], + self: DefaultedTool[_I, _O, _C], func: CtxDefaultInputFn[ToolContext[_C], _I, _O], *, name: str | None = None, @@ -414,7 +418,7 @@ def __init__( @overload def __init__( - self: Tool[_I | None, _O, Any], + self: DefaultedTool[_I, _O, Any], func: DefaultInputFn[_I, _O], *, name: str | None = None, @@ -577,6 +581,16 @@ async def _invoke(self, input: object | None, ctx: ActionContext) -> OutputT: return output +class DefaultedTool(DefaultedAction[InputT, OutputT, ChunkT, None], Tool[InputT, OutputT, ChunkT]): + """A ``Tool`` whose function gives the input a default. + + ``@ai.tool`` and ``define_tool`` return one for ``async def + check_allergens(dish: str = 'pad thai')``. ``await check_allergens()`` + runs with the default; ``await check_allergens(None)`` is a type error. + It's still a ``Tool``, so a ``Tool[str, str]`` annotation accepts it. + """ + + class _ActionTool(Tool[InputT, OutputT, ChunkT]): """A ``Tool`` view over a plain ``Action`` with no ``tool.v2`` companion.""" diff --git a/packages/genkit/tests/genkit/ai/flow_signature_test.py b/packages/genkit/tests/genkit/ai/flow_signature_test.py index 56d89a126..cc09834d3 100644 --- a/packages/genkit/tests/genkit/ai/flow_signature_test.py +++ b/packages/genkit/tests/genkit/ai/flow_signature_test.py @@ -12,6 +12,7 @@ from typing_extensions import assert_type from genkit import Flow, FlowContext, Genkit +from genkit._core._flow import DefaultedFlow @pytest.mark.asyncio @@ -404,7 +405,7 @@ async def with_default(dish: str = 'soup') -> str: assert_type(ai.flow(stream_order), Flow[_Order, str, str]) assert_type(ai.flow(stream_any), Flow[Any, str, str]) # ty: ignore[type-assertion-failure] assert_type(ai.flow(specials), Flow[None, str]) - assert_type(ai.flow(with_default), Flow[str | None, str]) + assert_type(ai.flow(with_default), DefaultedFlow[str, str]) # 2. Standalone Flow(fn). An __init__ overload can't pin InputT to None, # so ctx-only and no-arg flows leave it at its Any default. @@ -416,7 +417,7 @@ async def with_default(dish: str = 'soup') -> str: assert_type(Flow(stream_order), Flow[_Order, str, str]) assert_type(Flow(stream_any), Flow[Any, str, str]) assert_type(Flow(specials), Flow[Any, str]) - assert_type(Flow(with_default), Flow[str | None, str]) # ty: ignore[type-assertion-failure] + assert_type(Flow(with_default), Flow[str, str]) # 3. An Any/object flow takes any input at the call site. echo = Flow(echo_object) diff --git a/packages/genkit/tests/typecheck/action_and_ref_contract_test.py b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py index 8f74bcd67..1f96366e5 100644 --- a/packages/genkit/tests/typecheck/action_and_ref_contract_test.py +++ b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py @@ -44,6 +44,8 @@ ToolContext, ) from genkit._core._action import ActionResponse +from genkit._core._flow import DefaultedFlow +from genkit._core._tool import DefaultedTool from genkit.embedder import EmbedderRef, EmbedRequest, EmbedResponse from genkit.model import ModelConfig, ModelContext, ModelRef, ModelRequest from genkit.plugin_api import Action, ActionKind @@ -132,18 +134,18 @@ async def list_specials(ctx: ToolContext) -> list[str]: assert_type(await list_specials(), list[str]) with pytest.raises(GenkitError): - await create_invoice() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + await create_invoice() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] with pytest.raises(GenkitError): - await create_invoice.run() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + await create_invoice.run() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] with pytest.raises(GenkitError): - await lookup_allergens() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + await lookup_allergens() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] @pytest.mark.asyncio async def test_defaulted_inputs_can_be_omitted() -> None: - """A flow or tool whose input has a default types as ``[T | None, ...]`` and runs with no input.""" + """A flow or tool whose input has a default is a ``DefaultedFlow`` / ``DefaultedTool`` and runs with no input.""" ai = Genkit() @ai.flow @@ -158,9 +160,9 @@ async def reprint_receipt(order: OrderReq | None = None) -> str: async def todays_soup(day: str = 'monday') -> str: return f'{day}: bouillabaisse' - assert_type(suggest_dish, Flow[str | None, str]) - assert_type(reprint_receipt, Flow[OrderReq | None, str]) - assert_type(todays_soup, Tool[str | None, str]) + assert_type(suggest_dish, DefaultedFlow[str, str]) + assert_type(reprint_receipt, DefaultedFlow[OrderReq | None, str]) + assert_type(todays_soup, DefaultedTool[str, str]) assert await suggest_dish() == 'french: tartine' assert await suggest_dish('thai') == 'thai: tartine' @@ -170,11 +172,11 @@ async def todays_soup(day: str = 'monday') -> str: assert await todays_soup() == 'monday: bouillabaisse' with pytest.raises(GenkitError): - await suggest_dish(3) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + await suggest_dish(3) # pyright: ignore[reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] def test_input_is_contravariant() -> None: - """A flow or tool with a defaulted input fits a required-input or no-input annotation.""" + """A flow or tool with a defaulted input fits a required-input annotation, not a no-input one.""" ai = Genkit() @ai.flow @@ -189,15 +191,17 @@ async def todays_soup(day: str = 'monday') -> str: async def kitchen_status() -> str: return 'open' - # 1. Flow[str | None, str] accepts everything Flow[str, str] and Flow[None, str] do + # 1. DefaultedFlow[str, str] is a Flow[str, str] by_cuisine: Flow[str, str] = suggest_dish - house_pick: Flow[None, str] = suggest_dish - # 2. Same for tools + # 2. It isn't a Flow[None, str]: that would accept an explicit None, which a str input rejects + house_pick: Flow[None, str] = suggest_dish # pyright: ignore[reportAssignmentType] # pyrefly: ignore[bad-assignment] # ty: ignore[invalid-assignment] + + # 3. Same for tools soup_for_day: Tool[str, str] = todays_soup - soup_today: Tool[None, str] = todays_soup + soup_today: Tool[None, str] = todays_soup # pyright: ignore[reportAssignmentType] # pyrefly: ignore[bad-assignment] # ty: ignore[invalid-assignment] - # 3. A no-input flow can't stand in for one that needs an order + # 4. A no-input flow can't stand in for one that needs an order needs_order: Flow[OrderReq, str] = kitchen_status # pyright: ignore[reportAssignmentType] # pyrefly: ignore[bad-assignment] # ty: ignore[invalid-assignment] assert by_cuisine is house_pick From 62ac92fb41ebabb24e15ee66a027441fe98420a1 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 16 Nov 2026 13:33:21 -0600 Subject: [PATCH 15/20] fix(py): type a defaulted input followed by a context `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. --- packages/genkit/src/genkit/_ai/_aio.py | 15 +++++++++++ packages/genkit/src/genkit/_ai/_decorators.py | 15 +++++++++-- packages/genkit/src/genkit/_ai/_tools.py | 15 ++++++++++- packages/genkit/src/genkit/_core/_action.py | 16 ++++++++++++ packages/genkit/src/genkit/_core/_flow.py | 25 ++++++++++++++++--- packages/genkit/src/genkit/_core/_tool.py | 17 ++++++++++--- 6 files changed, 94 insertions(+), 9 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index d4a483d5c..4f6b5718c 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -87,6 +87,7 @@ Action, ActionKind, CtxDefaultInputFn, + DefaultInputCtxFn, DefaultInputFn, FlowContext, get_current_context, @@ -325,6 +326,13 @@ def flow( /, ) -> Flow[Any, OutputT, ChunkT]: ... + @overload + def flow( + self, + func: DefaultInputCtxFn[FlowContext[ChunkT], InputT, OutputT], + /, + ) -> DefaultedFlow[InputT, OutputT, ChunkT]: ... + @overload def flow( self, @@ -506,6 +514,13 @@ def tool( /, ) -> Tool[Any, OutputT, ChunkT]: ... + @overload + def tool( + self, + func: DefaultInputCtxFn[ToolContext[ChunkT], InputT, OutputT], + /, + ) -> DefaultedTool[InputT, OutputT, ChunkT]: ... + @overload def tool( self, diff --git a/packages/genkit/src/genkit/_ai/_decorators.py b/packages/genkit/src/genkit/_ai/_decorators.py index c957ea85e..fae88e8ca 100644 --- a/packages/genkit/src/genkit/_ai/_decorators.py +++ b/packages/genkit/src/genkit/_ai/_decorators.py @@ -24,7 +24,7 @@ from pydantic import BaseModel from genkit._ai._tools import define_tool -from genkit._core._action import CtxDefaultInputFn, DefaultInputFn, FlowContext +from genkit._core._action import CtxDefaultInputFn, DefaultInputCtxFn, DefaultInputFn, FlowContext from genkit._core._flow import DefaultedFlow, Flow, define_flow from genkit._core._registry import Registry from genkit._core._tool import DefaultedTool, Tool, ToolContext @@ -47,7 +47,8 @@ def __init__(self, registry: Registry, name: str | None, description: str | None # # - A defaulted input (`async def f(x: str = '...')`) matches the # Default*Fn Protocols and returns DefaultedFlow[str, ...]: the input may - # be omitted, but None isn't a str. + # be omitted, but None isn't a str. `(x = ..., ctx = None)` also fits + # the (input, ctx) shape, so DefaultInputCtxFn comes before it. # - `(x: Any)` and `(x: object)` also accept a FlowContext, so they'd match # the ctx-only shape and type as Flow[None, ...]. The `object` shapes # come first and catch them as Flow[Any, ...]. A real `(ctx: FlowContext)` @@ -60,6 +61,11 @@ def __call__( self, func: Callable[[FlowContext[ChunkT], object], Awaitable[OutputT]] ) -> Flow[Any, OutputT, ChunkT]: ... + @overload + def __call__( + self, func: DefaultInputCtxFn[FlowContext[ChunkT], InputT, OutputT] + ) -> DefaultedFlow[InputT, OutputT, ChunkT]: ... + @overload def __call__( self, func: Callable[[InputT, FlowContext[ChunkT]], Awaitable[OutputT]] @@ -116,6 +122,11 @@ def __call__( self, func: Callable[[ToolContext[ChunkT], object], Awaitable[OutputT]] ) -> Tool[Any, OutputT, ChunkT]: ... + @overload + def __call__( + self, func: DefaultInputCtxFn[ToolContext[ChunkT], InputT, OutputT] + ) -> DefaultedTool[InputT, OutputT, ChunkT]: ... + @overload def __call__( self, func: Callable[[InputT, ToolContext[ChunkT]], Awaitable[OutputT]] diff --git a/packages/genkit/src/genkit/_ai/_tools.py b/packages/genkit/src/genkit/_ai/_tools.py index 76b75c188..a51dce5c0 100644 --- a/packages/genkit/src/genkit/_ai/_tools.py +++ b/packages/genkit/src/genkit/_ai/_tools.py @@ -25,6 +25,7 @@ Action, ActionKind, CtxDefaultInputFn, + DefaultInputCtxFn, DefaultInputFn, input_from_json, input_has_default, @@ -301,7 +302,8 @@ def _define_tool( # flow: the function takes no input, so a direct call passes none. # - ty types ``(ctx, x: Any)`` as Unknown: the typing spec's overload rule for # Any arguments makes it ambiguous, and no order fixes that. -# - A defaulted input returns ``DefaultedTool``. +# - A defaulted input returns ``DefaultedTool``. ``(x = ..., ctx = None)`` +# also fits ``[InputT, ToolContext]``, so its shape comes before that one. @overload def define_tool( registry: Registry, @@ -313,6 +315,17 @@ def define_tool( ) -> _Tool[Any, ToolOutputT, ToolChunkT]: ... +@overload +def define_tool( + registry: Registry, + func: DefaultInputCtxFn[ToolContext[ToolChunkT], ToolInputT, ToolOutputT], + name: str | None = None, + description: str | None = None, + *, + input_schema: type[BaseModel] | dict[str, object] | None = None, +) -> DefaultedTool[ToolInputT, ToolOutputT, ToolChunkT]: ... + + @overload def define_tool( registry: Registry, diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index 41eb34c77..daaabde5a 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -886,6 +886,22 @@ def __call__( ) -> Awaitable[_FnOutputT_co]: ... +class DefaultInputCtxFn(Protocol[_FnCtxT_contra, _FnInputT_contra, _FnOutputT_co]): + """``DefaultInputFn`` with the context last. + + ``async def greet(name: str = 'world', ctx: FlowContext | None = None)``. + Python makes a parameter after a defaulted one take a default too. Both + are positional here, so the context matches by position, whatever it's named. + """ + + def __call__( + self, + input: _FnInputT_contra = ..., # noqa: A002 + ctx: _FnCtxT_contra = ..., + /, + ) -> Awaitable[_FnOutputT_co]: ... + + # Generic streaming callback - use Callable[[ChunkT], None] for typed chunks # This untyped version is for internal use where chunk type is unknown StreamingCallback = Callable[[object], None] diff --git a/packages/genkit/src/genkit/_core/_flow.py b/packages/genkit/src/genkit/_core/_flow.py index 3ad094644..ce1eb627d 100644 --- a/packages/genkit/src/genkit/_core/_flow.py +++ b/packages/genkit/src/genkit/_core/_flow.py @@ -30,6 +30,7 @@ ChunkT, CtxDefaultInputFn, DefaultedAction, + DefaultInputCtxFn, DefaultInputFn, FlowContext, InputT, @@ -62,6 +63,18 @@ def __init__( description: str | None = None, ) -> None: ... + # The defaulted-input shapes are self-typed to DefaultedFlow, so they + # apply when define_flow builds one. Flow(fn) itself stays a Flow and + # skips them. `(x = ..., ctx = None)` also fits (input, ctx); catch it first. + @overload + def __init__( + self: DefaultedFlow[_FlowInputT, _FlowOutputT, _FlowChunkT], + func: DefaultInputCtxFn[FlowContext[_FlowChunkT], _FlowInputT, _FlowOutputT], + *, + name: str | None = None, + description: str | None = None, + ) -> None: ... + @overload def __init__( self, @@ -71,9 +84,6 @@ def __init__( description: str | None = None, ) -> None: ... - # The defaulted-input shapes are self-typed to DefaultedFlow, so they - # apply when define_flow builds one. Flow(fn) itself stays a Flow and - # skips them. @overload def __init__( self: DefaultedFlow[_FlowInputT, _FlowOutputT, _FlowChunkT], @@ -178,6 +188,15 @@ def define_flow( ) -> Flow[Any, _FlowOutputT, _FlowChunkT]: ... +@overload +def define_flow( + registry: Registry, + func: DefaultInputCtxFn[FlowContext[_FlowChunkT], _FlowInputT, _FlowOutputT], + name: str | None = None, + description: str | None = None, +) -> DefaultedFlow[_FlowInputT, _FlowOutputT, _FlowChunkT]: ... + + @overload def define_flow( registry: Registry, diff --git a/packages/genkit/src/genkit/_core/_tool.py b/packages/genkit/src/genkit/_core/_tool.py index ab3722ff4..db96fd5b4 100644 --- a/packages/genkit/src/genkit/_core/_tool.py +++ b/packages/genkit/src/genkit/_core/_tool.py @@ -34,6 +34,7 @@ ActionKind, CtxDefaultInputFn, DefaultedAction, + DefaultInputCtxFn, DefaultInputFn, get_func_description, resolve_type_hints, @@ -363,6 +364,19 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... + # The defaulted-input shapes are self-typed to DefaultedTool, so they + # apply when define_tool builds one. Tool(fn) itself stays a Tool and + # skips them. `(x = ..., ctx = None)` also fits (input, ctx); catch it first. + @overload + def __init__( + self: DefaultedTool[_I, _O, _C], + func: DefaultInputCtxFn[ToolContext[_C], _I, _O], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> None: ... + @overload def __init__( self: Tool[_I, _O, _C], @@ -373,9 +387,6 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... - # The defaulted-input shapes are self-typed to DefaultedTool, so they - # apply when define_tool builds one. Tool(fn) itself stays a Tool and - # skips them. @overload def __init__( self: DefaultedTool[_I, _O, _C], From fbcbdee0fb228943abaa052a4e10066d70baea1a Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 16 Nov 2026 13:33:29 -0600 Subject: [PATCH 16/20] fix(py): add a catch-all handler overload and pin every shape in contracts 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. --- packages/genkit/src/genkit/_ai/_aio.py | 16 + packages/genkit/src/genkit/_ai/_decorators.py | 13 + packages/genkit/src/genkit/_ai/_tools.py | 15 + packages/genkit/src/genkit/_core/_flow.py | 22 + packages/genkit/src/genkit/_core/_tool.py | 11 + .../flow_tool_shapes_contract_test.py | 449 ++++++++++++++++++ 6 files changed, 526 insertions(+) create mode 100644 packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 4f6b5718c..af4f87d96 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -389,6 +389,14 @@ def flow( /, ) -> Flow[None, OutputT]: ... + # Last: shapes the overloads above can't model, like a keyword-only context. + @overload + def flow( + self, + func: Callable[..., Awaitable[OutputT]], + /, + ) -> Flow[Any, OutputT]: ... + def flow( self, name: str | Callable[..., Awaitable[Any]] | None = None, @@ -577,6 +585,14 @@ def tool( /, ) -> Tool[None, OutputT]: ... + # Last: shapes the overloads above can't model, like a keyword-only context. + @overload + def tool( + self, + func: Callable[..., Awaitable[OutputT]], + /, + ) -> Tool[Any, OutputT]: ... + def tool( self, name: str | Callable[..., Awaitable[Any]] | None = None, diff --git a/packages/genkit/src/genkit/_ai/_decorators.py b/packages/genkit/src/genkit/_ai/_decorators.py index fae88e8ca..8a46a791a 100644 --- a/packages/genkit/src/genkit/_ai/_decorators.py +++ b/packages/genkit/src/genkit/_ai/_decorators.py @@ -56,6 +56,9 @@ def __init__(self, registry: Registry, name: str | None, description: str | None # - ty follows the typing spec's overload rule for Any: `(x: Any)` matches # overloads with different returns, so ty types it Unknown. That's the # best any arrangement can do there without breaking `(ctx: FlowContext)`. + # - The Callable[..., ...] catch-all is last. A shape that lands there + # types Flow[Any, ...]; the typecheck contracts pin every other shape so + # one can't fall through unnoticed. @overload def __call__( self, func: Callable[[FlowContext[ChunkT], object], Awaitable[OutputT]] @@ -96,6 +99,11 @@ def __call__(self, func: Callable[[InputT], Awaitable[OutputT]]) -> Flow[InputT, @overload def __call__(self, func: Callable[[], Awaitable[OutputT]]) -> Flow[None, OutputT]: ... + # Last: shapes the overloads above can't model, like a keyword-only + # context. The output stays typed; the input is Any. + @overload + def __call__(self, func: Callable[..., Awaitable[OutputT]]) -> Flow[Any, OutputT]: ... + def __call__(self, func: Callable[..., Awaitable[Any]]) -> Flow[Any, Any, Any]: return define_flow(self._registry, func, self._name, self._description) @@ -157,6 +165,11 @@ def __call__(self, func: Callable[[InputT], Awaitable[OutputT]]) -> Tool[InputT, @overload def __call__(self, func: Callable[[], Awaitable[OutputT]]) -> Tool[None, OutputT]: ... + # Last: shapes the overloads above can't model, like a keyword-only + # context. The output stays typed; the input is Any. + @overload + def __call__(self, func: Callable[..., Awaitable[OutputT]]) -> Tool[Any, OutputT]: ... + def __call__(self, func: Callable[..., Awaitable[Any]]) -> Tool[Any, Any, Any]: return define_tool( self._registry, diff --git a/packages/genkit/src/genkit/_ai/_tools.py b/packages/genkit/src/genkit/_ai/_tools.py index a51dce5c0..a7c410d83 100644 --- a/packages/genkit/src/genkit/_ai/_tools.py +++ b/packages/genkit/src/genkit/_ai/_tools.py @@ -304,6 +304,8 @@ def _define_tool( # Any arguments makes it ambiguous, and no order fixes that. # - A defaulted input returns ``DefaultedTool``. ``(x = ..., ctx = None)`` # also fits ``[InputT, ToolContext]``, so its shape comes before that one. +# - The ``Callable[..., ...]`` catch-all is last, for shapes no overload +# models, like a keyword-only context. @overload def define_tool( registry: Registry, @@ -414,6 +416,19 @@ def define_tool( ) -> _Tool[None, ToolOutputT]: ... +# Last: a shape the overloads above can't model, like a keyword-only +# context. The output stays typed; the input is Any. +@overload +def define_tool( + registry: Registry, + func: Callable[..., Awaitable[ToolOutputT]], + name: str | None = None, + description: str | None = None, + *, + input_schema: type[BaseModel] | dict[str, object] | None = None, +) -> _Tool[Any, ToolOutputT]: ... + + def define_tool( registry: Registry, func: Callable[..., Any], diff --git a/packages/genkit/src/genkit/_core/_flow.py b/packages/genkit/src/genkit/_core/_flow.py index ce1eb627d..31098f451 100644 --- a/packages/genkit/src/genkit/_core/_flow.py +++ b/packages/genkit/src/genkit/_core/_flow.py @@ -138,6 +138,17 @@ def __init__( description: str | None = None, ) -> None: ... + # Shapes the overloads above can't model, like a keyword-only context. + # InputT isn't bound, so it defaults to Any. + @overload + def __init__( + self, + func: Callable[..., Awaitable[OutputT]], + *, + name: str | None = None, + description: str | None = None, + ) -> None: ... + def __init__( self, func: Callable[..., Awaitable[Any]], @@ -269,6 +280,17 @@ def define_flow( ) -> Flow[None, _FlowOutputT]: ... +# Last: a shape the overloads above can't model, like a keyword-only +# context. The output stays typed; the input is Any. +@overload +def define_flow( + registry: Registry, + func: Callable[..., Awaitable[_FlowOutputT]], + name: str | None = None, + description: str | None = None, +) -> Flow[Any, _FlowOutputT]: ... + + def define_flow( registry: Registry, func: Callable[..., Awaitable[Any]], diff --git a/packages/genkit/src/genkit/_core/_tool.py b/packages/genkit/src/genkit/_core/_tool.py index db96fd5b4..d5d223baf 100644 --- a/packages/genkit/src/genkit/_core/_tool.py +++ b/packages/genkit/src/genkit/_core/_tool.py @@ -457,6 +457,17 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... + # Shapes the overloads above can't model, like a keyword-only context. + @overload + def __init__( + self: Tool[Any, _O, Any], + func: Callable[..., Awaitable[_O]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> None: ... + def __init__( self, func: Callable[..., Awaitable[Any]], diff --git a/packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py b/packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py new file mode 100644 index 000000000..63d63cf7e --- /dev/null +++ b/packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py @@ -0,0 +1,449 @@ +# 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 every flow and tool handler shape. + +Each ``@ai.flow`` / ``@ai.tool`` / ``define_flow`` / ``define_tool`` overload +set ends in a ``Callable[..., Awaitable[O]]`` catch-all that types the input +as ``Any``. Every shape the specific overloads cover is pinned here with its +exact type, so a shape that falls through to the catch-all fails as +``Flow[Any, ...]`` instead of passing quietly. The runtime checks assert the +built object is a ``DefaultedFlow`` / ``DefaultedTool`` exactly when the +input has a default, so ``isinstance`` agrees with the static type. +""" + +import copy +from typing import Any + +import pytest +from pydantic import BaseModel +from typing_extensions import assert_type + +from genkit import Flow, FlowContext, Genkit, GenkitError, Tool, ToolContext +from genkit._ai._tools import define_tool +from genkit._core._flow import DefaultedFlow, define_flow +from genkit._core._registry import Registry +from genkit._core._tool import DefaultedTool +from genkit.plugin_api import ActionContext + + +class Diet(BaseModel): + vegan: bool = False + + +class Order(BaseModel): + dish: str + + +# Flow handlers, one per shape. + + +async def recommend_dish(diet: Diet) -> str: + return 'tofu larb' if diet.vegan else 'pork larb' + + +async def todays_special(cuisine: str = 'italian') -> str: + return f'{cuisine}: risotto' + + +async def lookup_reservation(res_id: str | None = None) -> str: + return res_id or 'walk-in' + + +async def staff_on_shift(ctx: FlowContext) -> str: + del ctx + return 'chef, two cooks' + + +async def kitchen_status() -> str: + return 'open' + + +async def plan_menu(ctx: FlowContext, diet: Diet) -> str: + del ctx + return 'tasting menu' if diet.vegan else 'prix fixe' + + +async def plate_dish(diet: Diet, ctx: FlowContext) -> str: + del ctx + return 'plated' if diet.vegan else 'plated with jus' + + +async def chef_pick(ctx: FlowContext, cuisine: str = 'thai') -> str: + del ctx + return f'{cuisine}: chef pick' + + +async def special(cuisine: str = 'thai', ctx: FlowContext | None = None) -> str: + del ctx + return cuisine + + +async def streamed_special(cuisine: str = 'thai', ctx: FlowContext[str] | None = None) -> str: + if ctx is not None: + ctx.send_chunk('plating') + return cuisine + + +async def open_tables(ctx: ActionContext) -> str: + del ctx + return '4 tables' + + +async def echo_order(order: Any) -> str: # noqa: ANN401 - pins the Any-input shape + return str(order) + + +async def kwonly_special(cuisine: str = 'thai', *, ctx: FlowContext) -> str: + del ctx + return cuisine + + +# Tool handlers, one per shape. + + +async def place_order(order: Order) -> str: + return f'ordered {order.dish}' + + +async def check_allergens(dish: str = 'pad thai') -> str: + return f'{dish}: peanuts' + + +async def find_table(res_id: str | None = None) -> str: + return res_id or 'bar seat' + + +async def whoami(ctx: ToolContext) -> str: + del ctx + return 'server 3' + + +async def list_specials() -> str: + return 'soup, tartine' + + +async def fire_order(ctx: ToolContext, order: Order) -> str: + del ctx + return f'fired {order.dish}' + + +async def void_order(order: Order, ctx: ToolContext) -> str: + del ctx + return f'voided {order.dish}' + + +async def suggest_wine(ctx: ToolContext, dish: str = 'steak') -> str: + del ctx + return f'{dish}: malbec' + + +async def soup_of_day(day: str = 'monday', ctx: ToolContext | None = None) -> str: + del ctx + return f'{day}: bouillabaisse' + + +async def echo_ticket(ticket: Any) -> str: # noqa: ANN401 - pins the Any-input shape + return str(ticket) + + +async def kwonly_soup(day: str = 'monday', *, ctx: ToolContext) -> str: + del ctx + return day + + +def test_ai_flow_shapes() -> None: + """``@ai.flow`` types every handler shape exactly; defaulted inputs build a ``DefaultedFlow``.""" + ai = Genkit() + + # 1. Required, defaulted and Optional-typed inputs + assert_type(ai.flow(recommend_dish), Flow[Diet, str]) + assert_type(ai.flow(todays_special), DefaultedFlow[str, str]) + assert_type(ai.flow(lookup_reservation), DefaultedFlow[str | None, str]) + + # 2. No input + assert_type(ai.flow(staff_on_shift), Flow[None, str]) + assert_type(ai.flow(kitchen_status), Flow[None, str]) + assert_type(ai.flow(open_tables), Flow[None, str]) + + # 3. Input plus context, in either order + assert_type(ai.flow(plan_menu), Flow[Diet, str]) + assert_type(ai.flow(plate_dish), Flow[Diet, str]) + assert_type(ai.flow(chef_pick), DefaultedFlow[str, str]) + assert_type(ai.flow(special), DefaultedFlow[str, str]) + assert_type(ai.flow(streamed_special), DefaultedFlow[str, str, str]) + + # 4. Any input; ty types it Unknown (see _FlowDecorator) + assert_type(ai.flow(echo_order), Flow[Any, str]) # ty: ignore[type-assertion-failure] + + # 5. Keyword-only context: no overload models it, so the catch-all types the input Any + assert_type(ai.flow(kwonly_special), Flow[Any, str]) + + +def test_ai_flow_called_shapes() -> None: + """``@ai.flow()`` (the decorator object) types the same shapes the same way.""" + ai = Genkit() + flow = ai.flow() + + assert_type(flow(recommend_dish), Flow[Diet, str]) + assert_type(flow(todays_special), DefaultedFlow[str, str]) + assert_type(flow(lookup_reservation), DefaultedFlow[str | None, str]) + assert_type(flow(staff_on_shift), Flow[None, str]) + assert_type(flow(kitchen_status), Flow[None, str]) + assert_type(flow(open_tables), Flow[None, str]) + assert_type(flow(plan_menu), Flow[Diet, str]) + assert_type(flow(plate_dish), Flow[Diet, str]) + assert_type(flow(chef_pick), DefaultedFlow[str, str]) + assert_type(flow(special), DefaultedFlow[str, str]) + assert_type(flow(streamed_special), DefaultedFlow[str, str, str]) + assert_type(flow(echo_order), Flow[Any, str]) # ty: ignore[type-assertion-failure] + assert_type(flow(kwonly_special), Flow[Any, str]) + + +def test_define_flow_shapes() -> None: + """``define_flow`` types the same shapes the same way.""" + registry = Registry() + + assert_type(define_flow(registry, recommend_dish), Flow[Diet, str]) + assert_type(define_flow(registry, todays_special), DefaultedFlow[str, str]) + assert_type(define_flow(registry, lookup_reservation), DefaultedFlow[str | None, str]) + assert_type(define_flow(registry, staff_on_shift), Flow[None, str]) + assert_type(define_flow(registry, kitchen_status), Flow[None, str]) + assert_type(define_flow(registry, open_tables), Flow[None, str]) + assert_type(define_flow(registry, plan_menu), Flow[Diet, str]) + assert_type(define_flow(registry, plate_dish), Flow[Diet, str]) + assert_type(define_flow(registry, chef_pick), DefaultedFlow[str, str]) + assert_type(define_flow(registry, special), DefaultedFlow[str, str]) + assert_type(define_flow(registry, streamed_special), DefaultedFlow[str, str, str]) + assert_type(define_flow(registry, echo_order), Flow[Any, str]) # ty: ignore[type-assertion-failure] + assert_type(define_flow(registry, kwonly_special), Flow[Any, str]) + + +def test_ai_tool_shapes() -> None: + """``@ai.tool`` types every handler shape exactly; defaulted inputs build a ``DefaultedTool``.""" + ai = Genkit() + + assert_type(ai.tool(place_order), Tool[Order, str]) + assert_type(ai.tool(check_allergens), DefaultedTool[str, str]) + assert_type(ai.tool(find_table), DefaultedTool[str | None, str]) + assert_type(ai.tool(whoami), Tool[None, str]) + assert_type(ai.tool(list_specials), Tool[None, str]) + assert_type(ai.tool(fire_order), Tool[Order, str]) + assert_type(ai.tool(void_order), Tool[Order, str]) + assert_type(ai.tool(suggest_wine), DefaultedTool[str, str]) + assert_type(ai.tool(soup_of_day), DefaultedTool[str, str]) + assert_type(ai.tool(echo_ticket), Tool[Any, str]) # ty: ignore[type-assertion-failure] + assert_type(ai.tool(kwonly_soup), Tool[Any, str]) + + +def test_ai_tool_called_shapes() -> None: + """``@ai.tool()`` (the decorator object) types the same shapes the same way.""" + ai = Genkit() + tool = ai.tool() + + assert_type(tool(place_order), Tool[Order, str]) + assert_type(tool(check_allergens), DefaultedTool[str, str]) + assert_type(tool(find_table), DefaultedTool[str | None, str]) + assert_type(tool(whoami), Tool[None, str]) + assert_type(tool(list_specials), Tool[None, str]) + assert_type(tool(fire_order), Tool[Order, str]) + assert_type(tool(void_order), Tool[Order, str]) + assert_type(tool(suggest_wine), DefaultedTool[str, str]) + assert_type(tool(soup_of_day), DefaultedTool[str, str]) + assert_type(tool(echo_ticket), Tool[Any, str]) # ty: ignore[type-assertion-failure] + assert_type(tool(kwonly_soup), Tool[Any, str]) + + +def test_define_tool_shapes() -> None: + """``define_tool`` types the same shapes the same way.""" + registry = Registry() + + assert_type(define_tool(registry, place_order), Tool[Order, str]) + assert_type(define_tool(registry, check_allergens), DefaultedTool[str, str]) + assert_type(define_tool(registry, find_table), DefaultedTool[str | None, str]) + assert_type(define_tool(registry, whoami), Tool[None, str]) + assert_type(define_tool(registry, list_specials), Tool[None, str]) + assert_type(define_tool(registry, fire_order), Tool[Order, str]) + assert_type(define_tool(registry, void_order), Tool[Order, str]) + assert_type(define_tool(registry, suggest_wine), DefaultedTool[str, str]) + assert_type(define_tool(registry, soup_of_day), DefaultedTool[str, str]) + assert_type(define_tool(registry, echo_ticket), Tool[Any, str]) # ty: ignore[type-assertion-failure] + assert_type(define_tool(registry, kwonly_soup), Tool[Any, str]) + + +def test_runtime_class_matches_the_static_type() -> None: + """A defaulted input builds a ``DefaultedFlow`` / ``DefaultedTool``; anything else builds a plain one.""" + ai = Genkit() + registry = Registry() + + # 1. Flows: a defaulted input, with or without a context, in any position + for fn in (todays_special, lookup_reservation, chef_pick, special, streamed_special, kwonly_special): + assert isinstance(ai.flow(fn), DefaultedFlow), fn.__name__ + assert isinstance(define_flow(registry, fn), DefaultedFlow), fn.__name__ + for fn in (recommend_dish, staff_on_shift, kitchen_status, open_tables, plan_menu, plate_dish, echo_order): + built = define_flow(registry, fn) + assert isinstance(built, Flow), fn.__name__ + assert not isinstance(built, DefaultedFlow), fn.__name__ + + # 2. Tools, the same way + for fn in (check_allergens, find_table, suggest_wine, soup_of_day, kwonly_soup): + assert isinstance(ai.tool(fn), DefaultedTool), fn.__name__ + assert isinstance(define_tool(registry, fn), DefaultedTool), fn.__name__ + for fn in (place_order, whoami, list_specials, fire_order, void_order, echo_ticket): + built_tool = define_tool(registry, fn) + assert isinstance(built_tool, Tool), fn.__name__ + assert not isinstance(built_tool, DefaultedTool), fn.__name__ + + # 3. Flow(fn) / Tool(fn) built directly stay plain, matching their static type + assert type(Flow(todays_special)) is Flow + assert type(Tool(check_allergens)) is Tool + + +@pytest.mark.asyncio +async def test_defaulted_flow_calls() -> None: + """A ``DefaultedFlow`` runs with no input or a ``T``; ``None`` and wrong types are errors.""" + ai = Genkit() + + @ai.flow + async def todays_special(cuisine: str = 'italian') -> str: + return f'{cuisine}: risotto' + + @ai.flow + async def lookup_reservation(res_id: str | None = None) -> str: + return res_id or 'walk-in' + + @ai.flow + async def recommend_dish(diet: Diet) -> str: + return 'tofu larb' if diet.vegan else 'pork larb' + + @ai.flow + async def kitchen_status() -> str: + return 'open' + + @ai.flow + async def special(cuisine: str = 'thai', ctx: FlowContext | None = None) -> str: + del ctx + return cuisine + + @ai.flow + async def kwonly_special(cuisine: str = 'thai', *, ctx: FlowContext) -> str: + del ctx + return cuisine + + # 1. Omit the input to use the default, or pass a str + assert_type(await todays_special(), str) + assert await todays_special() == 'italian: risotto' + assert await todays_special('thai') == 'thai: risotto' + assert (await todays_special.run()).response == 'italian: risotto' + assert await todays_special.stream().response == 'italian: risotto' + assert await todays_special.stream('thai').response == 'thai: risotto' + + # 2. None is a value when the input type includes it + assert await lookup_reservation(None) == 'walk-in' + assert await lookup_reservation() == 'walk-in' + + # 3. No-input flows, defaulted input before a context, and the keyword-only catch-all + assert await kitchen_status() == 'open' + assert await special() == 'thai' + assert await special('isan') == 'isan' + assert await kwonly_special() == 'thai' + + # 4. None isn't a str; neither is 3 + with pytest.raises(GenkitError): + await todays_special(None) # pyright: ignore[reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] + with pytest.raises(GenkitError): + await todays_special.run(None) # pyright: ignore[reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] + with pytest.raises(GenkitError): + await todays_special(3) # pyright: ignore[reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] + + # 5. A required input can't be omitted + with pytest.raises(GenkitError): + await recommend_dish() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] + + # 6. A no-input flow takes no input; at runtime the extra input is ignored + assert await kitchen_status('x') == 'open' # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + + +@pytest.mark.asyncio +async def test_defaulted_tool_calls() -> None: + """A ``DefaultedTool`` runs with no input or a ``T``; ``None`` is an error.""" + ai = Genkit() + + @ai.tool() + async def check_allergens(dish: str = 'pad thai') -> str: + return f'{dish}: peanuts' + + assert await check_allergens() == 'pad thai: peanuts' + assert await check_allergens('larb') == 'larb: peanuts' + + with pytest.raises(GenkitError): + await check_allergens(None) # pyright: ignore[reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] + + +def test_defaulted_flows_fit_flow_annotations() -> None: + """A ``DefaultedFlow`` / ``DefaultedTool`` is assignable wherever a ``Flow[T, O]`` / ``Tool[T, O]`` is.""" + ai = Genkit() + + @ai.flow + async def todays_special(cuisine: str = 'italian') -> str: + return f'{cuisine}: risotto' + + @ai.tool() + async def check_allergens(dish: str = 'pad thai') -> str: + return f'{dish}: peanuts' + + def menu_flow(f: Flow[str, str]) -> str: + return f.name + + def menu_tool(t: Tool[str, str]) -> str: + return t.name + + # 1. Annotate as Flow[str, str] + by_cuisine: Flow[str, str] = todays_special + allergens: Tool[str, str] = check_allergens + + # 2. Pass to a Flow[str, str] / Tool[str, str] parameter + assert menu_flow(todays_special) == 'todays_special' + assert menu_tool(check_allergens) == 'check_allergens' + assert by_cuisine is todays_special + assert allergens is check_allergens + + +@pytest.mark.asyncio +async def test_defaulted_tool_survives_copy_and_lookup() -> None: + """``copy``, ``deepcopy``, ``Tool.from_action`` and registry lookup keep a ``DefaultedTool`` working.""" + ai = Genkit() + + @ai.tool() + async def check_allergens(dish: str = 'pad thai') -> str: + return f'{dish}: peanuts' + + # 1. Shallow and deep copies keep the class and still run with the default + shallow = copy.copy(check_allergens) + deep = copy.deepcopy(check_allergens) + assert isinstance(shallow, DefaultedTool) + assert isinstance(deep, DefaultedTool) + assert await shallow() == 'pad thai: peanuts' + assert await deep() == 'pad thai: peanuts' + + # 2. Tool.from_action returns the same object + assert Tool.from_action(check_allergens) is check_allergens + + # 3. The registry hands back the DefaultedTool + found = await ai.lookup_tool('check_allergens') + assert found is check_allergens From d4f9c0c1236cbc620021b812038c9ec839729a46 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 16 Nov 2026 13:47:45 -0600 Subject: [PATCH 17/20] fix(py): reject keyword-only handler params and drop the catch-all overload 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. --- packages/genkit/src/genkit/_ai/_aio.py | 16 ----- packages/genkit/src/genkit/_ai/_decorators.py | 13 ---- packages/genkit/src/genkit/_ai/_tools.py | 15 ----- packages/genkit/src/genkit/_core/_action.py | 9 +++ packages/genkit/src/genkit/_core/_flow.py | 22 ------- packages/genkit/src/genkit/_core/_tool.py | 11 ---- .../flow_tool_shapes_contract_test.py | 65 ++++++++++++------- 7 files changed, 50 insertions(+), 101 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index af4f87d96..4f6b5718c 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -389,14 +389,6 @@ def flow( /, ) -> Flow[None, OutputT]: ... - # Last: shapes the overloads above can't model, like a keyword-only context. - @overload - def flow( - self, - func: Callable[..., Awaitable[OutputT]], - /, - ) -> Flow[Any, OutputT]: ... - def flow( self, name: str | Callable[..., Awaitable[Any]] | None = None, @@ -585,14 +577,6 @@ def tool( /, ) -> Tool[None, OutputT]: ... - # Last: shapes the overloads above can't model, like a keyword-only context. - @overload - def tool( - self, - func: Callable[..., Awaitable[OutputT]], - /, - ) -> Tool[Any, OutputT]: ... - def tool( self, name: str | Callable[..., Awaitable[Any]] | None = None, diff --git a/packages/genkit/src/genkit/_ai/_decorators.py b/packages/genkit/src/genkit/_ai/_decorators.py index 8a46a791a..fae88e8ca 100644 --- a/packages/genkit/src/genkit/_ai/_decorators.py +++ b/packages/genkit/src/genkit/_ai/_decorators.py @@ -56,9 +56,6 @@ def __init__(self, registry: Registry, name: str | None, description: str | None # - ty follows the typing spec's overload rule for Any: `(x: Any)` matches # overloads with different returns, so ty types it Unknown. That's the # best any arrangement can do there without breaking `(ctx: FlowContext)`. - # - The Callable[..., ...] catch-all is last. A shape that lands there - # types Flow[Any, ...]; the typecheck contracts pin every other shape so - # one can't fall through unnoticed. @overload def __call__( self, func: Callable[[FlowContext[ChunkT], object], Awaitable[OutputT]] @@ -99,11 +96,6 @@ def __call__(self, func: Callable[[InputT], Awaitable[OutputT]]) -> Flow[InputT, @overload def __call__(self, func: Callable[[], Awaitable[OutputT]]) -> Flow[None, OutputT]: ... - # Last: shapes the overloads above can't model, like a keyword-only - # context. The output stays typed; the input is Any. - @overload - def __call__(self, func: Callable[..., Awaitable[OutputT]]) -> Flow[Any, OutputT]: ... - def __call__(self, func: Callable[..., Awaitable[Any]]) -> Flow[Any, Any, Any]: return define_flow(self._registry, func, self._name, self._description) @@ -165,11 +157,6 @@ def __call__(self, func: Callable[[InputT], Awaitable[OutputT]]) -> Tool[InputT, @overload def __call__(self, func: Callable[[], Awaitable[OutputT]]) -> Tool[None, OutputT]: ... - # Last: shapes the overloads above can't model, like a keyword-only - # context. The output stays typed; the input is Any. - @overload - def __call__(self, func: Callable[..., Awaitable[OutputT]]) -> Tool[Any, OutputT]: ... - def __call__(self, func: Callable[..., Awaitable[Any]]) -> Tool[Any, Any, Any]: return define_tool( self._registry, diff --git a/packages/genkit/src/genkit/_ai/_tools.py b/packages/genkit/src/genkit/_ai/_tools.py index a7c410d83..a51dce5c0 100644 --- a/packages/genkit/src/genkit/_ai/_tools.py +++ b/packages/genkit/src/genkit/_ai/_tools.py @@ -304,8 +304,6 @@ def _define_tool( # Any arguments makes it ambiguous, and no order fixes that. # - A defaulted input returns ``DefaultedTool``. ``(x = ..., ctx = None)`` # also fits ``[InputT, ToolContext]``, so its shape comes before that one. -# - The ``Callable[..., ...]`` catch-all is last, for shapes no overload -# models, like a keyword-only context. @overload def define_tool( registry: Registry, @@ -416,19 +414,6 @@ def define_tool( ) -> _Tool[None, ToolOutputT]: ... -# Last: a shape the overloads above can't model, like a keyword-only -# context. The output stays typed; the input is Any. -@overload -def define_tool( - registry: Registry, - func: Callable[..., Awaitable[ToolOutputT]], - name: str | None = None, - description: str | None = None, - *, - input_schema: type[BaseModel] | dict[str, object] | None = None, -) -> _Tool[Any, ToolOutputT]: ... - - def define_tool( registry: Registry, func: Callable[..., Any], diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index daaabde5a..0f9852f76 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -465,6 +465,15 @@ def find_input_and_context( f"{owner} parameter '{p.name}' is positional-only, but Genkit passes the input " "and context by name. Remove the '/' from the signature." ) + # Genkit could pass it by name, but the flow and tool overloads only + # model one input and one context as regular parameters, so a + # keyword-only one fails the type check at the decorator. Raise here + # too, so runtime agrees. + if p.kind is inspect.Parameter.KEYWORD_ONLY: + raise TypeError( + f"{owner} parameter '{p.name}' is keyword-only. Take the input and context as " + "regular parameters: remove the '*' from the signature." + ) contexts: list[inspect.Parameter] = [] inputs: list[inspect.Parameter] = [] diff --git a/packages/genkit/src/genkit/_core/_flow.py b/packages/genkit/src/genkit/_core/_flow.py index 31098f451..ce1eb627d 100644 --- a/packages/genkit/src/genkit/_core/_flow.py +++ b/packages/genkit/src/genkit/_core/_flow.py @@ -138,17 +138,6 @@ def __init__( description: str | None = None, ) -> None: ... - # Shapes the overloads above can't model, like a keyword-only context. - # InputT isn't bound, so it defaults to Any. - @overload - def __init__( - self, - func: Callable[..., Awaitable[OutputT]], - *, - name: str | None = None, - description: str | None = None, - ) -> None: ... - def __init__( self, func: Callable[..., Awaitable[Any]], @@ -280,17 +269,6 @@ def define_flow( ) -> Flow[None, _FlowOutputT]: ... -# Last: a shape the overloads above can't model, like a keyword-only -# context. The output stays typed; the input is Any. -@overload -def define_flow( - registry: Registry, - func: Callable[..., Awaitable[_FlowOutputT]], - name: str | None = None, - description: str | None = None, -) -> Flow[Any, _FlowOutputT]: ... - - def define_flow( registry: Registry, func: Callable[..., Awaitable[Any]], diff --git a/packages/genkit/src/genkit/_core/_tool.py b/packages/genkit/src/genkit/_core/_tool.py index d5d223baf..db96fd5b4 100644 --- a/packages/genkit/src/genkit/_core/_tool.py +++ b/packages/genkit/src/genkit/_core/_tool.py @@ -457,17 +457,6 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... - # Shapes the overloads above can't model, like a keyword-only context. - @overload - def __init__( - self: Tool[Any, _O, Any], - func: Callable[..., Awaitable[_O]], - *, - name: str | None = None, - description: str | None = None, - input_schema: type[BaseModel] | dict[str, object] | None = None, - ) -> None: ... - def __init__( self, func: Callable[..., Awaitable[Any]], diff --git a/packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py b/packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py index 63d63cf7e..e81623161 100644 --- a/packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py +++ b/packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py @@ -18,13 +18,13 @@ """Type-checker contract for every flow and tool handler shape. -Each ``@ai.flow`` / ``@ai.tool`` / ``define_flow`` / ``define_tool`` overload -set ends in a ``Callable[..., Awaitable[O]]`` catch-all that types the input -as ``Any``. Every shape the specific overloads cover is pinned here with its -exact type, so a shape that falls through to the catch-all fails as -``Flow[Any, ...]`` instead of passing quietly. The runtime checks assert the -built object is a ``DefaultedFlow`` / ``DefaultedTool`` exactly when the -input has a default, so ``isinstance`` agrees with the static type. +Every shape the ``@ai.flow`` / ``@ai.tool`` / ``define_flow`` / +``define_tool`` overloads cover is pinned here with its exact type, so a +shape that resolves to the wrong overload fails CI. Shapes Genkit doesn't +support (a keyword-only parameter, two inputs) fail at the decorator in all +three checkers and raise ``TypeError`` at definition. The runtime checks +assert the built object is a ``DefaultedFlow`` / ``DefaultedTool`` exactly +when the input has a default, so ``isinstance`` agrees with the static type. """ import copy @@ -109,11 +109,18 @@ async def echo_order(order: Any) -> str: # noqa: ANN401 - pins the Any-input sh return str(order) +# Unsupported: a keyword-only context, and two inputs. + + async def kwonly_special(cuisine: str = 'thai', *, ctx: FlowContext) -> str: del ctx return cuisine +async def pair_dishes(main: str, side: str) -> str: + return f'{main} with {side}' + + # Tool handlers, one per shape. @@ -162,11 +169,18 @@ async def echo_ticket(ticket: Any) -> str: # noqa: ANN401 - pins the Any-input return str(ticket) +# Unsupported tool shapes. + + async def kwonly_soup(day: str = 'monday', *, ctx: ToolContext) -> str: del ctx return day +async def split_bill(total: str, guests: str) -> str: + return f'{total} / {guests}' + + def test_ai_flow_shapes() -> None: """``@ai.flow`` types every handler shape exactly; defaulted inputs build a ``DefaultedFlow``.""" ai = Genkit() @@ -191,9 +205,6 @@ def test_ai_flow_shapes() -> None: # 4. Any input; ty types it Unknown (see _FlowDecorator) assert_type(ai.flow(echo_order), Flow[Any, str]) # ty: ignore[type-assertion-failure] - # 5. Keyword-only context: no overload models it, so the catch-all types the input Any - assert_type(ai.flow(kwonly_special), Flow[Any, str]) - def test_ai_flow_called_shapes() -> None: """``@ai.flow()`` (the decorator object) types the same shapes the same way.""" @@ -212,7 +223,6 @@ def test_ai_flow_called_shapes() -> None: assert_type(flow(special), DefaultedFlow[str, str]) assert_type(flow(streamed_special), DefaultedFlow[str, str, str]) assert_type(flow(echo_order), Flow[Any, str]) # ty: ignore[type-assertion-failure] - assert_type(flow(kwonly_special), Flow[Any, str]) def test_define_flow_shapes() -> None: @@ -231,7 +241,6 @@ def test_define_flow_shapes() -> None: assert_type(define_flow(registry, special), DefaultedFlow[str, str]) assert_type(define_flow(registry, streamed_special), DefaultedFlow[str, str, str]) assert_type(define_flow(registry, echo_order), Flow[Any, str]) # ty: ignore[type-assertion-failure] - assert_type(define_flow(registry, kwonly_special), Flow[Any, str]) def test_ai_tool_shapes() -> None: @@ -248,7 +257,6 @@ def test_ai_tool_shapes() -> None: assert_type(ai.tool(suggest_wine), DefaultedTool[str, str]) assert_type(ai.tool(soup_of_day), DefaultedTool[str, str]) assert_type(ai.tool(echo_ticket), Tool[Any, str]) # ty: ignore[type-assertion-failure] - assert_type(ai.tool(kwonly_soup), Tool[Any, str]) def test_ai_tool_called_shapes() -> None: @@ -266,7 +274,6 @@ def test_ai_tool_called_shapes() -> None: assert_type(tool(suggest_wine), DefaultedTool[str, str]) assert_type(tool(soup_of_day), DefaultedTool[str, str]) assert_type(tool(echo_ticket), Tool[Any, str]) # ty: ignore[type-assertion-failure] - assert_type(tool(kwonly_soup), Tool[Any, str]) def test_define_tool_shapes() -> None: @@ -283,7 +290,23 @@ def test_define_tool_shapes() -> None: assert_type(define_tool(registry, suggest_wine), DefaultedTool[str, str]) assert_type(define_tool(registry, soup_of_day), DefaultedTool[str, str]) assert_type(define_tool(registry, echo_ticket), Tool[Any, str]) # ty: ignore[type-assertion-failure] - assert_type(define_tool(registry, kwonly_soup), Tool[Any, str]) + + +def test_unsupported_shapes_fail_at_the_decorator() -> None: + """A keyword-only parameter or a second input fails every checker at the decorator, and raises at definition.""" + ai = Genkit() + + # 1. Keyword-only context + with pytest.raises(TypeError, match="flow 'kwonly_special' parameter 'ctx' is keyword-only"): + ai.flow(kwonly_special) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + with pytest.raises(TypeError, match="tool 'kwonly_soup' parameter 'ctx' is keyword-only"): + ai.tool()(kwonly_soup) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + + # 2. Two inputs + with pytest.raises(TypeError, match="flow 'pair_dishes' takes one input, but 'side' is a second parameter"): + ai.flow(pair_dishes) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + with pytest.raises(TypeError, match="tool 'split_bill' takes one input, but 'guests' is a second parameter"): + ai.tool()(split_bill) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] def test_runtime_class_matches_the_static_type() -> None: @@ -292,7 +315,7 @@ def test_runtime_class_matches_the_static_type() -> None: registry = Registry() # 1. Flows: a defaulted input, with or without a context, in any position - for fn in (todays_special, lookup_reservation, chef_pick, special, streamed_special, kwonly_special): + for fn in (todays_special, lookup_reservation, chef_pick, special, streamed_special): assert isinstance(ai.flow(fn), DefaultedFlow), fn.__name__ assert isinstance(define_flow(registry, fn), DefaultedFlow), fn.__name__ for fn in (recommend_dish, staff_on_shift, kitchen_status, open_tables, plan_menu, plate_dish, echo_order): @@ -301,7 +324,7 @@ def test_runtime_class_matches_the_static_type() -> None: assert not isinstance(built, DefaultedFlow), fn.__name__ # 2. Tools, the same way - for fn in (check_allergens, find_table, suggest_wine, soup_of_day, kwonly_soup): + for fn in (check_allergens, find_table, suggest_wine, soup_of_day): assert isinstance(ai.tool(fn), DefaultedTool), fn.__name__ assert isinstance(define_tool(registry, fn), DefaultedTool), fn.__name__ for fn in (place_order, whoami, list_specials, fire_order, void_order, echo_ticket): @@ -340,11 +363,6 @@ async def special(cuisine: str = 'thai', ctx: FlowContext | None = None) -> str: del ctx return cuisine - @ai.flow - async def kwonly_special(cuisine: str = 'thai', *, ctx: FlowContext) -> str: - del ctx - return cuisine - # 1. Omit the input to use the default, or pass a str assert_type(await todays_special(), str) assert await todays_special() == 'italian: risotto' @@ -357,11 +375,10 @@ async def kwonly_special(cuisine: str = 'thai', *, ctx: FlowContext) -> str: assert await lookup_reservation(None) == 'walk-in' assert await lookup_reservation() == 'walk-in' - # 3. No-input flows, defaulted input before a context, and the keyword-only catch-all + # 3. No-input flows, and a defaulted input before a context assert await kitchen_status() == 'open' assert await special() == 'thai' assert await special('isan') == 'isan' - assert await kwonly_special() == 'thai' # 4. None isn't a str; neither is 3 with pytest.raises(GenkitError): From 54115f887774b40764bfc95c3971877c0cba0ce0 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 16 Nov 2026 15:11:36 -0600 Subject: [PATCH 18/20] test(py): separate an omitted input from an explicit None in the shapes contract --- .../flow_tool_shapes_contract_test.py | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py b/packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py index e81623161..44334a484 100644 --- a/packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py +++ b/packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py @@ -61,7 +61,7 @@ async def todays_special(cuisine: str = 'italian') -> str: return f'{cuisine}: risotto' -async def lookup_reservation(res_id: str | None = None) -> str: +async def lookup_reservation(res_id: str | None = 'R-100') -> str: return res_id or 'walk-in' @@ -132,7 +132,7 @@ async def check_allergens(dish: str = 'pad thai') -> str: return f'{dish}: peanuts' -async def find_table(res_id: str | None = None) -> str: +async def find_table(res_id: str | None = 'R-100') -> str: return res_id or 'bar seat' @@ -347,7 +347,7 @@ async def todays_special(cuisine: str = 'italian') -> str: return f'{cuisine}: risotto' @ai.flow - async def lookup_reservation(res_id: str | None = None) -> str: + async def lookup_reservation(res_id: str | None = 'R-100') -> str: return res_id or 'walk-in' @ai.flow @@ -371,9 +371,9 @@ async def special(cuisine: str = 'thai', ctx: FlowContext | None = None) -> str: assert await todays_special.stream().response == 'italian: risotto' assert await todays_special.stream('thai').response == 'thai: risotto' - # 2. None is a value when the input type includes it + # 2. Omitting the input uses the default; an explicit None is a value, not "use the default" + assert await lookup_reservation() == 'R-100' assert await lookup_reservation(None) == 'walk-in' - assert await lookup_reservation() == 'walk-in' # 3. No-input flows, and a defaulted input before a context assert await kitchen_status() == 'open' @@ -405,9 +405,19 @@ async def test_defaulted_tool_calls() -> None: async def check_allergens(dish: str = 'pad thai') -> str: return f'{dish}: peanuts' + @ai.tool() + async def find_table(res_id: str | None = 'R-100') -> str: + return res_id or 'bar seat' + + # 1. Omit the input to use the default, or pass a str assert await check_allergens() == 'pad thai: peanuts' assert await check_allergens('larb') == 'larb: peanuts' + # 2. Omitting the input uses the default; an explicit None is a value, same as flows + assert await find_table() == 'R-100' + assert await find_table(None) == 'bar seat' + + # 3. None isn't a str with pytest.raises(GenkitError): await check_allergens(None) # pyright: ignore[reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] From ec7d06d747f2dabccdade82b1c6e84413ec445ee Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 16 Nov 2026 15:36:37 -0600 Subject: [PATCH 19/20] fix(py): accept a ref picked between providers when no config is passed 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. --- packages/genkit/src/genkit/_ai/_aio.py | 305 +++++++++++++++++- packages/genkit/src/genkit/exp/_api.py | 22 +- .../typecheck/action_and_ref_contract_test.py | 2 +- .../typecheck/ref_config_contract_test.py | 245 ++++++++++++++ 4 files changed, 561 insertions(+), 13 deletions(-) create mode 100644 packages/genkit/tests/typecheck/ref_config_contract_test.py diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 4f6b5718c..02a07e5e3 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -809,6 +809,34 @@ def define_value(self, *, kind: str, name: str, value: object) -> None: self._registry.register_value(kind, name, value, allow_overwrite=True) # Overload 1: Both input_schema and output_schema typed -> Prompt[InputT, OutputT] + # No config: any ref, including one picked between providers. + @overload + def define_prompt( + self, + name: str | None = None, + *, + variant: str | None = None, + model: ModelRef[Any] | Action | str | None = None, + config: None = None, + description: str | None = None, + system: str | list[Part] | None = None, + prompt: str | list[Part] | None = None, + messages: str | list[Message] | None = None, + output_format: str | None = None, + output_content_type: str | None = None, + output_instructions: bool | str | None = None, + output_constrained: bool | None = None, + max_turns: int | None = None, + return_tool_requests: bool | None = None, + metadata: dict[str, object] | None = None, + tools: Sequence[str | Tool] | None = None, + tool_choice: ToolChoice | None = None, + use: Sequence[Middleware] | None = None, + docs: list[Document] | None = None, + input_schema: type[InputT], + output_schema: type[OutputT], + ) -> Prompt[InputT, OutputT]: ... + @overload def define_prompt( self, @@ -843,7 +871,7 @@ def define_prompt( *, variant: str | None = None, model: ModelRef[ModelRefConfigT] | Action | str | None = None, - config: ModelRefConfigT | Mapping[str, Any] | None = None, + config: ModelRefConfigT | Mapping[str, Any] | None, description: str | None = None, system: str | list[Part] | None = None, prompt: str | list[Part] | None = None, @@ -864,6 +892,34 @@ def define_prompt( ) -> Prompt[InputT, OutputT]: ... # Overload 2: Only input_schema typed -> Prompt[InputT, Any] + # No config: any ref, including one picked between providers. + @overload + def define_prompt( + self, + name: str | None = None, + *, + variant: str | None = None, + model: ModelRef[Any] | Action | str | None = None, + config: None = None, + description: str | None = None, + system: str | list[Part] | None = None, + prompt: str | list[Part] | None = None, + messages: str | list[Message] | None = None, + output_format: str | None = None, + output_content_type: str | None = None, + output_instructions: bool | str | None = None, + output_constrained: bool | None = None, + max_turns: int | None = None, + return_tool_requests: bool | None = None, + metadata: dict[str, object] | None = None, + tools: Sequence[str | Tool] | None = None, + tool_choice: ToolChoice | None = None, + use: Sequence[Middleware] | None = None, + docs: list[Document] | None = None, + input_schema: type[InputT], + output_schema: dict[str, object] | str | None = None, + ) -> Prompt[InputT, Any]: ... + @overload def define_prompt( self, @@ -898,7 +954,7 @@ def define_prompt( *, variant: str | None = None, model: ModelRef[ModelRefConfigT] | Action | str | None = None, - config: ModelRefConfigT | Mapping[str, Any] | None = None, + config: ModelRefConfigT | Mapping[str, Any] | None, description: str | None = None, system: str | list[Part] | None = None, prompt: str | list[Part] | None = None, @@ -919,6 +975,34 @@ def define_prompt( ) -> Prompt[InputT, Any]: ... # Overload 3: Only output_schema typed -> Prompt[Any, OutputT] + # No config: any ref, including one picked between providers. + @overload + def define_prompt( + self, + name: str | None = None, + *, + variant: str | None = None, + model: ModelRef[Any] | Action | str | None = None, + config: None = None, + description: str | None = None, + system: str | list[Part] | None = None, + prompt: str | list[Part] | None = None, + messages: str | list[Message] | None = None, + output_format: str | None = None, + output_content_type: str | None = None, + output_instructions: bool | str | None = None, + output_constrained: bool | None = None, + max_turns: int | None = None, + return_tool_requests: bool | None = None, + metadata: dict[str, object] | None = None, + tools: Sequence[str | Tool] | None = None, + tool_choice: ToolChoice | None = None, + use: Sequence[Middleware] | None = None, + docs: list[Document] | None = None, + input_schema: dict[str, object] | str | None = None, + output_schema: type[OutputT], + ) -> Prompt[Any, OutputT]: ... + @overload def define_prompt( self, @@ -953,7 +1037,7 @@ def define_prompt( *, variant: str | None = None, model: ModelRef[ModelRefConfigT] | Action | str | None = None, - config: ModelRefConfigT | Mapping[str, Any] | None = None, + config: ModelRefConfigT | Mapping[str, Any] | None, description: str | None = None, system: str | list[Part] | None = None, prompt: str | list[Part] | None = None, @@ -974,6 +1058,34 @@ def define_prompt( ) -> Prompt[Any, OutputT]: ... # Overload 4: Neither typed -> Prompt[Any, Any] + # No config: any ref, including one picked between providers. + @overload + def define_prompt( + self, + name: str | None = None, + *, + variant: str | None = None, + model: ModelRef[Any] | Action | str | None = None, + config: None = None, + description: str | None = None, + system: str | list[Part] | None = None, + prompt: str | list[Part] | None = None, + messages: str | list[Message] | None = None, + output_format: str | None = None, + output_content_type: str | None = None, + output_instructions: bool | str | None = None, + output_constrained: bool | None = None, + max_turns: int | None = None, + return_tool_requests: bool | None = None, + metadata: dict[str, object] | None = None, + tools: Sequence[str | Tool] | None = None, + tool_choice: ToolChoice | None = None, + use: Sequence[Middleware] | None = None, + docs: list[Document] | None = None, + input_schema: type | dict[str, object] | str | None = None, + output_schema: type | dict[str, object] | str | None = None, + ) -> Prompt[Any, Any]: ... + @overload def define_prompt( self, @@ -1008,7 +1120,7 @@ def define_prompt( *, variant: str | None = None, model: ModelRef[ModelRefConfigT] | Action | str | None = None, - config: ModelRefConfigT | Mapping[str, Any] | None = None, + config: ModelRefConfigT | Mapping[str, Any] | None, description: str | None = None, system: str | list[Part] | None = None, prompt: str | list[Part] | None = None, @@ -1525,6 +1637,33 @@ async def _embedder_and_options( return action, options # Overload: config=ModelConfigDict, output_schema=type[T] -> ModelResponse[T] + # No config: any ref, including one picked between providers. + @overload + async def generate( + self, + *, + model: ModelRef[Any] | Action | str | None = None, + prompt: str | list[Part] | None = None, + system: str | list[Part] | None = None, + messages: list[Message] | None = None, + tools: Sequence[str | Tool] | None = None, + return_tool_requests: bool | None = None, + tool_choice: ToolChoice | None = None, + resume_respond: Part | list[Part] | None = None, + resume_restart: Part | list[Part] | None = None, + resume_metadata: dict[str, Any] | None = None, + config: None = None, + max_turns: int | None = None, + context: dict[str, object] | None = None, + output_schema: type[OutputT], + output_format: str | None = None, + output_content_type: str | None = None, + output_instructions: bool | str | None = None, + output_constrained: bool | None = None, + use: Sequence[Middleware] | None = None, + docs: list[Document] | None = None, + ) -> ModelResponse[OutputT]: ... + @overload async def generate( self, @@ -1566,7 +1705,7 @@ async def generate( resume_respond: Part | list[Part] | None = None, resume_restart: Part | list[Part] | None = None, resume_metadata: dict[str, Any] | None = None, - config: ModelRefConfigT | Mapping[str, Any] | None = None, + config: ModelRefConfigT | Mapping[str, Any] | None, max_turns: int | None = None, context: dict[str, object] | None = None, output_schema: type[OutputT], @@ -1579,6 +1718,33 @@ async def generate( ) -> ModelResponse[OutputT]: ... # Overload: config=ModelConfigDict, no output_schema -> ModelResponse[Any] + # No config: any ref, including one picked between providers. + @overload + async def generate( + self, + *, + model: ModelRef[Any] | Action | str | None = None, + prompt: str | list[Part] | None = None, + system: str | list[Part] | None = None, + messages: list[Message] | None = None, + tools: Sequence[str | Tool] | None = None, + return_tool_requests: bool | None = None, + tool_choice: ToolChoice | None = None, + resume_respond: Part | list[Part] | None = None, + resume_restart: Part | list[Part] | None = None, + resume_metadata: dict[str, Any] | None = None, + config: None = None, + max_turns: int | None = None, + context: dict[str, object] | None = None, + output_schema: type[Any] | dict[str, Any] | str | None = None, + output_format: str | None = None, + output_content_type: str | None = None, + output_instructions: bool | str | None = None, + output_constrained: bool | None = None, + use: Sequence[Middleware] | None = None, + docs: list[Document] | None = None, + ) -> ModelResponse[Any]: ... + @overload async def generate( self, @@ -1620,7 +1786,7 @@ async def generate( resume_respond: Part | list[Part] | None = None, resume_restart: Part | list[Part] | None = None, resume_metadata: dict[str, Any] | None = None, - config: ModelRefConfigT | Mapping[str, Any] | None = None, + config: ModelRefConfigT | Mapping[str, Any] | None, max_turns: int | None = None, context: dict[str, object] | None = None, output_schema: type[Any] | dict[str, Any] | str | None = None, @@ -1726,6 +1892,33 @@ class Weather(BaseModel): ) # Overload: config=ModelConfigDict, output_schema=type[T] -> ModelStreamResponse[T] + # No config: any ref, including one picked between providers. + @overload + def generate_stream( + self, + *, + model: ModelRef[Any] | Action | str | None = None, + prompt: str | list[Part] | None = None, + system: str | list[Part] | None = None, + messages: list[Message] | None = None, + tools: Sequence[str | Tool] | None = None, + return_tool_requests: bool | None = None, + tool_choice: ToolChoice | None = None, + resume_respond: Part | list[Part] | None = None, + resume_restart: Part | list[Part] | None = None, + resume_metadata: dict[str, Any] | None = None, + config: None = None, + max_turns: int | None = None, + context: dict[str, object] | None = None, + output_schema: type[OutputT], + output_format: str | None = None, + output_content_type: str | None = None, + output_instructions: bool | str | None = None, + output_constrained: bool | None = None, + use: Sequence[Middleware] | None = None, + docs: list[Document] | None = None, + ) -> ModelStreamResponse[OutputT]: ... + @overload def generate_stream( self, @@ -1767,7 +1960,7 @@ def generate_stream( resume_respond: Part | list[Part] | None = None, resume_restart: Part | list[Part] | None = None, resume_metadata: dict[str, Any] | None = None, - config: ModelRefConfigT | Mapping[str, Any] | None = None, + config: ModelRefConfigT | Mapping[str, Any] | None, max_turns: int | None = None, context: dict[str, object] | None = None, output_schema: type[OutputT], @@ -1780,6 +1973,33 @@ def generate_stream( ) -> ModelStreamResponse[OutputT]: ... # Overload: config=ModelConfigDict, no output_schema -> ModelStreamResponse[Any] + # No config: any ref, including one picked between providers. + @overload + def generate_stream( + self, + *, + model: ModelRef[Any] | Action | str | None = None, + prompt: str | list[Part] | None = None, + system: str | list[Part] | None = None, + messages: list[Message] | None = None, + tools: Sequence[str | Tool] | None = None, + return_tool_requests: bool | None = None, + tool_choice: ToolChoice | None = None, + resume_respond: Part | list[Part] | None = None, + resume_restart: Part | list[Part] | None = None, + resume_metadata: dict[str, Any] | None = None, + config: None = None, + max_turns: int | None = None, + context: dict[str, object] | None = None, + output_schema: type[Any] | dict[str, Any] | str | None = None, + output_format: str | None = None, + output_content_type: str | None = None, + output_instructions: bool | str | None = None, + output_constrained: bool | None = None, + use: Sequence[Middleware] | None = None, + docs: list[Document] | None = None, + ) -> ModelStreamResponse[Any]: ... + @overload def generate_stream( self, @@ -1821,7 +2041,7 @@ def generate_stream( resume_respond: Part | list[Part] | None = None, resume_restart: Part | list[Part] | None = None, resume_metadata: dict[str, Any] | None = None, - config: ModelRefConfigT | Mapping[str, Any] | None = None, + config: ModelRefConfigT | Mapping[str, Any] | None, max_turns: int | None = None, context: dict[str, object] | None = None, output_schema: type[Any] | dict[str, Any] | str | None = None, @@ -2021,13 +2241,37 @@ async def _generate( caller_stopped=caller_stopped, ) + # No config: any ref, including one picked between providers. + @overload + async def embed( + self, + *, + embedder: str | EmbedderRef[Any], + content: str | Document, + metadata: dict[str, object] | None = None, + config: None = None, + context: dict[str, Any] | None = None, + ) -> list[Embedding]: ... + + # A config is pinned to the ref's config class. + @overload async def embed( self, *, embedder: str | EmbedderRef[EmbedderRefConfigT], content: str | Document, metadata: dict[str, object] | None = None, - config: EmbedderRefConfigT | Mapping[str, Any] | None = None, + config: EmbedderRefConfigT | Mapping[str, Any] | None, + context: dict[str, Any] | None = None, + ) -> list[Embedding]: ... + + async def embed( + self, + *, + embedder: str | EmbedderRef[Any], + content: str | Document, + metadata: dict[str, object] | None = None, + config: BaseModel | Mapping[str, Any] | None = None, context: dict[str, Any] | None = None, ) -> list[Embedding]: """Generate vector embeddings for a single document or string. @@ -2075,13 +2319,37 @@ async def embed( ).response return response.embeddings + # No config: any ref, including one picked between providers. + @overload + async def embed_many( + self, + *, + embedder: str | EmbedderRef[Any], + content: Sequence[str | Document], + metadata: dict[str, object] | None = None, + config: None = None, + context: dict[str, Any] | None = None, + ) -> list[Embedding]: ... + + # A config is pinned to the ref's config class. + @overload async def embed_many( self, *, embedder: str | EmbedderRef[EmbedderRefConfigT], content: Sequence[str | Document], metadata: dict[str, object] | None = None, - config: EmbedderRefConfigT | Mapping[str, Any] | None = None, + config: EmbedderRefConfigT | Mapping[str, Any] | None, + context: dict[str, Any] | None = None, + ) -> list[Embedding]: ... + + async def embed_many( + self, + *, + embedder: str | EmbedderRef[Any], + content: Sequence[str | Document], + metadata: dict[str, object] | None = None, + config: BaseModel | Mapping[str, Any] | None = None, context: dict[str, Any] | None = None, ) -> list[Embedding]: """Generate vector embeddings for multiple documents in a single batch call. @@ -2258,6 +2526,21 @@ async def cancel_operation( """ return await cancel_operation(self._registry, operation, context=context, config=config) + # No config: any ref, including one picked between providers. + @overload + async def generate_operation( + self, + *, + model: ModelRef[Any] | BackgroundModel | str | None = None, + prompt: str | list[Part] | None = None, + system: str | list[Part] | None = None, + messages: list[Message] | None = None, + config: None = None, + context: dict[str, object] | None = None, + use: Sequence[Middleware] | None = None, + docs: list[Document] | None = None, + ) -> Operation[ModelResponse]: ... + @overload async def generate_operation( self, @@ -2280,7 +2563,7 @@ async def generate_operation( prompt: str | list[Part] | None = None, system: str | list[Part] | None = None, messages: list[Message] | None = None, - config: ModelRefConfigT | Mapping[str, Any] | None = None, + config: ModelRefConfigT | Mapping[str, Any] | None, context: dict[str, object] | None = None, use: Sequence[Middleware] | None = None, docs: list[Document] | None = None, diff --git a/packages/genkit/src/genkit/exp/_api.py b/packages/genkit/src/genkit/exp/_api.py index 2ad3fe87b..e689039ef 100644 --- a/packages/genkit/src/genkit/exp/_api.py +++ b/packages/genkit/src/genkit/exp/_api.py @@ -102,6 +102,26 @@ def define_custom_agent( metadata=metadata, ) + # No config: any ref, including one picked between providers. + @overload + def define_agent( + self, + name: str, + *, + model: ModelRef[Any] | Action | str | None = None, + system: str | list[Part] | None = None, + tools: Sequence[str | Tool] | None = None, + use: Sequence[Middleware] | None = None, + config: None = None, + max_turns: int | None = None, + description: str | None = None, + metadata: dict[str, object] | None = None, + store: SessionStore[StateT] | None = None, + state_transform: StateTransform | None = None, + chunk_transform: ChunkTransform | None = None, + state_schema: type[StateT] | None = None, + ) -> Agent[StateT]: ... + @overload def define_agent( self, @@ -130,7 +150,7 @@ def define_agent( system: str | list[Part] | None = None, tools: Sequence[str | Tool] | None = None, use: Sequence[Middleware] | None = None, - config: ModelRefConfigT | Mapping[str, Any] | None = None, + config: ModelRefConfigT | Mapping[str, Any] | None, max_turns: int | None = None, description: str | None = None, metadata: dict[str, object] | None = None, diff --git a/packages/genkit/tests/typecheck/action_and_ref_contract_test.py b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py index 1f96366e5..69b139451 100644 --- a/packages/genkit/tests/typecheck/action_and_ref_contract_test.py +++ b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py @@ -248,4 +248,4 @@ async def embed_menu(req: EmbedRequest[MenuEmbedConfig]) -> EmbedResponse: await ai.generate(model=bistro_ref, prompt='dish', config=OtherModelConfig()) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] with pytest.raises(GenkitError): - await ai.embed(embedder=embed_ref, content='tartine', config=OtherEmbedConfig()) # pyright: ignore[reportArgumentType] # pyrefly: ignore[bad-argument-type] # ty: ignore[invalid-argument-type] + await ai.embed(embedder=embed_ref, content='tartine', config=OtherEmbedConfig()) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] diff --git a/packages/genkit/tests/typecheck/ref_config_contract_test.py b/packages/genkit/tests/typecheck/ref_config_contract_test.py new file mode 100644 index 000000000..6149c4e9a --- /dev/null +++ b/packages/genkit/tests/typecheck/ref_config_contract_test.py @@ -0,0 +1,245 @@ +# 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 a ref's config class at every entry point. + +Each entry point that takes a ``ModelRef`` / ``EmbedderRef`` has two arms. +With no ``config``, any ref fits, including one picked between providers +(``ModelRef[BistroConfig] | ModelRef[CafeConfig]``). With a ``config``, the +config is pinned to the ref's class: the right class or a dict passes, another +family's class fails, and so does a typed config on a ref picked between +providers. A typed ``output_schema`` types ``response.output`` in both arms. +""" + +import pytest +from pydantic import BaseModel +from typing_extensions import assert_type + +from genkit import Embedding, Genkit, GenkitError, Message, ModelResponse, Operation, Part, Role +from genkit.embedder import EmbedderRef, EmbedRequest, EmbedResponse +from genkit.exp import Genkit as ExpGenkit +from genkit.model import ModelConfig, ModelContext, ModelRef, ModelRequest + + +class BistroConfig(ModelConfig): + spice_level: int = 1 + + +class CafeConfig(ModelConfig): + roast: str = 'medium' + + +class BistroEmbedConfig(BaseModel): + dimensions: int = 4 + + +class CafeEmbedConfig(BaseModel): + task_type: str = 'menu' + + +class Dish(BaseModel): + name: str + + +BISTRO = ModelRef(name='bistro/chef', config_schema=BistroConfig) +CAFE = ModelRef(name='cafe/barista', config_schema=CafeConfig) +BISTRO_REEL = ModelRef(name='bistro/reel', config_schema=BistroConfig) +CAFE_REEL = ModelRef(name='cafe/reel', config_schema=CafeConfig) +BISTRO_EMBED = EmbedderRef(name='bistro/embed', config_schema=BistroEmbedConfig) +CAFE_EMBED = EmbedderRef(name='cafe/embed', config_schema=CafeEmbedConfig) + + +def pick_model(use_bistro: bool) -> ModelRef[BistroConfig] | ModelRef[CafeConfig]: + return BISTRO if use_bistro else CAFE + + +def pick_reel(use_bistro: bool) -> ModelRef[BistroConfig] | ModelRef[CafeConfig]: + return BISTRO_REEL if use_bistro else CAFE_REEL + + +def pick_embedder(use_bistro: bool) -> EmbedderRef[BistroEmbedConfig] | EmbedderRef[CafeEmbedConfig]: + return BISTRO_EMBED if use_bistro else CAFE_EMBED + + +def _app() -> Genkit: + ai = Genkit() + + async def chef(req: ModelRequest[BistroConfig], ctx: ModelContext) -> ModelResponse: + del req, ctx + return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('{"name": "tartine"}')])) + + async def barista(req: ModelRequest[CafeConfig], ctx: ModelContext) -> ModelResponse: + del req, ctx + return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('{"name": "cortado"}')])) + + async def start_reel(req: ModelRequest, ctx: ModelContext) -> Operation: + del req, ctx + return Operation(id='reel-1') + + async def check_reel(op: Operation[ModelResponse], ctx: ModelContext) -> Operation: + del ctx + return op + + async def embed(req: EmbedRequest) -> EmbedResponse: + return EmbedResponse(embeddings=[Embedding(embedding=[0.25]) for _ in req.input]) + + ai.define_model(name='bistro/chef', fn=chef, config_schema=BistroConfig) + ai.define_model(name='cafe/barista', fn=barista, config_schema=CafeConfig) + ai.define_background_model(name='bistro/reel', start=start_reel, check=check_reel, config_schema=BistroConfig) + ai.define_background_model(name='cafe/reel', start=start_reel, check=check_reel, config_schema=CafeConfig) + ai.define_embedder(name='bistro/embed', fn=embed, config_schema=BistroEmbedConfig) + ai.define_embedder(name='cafe/embed', fn=embed, config_schema=CafeEmbedConfig) + return ai + + +@pytest.mark.asyncio +async def test_generate_ref_config() -> None: + """``generate``: any ref without config; a config pinned to the ref's class.""" + ai = _app() + either = pick_model(use_bistro=False) + + # 1. A ref picked between providers, no config, untyped and typed output + assert (await ai.generate(model=either, prompt='Suggest a drink.')).text == '{"name": "cortado"}' + picked = await ai.generate(model=either, prompt='Suggest a drink.', output_schema=Dish) + assert_type(picked.output, Dish | None) + assert picked.output is not None + assert picked.output.name == 'cortado' + + # 2. The ref's own config class or a dict, untyped and typed output + await ai.generate(model=BISTRO, prompt='Suggest a dish.', config=BistroConfig(spice_level=3)) + await ai.generate(model=BISTRO, prompt='Suggest a dish.', config={'spice_level': 3}) + pinned = await ai.generate(model=BISTRO, prompt='Suggest a dish.', config=BistroConfig(), output_schema=Dish) + assert_type(pinned.output, Dish | None) + assert pinned.output is not None + assert pinned.output.name == 'tartine' + + # 3. Another family's config fails, with a single ref or one picked between providers + with pytest.raises(GenkitError): + await ai.generate(model=BISTRO, prompt='Suggest a dish.', config=CafeConfig()) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + with pytest.raises(GenkitError): + await ai.generate(model=either, prompt='Suggest a drink.', config=BistroConfig()) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + + +@pytest.mark.asyncio +async def test_generate_stream_ref_config() -> None: + """``generate_stream``: same two arms as ``generate``.""" + ai = _app() + either = pick_model(use_bistro=False) + + # 1. No config + assert (await ai.generate_stream(model=either, prompt='Suggest a drink.').response).text == '{"name": "cortado"}' + picked = await ai.generate_stream(model=either, prompt='Suggest a drink.', output_schema=Dish).response + assert_type(picked.output, Dish | None) + + # 2. Pinned config or a dict + await ai.generate_stream(model=BISTRO, prompt='Suggest a dish.', config=BistroConfig()).response + await ai.generate_stream(model=BISTRO, prompt='Suggest a dish.', config={'spice_level': 2}).response + pinned = await ai.generate_stream(model=BISTRO, prompt='x', config=BistroConfig(), output_schema=Dish).response + assert_type(pinned.output, Dish | None) + + # 3. Wrong family + with pytest.raises(GenkitError): + await ai.generate_stream(model=BISTRO, prompt='Suggest a dish.', config=CafeConfig()).response # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + with pytest.raises(GenkitError): + await ai.generate_stream(model=either, prompt='Suggest a drink.', config=BistroConfig()).response # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + + +@pytest.mark.asyncio +async def test_generate_operation_ref_config() -> None: + """``generate_operation``: same two arms for background models.""" + ai = _app() + either = pick_reel(use_bistro=False) + + assert (await ai.generate_operation(model=either, prompt='A pour-over.')).id == 'reel-1' + await ai.generate_operation(model=BISTRO_REEL, prompt='A risotto.', config=BistroConfig()) + await ai.generate_operation(model=BISTRO_REEL, prompt='A risotto.', config={'spice_level': 2}) + + with pytest.raises(GenkitError): + await ai.generate_operation(model=BISTRO_REEL, prompt='A risotto.', config=CafeConfig()) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + with pytest.raises(GenkitError): + await ai.generate_operation(model=either, prompt='A pour-over.', config=BistroConfig()) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + + +@pytest.mark.asyncio +async def test_embed_ref_config() -> None: + """``embed`` and ``embed_many``: any ref without config; a config pinned to the ref's class.""" + ai = _app() + either = pick_embedder(use_bistro=False) + + # 1. No config + assert (await ai.embed(embedder=either, content='cortado'))[0].embedding == [0.25] + assert len(await ai.embed_many(embedder=either, content=['cortado', 'flat white'])) == 2 + + # 2. Pinned config or a dict + await ai.embed(embedder=BISTRO_EMBED, content='tartine', config=BistroEmbedConfig(dimensions=8)) + await ai.embed(embedder=BISTRO_EMBED, content='tartine', config={'dimensions': 8}) + await ai.embed_many(embedder=BISTRO_EMBED, content=['tartine'], config=BistroEmbedConfig()) + await ai.embed_many(embedder=BISTRO_EMBED, content=['tartine'], config={'dimensions': 8}) + + # 3. Wrong family, with a single ref or one picked between providers + with pytest.raises(GenkitError): + await ai.embed(embedder=BISTRO_EMBED, content='tartine', config=CafeEmbedConfig()) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + with pytest.raises(GenkitError): + await ai.embed(embedder=either, content='cortado', config=BistroEmbedConfig()) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + with pytest.raises(GenkitError): + await ai.embed_many(embedder=BISTRO_EMBED, content=['tartine'], config=CafeEmbedConfig()) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + with pytest.raises(GenkitError): + await ai.embed_many(embedder=either, content=['cortado'], config=BistroEmbedConfig()) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + + +@pytest.mark.asyncio +async def test_define_prompt_ref_config() -> None: + """``define_prompt``: any ref without config; a config pinned to the ref's class; typed output either way.""" + ai = _app() + either = pick_model(use_bistro=False) + + # 1. No config, untyped and typed output + drink = ai.define_prompt(name='drink', model=either, prompt='Suggest a drink.') + typed_drink = ai.define_prompt(name='typed_drink', model=either, prompt='Suggest a drink.', output_schema=Dish) + assert (await drink()).text == '{"name": "cortado"}' + assert_type((await typed_drink()).output, Dish | None) + + # 2. Pinned config or a dict, typed output + ai.define_prompt(name='dish', model=BISTRO, prompt='Suggest a dish.', config=BistroConfig()) + ai.define_prompt(name='dish_dict', model=BISTRO, prompt='Suggest a dish.', config={'spice_level': 2}) + typed_dish = ai.define_prompt( + name='typed_dish', model=BISTRO, prompt='Suggest a dish.', config=BistroConfig(), output_schema=Dish + ) + # ty types define_prompt Unknown whenever config and a typed output_schema are both + # passed, with a ref or a model name. Same on the base branch; pyright and pyrefly get it. + assert_type((await typed_dish()).output, Dish | None) # ty: ignore[type-assertion-failure] + + # 3. Wrong family + with pytest.raises(GenkitError): + ai.define_prompt(name='bad', model=BISTRO, prompt='x', config=CafeConfig()) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + with pytest.raises(GenkitError): + ai.define_prompt(name='bad_either', model=either, prompt='x', config=BistroConfig()) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + + +def test_define_agent_ref_config() -> None: + """``genkit.exp`` ``define_agent``: same two arms.""" + ai = ExpGenkit() + either = pick_model(use_bistro=False) + + ai.define_agent('host', model=either, system='Seat guests.') + ai.define_agent('sommelier', model=BISTRO, config=BistroConfig()) + ai.define_agent('sommelier_dict', model=BISTRO, config={'spice_level': 2}) + with pytest.raises(GenkitError): + ai.define_agent('bad', model=BISTRO, config=CafeConfig()) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + with pytest.raises(GenkitError): + ai.define_agent('bad_either', model=either, config=BistroConfig()) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] From d78471463e00715887b439d8169fb2f090ee3ae5 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 16 Nov 2026 16:15:23 -0600 Subject: [PATCH 20/20] test(py): note the ty overload-order bug behind the define_prompt pin --- packages/genkit/tests/typecheck/ref_config_contract_test.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/genkit/tests/typecheck/ref_config_contract_test.py b/packages/genkit/tests/typecheck/ref_config_contract_test.py index 6149c4e9a..defeb3f61 100644 --- a/packages/genkit/tests/typecheck/ref_config_contract_test.py +++ b/packages/genkit/tests/typecheck/ref_config_contract_test.py @@ -220,8 +220,9 @@ async def test_define_prompt_ref_config() -> None: typed_dish = ai.define_prompt( name='typed_dish', model=BISTRO, prompt='Suggest a dish.', config=BistroConfig(), output_schema=Dish ) - # ty types define_prompt Unknown whenever config and a typed output_schema are both - # passed, with a ref or a model name. Same on the base branch; pyright and pyrefly get it. + # ty < 0.0.33 bug: the overload result depends on keyword-argument order, so prompt= + # before config= types this Unknown. Fixed upstream (astral-sh/ty#3139). Remove when + # ty is bumped. assert_type((await typed_dish()).output, Dish | None) # ty: ignore[type-assertion-failure] # 3. Wrong family