Skip to content

Commit cce4119

Browse files
authored
fix(observe): wrap returned async generators (#1259)
Co-authored-by: @kouk
1 parent 31e4b73 commit cce4119

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

langfuse/_client/observe.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919
overload,
2020
)
2121

22-
from typing_extensions import ParamSpec
2322
from opentelemetry.util._decorator import _AgnosticContextManager
23+
from typing_extensions import ParamSpec
2424

2525
from langfuse._client.environment_variables import (
2626
LANGFUSE_OBSERVE_DECORATOR_IO_CAPTURE_ENABLED,
@@ -267,6 +267,15 @@ async def async_wrapper(*args: Tuple[Any], **kwargs: Dict[str, Any]) -> Any:
267267
result = await func(*args, **kwargs)
268268

269269
if capture_output is True:
270+
if inspect.isgenerator(result):
271+
is_return_type_generator = True
272+
273+
return self._wrap_sync_generator_result(
274+
langfuse_span_or_generation,
275+
result,
276+
transform_to_string,
277+
)
278+
270279
if inspect.isasyncgen(result):
271280
is_return_type_generator = True
272281

@@ -369,6 +378,15 @@ def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
369378
transform_to_string,
370379
)
371380

381+
if inspect.isasyncgen(result):
382+
is_return_type_generator = True
383+
384+
return self._wrap_async_generator_result(
385+
langfuse_span_or_generation,
386+
result,
387+
transform_to_string,
388+
)
389+
372390
langfuse_span_or_generation.update(output=result)
373391

374392
return result

tests/test_decorators.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -798,7 +798,7 @@ async def main_async(**kwargs):
798798
assert main_observation.output == mock_output
799799

800800
assert nested_observation.name == "async_generator_function"
801-
assert nested_observation.output == "<async_generator>"
801+
assert nested_observation.output == "Hello--, async --World!"
802802

803803

804804
@pytest.mark.asyncio

0 commit comments

Comments
 (0)