Skip to content

Commit bc6b3ce

Browse files
authored
fix: make async custom functions work (#1255)
1 parent c2f5c8c commit bc6b3ce

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

python/cocoindex/runtime.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,10 @@ def run(self, coro: Coroutine[Any, Any, T]) -> T:
6969

7070

7171
def to_async_call(call: Callable[..., Any]) -> Callable[..., Awaitable[Any]]:
72-
if inspect.iscoroutinefunction(call):
72+
if isinstance(call, (staticmethod, classmethod)):
73+
base_call = call.__func__
74+
else:
75+
base_call = call
76+
if inspect.iscoroutinefunction(base_call):
7377
return call
7478
return lambda *args, **kwargs: asyncio.to_thread(lambda: call(*args, **kwargs))

python/cocoindex/tests/test_transform_flow.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,3 +268,33 @@ def transform_flow_with_analyze_prepare(
268268

269269
result = transform_flow_with_analyze_prepare.eval("Hello")
270270
expected = "Hello world!!"
271+
272+
273+
@cocoindex.op.function()
274+
async def async_custom_function(text: str) -> str:
275+
"""Append ' world' to the input text."""
276+
return f"{text} world"
277+
278+
279+
class AsyncCustomFunctionSpec(cocoindex.op.FunctionSpec):
280+
suffix: str
281+
282+
283+
@cocoindex.op.executor_class()
284+
class AsyncAppendSuffixExecutor:
285+
spec: AsyncCustomFunctionSpec
286+
287+
async def __call__(self, text: str) -> str:
288+
return f"{text}{self.spec.suffix}"
289+
290+
291+
def test_async_custom_function() -> None:
292+
@cocoindex.transform_flow()
293+
def transform_flow(text: cocoindex.DataSlice[str]) -> cocoindex.DataSlice[str]:
294+
return text.transform(async_custom_function).transform(
295+
AsyncCustomFunctionSpec(suffix="!")
296+
)
297+
298+
result = transform_flow.eval("Hello")
299+
expected = "Hello world!"
300+
assert result == expected, f"Expected {expected}, got {result}"

0 commit comments

Comments
 (0)