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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 61 additions & 1 deletion packages/genkit/src/genkit/_ai/_aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -69,6 +77,7 @@
start_generate_stream,
)
from genkit._ai._model import (
CtxFirstModelFn,
Message,
Model,
ModelArg,
Expand Down Expand Up @@ -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,
Expand All @@ -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)
Expand Down Expand Up @@ -820,6 +856,7 @@ def define_background_model(
description=description,
)

@overload
def define_embedder(
self,
name: str,
Expand All @@ -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.

Expand Down
16 changes: 13 additions & 3 deletions packages/genkit/src/genkit/_ai/_background_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'})
Expand Down
60 changes: 57 additions & 3 deletions packages/genkit/src/genkit/_ai/_embedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]):
Expand All @@ -104,6 +108,7 @@ class Embedder(Action[EmbedRequest, EmbedResponse, Never]):
when that is a Pydantic class.
"""

@overload
def __init__(
self,
name: str,
Expand All @@ -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] = {}

Expand Down Expand Up @@ -170,6 +198,7 @@ def __init__(
embedder_info['customOptions'] = custom_options_schema(self.config_schema)


@overload
def define_embedder(
registry: Registry,
name: str,
Expand All @@ -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(
Expand Down
80 changes: 70 additions & 10 deletions packages/genkit/src/genkit/_ai/_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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 (
Expand Down Expand Up @@ -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__)

Expand Down Expand Up @@ -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
Expand All @@ -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
Comment thread
huangjeff5 marked this conversation as resolved.
Resolved
except Exception: # noqa: BLE001 - unresolvable annotations or a bad shape: let Action report it
return
if not params:
if request is None:
Comment thread
huangjeff5 marked this conversation as resolved.
Resolved
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:
Expand Down Expand Up @@ -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,
Expand All @@ -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)
Expand All @@ -511,6 +547,7 @@ def __init__(
model_options['customOptions'] = custom_options_schema(self.config_schema)


@overload
def define_model(
registry: Registry,
name: str,
Expand All @@ -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)
Expand Down
Loading
Loading