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-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/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 46924c462..02a07e5e3 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -83,14 +83,22 @@ 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, + DefaultInputCtxFn, + 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 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, @@ -105,7 +113,6 @@ EmbedRequest, ModelConfigDict, ModelRef, - ModelRefConfigT, ModelRequest, Part, ToolChoice, @@ -124,7 +131,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, @@ -141,6 +148,7 @@ InputT = TypeVar('InputT') OutputT = TypeVar('OutputT') ChunkT = TypeVar('ChunkT') +ModelRefConfigT = TypeVar('ModelRefConfigT', bound=BaseModel) R = TypeVar('R') T = TypeVar('T') @@ -318,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, @@ -325,6 +340,13 @@ def flow( /, ) -> Flow[InputT, OutputT, ChunkT]: ... + @overload + def flow( + self, + func: CtxDefaultInputFn[FlowContext[ChunkT], InputT, OutputT], + /, + ) -> DefaultedFlow[InputT, OutputT, ChunkT]: ... + @overload def flow( self, @@ -349,23 +371,23 @@ def flow( @overload def flow( self, - func: Callable[[InputT], Awaitable[OutputT]], + func: DefaultInputFn[InputT, OutputT], /, - ) -> Flow[InputT, OutputT]: ... + ) -> DefaultedFlow[InputT, OutputT]: ... @overload def flow( self, - func: Callable[[], Awaitable[OutputT]], + func: Callable[[InputT], Awaitable[OutputT]], /, - ) -> Flow[None, OutputT]: ... + ) -> Flow[InputT, OutputT]: ... @overload def flow( self, - func: Callable[..., Awaitable[OutputT]], + func: Callable[[], Awaitable[OutputT]], /, - ) -> Flow[Any, OutputT, Any]: ... + ) -> Flow[None, OutputT]: ... def flow( self, @@ -492,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, @@ -499,6 +528,13 @@ def tool( /, ) -> Tool[InputT, OutputT, ChunkT]: ... + @overload + def tool( + self, + func: CtxDefaultInputFn[ToolContext[ChunkT], InputT, OutputT], + /, + ) -> DefaultedTool[InputT, OutputT, ChunkT]: ... + @overload def tool( self, @@ -518,7 +554,14 @@ def tool( self, func: Callable[[ToolContext[ChunkT]], Awaitable[OutputT]], /, - ) -> Tool[Any, OutputT, ChunkT]: ... + ) -> Tool[None, OutputT, ChunkT]: ... + + @overload + def tool( + self, + func: DefaultInputFn[InputT, OutputT], + /, + ) -> DefaultedTool[InputT, OutputT]: ... @overload def tool( @@ -766,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, @@ -800,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, @@ -821,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, @@ -855,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, @@ -876,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, @@ -910,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, @@ -931,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, @@ -965,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, @@ -990,7 +1145,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, @@ -1446,7 +1601,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. @@ -1465,10 +1620,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) @@ -1481,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, @@ -1522,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], @@ -1535,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, @@ -1552,7 +1762,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, @@ -1576,10 +1786,10 @@ 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 | 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, @@ -1591,7 +1801,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, @@ -1604,7 +1814,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, @@ -1682,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, @@ -1723,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], @@ -1736,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, @@ -1753,7 +2017,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, @@ -1777,10 +2041,10 @@ 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 | 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, @@ -1792,7 +2056,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, @@ -1805,7 +2069,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, @@ -1889,7 +2153,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, @@ -1902,7 +2166,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, @@ -1977,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. @@ -2031,19 +2319,48 @@ 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: list[str] | list[Document], + 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. + ``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) @@ -2209,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, @@ -2231,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/_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/_ai/_decorators.py b/packages/genkit/src/genkit/_ai/_decorators.py index 2c87be6cb..fae88e8ca 100644 --- a/packages/genkit/src/genkit/_ai/_decorators.py +++ b/packages/genkit/src/genkit/_ai/_decorators.py @@ -24,10 +24,10 @@ from pydantic import BaseModel from genkit._ai._tools import define_tool -from genkit._core._action import FlowContext -from genkit._core._flow import Flow, define_flow +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 Tool, ToolContext +from genkit._core._tool import DefaultedTool, Tool, ToolContext # TypeVars for generic input/output typing InputT = TypeVar('InputT') @@ -45,9 +45,10 @@ 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 = ..., 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,11 +61,21 @@ 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]] ) -> Flow[InputT, OutputT, ChunkT]: ... + @overload + def __call__( + self, func: CtxDefaultInputFn[FlowContext[ChunkT], InputT, OutputT] + ) -> DefaultedFlow[InputT, OutputT, ChunkT]: ... + @overload def __call__( self, func: Callable[[FlowContext[ChunkT], InputT], Awaitable[OutputT]] @@ -77,13 +88,13 @@ 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: Callable[[InputT], Awaitable[OutputT]]) -> Flow[InputT, OutputT]: ... + def __call__(self, func: DefaultInputFn[InputT, OutputT]) -> DefaultedFlow[InputT, OutputT]: ... @overload - def __call__(self, func: Callable[[], Awaitable[OutputT]]) -> Flow[None, OutputT]: ... + def __call__(self, func: Callable[[InputT], Awaitable[OutputT]]) -> Flow[InputT, OutputT]: ... @overload - def __call__(self, func: Callable[..., Awaitable[OutputT]]) -> Flow[Any, OutputT, Any]: ... + def __call__(self, func: Callable[[], Awaitable[OutputT]]) -> Flow[None, OutputT]: ... def __call__(self, func: Callable[..., Awaitable[Any]]) -> Flow[Any, Any, Any]: return define_flow(self._registry, func, self._name, self._description) @@ -111,11 +122,21 @@ 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]] ) -> Tool[InputT, OutputT, ChunkT]: ... + @overload + def __call__( + self, func: CtxDefaultInputFn[ToolContext[ChunkT], InputT, OutputT] + ) -> DefaultedTool[InputT, OutputT, ChunkT]: ... + @overload def __call__( self, func: Callable[[ToolContext[ChunkT], InputT], Awaitable[OutputT]] @@ -125,7 +146,10 @@ 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: 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/_embedding.py b/packages/genkit/src/genkit/_ai/_embedding.py index 9880b0db6..bce598d7b 100644 --- a/packages/genkit/src/genkit/_ai/_embedding.py +++ b/packages/genkit/src/genkit/_ai/_embedding.py @@ -51,8 +51,11 @@ 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 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) @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..69a587dc4 100644 --- a/packages/genkit/src/genkit/_ai/_model.py +++ b/packages/genkit/src/genkit/_ai/_model.py @@ -77,7 +77,7 @@ # 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 +101,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 +157,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 90cbcb005..53e7d4dd4 100644 --- a/packages/genkit/src/genkit/_ai/_prompt.py +++ b/packages/genkit/src/genkit/_ai/_prompt.py @@ -68,7 +68,6 @@ from genkit._core._action import ( Action, ActionKind, - StreamingCallback, StreamResponse, create_action_key, get_current_context, @@ -98,8 +97,6 @@ Role, ) -ModelStreamingCallback = StreamingCallback - logger = get_logger(__name__) # TypeVars for generic input/output typing @@ -303,7 +300,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, @@ -454,7 +451,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. @@ -484,7 +481,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 39f37efa6..a51dce5c0 100644 --- a/packages/genkit/src/genkit/_ai/_tools.py +++ b/packages/genkit/src/genkit/_ai/_tools.py @@ -21,7 +21,15 @@ from pydantic import BaseModel, ValidationError -from genkit._core._action import Action +from genkit._core._action import ( + Action, + ActionKind, + CtxDefaultInputFn, + DefaultInputCtxFn, + 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 +37,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, @@ -167,7 +176,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, @@ -273,7 +284,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 @@ -284,10 +298,12 @@ 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. +# - 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, @@ -299,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, @@ -310,6 +337,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, +) -> DefaultedTool[ToolInputT, ToolOutputT, ToolChunkT]: ... + + @overload def define_tool( registry: Registry, @@ -340,7 +378,18 @@ 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 +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, +) -> DefaultedTool[ToolInputT, ToolOutputT]: ... @overload diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index 2ce3f2d92..b50e960c8 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 @@ -32,11 +34,13 @@ ClassVar, Generic, NamedTuple, + Protocol, Union, cast, get_args, get_origin, get_type_hints, + overload, ) from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError @@ -342,6 +346,7 @@ def parse_plugin_name_from_action_name(name: str) -> str | None: # async def ping(ctx: FlowContext) -> str: ... # no input # # Rules for the function: +# - Input and context are regular parameters (neither positional-only nor keyword-only). # - The context is the parameter annotated ActionContext or a subclass # (FlowContext, ToolContext, ModelContext, AgentContext). # - Any other parameter is the input, so there's only one. Put more fields @@ -372,13 +377,13 @@ 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. 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: @@ -461,6 +466,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." ) + # Every action kind takes at most one input and one context as regular + # parameters. A required `*, ctx` fails the handler overloads, and a + # defaulted one (`*, ctx: FlowContext | None = None`) still matches + # `Callable[[InputT], ...]` statically, so reject both here. + 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] = [] @@ -496,6 +510,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. @@ -833,10 +861,56 @@ 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 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) +_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 ``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 + + +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]: ... + + +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 @@ -1056,8 +1130,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 @@ -1173,7 +1247,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 @@ -1217,12 +1291,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, @@ -1233,9 +1350,11 @@ 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 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. @@ -1276,9 +1395,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. @@ -1324,8 +1447,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, @@ -1550,7 +1693,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 @@ -1629,7 +1772,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 @@ -1802,7 +1945,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 @@ -1814,6 +1957,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/_background.py b/packages/genkit/src/genkit/_core/_background.py index 86046a8b5..4d32de118 100644 --- a/packages/genkit/src/genkit/_core/_background.py +++ b/packages/genkit/src/genkit/_core/_background.py @@ -49,12 +49,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, ActionContext], Awaitable[Operation]] -CheckOpFn = Callable[[Operation[OutT], ActionContext], Awaitable[Operation]] -CancelOpFn = Callable[[Operation[OutT], ActionContext], Awaitable[Operation]] def _make_action_key(action_type: ActionKind | str, name: str) -> str: @@ -251,10 +246,10 @@ def __init__( self, name: str, start: StartOpFn[InT], - check: CheckOpFn[OutT], + check: Callable[[Operation[OutT], ActionContext], Awaitable[Operation]], *, kind: ActionKind, - cancel: CancelOpFn[OutT] | None = None, + cancel: Callable[[Operation[OutT], ActionContext], 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..ce1eb627d 100644 --- a/packages/genkit/src/genkit/_core/_flow.py +++ b/packages/genkit/src/genkit/_core/_flow.py @@ -28,10 +28,15 @@ Action, ActionKind, ChunkT, + CtxDefaultInputFn, + DefaultedAction, + DefaultInputCtxFn, + DefaultInputFn, FlowContext, InputT, OutputT, get_func_description, + input_has_default, ) from genkit._core._registry import Registry @@ -58,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, @@ -67,6 +84,15 @@ def __init__( description: str | None = None, ) -> None: ... + @overload + def __init__( + self: DefaultedFlow[_FlowInputT, _FlowOutputT, _FlowChunkT], + func: CtxDefaultInputFn[FlowContext[_FlowChunkT], _FlowInputT, _FlowOutputT], + *, + name: str | None = None, + description: str | None = None, + ) -> None: ... + @overload def __init__( self, @@ -87,8 +113,8 @@ def __init__( @overload def __init__( - self, - func: Callable[[InputT], Awaitable[OutputT]], + self: DefaultedFlow[_FlowInputT, _FlowOutputT, Any], + func: DefaultInputFn[_FlowInputT, _FlowOutputT], *, name: str | None = None, description: str | None = None, @@ -97,7 +123,7 @@ def __init__( @overload def __init__( self, - func: Callable[[], Awaitable[OutputT]], + func: Callable[[InputT], Awaitable[OutputT]], *, name: str | None = None, description: str | None = None, @@ -106,7 +132,7 @@ def __init__( @overload def __init__( self, - func: Callable[..., Awaitable[OutputT]], + func: Callable[[], Awaitable[OutputT]], *, name: str | None = None, description: str | None = None, @@ -141,6 +167,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 @@ -152,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, @@ -161,6 +206,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, +) -> DefaultedFlow[_FlowInputT, _FlowOutputT, _FlowChunkT]: ... + + @overload def define_flow( registry: Registry, @@ -188,6 +242,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, +) -> DefaultedFlow[_FlowInputT, _FlowOutputT]: ... + + @overload def define_flow( registry: Registry, @@ -212,7 +275,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/_model.py b/packages/genkit/src/genkit/_core/_model.py index 2bee1b80a..5ed1e1346 100644 --- a/packages/genkit/src/genkit/_core/_model.py +++ b/packages/genkit/src/genkit/_core/_model.py @@ -312,9 +312,12 @@ 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. -# Covariant so ModelRef[GeminiConfig] is assignable to ModelRef[BaseModel] or ModelRef[Any]. -ModelRefConfigT = TypeVar('ModelRefConfigT', bound=BaseModel, covariant=True) +# 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] and EmbedRequest[X] 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 the @@ -1854,6 +1857,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 @@ -1898,7 +1906,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. @@ -1926,6 +1934,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: @@ -1936,15 +1950,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 7cd211adc..0075db73a 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, @@ -952,3 +953,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 94038dae7..db96fd5b4 100644 --- a/packages/genkit/src/genkit/_core/_tool.py +++ b/packages/genkit/src/genkit/_core/_tool.py @@ -32,6 +32,10 @@ Action, ActionContext, ActionKind, + CtxDefaultInputFn, + DefaultedAction, + DefaultInputCtxFn, + DefaultInputFn, get_func_description, resolve_type_hints, ) @@ -41,7 +45,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) @@ -359,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], @@ -369,6 +387,16 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... + @overload + def __init__( + self: DefaultedTool[_I, _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], @@ -391,7 +419,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, @@ -399,6 +427,16 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... + @overload + def __init__( + self: DefaultedTool[_I, _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], @@ -501,7 +539,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 @@ -554,6 +592,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/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/genkit/ai/embedding_test.py b/packages/genkit/tests/genkit/ai/embedding_test.py index d19d91dd5..d3f1a2642 100644 --- a/packages/genkit/tests/genkit/ai/embedding_test.py +++ b/packages/genkit/tests/genkit/ai/embedding_test.py @@ -363,6 +363,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/flow_signature_test.py b/packages/genkit/tests/genkit/ai/flow_signature_test.py index 30e758756..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, 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. 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_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' 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..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] @@ -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[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]) @@ -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_signature_test.py b/packages/genkit/tests/genkit/core/action_signature_test.py index db75b65cc..6cf5df9a2 100644 --- a/packages/genkit/tests/genkit/core/action_signature_test.py +++ b/packages/genkit/tests/genkit/core/action_signature_test.py @@ -207,6 +207,25 @@ async def chef(request: ModelRequest, /, ctx: ActionContext) -> ModelResponse: Action(ActionKind.MODEL, 'chef', chef) +def test_action_with_keyword_only_parameter_raises_type_error() -> None: + """Every action kind takes regular parameters, so a keyword-only one raises at definition.""" + + async def chef(request: ModelRequest, *, ctx: ActionContext) -> ModelResponse: + del request, ctx + return _REPLY + + async def index_menu(doc: str, *, ctx: ActionContext | None = None) -> str: + del ctx + return doc + + with pytest.raises(TypeError, match="model 'chef' parameter 'ctx' is keyword-only"): + Action(ActionKind.MODEL, 'chef', chef) + with pytest.raises(TypeError, match="embedder 'menu' parameter 'ctx' is keyword-only"): + Action(ActionKind.EMBEDDER, 'menu', index_menu) + with pytest.raises(TypeError, match="custom 'menu' parameter 'ctx' is keyword-only"): + Action(ActionKind.CUSTOM, 'menu', index_menu) + + @pytest.mark.asyncio async def test_background_model_with_context_first_start_gets_both() -> None: """`start(ctx, request)` gets each by name, and the handle has the start action key.""" diff --git a/packages/genkit/tests/genkit/core/action_test.py b/packages/genkit/tests/genkit/core/action_test.py index 22bc38b20..d8c27ab0a 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..6ceffd996 --- /dev/null +++ b/packages/genkit/tests/genkit/core/public_types_runtime_test.py @@ -0,0 +1,90 @@ +# 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, + ], + 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 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')]), + ) + + assert usage.input_characters == len('Table for two') + assert usage.output_characters == len('Booked') + + +@pytest.mark.parametrize( + ('module', 'names'), + [ + ( + 'genkit', + [ + 'ActionResponse', + 'ModelConfig', + 'ModelConfigDict', + 'ModelStreamingCallback', + 'Resource', + 'StatusName', + 'StoppableStream', + 'ToolRequest', + 'ToolResponse', + ], + ), + ('genkit.middleware', ['MiddlewareRef']), + ('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: + """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..69b139451 --- /dev/null +++ b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py @@ -0,0 +1,251 @@ +# 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 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. +""" + +from typing import Any + +import pytest +from pydantic import BaseModel +from typing_extensions import assert_type + +from genkit import ( + Document, + Embedding, + Flow, + FlowContext, + Genkit, + GenkitError, + Message, + ModelResponse, + Part, + Role, + StreamResponse, + Tool, + 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 + + +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_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) + + 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_defaulted_inputs_can_be_omitted() -> None: + """A flow or tool whose input has a default is a ``DefaultedFlow`` / ``DefaultedTool`` 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, 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' + 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[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 annotation, not a no-input one.""" + 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. DefaultedFlow[str, str] is a Flow[str, str] + by_cuisine: Flow[str, str] = suggest_dish + + # 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 # pyright: ignore[reportAssignmentType] # pyrefly: ignore[bad-assignment] # ty: ignore[invalid-assignment] + + # 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 + 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.""" + 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[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] 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..0cc590b15 --- /dev/null +++ b/packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py @@ -0,0 +1,507 @@ +# 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. + +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. Unsupported shapes raise +``TypeError`` at definition: a required keyword-only parameter or two inputs +also fails at the decorator in all three checkers, while a defaulted +keyword-only parameter matches the 1-arg ``Callable`` overload statically and +is caught 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 +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 = 'R-100') -> 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) + + +# Unsupported: a keyword-only context (required or defaulted), and two inputs. + + +async def kwonly_special(cuisine: str = 'thai', *, ctx: FlowContext) -> str: + del ctx + return cuisine + + +async def kwonly_default_special(cuisine: str = 'thai', *, ctx: FlowContext | None = None) -> str: + del ctx + return cuisine + + +async def pair_dishes(main: str, side: str) -> str: + return f'{main} with {side}' + + +# 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 = 'R-100') -> 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) + + +# Unsupported tool shapes. + + +async def kwonly_soup(day: str = 'monday', *, ctx: ToolContext) -> str: + del ctx + return day + + +async def kwonly_default_soup(day: str = 'monday', *, ctx: ToolContext | None = None) -> 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() + + # 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] + + +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] + + +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] + + +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] + + +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] + + +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] + + +def test_unsupported_shapes_fail_at_the_decorator() -> None: + """Unsupported shapes raise ``TypeError`` at definition; required ``*, ctx`` and two inputs fail the decorator.""" + ai = Genkit() + + # 1. Required keyword-only context: fails all three checkers and raises at definition + 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. Defaulted keyword-only context: matches the 1-arg overload statically, rejected at definition + with pytest.raises(TypeError, match="flow 'kwonly_default_special' parameter 'ctx' is keyword-only"): + ai.flow(kwonly_default_special) + with pytest.raises(TypeError, match="tool 'kwonly_default_soup' parameter 'ctx' is keyword-only"): + ai.tool()(kwonly_default_soup) + + # 3. 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: + """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): + 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): + 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 = 'R-100') -> 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 + + # 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. 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' + + # 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' + + # 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' + + @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] + + +@pytest.mark.asyncio +async def test_defaulted_flows_fit_flow_annotations() -> None: + """A ``DefaultedFlow`` / ``DefaultedTool`` fits ``Flow[T, O]`` / ``Tool[T, O]``, where callers pass ``T``.""" + 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] / Tool[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 + + async def call_flow_no_input(f: Flow[str, str]) -> str: + return await f() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] + + async def call_tool_no_input(t: Tool[str, str]) -> str: + return await t() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] + + # 3. Through a Flow[str, str] / Tool[str, str] parameter, passing str works and omitting input fails the type check + assert await by_cuisine('thai') == 'thai: risotto' + assert await allergens('larb') == 'larb: peanuts' + assert await call_flow_no_input(todays_special) == 'italian: risotto' + assert await call_tool_no_input(check_allergens) == 'pad thai: peanuts' + + +@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 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/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..defeb3f61 --- /dev/null +++ b/packages/genkit/tests/typecheck/ref_config_contract_test.py @@ -0,0 +1,246 @@ +# 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 < 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 + 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] 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.