Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
7 changes: 6 additions & 1 deletion packages/genkit/src/genkit/_core/_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions packages/genkit/src/genkit/_core/_background.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -36,6 +35,7 @@
ActionContext,
ActionKind,
get_current_context,
is_async_callable,
set_action_name,
)
from genkit._core._error import ErrorReason, GenkitError, StatusName
Expand Down Expand Up @@ -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

Expand Down
6 changes: 3 additions & 3 deletions packages/genkit/src/genkit/_core/_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

from __future__ import annotations

import inspect
from collections.abc import Awaitable, Callable
from typing import Any, overload

Expand All @@ -37,6 +36,7 @@
OutputT,
get_func_description,
input_has_default,
is_async_callable,
)
from genkit._core._registry import Registry

Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}
Expand Down
5 changes: 2 additions & 3 deletions packages/genkit/src/genkit/_core/_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

from __future__ import annotations

import inspect
from collections.abc import Awaitable, Callable
from contextvars import ContextVar
from types import UnionType
Expand All @@ -36,6 +35,7 @@
DefaultInputCtxFn,
DefaultInputFn,
get_func_description,
is_async_callable,
resolve_type_hints,
)
from genkit._core._error import ErrorReason, GenkitError
Expand Down Expand Up @@ -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:
Expand Down
27 changes: 26 additions & 1 deletion packages/genkit/tests/genkit/core/action_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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]
30 changes: 30 additions & 0 deletions packages/genkit/tests/genkit/core/background_registry_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
18 changes: 18 additions & 0 deletions packages/genkit/tests/genkit/core/run_in_new_span_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Loading