diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index fccc00f2..3cb81632 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -45,6 +45,7 @@ from pydantic.errors import PydanticInvalidForJsonSchema, PydanticSchemaGenerationError, PydanticUserError from typing_extensions import Never, Self, TypeVar +from genkit._core._async_call import is_async_callable from genkit._core._channel import Channel, CloseableQueue, StoppableStream, _stop_scope from genkit._core._compat import StrEnum from genkit._core._config_check import ( @@ -1105,7 +1106,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/_async_call.py b/packages/genkit/src/genkit/_core/_async_call.py new file mode 100644 index 00000000..f851224f --- /dev/null +++ b/packages/genkit/src/genkit/_core/_async_call.py @@ -0,0 +1,30 @@ +# 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 + +"""One definition of an async handler: a coroutine function or a callable instance.""" + +from __future__ import annotations + +import inspect + + +def is_async_callable(func: object) -> bool: + """True for ``async def`` functions and for instances whose ``__call__`` is ``async def``. + + ``inspect.iscoroutinefunction`` alone only looks at functions, so a callable + instance would be rejected here while the same object is accepted by ``Tool``. + """ + return inspect.iscoroutinefunction(func) or inspect.iscoroutinefunction(type(func).__call__) diff --git a/packages/genkit/src/genkit/_core/_background.py b/packages/genkit/src/genkit/_core/_background.py index 86046a8b..00d9bd59 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._async_call 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 @@ -486,7 +486,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 882bc613..cf01dc44 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 @@ -33,6 +32,7 @@ OutputT, get_func_description, ) +from genkit._core._async_call import is_async_callable from genkit._core._registry import Registry _FlowInputT = TypeVar('_FlowInputT') @@ -127,10 +127,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..5b8c88ed 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._async_call 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/tests/genkit/core/async_callable_test.py b/packages/genkit/tests/genkit/core/async_callable_test.py new file mode 100644 index 00000000..e8a3dfd7 --- /dev/null +++ b/packages/genkit/tests/genkit/core/async_callable_test.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +# +# Copyright 2026 Google LLC +# SPDX-License-Identifier: Apache-2.0 + +"""A callable instance whose __call__ is async is a handler everywhere, not only in Tool.""" + +import pytest + +from genkit._core._action import Action +from genkit._core._flow import Flow +from genkit._core._telemetry._instrumentation import run_in_new_span +from genkit.plugin_api import ActionKind + + +class Echo: + """Async callable instance; deliberately has no __name__.""" + + async def __call__(self, value: str) -> str: + """Return the argument unchanged.""" + return value + + +class SyncEcho: + """Sync callable instance; still not a valid handler.""" + + def __call__(self, value: str) -> str: + """Return the argument unchanged.""" + return value + + +@pytest.mark.asyncio +async def test_action_accepts_async_callable_instance() -> None: + """Action builds and runs from an instance, not just a bare coroutine function.""" + action = Action(ActionKind.CUSTOM, 'echo', Echo()) + assert (await action.run('hi')).response == 'hi' + + +@pytest.mark.asyncio +async def test_flow_accepts_async_callable_instance() -> None: + """Flow builds, names the instance after its class, and runs.""" + flow = Flow(Echo()) + assert flow.name == 'Echo' + assert (await flow.run('yo')).response == 'yo' + + +@pytest.mark.asyncio +async def test_run_in_new_span_accepts_async_callable_instance() -> None: + """The span helper accepts the same objects Action and Flow accept.""" + span = await run_in_new_span('probe', Echo()) + assert span is not None + + +def test_sync_callable_instance_is_rejected() -> None: + """A sync __call__ keeps the existing TypeError and message.""" + with pytest.raises(TypeError, match='Action handlers must be async functions'): + Action(ActionKind.CUSTOM, 'sync-echo', SyncEcho()) + with pytest.raises(TypeError, match='Flow must be async'): + Flow(SyncEcho()) + + +@pytest.mark.asyncio +async def test_run_in_new_span_rejects_sync_instance() -> None: + """The span helper still refuses a sync callable instance.""" + with pytest.raises(TypeError, match='expected an async callback'): + await run_in_new_span('probe', SyncEcho())