diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 874f29b2..1908ab40 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -44,7 +44,15 @@ check_operation, define_background_model, ) -from genkit._ai._embedding import Embedder, EmbedderFn, EmbedderInfo, EmbedderRef, EmbedderRefConfigT, define_embedder +from genkit._ai._embedding import ( + CtxFirstEmbedderFn, + Embedder, + EmbedderFn, + EmbedderInfo, + EmbedderRef, + EmbedderRefConfigT, + define_embedder, +) from genkit._ai._evaluator import ( BatchEvaluator, BatchEvaluatorFn, @@ -69,6 +77,7 @@ start_generate_stream, ) from genkit._ai._model import ( + CtxFirstModelFn, Message, Model, ModelArg, @@ -782,6 +791,10 @@ def define_batch_evaluator( description=description, ) + # define_model and define_embedder: the first overload takes the request + # and an optional context after it, so `lambda req: ...` infers req as the + # request. The second takes the context first. See CtxFirstModelFn. + @overload def define_model( self, name: str, @@ -791,6 +804,29 @@ def define_model( metadata: dict[str, object] | None = None, info: ModelInfo | None = None, description: str | None = None, + ) -> Model: ... + + @overload + def define_model( + self, + name: str, + fn: CtxFirstModelFn, + *, + config_schema: type[BaseModel] | dict[str, object] | None = None, + metadata: dict[str, object] | None = None, + info: ModelInfo | None = None, + description: str | None = None, + ) -> Model: ... + + def define_model( + self, + name: str, + fn: ModelFn | CtxFirstModelFn, + *, + config_schema: type[BaseModel] | dict[str, object] | None = None, + metadata: dict[str, object] | None = None, + info: ModelInfo | None = None, + description: str | None = None, ) -> Model: """Register a custom model action.""" return define_model(self._registry, name, fn, config_schema, metadata, info, description) @@ -820,6 +856,7 @@ def define_background_model( description=description, ) + @overload def define_embedder( self, name: str, @@ -829,6 +866,29 @@ def define_embedder( metadata: dict[str, object] | None = None, description: str | None = None, config_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> Embedder: ... + + @overload + def define_embedder( + self, + name: str, + fn: CtxFirstEmbedderFn, + *, + info: EmbedderInfo | None = None, + metadata: dict[str, object] | None = None, + description: str | None = None, + config_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> Embedder: ... + + def define_embedder( + self, + name: str, + fn: EmbedderFn | CtxFirstEmbedderFn, + *, + info: EmbedderInfo | None = None, + metadata: dict[str, object] | None = None, + description: str | None = None, + config_schema: type[BaseModel] | dict[str, object] | None = None, ) -> Embedder: """Register a custom embedder action. diff --git a/packages/genkit/src/genkit/_ai/_background_model.py b/packages/genkit/src/genkit/_ai/_background_model.py index ec59c093..0300edd0 100644 --- a/packages/genkit/src/genkit/_ai/_background_model.py +++ b/packages/genkit/src/genkit/_ai/_background_model.py @@ -47,9 +47,19 @@ from genkit._core._typing import ModelInfo # 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]] -CancelModelOpFn = Callable[[Operation[ModelResponse], ModelContext], Awaitable[Operation]] +# Like a model fn, each takes its input and an optional ModelContext, in +# either order. +StartModelOpFn = ( + Callable[[ModelRequest, ModelContext], Awaitable[Operation]] + | Callable[[ModelContext, ModelRequest], Awaitable[Operation]] + | Callable[[ModelRequest], Awaitable[Operation]] +) +CheckModelOpFn = ( + Callable[[Operation[ModelResponse], ModelContext], Awaitable[Operation]] + | Callable[[ModelContext, Operation[ModelResponse]], Awaitable[Operation]] + | Callable[[Operation[ModelResponse]], Awaitable[Operation]] +) +CancelModelOpFn = CheckModelOpFn # Keys a ModelResponse dump carries. An Operation dump always has 'id'. _MODEL_RESPONSE_KEYS = frozenset({'message', 'finishReason', 'finish_reason', 'operation'}) diff --git a/packages/genkit/src/genkit/_ai/_embedding.py b/packages/genkit/src/genkit/_ai/_embedding.py index bce598d7..5348f65e 100644 --- a/packages/genkit/src/genkit/_ai/_embedding.py +++ b/packages/genkit/src/genkit/_ai/_embedding.py @@ -18,7 +18,7 @@ from collections.abc import Awaitable, Callable, Mapping from dataclasses import dataclass -from typing import Any, ClassVar, Generic, cast +from typing import Any, ClassVar, Generic, cast, overload from pydantic import BaseModel, ConfigDict from pydantic.alias_generators import to_camel @@ -86,10 +86,14 @@ def __post_init__(self) -> None: object.__setattr__(self, 'info', check_ref_info(name=self.name, info=self.info, info_type=EmbedderInfo)) +# The request and an optional EmbedContext, like a model fn. EmbedderFn = ( - Callable[[EmbedRequest[Any]], Awaitable[EmbedResponse]] - | Callable[[EmbedRequest[Any], EmbedContext], Awaitable[EmbedResponse]] + Callable[[EmbedRequest[Any], EmbedContext], Awaitable[EmbedResponse]] + | Callable[[EmbedRequest[Any]], Awaitable[EmbedResponse]] ) +# Context first, taken through a second overload. See CtxFirstModelFn for why +# it isn't a third arm on EmbedderFn. +CtxFirstEmbedderFn = Callable[[EmbedContext, EmbedRequest[Any]], Awaitable[EmbedResponse]] class Embedder(Action[EmbedRequest, EmbedResponse, Never]): @@ -104,6 +108,7 @@ class Embedder(Action[EmbedRequest, EmbedResponse, Never]): when that is a Pydantic class. """ + @overload def __init__( self, name: str, @@ -113,6 +118,29 @@ def __init__( metadata: dict[str, object] | None = None, info: EmbedderInfo | None = None, description: str | None = None, + ) -> None: ... + + @overload + def __init__( + self, + name: str, + fn: CtxFirstEmbedderFn, + *, + config_schema: type[BaseModel] | dict[str, object] | None = None, + metadata: dict[str, object] | None = None, + info: EmbedderInfo | None = None, + description: str | None = None, + ) -> None: ... + + def __init__( + self, + name: str, + fn: EmbedderFn | CtxFirstEmbedderFn, + *, + config_schema: type[BaseModel] | dict[str, object] | None = None, + metadata: dict[str, object] | None = None, + info: EmbedderInfo | None = None, + description: str | None = None, ) -> None: embedder_info: dict[str, object] = {} @@ -170,6 +198,7 @@ def __init__( embedder_info['customOptions'] = custom_options_schema(self.config_schema) +@overload def define_embedder( registry: Registry, name: str, @@ -179,6 +208,31 @@ def define_embedder( description: str | None = None, *, config_schema: type[BaseModel] | dict[str, object] | None = None, +) -> Embedder: ... + + +@overload +def define_embedder( + registry: Registry, + name: str, + fn: CtxFirstEmbedderFn, + info: EmbedderInfo | None = None, + metadata: dict[str, object] | None = None, + description: str | None = None, + *, + config_schema: type[BaseModel] | dict[str, object] | None = None, +) -> Embedder: ... + + +def define_embedder( + registry: Registry, + name: str, + fn: EmbedderFn | CtxFirstEmbedderFn, + info: EmbedderInfo | None = None, + metadata: dict[str, object] | None = None, + description: str | None = None, + *, + config_schema: type[BaseModel] | dict[str, object] | None = None, ) -> Embedder: """Register a custom embedder action.""" action = Embedder( diff --git a/packages/genkit/src/genkit/_ai/_model.py b/packages/genkit/src/genkit/_ai/_model.py index 69a587dc..265ed83c 100644 --- a/packages/genkit/src/genkit/_ai/_model.py +++ b/packages/genkit/src/genkit/_ai/_model.py @@ -18,10 +18,9 @@ from __future__ import annotations -import inspect from collections.abc import Awaitable, Callable, Mapping from dataclasses import dataclass, replace -from typing import Annotated, Any, TypeAlias, cast, get_args, get_origin, get_type_hints +from typing import Annotated, Any, TypeAlias, cast, get_args, get_origin, get_type_hints, overload from pydantic import BaseModel, ValidationError @@ -30,7 +29,10 @@ Action, ActionKind, ModelContext, + find_input_and_context, get_func_description, + known_annotation_names, + resolve_type_hints, with_request_annotation, ) from genkit._core._config_check import ( @@ -68,9 +70,17 @@ from genkit._core._schema import custom_options_schema, fixed_json_schema from genkit._core._typing import GenerationCommonConfig, ModelInfo -# Type alias for model functions (must be async) -# Use ctx.send_chunk() for streaming -ModelFn = Callable[[ModelRequest, ModelContext], Awaitable[ModelResponse[Any]]] +# A model fn takes the request and an optional ModelContext, like a flow or +# tool takes its input and context. Use ctx.send_chunk() to stream. +ModelFn = ( + Callable[[ModelRequest, ModelContext], Awaitable[ModelResponse[Any]]] + | Callable[[ModelRequest], Awaitable[ModelResponse[Any]]] +) +# The context can also come first. Entry points take this through a second +# overload instead of a third arm on ModelFn: in one union, pyright and pyrefly +# infer a lambda's first parameter as ModelContext, so `lambda req: ...` stops +# type-checking. +CtxFirstModelFn = Callable[[ModelContext, ModelRequest], Awaitable[ModelResponse[Any]]] logger = get_logger(__name__) @@ -416,7 +426,7 @@ def _model_options( return options -def _check_request_annotation(name: str, fn: ModelFn) -> None: +def _check_request_annotation(name: str, fn: ModelFn | CtxFirstModelFn) -> None: """Reject model fns whose request annotation is not a ModelRequest class. Unions like ``ModelRequest[X] | None`` are an antipattern: generate() never @@ -426,12 +436,14 @@ def _check_request_annotation(name: str, fn: ModelFn) -> None: """ try: hints = get_type_hints(fn, include_extras=True) - params = list(inspect.signature(fn).parameters) - except Exception: # noqa: BLE001 - unresolvable annotations: let Action handle it + # The request is the input parameter, wherever the context sits. + resolved = resolve_type_hints(fn, known_annotation_names(ActionKind.MODEL)) + request = find_input_and_context(fn, resolved, kind=ActionKind.MODEL, name=name).input + except Exception: # noqa: BLE001 - unresolvable annotations or a bad shape: let Action report it return - if not params: + if request is None: return - ann = hints.get(params[0]) + ann = hints.get(request.name) if ann is None: return # unannotated stays allowed if get_origin(ann) is Annotated: @@ -477,6 +489,7 @@ class Model(Action[ModelRequest, ModelResponse, ModelResponseChunk]): annotation; given both, they must be the same class. """ + @overload def __init__( self, name: str, @@ -486,6 +499,29 @@ def __init__( metadata: dict[str, object] | None = None, info: ModelInfo | None = None, description: str | None = None, + ) -> None: ... + + @overload + def __init__( + self, + name: str, + fn: CtxFirstModelFn, + *, + config_schema: type[BaseModel] | dict[str, object] | None = None, + metadata: dict[str, object] | None = None, + info: ModelInfo | None = None, + description: str | None = None, + ) -> None: ... + + def __init__( + self, + name: str, + fn: ModelFn | CtxFirstModelFn, + *, + config_schema: type[BaseModel] | dict[str, object] | None = None, + metadata: dict[str, object] | None = None, + info: ModelInfo | None = None, + description: str | None = None, ) -> None: """Build a model action.""" model_options = _model_options(name=name, info=info, config_schema=config_schema, metadata=metadata) @@ -511,6 +547,7 @@ def __init__( model_options['customOptions'] = custom_options_schema(self.config_schema) +@overload def define_model( registry: Registry, name: str, @@ -519,6 +556,29 @@ def define_model( metadata: dict[str, object] | None = None, info: ModelInfo | None = None, description: str | None = None, +) -> Model: ... + + +@overload +def define_model( + registry: Registry, + name: str, + fn: CtxFirstModelFn, + config_schema: type[BaseModel] | dict[str, object] | None = None, + metadata: dict[str, object] | None = None, + info: ModelInfo | None = None, + description: str | None = None, +) -> Model: ... + + +def define_model( + registry: Registry, + name: str, + fn: ModelFn | CtxFirstModelFn, + config_schema: type[BaseModel] | dict[str, object] | None = None, + metadata: dict[str, object] | None = None, + info: ModelInfo | None = None, + description: str | None = None, ) -> Model: """Register a custom model action.""" _check_request_annotation(name, fn) diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index e40e91ba..ef80e851 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -348,7 +348,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). +# - Input and context are regular parameters: no '/', no '*', no *args or **kwargs. # - 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 @@ -451,18 +451,23 @@ def find_input_and_context( ) -> ActionParams: """Find ``fn``'s input and run-context parameters, or raise a TypeError saying how to fix it. - ``hints`` is ``resolve_type_hints(fn)``. ``*args`` and ``**kwargs`` are ignored. + ``hints`` is ``resolve_type_hints(fn)``. """ owner = describe_action(kind, name) context_class = _public_context_name(context_kind if context_kind is not None else kind) - params = [ - p - for p in signature_of(fn).parameters.values() - if p.kind not in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD) - ] + params = list(signature_of(fn).parameters.values()) for p in params: + # Genkit passes only the input and context, by name, so *args and + # **kwargs would never receive anything. A decorator without + # functools.wraps is the usual source: the fn would run with no input. + if p.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD): + star = '*' if p.kind is inspect.Parameter.VAR_POSITIONAL else '**' + raise TypeError( + f'{owner} takes {star}{p.name}, but Genkit passes only the input and context. ' + 'Remove it, or if a decorator added it, apply functools.wraps in the decorator.' + ) if p.kind is inspect.Parameter.POSITIONAL_ONLY: raise TypeError( f"{owner} parameter '{p.name}' is positional-only, but Genkit passes the input " diff --git a/packages/genkit/tests/genkit/ai/model_definition_contract_test.py b/packages/genkit/tests/genkit/ai/model_definition_contract_test.py index 72b60ea2..e89aff56 100644 --- a/packages/genkit/tests/genkit/ai/model_definition_contract_test.py +++ b/packages/genkit/tests/genkit/ai/model_definition_contract_test.py @@ -5,13 +5,16 @@ """define_model accepts ModelRequest / ModelRequest[Cfg] and rejects the rest.""" +import functools import sys import typing -from typing import Annotated, Any, Optional, cast +from collections.abc import Awaitable, Callable +from typing import Annotated, Any, Optional, TypeVar, cast import pytest import typing_extensions from pydantic import BaseModel +from typing_extensions import ParamSpec from genkit import Genkit, Part from genkit._core._error import GenkitError @@ -198,3 +201,81 @@ async def fn(request: NotARequest, ctx: ModelContext) -> ModelResponse: with pytest.raises(GenkitError, match='must be annotated as ModelRequest'): ai.define_model(name='arbitrary', fn=fn) + + +# --- context first ------------------------------------------------------------ + + +def test_ctx_first_union_with_none_rejected(ai: Genkit) -> None: + """The request check finds the request after the context: ``(ctx, req: ModelRequest[Cfg] | None)`` is rejected.""" + + async def fn(ctx: ModelContext, request: ModelRequest[Cfg] | None) -> ModelResponse: + return OK + + with pytest.raises(GenkitError, match=r"Model 'ctx_union': the request parameter must be annotated") as exc: + ai.define_model(name='ctx_union', fn=fn) + assert 'ModelContext' not in str(exc.value) + + +def test_ctx_first_dict_annotation_rejected(ai: Genkit) -> None: + """``(ctx, req: dict)`` is rejected the same as ``(req: dict, ctx)``.""" + + async def fn(ctx: ModelContext, request: dict) -> ModelResponse: + return OK + + with pytest.raises(GenkitError, match='must be annotated as ModelRequest'): + ai.define_model(name='ctx_rawdict', fn=fn) + + +# --- decorated model fns ------------------------------------------------------ + +P = ParamSpec('P') +R = TypeVar('R') + + +def _timed_without_wraps(fn: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]: + async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: + return await fn(*args, **kwargs) + + return wrapper + + +def _timed(fn: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]: + @functools.wraps(fn) + async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: + return await fn(*args, **kwargs) + + return wrapper + + +def test_wrapper_without_functools_wraps_rejected(ai: Genkit) -> None: + """A decorator that drops the signature raises at definition instead of failing every generate().""" + + @_timed_without_wraps + async def chef(request: ModelRequest[Cfg], ctx: ModelContext) -> ModelResponse: + return OK + + with pytest.raises(TypeError, match=r"model 'timed' takes \*args, but Genkit passes only the input and context"): + ai.define_model(name='timed', fn=chef) + + +@pytest.mark.asyncio +async def test_wrapper_with_functools_wraps_runs(ai: Genkit) -> None: + """With functools.wraps the wrapper keeps the signature, so it defines and answers generate.""" + + @_timed + async def chef(request: ModelRequest[Cfg], ctx: ModelContext) -> ModelResponse: + return OK + + ai.define_model(name='timed', fn=chef) + + assert (await ai.generate(model='timed', prompt='hi')).text == 'ok' + + +def test_no_parameters_still_allowed(ai: Genkit) -> None: + """A model fn with no parameters ignores the request; it still registers.""" + + async def fn() -> ModelResponse: + return OK + + ai.define_model(name='no_params', fn=cast(Any, fn)) diff --git a/packages/genkit/tests/genkit/core/action_signature_test.py b/packages/genkit/tests/genkit/core/action_signature_test.py index 6cf5df9a..c6bdc70a 100644 --- a/packages/genkit/tests/genkit/core/action_signature_test.py +++ b/packages/genkit/tests/genkit/core/action_signature_test.py @@ -6,7 +6,7 @@ import sys import types from collections.abc import Awaitable, Callable -from typing import Optional, cast +from typing import Any, Optional, cast import pytest from pydantic import TypeAdapter @@ -15,7 +15,8 @@ from genkit._ai._background_model import CheckModelOpFn, StartModelOpFn from genkit._core._action import Action, ActionContext, ActionKind from genkit._core._typing import Role -from genkit.model import ModelRequest +from genkit.embedder import Embedder +from genkit.model import Model, ModelRequest from genkit.plugin_api import Plugin _REPLY = ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('Smoked Salmon Tartine')])) @@ -226,6 +227,59 @@ async def index_menu(doc: str, *, ctx: ActionContext | None = None) -> str: Action(ActionKind.CUSTOM, 'menu', index_menu) +async def _wrapper(*args: Any, **kwargs: Any) -> Any: # noqa: ANN401 - a decorator's wrapper without functools.wraps + del args, kwargs + + +async def _plate_with_extras(dish: str, **extras: Any) -> Any: # noqa: ANN401 - the shape under test + del extras + return dish + + +async def _start_ok(request: ModelRequest) -> Operation: + return Operation(id='op-1') + + +async def _check_ok(op: Operation) -> Operation: + return op + + +# Every entry point whose handler Genkit calls by name, as (expected owner, build). +_BY_NAME_ENTRY_POINTS: list[tuple[str, Callable[[Genkit, Callable[..., Any]], object]]] = [ + ("flow 'h'", lambda ai, fn: ai.flow('h')(fn)), + ("tool 'h'", lambda ai, fn: ai.tool('h')(fn)), + ("model 'h'", lambda ai, fn: ai.define_model(name='h', fn=fn)), + ("model 'h'", lambda ai, fn: Model('h', fn)), + ("embedder 'h'", lambda ai, fn: ai.define_embedder(name='h', fn=fn)), + ("embedder 'h'", lambda ai, fn: Embedder('h', fn)), + ("background model 'h'", lambda ai, fn: ai.define_background_model(name='h', start=fn, check=_check_ok)), + ('h', lambda ai, fn: ai.define_background_model(name='h', start=_start_ok, check=fn)), + ('h', lambda ai, fn: ai.define_background_model(name='h', start=_start_ok, check=_check_ok, cancel=fn)), + ( + "evaluator 'h'", + lambda ai, fn: ai.define_batch_evaluator(name='h', fn=fn, display_name='H', definition='scores rows'), + ), + ("custom 'h'", lambda ai, fn: Action(ActionKind.CUSTOM, 'h', fn)), +] + + +@pytest.mark.parametrize(('owner', 'build'), _BY_NAME_ENTRY_POINTS) +def test_variadic_only_handler_raises_at_definition(owner: str, build: Callable[..., object]) -> None: + """A ``(*args, **kwargs)`` wrapper raises at definition and names functools.wraps.""" + with pytest.raises(TypeError, match=r'takes \*args, but Genkit passes only the input and context') as exc: + build(Genkit(), _wrapper) + assert owner in str(exc.value) + assert 'functools.wraps' in str(exc.value) + + +@pytest.mark.parametrize(('owner', 'build'), _BY_NAME_ENTRY_POINTS) +def test_extra_kwargs_next_to_the_input_raise_at_definition(owner: str, build: Callable[..., object]) -> None: + """``(dish, **extras)`` raises too: ``extras`` would never receive anything.""" + with pytest.raises(TypeError, match=r'takes \*\*extras, but Genkit passes only the input and context') as exc: + build(Genkit(), _plate_with_extras) + assert owner in str(exc.value) + + @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/typecheck/model_embedder_shapes_contract_test.py b/packages/genkit/tests/typecheck/model_embedder_shapes_contract_test.py new file mode 100644 index 00000000..16e0eb1a --- /dev/null +++ b/packages/genkit/tests/typecheck/model_embedder_shapes_contract_test.py @@ -0,0 +1,340 @@ +# 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 model, embedder and background-model handler shapes. + +A handler takes its request plus an optional context, in either order, the +same rule as flows and tools. Every supported shape type-checks at +``ai.define_*``, the plugin-level constructors (``Model``, ``Embedder``, +``BackgroundModel``) and the registry-level ``define_*``, and runs. A lambda +infers its parameter as the request. A ``ModelRequest[Cfg]`` request +keeps its config class with the context in either position. Two inputs or a +keyword-only parameter fail every checker and raise ``TypeError`` at +definition. +""" + +import pytest +from pydantic import BaseModel + +from genkit import Embedding, Genkit, Message, ModelResponse, ModelResponseChunk, Operation, Part, Role +from genkit._ai._embedding import define_embedder +from genkit._ai._model import define_model +from genkit._core._registry import Registry +from genkit.embedder import EmbedContext, Embedder, EmbedRequest, EmbedResponse +from genkit.model import BackgroundModel, Model, ModelConfig, ModelContext, ModelRequest + + +class SpiceConfig(ModelConfig): + heat: int = 1 + + +class MenuEmbedConfig(BaseModel): + dimensions: int = 4 + + +def _reply(text: str) -> ModelResponse: + return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text(text)])) + + +def _config_name(req: ModelRequest[SpiceConfig] | ModelRequest) -> str: + return type(req.config).__name__ + + +# Model handlers, one per shape. + + +async def chef(req: ModelRequest) -> ModelResponse: + return _reply(f'chef: {len(req.messages)} messages') + + +async def chef_streaming(req: ModelRequest, ctx: ModelContext) -> ModelResponse: + ctx.send_chunk(ModelResponseChunk(content=[Part.from_text('plating')])) + return _reply('chef_streaming') + + +async def chef_ctx_first(ctx: ModelContext, req: ModelRequest) -> ModelResponse: + del ctx + return _reply(f'chef_ctx_first: {len(req.messages)} messages') + + +async def spicy_chef(req: ModelRequest[SpiceConfig]) -> ModelResponse: + return _reply(_config_name(req)) + + +async def spicy_chef_ctx_last(req: ModelRequest[SpiceConfig], ctx: ModelContext) -> ModelResponse: + del ctx + return _reply(_config_name(req)) + + +async def spicy_chef_ctx_first(ctx: ModelContext, req: ModelRequest[SpiceConfig]) -> ModelResponse: + del ctx + return _reply(_config_name(req)) + + +# Unsupported model shapes. + + +async def chef_two_inputs(req: ModelRequest, table: str) -> ModelResponse: + return _reply(table) + + +async def chef_kwonly(req: ModelRequest, *, ctx: ModelContext) -> ModelResponse: + del ctx + return _reply('kwonly') + + +# Embedder handlers. + + +def _embed(req: EmbedRequest) -> EmbedResponse: + return EmbedResponse(embeddings=[Embedding(embedding=[0.25]) for _ in req.input]) + + +async def embed_menu(req: EmbedRequest) -> EmbedResponse: + return _embed(req) + + +async def embed_menu_ctx_last(req: EmbedRequest, ctx: EmbedContext) -> EmbedResponse: + del ctx + return _embed(req) + + +async def embed_menu_ctx_first(ctx: EmbedContext, req: EmbedRequest) -> EmbedResponse: + del ctx + return _embed(req) + + +async def embed_typed_ctx_first(ctx: EmbedContext, req: EmbedRequest[MenuEmbedConfig]) -> EmbedResponse: + del ctx + assert isinstance(req.options, MenuEmbedConfig) + return _embed(req) + + +async def embed_two_inputs(req: EmbedRequest, locale: str) -> EmbedResponse: + del locale + return _embed(req) + + +async def embed_kwonly(req: EmbedRequest, *, ctx: EmbedContext) -> EmbedResponse: + del ctx + return _embed(req) + + +# Background model handlers. + + +def _finished(op: Operation) -> Operation: + return Operation(id=op.id, done=True, output={'message': {'role': 'model', 'content': [{'text': 'video ready'}]}}) + + +async def start_render(req: ModelRequest[SpiceConfig]) -> Operation: + return Operation(id=f'render-{_config_name(req)}') + + +async def start_render_ctx_last(req: ModelRequest[SpiceConfig], ctx: ModelContext) -> Operation: + del ctx + return Operation(id=f'render-{_config_name(req)}') + + +async def start_render_ctx_first(ctx: ModelContext, req: ModelRequest[SpiceConfig]) -> Operation: + del ctx + return Operation(id=f'render-{_config_name(req)}') + + +async def check_render(op: Operation[ModelResponse]) -> Operation: + return _finished(op) + + +async def check_render_ctx_last(op: Operation[ModelResponse], ctx: ModelContext) -> Operation: + del ctx + return _finished(op) + + +async def check_render_ctx_first(ctx: ModelContext, op: Operation[ModelResponse]) -> Operation: + del ctx + return _finished(op) + + +MODEL_SHAPES = (chef, chef_streaming, chef_ctx_first, spicy_chef, spicy_chef_ctx_last, spicy_chef_ctx_first) +EMBEDDER_SHAPES = (embed_menu, embed_menu_ctx_last, embed_menu_ctx_first, embed_typed_ctx_first) + + +def test_model_shapes_type_check_at_every_entry_point() -> None: + """``(req)``, ``(req, ctx)`` and ``(ctx, req)`` type-check at ai.define_model, Model and define_model.""" + ai = Genkit() + registry = Registry() + + # 1. ai.define_model + ai.define_model(name='chef', fn=chef) + ai.define_model(name='chef_streaming', fn=chef_streaming) + ai.define_model(name='chef_ctx_first', fn=chef_ctx_first) + ai.define_model(name='spicy_chef', fn=spicy_chef) + ai.define_model(name='spicy_chef_ctx_last', fn=spicy_chef_ctx_last) + ai.define_model(name='spicy_chef_ctx_first', fn=spicy_chef_ctx_first) + + # 2. Model(...), what a plugin's init / resolve returns + Model('chef', chef) + Model('chef_streaming', chef_streaming) + Model('chef_ctx_first', chef_ctx_first) + Model('spicy_chef_ctx_first', spicy_chef_ctx_first) + + # 3. Registry-level define_model + define_model(registry, 'chef', chef) + define_model(registry, 'chef_streaming', chef_streaming) + define_model(registry, 'chef_ctx_first', chef_ctx_first) + define_model(registry, 'spicy_chef_ctx_first', spicy_chef_ctx_first) + + +def test_embedder_shapes_type_check_at_every_entry_point() -> None: + """``(req)``, ``(req, ctx)`` and ``(ctx, req)`` type-check at ai.define_embedder, Embedder and define_embedder.""" + ai = Genkit() + registry = Registry() + + ai.define_embedder(name='embed_menu', fn=embed_menu) + ai.define_embedder(name='embed_menu_ctx_last', fn=embed_menu_ctx_last) + ai.define_embedder(name='embed_menu_ctx_first', fn=embed_menu_ctx_first) + ai.define_embedder(name='embed_typed_ctx_first', fn=embed_typed_ctx_first) + + Embedder('embed_menu', embed_menu) + Embedder('embed_menu_ctx_last', embed_menu_ctx_last) + Embedder('embed_menu_ctx_first', embed_menu_ctx_first) + + define_embedder(registry, 'embed_menu', embed_menu) + define_embedder(registry, 'embed_menu_ctx_last', embed_menu_ctx_last) + define_embedder(registry, 'embed_menu_ctx_first', embed_menu_ctx_first) + + +def test_background_model_shapes_type_check() -> None: + """Start, check and cancel take their input plus an optional context, in either order, mixed freely.""" + ai = Genkit() + + ai.define_background_model(name='render', start=start_render, check=check_render, cancel=check_render) + ai.define_background_model( + name='render_ctx_last', start=start_render_ctx_last, check=check_render_ctx_last, cancel=check_render_ctx_last + ) + ai.define_background_model( + name='render_ctx_first', + start=start_render_ctx_first, + check=check_render_ctx_first, + cancel=check_render_ctx_first, + ) + ai.define_background_model(name='render_mixed', start=start_render_ctx_first, check=check_render) + BackgroundModel('render_plugin', start=start_render_ctx_first, check=check_render_ctx_first) + + +def test_lambdas_infer_the_request_at_every_entry_point() -> None: + """``lambda req: ...`` infers ``req`` as the request, not the context. + + A two-argument lambda can't run: its ``ctx`` has no ``ModelContext`` + annotation, so Genkit reads it as a second input. Background-model + handlers must be ``async def``, so they take no lambdas at all. + """ + ai = Genkit() + registry = Registry() + + # 1. Models + ai.define_model(name='m1', fn=lambda req: chef(req)) + Model('m2', lambda req: chef(req)) + define_model(registry, 'm3', lambda req: chef(req)) + + # 2. Embedders + ai.define_embedder(name='e1', fn=lambda req: embed_menu(req)) + Embedder('e2', lambda req: embed_menu(req)) + define_embedder(registry, 'e3', lambda req: embed_menu(req)) + + +@pytest.mark.asyncio +async def test_lambda_handlers_run() -> None: + """Lambda handlers answer generate and embed.""" + ai = Genkit() + ai.define_model(name='chef_lambda', fn=lambda req: chef(req)) + ai.define_embedder(name='embed_lambda', fn=lambda req: embed_menu(req)) + + assert (await ai.generate(model='chef_lambda', prompt='hi')).text == 'chef: 1 messages' + assert (await ai.embed(embedder='embed_lambda', content='tartine'))[0].embedding == [0.25] + + +def test_unsupported_shapes_fail_at_definition() -> None: + """Two inputs or a keyword-only parameter fail every checker and raise TypeError at definition.""" + ai = Genkit() + + # 1. Models + with pytest.raises(TypeError, match="model 'chef_two_inputs' takes one input, but 'table' is a second parameter"): + ai.define_model(name='chef_two_inputs', fn=chef_two_inputs) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + with pytest.raises(TypeError, match="model 'chef_kwonly' parameter 'ctx' is keyword-only"): + ai.define_model(name='chef_kwonly', fn=chef_kwonly) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + + # 2. Embedders + with pytest.raises(TypeError, match="embedder 'embed_two_inputs' takes one input, but 'locale' is a second"): + ai.define_embedder(name='embed_two_inputs', fn=embed_two_inputs) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + with pytest.raises(TypeError, match="embedder 'embed_kwonly' parameter 'ctx' is keyword-only"): + ai.define_embedder(name='embed_kwonly', fn=embed_kwonly) # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + + +@pytest.mark.asyncio +async def test_every_model_shape_runs_and_keeps_its_config_class() -> None: + """Each model shape answers generate, and ``ModelRequest[SpiceConfig]`` gets a SpiceConfig either way round.""" + ai = Genkit() + for fn in MODEL_SHAPES: + ai.define_model(name=fn.__name__, fn=fn) + + # 1. Untyped shapes run with the context in either position + assert (await ai.generate(model='chef', prompt='hi')).text == 'chef: 1 messages' + assert (await ai.generate(model='chef_streaming', prompt='hi')).text == 'chef_streaming' + assert (await ai.generate(model='chef_ctx_first', prompt='hi')).text == 'chef_ctx_first: 1 messages' + + # 2. A dict config validates into the annotated class in every order + for name in ('spicy_chef', 'spicy_chef_ctx_last', 'spicy_chef_ctx_first'): + res = await ai.generate(model=name, prompt='hi', config={'heat': 3}) + assert res.text == 'SpiceConfig', name + model = await ai.lookup_model(name) + assert model is not None + assert model.config_schema is SpiceConfig, name + + +@pytest.mark.asyncio +async def test_every_embedder_shape_runs() -> None: + """Each embedder shape answers embed; ``EmbedRequest[Cfg]`` keeps its options class with ctx first.""" + ai = Genkit() + for fn in EMBEDDER_SHAPES: + ai.define_embedder(name=fn.__name__, fn=fn) + + for fn in EMBEDDER_SHAPES: + vecs = await ai.embed(embedder=fn.__name__, content='bouillabaisse') + assert vecs[0].embedding == [0.25], fn.__name__ + + vecs = await ai.embed(embedder='embed_typed_ctx_first', content='tartine', config={'dimensions': 8}) + assert vecs[0].embedding == [0.25] + + +@pytest.mark.asyncio +async def test_every_background_model_shape_runs() -> None: + """Start, check and cancel run in every shape, and start keeps its config class.""" + ai = Genkit() + pairs = ( + ('render', start_render, check_render), + ('render_ctx_last', start_render_ctx_last, check_render_ctx_last), + ('render_ctx_first', start_render_ctx_first, check_render_ctx_first), + ) + for name, start, check in pairs: + bm = ai.define_background_model(name=name, start=start, check=check, cancel=check) + req = ModelRequest(messages=[Message(role=Role.USER, content=[Part.from_text('a lobster reel')])]) + op = await bm.start(ModelRequest(messages=req.messages, config={'heat': 2})) + assert op.id == 'render-SpiceConfig', name + assert (await bm.check(op)).done, name + assert (await bm.cancel(op)).done, name