From 963fa2763c42ba104e2b0c8d5d8d68d650d32a36 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Tue, 1 Dec 2026 19:04:26 +0000 Subject: [PATCH 1/2] fix(core): accept async-callable instances consistently across handlers --- packages/genkit/src/genkit/_ai/_evaluator.py | 5 ++-- packages/genkit/src/genkit/_core/_action.py | 4 +-- .../genkit/src/genkit/_core/_background.py | 4 +-- packages/genkit/src/genkit/_core/_compat.py | 6 ++++ packages/genkit/src/genkit/_core/_flow.py | 6 ++-- .../_core/_telemetry/_instrumentation.py | 5 ++-- packages/genkit/src/genkit/_core/_tool.py | 5 ++-- .../genkit/tests/genkit/core/action_test.py | 27 ++++++++++++++++- .../genkit/core/background_registry_test.py | 30 +++++++++++++++++++ .../tests/genkit/core/run_in_new_span_test.py | 18 +++++++++++ 10 files changed, 95 insertions(+), 15 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_evaluator.py b/packages/genkit/src/genkit/_ai/_evaluator.py index 2227517b6..6147d658f 100644 --- a/packages/genkit/src/genkit/_ai/_evaluator.py +++ b/packages/genkit/src/genkit/_ai/_evaluator.py @@ -30,6 +30,7 @@ from typing_extensions import Never from genkit._core._action import Action, ActionContext, ActionKind +from genkit._core._compat import is_async_callable from genkit._core._logger import get_logger from genkit._core._registry import Registry from genkit._core._schema import to_json_schema @@ -163,7 +164,7 @@ def __init__( metadata: dict[str, object] | None = None, description: str | None = None, ) -> None: - if not inspect.iscoroutinefunction(fn): + if not is_async_callable(fn): raise TypeError(f"Action handlers must be async functions. Got sync function for '{name}'.") evaluator_meta = _evaluator_metadata(name, display_name, definition, is_billed, config_schema, metadata) @@ -273,7 +274,7 @@ def __init__( metadata: dict[str, object] | None = None, description: str | None = None, ) -> None: - if not inspect.iscoroutinefunction(fn): + if not is_async_callable(fn): raise TypeError(f"Action handlers must be async functions. Got sync function for '{name}'.") evaluator_meta = _evaluator_metadata(name, display_name, definition, is_billed, config_schema, metadata) diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index ef80e8512..dcc6d0d04 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -50,7 +50,7 @@ from typing_extensions import Never, Self, TypeVar from genkit._core._channel import Channel, CloseableQueue, StoppableStream, _stop_scope -from genkit._core._compat import StrEnum +from genkit._core._compat import StrEnum, is_async_callable from genkit._core._config_check import ( check_config_json_schema, check_config_values, @@ -1184,7 +1184,7 @@ def __init__( self._span_metadata: dict[str, SpanAttributeValue] = span_metadata if span_metadata is not None else {} # All action handlers must be async - if not inspect.iscoroutinefunction(fn): + if not is_async_callable(fn): raise TypeError(f"Action handlers must be async functions. Got sync function for '{name}'.") # Genkit calls fn. With a metadata_fn, fn is a wrapper (the tool wrapper diff --git a/packages/genkit/src/genkit/_core/_background.py b/packages/genkit/src/genkit/_core/_background.py index 4d32de118..61048f664 100644 --- a/packages/genkit/src/genkit/_core/_background.py +++ b/packages/genkit/src/genkit/_core/_background.py @@ -23,7 +23,6 @@ from __future__ import annotations -import inspect from collections.abc import Awaitable, Callable, Mapping from functools import wraps from typing import TYPE_CHECKING, Any, ClassVar, Generic, TypeVar, cast, get_args, get_origin @@ -38,6 +37,7 @@ get_current_context, set_action_name, ) +from genkit._core._compat import is_async_callable from genkit._core._error import ErrorReason, GenkitError, StatusName from genkit._core._operation import Operation from genkit._core._schema import fixed_json_schema @@ -481,7 +481,7 @@ def _operation_action( minus ``suffix`` (e.g. ``/check``) when it runs. """ # Action rejects a sync fn, but it only sees the async wrapper below. - if not inspect.iscoroutinefunction(fn): + if not is_async_callable(fn): raise TypeError(f"Action handlers must be async functions. Got sync function for '{name}{suffix}'.") output_type = cls._output_type diff --git a/packages/genkit/src/genkit/_core/_compat.py b/packages/genkit/src/genkit/_core/_compat.py index bc1904a8e..40d59a223 100644 --- a/packages/genkit/src/genkit/_core/_compat.py +++ b/packages/genkit/src/genkit/_core/_compat.py @@ -18,6 +18,7 @@ import asyncio import functools +import inspect import sys import weakref from collections.abc import Callable @@ -48,6 +49,11 @@ _PY310_CANCELLING: weakref.WeakKeyDictionary[asyncio.Task[Any], int] = weakref.WeakKeyDictionary() +def is_async_callable(func: object) -> bool: + """Return True for ``async def`` functions and instances whose ``__call__`` is ``async def``.""" + return inspect.iscoroutinefunction(func) or inspect.iscoroutinefunction(type(func).__call__) + + def uncancel(task: asyncio.Task[Any] | None) -> int: """Decrement the cancellation count of an asyncio.Task.""" if task is None: diff --git a/packages/genkit/src/genkit/_core/_flow.py b/packages/genkit/src/genkit/_core/_flow.py index ce1eb627d..02e242623 100644 --- a/packages/genkit/src/genkit/_core/_flow.py +++ b/packages/genkit/src/genkit/_core/_flow.py @@ -18,7 +18,6 @@ from __future__ import annotations -import inspect from collections.abc import Awaitable, Callable from typing import Any, overload @@ -38,6 +37,7 @@ get_func_description, input_has_default, ) +from genkit._core._compat import is_async_callable from genkit._core._registry import Registry _FlowInputT = TypeVar('_FlowInputT') @@ -153,10 +153,10 @@ def __init__( name: Optional flow name. Defaults to ``func.__name__``. description: Optional description. Defaults to ``func.__doc__``. """ - if not inspect.iscoroutinefunction(func): + if not is_async_callable(func): raise TypeError(f'Flow must be async: {getattr(func, "__name__", repr(func))}') - flow_name = name or getattr(func, '__name__', None) or 'unnamed_flow' + flow_name = name or getattr(func, '__name__', None) or type(func).__name__ super().__init__( kind=ActionKind.FLOW, name=flow_name, diff --git a/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py b/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py index 6c58c629a..596d52c21 100644 --- a/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py +++ b/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py @@ -24,7 +24,6 @@ import atexit import contextlib -import inspect import json from collections.abc import Awaitable, Callable, Mapping from contextvars import ContextVar @@ -33,6 +32,8 @@ from pydantic import BaseModel +from genkit._core._compat import is_async_callable + from ._attrs import METADATA_PREFIX, Attr from ._log_exporter import reset_log_export @@ -277,7 +278,7 @@ async def run_in_new_span( outermost. The provider list is snapshotted so configure/reset during an await cannot break the chain. """ - if not inspect.iscoroutinefunction(fn): + if not is_async_callable(fn): name = getattr(fn, '__qualname__', type(fn).__name__) raise TypeError(f'run_in_new_span expected an async callback, got {name}') attrs: dict[str, SpanAttributeValue] = dict(attributes) if attributes else {} diff --git a/packages/genkit/src/genkit/_core/_tool.py b/packages/genkit/src/genkit/_core/_tool.py index dfa8ae42a..4420db7c9 100644 --- a/packages/genkit/src/genkit/_core/_tool.py +++ b/packages/genkit/src/genkit/_core/_tool.py @@ -18,7 +18,6 @@ from __future__ import annotations -import inspect from collections.abc import Awaitable, Callable from contextvars import ContextVar from types import UnionType @@ -38,6 +37,7 @@ get_func_description, resolve_type_hints, ) +from genkit._core._compat import is_async_callable from genkit._core._error import ErrorReason, GenkitError from genkit._core._model import ( MultipartToolResponse, @@ -401,8 +401,7 @@ async def lookup_price(sku: str) -> str: ephemeral = Tool(lookup_price, name='lookup_price') res = await ai.generate(prompt='Price of SKU-1?', tools=[ephemeral]) """ - # A callable instance with `async def __call__` is async too. - if not (inspect.iscoroutinefunction(func) or inspect.iscoroutinefunction(type(func).__call__)): + if not is_async_callable(func): raise TypeError(f'Tool function must be async. Got sync function: {getattr(func, "__name__", repr(func))}') tool_name = name if name is not None else getattr(func, '__name__', None) if tool_name is None: diff --git a/packages/genkit/tests/genkit/core/action_test.py b/packages/genkit/tests/genkit/core/action_test.py index d8c27ab0a..937e2b177 100644 --- a/packages/genkit/tests/genkit/core/action_test.py +++ b/packages/genkit/tests/genkit/core/action_test.py @@ -14,7 +14,7 @@ import pytest from pydantic import BaseModel, ConfigDict -from genkit import FlowContext, Genkit, Message, Part, PublicError +from genkit import Flow, FlowContext, Genkit, Message, Part, PublicError from genkit._core._action import ( Action, ActionContext, @@ -936,3 +936,28 @@ async def tracked_aclose() -> None: assert seen == ['steeping oolong'] assert closed == [True] + + +@pytest.mark.asyncio +async def test_action_and_flow_accept_async_callable_instances() -> None: + """Async callable instances work in Action and Flow; sync callable instances are rejected.""" + + class Echo: + async def __call__(self, value: str) -> str: + return value + + class SyncEcho: + def __call__(self, value: str) -> str: + return value + + action = Action(name='echo', kind=ActionKind.CUSTOM, fn=Echo()) + assert (await action.run('hi')).response == 'hi' + + flow = Flow(Echo()) + assert flow.name == 'Echo' + assert (await flow.run('yo')).response == 'yo' + + with pytest.raises(TypeError, match='Action handlers must be async functions'): + Action(name='sync-echo', kind=ActionKind.CUSTOM, fn=SyncEcho()) # type: ignore[arg-type] + with pytest.raises(TypeError, match='Flow must be async'): + Flow(SyncEcho()) # type: ignore[arg-type] diff --git a/packages/genkit/tests/genkit/core/background_registry_test.py b/packages/genkit/tests/genkit/core/background_registry_test.py index af816177b..bf670d0fb 100644 --- a/packages/genkit/tests/genkit/core/background_registry_test.py +++ b/packages/genkit/tests/genkit/core/background_registry_test.py @@ -188,3 +188,33 @@ async def list_actions(self) -> list[Action | BackgroundAction[Any, Any]]: assert check is video.check_action assert ai._registry.registered_action(ActionKind.BACKGROUND_MODEL, 'routing/bistro-video') is None + + +@pytest.mark.asyncio +async def test_background_model_accepts_async_callable_instances() -> None: + """BackgroundModel start and check handlers accept async callable instances and reject sync ones.""" + + class AsyncStart: + async def __call__(self, request: ModelRequest, ctx: ModelContext) -> Operation: + return Operation(id='job-1', done=False) + + class AsyncCheck: + async def __call__(self, op: Operation, ctx: ModelContext) -> Operation: + return Operation( + id=op.id, + done=True, + output=ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('done')])), + ) + + class SyncStart: + def __call__(self, request: ModelRequest, ctx: ModelContext) -> Operation: + return Operation(id='job-1', done=False) + + model = BackgroundModel('callable-video', start=AsyncStart(), check=AsyncCheck()) + started = await model.start(ModelRequest(messages=[Message(role=Role.USER, content=[Part.from_text('go')])])) + assert started.id == 'job-1' + checked = await model.check(started) + assert checked.done is True + + with pytest.raises(TypeError, match='Action handlers must be async functions'): + BackgroundModel('sync-video', start=SyncStart(), check=AsyncCheck()) # type: ignore[arg-type] diff --git a/packages/genkit/tests/genkit/core/run_in_new_span_test.py b/packages/genkit/tests/genkit/core/run_in_new_span_test.py index 5674230fb..e0c02c1d2 100644 --- a/packages/genkit/tests/genkit/core/run_in_new_span_test.py +++ b/packages/genkit/tests/genkit/core/run_in_new_span_test.py @@ -558,3 +558,21 @@ def test_start_attributes_precedence_over_telemetry_labels() -> None: assert attrs['genkit:path'] == '/realPath' assert attrs['genkit:qualifiedPath'] == '/realPath' assert attrs['user:label'] == 'custom' + + +@pytest.mark.asyncio +async def test_run_in_new_span_accepts_async_callable_instance() -> None: + """run_in_new_span accepts an async callable instance and rejects a sync one.""" + + class AsyncBody: + async def __call__(self, _span: object) -> str: + return 'ok' + + class SyncBody: + def __call__(self, _span: object) -> str: + return 'ok' + + assert await run_in_new_span('callable-span', AsyncBody()) == 'ok' + + with pytest.raises(TypeError, match='expected an async callback'): + await run_in_new_span('sync-span', SyncBody()) # type: ignore[arg-type] From a07a48cbda3492f6a01eb94bf6f0555ee04036e2 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Tue, 1 Dec 2026 20:23:13 +0000 Subject: [PATCH 2/2] refactor(core): move is_async_callable from _compat to _action --- packages/genkit/src/genkit/_ai/_evaluator.py | 3 +-- packages/genkit/src/genkit/_core/_action.py | 7 ++++++- packages/genkit/src/genkit/_core/_background.py | 2 +- packages/genkit/src/genkit/_core/_compat.py | 6 ------ packages/genkit/src/genkit/_core/_flow.py | 2 +- .../genkit/src/genkit/_core/_telemetry/_instrumentation.py | 5 ++--- packages/genkit/src/genkit/_core/_tool.py | 2 +- 7 files changed, 12 insertions(+), 15 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_evaluator.py b/packages/genkit/src/genkit/_ai/_evaluator.py index 6147d658f..44b768ce0 100644 --- a/packages/genkit/src/genkit/_ai/_evaluator.py +++ b/packages/genkit/src/genkit/_ai/_evaluator.py @@ -29,8 +29,7 @@ from pydantic.alias_generators import to_camel from typing_extensions import Never -from genkit._core._action import Action, ActionContext, ActionKind -from genkit._core._compat import is_async_callable +from genkit._core._action import Action, ActionContext, ActionKind, is_async_callable from genkit._core._logger import get_logger from genkit._core._registry import Registry from genkit._core._schema import to_json_schema diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index dcc6d0d04..fea68bdff 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -50,7 +50,7 @@ from typing_extensions import Never, Self, TypeVar from genkit._core._channel import Channel, CloseableQueue, StoppableStream, _stop_scope -from genkit._core._compat import StrEnum, is_async_callable +from genkit._core._compat import StrEnum from genkit._core._config_check import ( check_config_json_schema, check_config_values, @@ -659,6 +659,11 @@ def json_schema_for( # ----------------------------------------------------------------------------- +def is_async_callable(fn: object) -> bool: + """Return True for ``async def`` functions and instances whose ``__call__`` is ``async def``.""" + return inspect.iscoroutinefunction(fn) or inspect.iscoroutinefunction(type(fn).__call__) + + def signature_of(fn: Callable[..., object]) -> inspect.Signature: """``inspect.signature(fn)``, without failing on a name missing at runtime. diff --git a/packages/genkit/src/genkit/_core/_background.py b/packages/genkit/src/genkit/_core/_background.py index 61048f664..283d52ff3 100644 --- a/packages/genkit/src/genkit/_core/_background.py +++ b/packages/genkit/src/genkit/_core/_background.py @@ -35,9 +35,9 @@ ActionContext, ActionKind, get_current_context, + is_async_callable, set_action_name, ) -from genkit._core._compat import is_async_callable from genkit._core._error import ErrorReason, GenkitError, StatusName from genkit._core._operation import Operation from genkit._core._schema import fixed_json_schema diff --git a/packages/genkit/src/genkit/_core/_compat.py b/packages/genkit/src/genkit/_core/_compat.py index 40d59a223..bc1904a8e 100644 --- a/packages/genkit/src/genkit/_core/_compat.py +++ b/packages/genkit/src/genkit/_core/_compat.py @@ -18,7 +18,6 @@ import asyncio import functools -import inspect import sys import weakref from collections.abc import Callable @@ -49,11 +48,6 @@ _PY310_CANCELLING: weakref.WeakKeyDictionary[asyncio.Task[Any], int] = weakref.WeakKeyDictionary() -def is_async_callable(func: object) -> bool: - """Return True for ``async def`` functions and instances whose ``__call__`` is ``async def``.""" - return inspect.iscoroutinefunction(func) or inspect.iscoroutinefunction(type(func).__call__) - - def uncancel(task: asyncio.Task[Any] | None) -> int: """Decrement the cancellation count of an asyncio.Task.""" if task is None: diff --git a/packages/genkit/src/genkit/_core/_flow.py b/packages/genkit/src/genkit/_core/_flow.py index 02e242623..adb925d9e 100644 --- a/packages/genkit/src/genkit/_core/_flow.py +++ b/packages/genkit/src/genkit/_core/_flow.py @@ -36,8 +36,8 @@ OutputT, get_func_description, input_has_default, + is_async_callable, ) -from genkit._core._compat import is_async_callable from genkit._core._registry import Registry _FlowInputT = TypeVar('_FlowInputT') diff --git a/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py b/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py index 596d52c21..cacfa988b 100644 --- a/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py +++ b/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py @@ -24,6 +24,7 @@ import atexit import contextlib +import inspect import json from collections.abc import Awaitable, Callable, Mapping from contextvars import ContextVar @@ -32,8 +33,6 @@ from pydantic import BaseModel -from genkit._core._compat import is_async_callable - from ._attrs import METADATA_PREFIX, Attr from ._log_exporter import reset_log_export @@ -278,7 +277,7 @@ async def run_in_new_span( outermost. The provider list is snapshotted so configure/reset during an await cannot break the chain. """ - if not is_async_callable(fn): + if not (inspect.iscoroutinefunction(fn) or inspect.iscoroutinefunction(type(fn).__call__)): name = getattr(fn, '__qualname__', type(fn).__name__) raise TypeError(f'run_in_new_span expected an async callback, got {name}') attrs: dict[str, SpanAttributeValue] = dict(attributes) if attributes else {} diff --git a/packages/genkit/src/genkit/_core/_tool.py b/packages/genkit/src/genkit/_core/_tool.py index 4420db7c9..e83a16eb6 100644 --- a/packages/genkit/src/genkit/_core/_tool.py +++ b/packages/genkit/src/genkit/_core/_tool.py @@ -35,9 +35,9 @@ DefaultInputCtxFn, DefaultInputFn, get_func_description, + is_async_callable, resolve_type_hints, ) -from genkit._core._compat import is_async_callable from genkit._core._error import ErrorReason, GenkitError from genkit._core._model import ( MultipartToolResponse,