Skip to content

Commit

Permalink
fix(sdk): aworkflow decorator for async generators (#2292)
Browse files Browse the repository at this point in the history
  • Loading branch information
eliasecchig authored Nov 13, 2024
1 parent 2cd6147 commit 64a110c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
21 changes: 21 additions & 0 deletions packages/traceloop-sdk/tests/test_workflows.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import asyncio
import json

import pytest
Expand Down Expand Up @@ -259,3 +260,23 @@ async def unserializable_workflow(obj: object):

spans = exporter.get_finished_spans()
assert [span.name for span in spans] == ["unserializable_task.task"]


@pytest.mark.asyncio
async def test_async_generator_workflow(exporter):

@aworkflow(name="async generator")
async def stream_numbers():
for i in range(3):
yield i
await asyncio.sleep(0.1)

results = []

async for num in await stream_numbers():
results.append(num)

spans = exporter.get_finished_spans()

assert results == [0, 1, 2]
assert [span.name for span in spans] == ['async generator.workflow']
9 changes: 6 additions & 3 deletions packages/traceloop-sdk/traceloop/sdk/decorators/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,11 +175,14 @@ async def wrap(*args, **kwargs):
except TypeError as e:
Telemetry().log_exception(e)

res = await fn(*args, **kwargs)
res = fn(*args, **kwargs)

# span will be ended in the generator
# If it's an async generator, return a new async generator that handles the span
if isinstance(res, types.AsyncGeneratorType):
return await _ahandle_generator(span, ctx_token, res)
return _ahandle_generator(span, ctx_token, res)

# Await here for non-generator async functions
res = await res

try:
if _should_send_prompts():
Expand Down

0 comments on commit 64a110c

Please sign in to comment.