diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index ef80e851..fea68bdf 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -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. @@ -1184,7 +1189,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 4d32de11..283d52ff 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 @@ -36,6 +35,7 @@ ActionContext, ActionKind, get_current_context, + is_async_callable, set_action_name, ) from genkit._core._error import ErrorReason, GenkitError, StatusName @@ -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/_flow.py b/packages/genkit/src/genkit/_core/_flow.py index ce1eb627..adb925d9 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 @@ -37,6 +36,7 @@ OutputT, get_func_description, input_has_default, + is_async_callable, ) from genkit._core._registry import Registry @@ -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 6c58c629..cacfa988 100644 --- a/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py +++ b/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py @@ -277,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 inspect.iscoroutinefunction(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 dfa8ae42..e83a16eb 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 @@ -36,6 +35,7 @@ DefaultInputCtxFn, DefaultInputFn, get_func_description, + is_async_callable, resolve_type_hints, ) from genkit._core._error import ErrorReason, GenkitError @@ -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 d8c27ab0..937e2b17 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 af816177..bf670d0f 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 5674230f..e0c02c1d 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]