Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: async streaming handler send to queue logic #162

Merged
merged 1 commit into from
Feb 25, 2025
Merged
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
15 changes: 13 additions & 2 deletions dynamiq/callbacks/streaming.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def on_node_execute_stream(
data=format_value(chunk),
event=serialized.get("streaming", {}).get("event"),
)
self.queue.put_nowait(event)
self.send_to_queue(event)

def on_workflow_end(
self, serialized: dict[str, Any], output_data: dict[str, Any], **kwargs: Any
Expand All @@ -80,7 +80,7 @@ def on_workflow_end(
data=format_value(output_data),
event=serialized.get("streaming", {}).get("event"),
)
self.queue.put_nowait(event)
self.send_to_queue(event)
self.done_event.set()

def on_workflow_error(
Expand All @@ -95,6 +95,10 @@ def on_workflow_error(
"""
self.done_event.set()

def send_to_queue(self, event: StreamingEventMessage):
"""Send the event to the queue."""
self.queue.put_nowait(event)


class StreamingIteratorCallbackHandler(StreamingQueueCallbackHandler):
"""Callback handler for streaming events using an iterator."""
Expand Down Expand Up @@ -154,19 +158,26 @@ def __init__(
self,
queue: asyncio.Queue | None = None,
done_event: asyncio.Event | None = None,
loop: asyncio.AbstractEventLoop | None = None,
) -> None:
"""Initialize AsyncStreamingIteratorCallbackHandler.

Args:
queue (asyncio.Queue | None): Queue for streaming events.
done_event (asyncio.Event | None): Event to signal completion.
loop (asyncio.AbstractEventLoop | None): Event loop.
"""
if queue is None:
queue = asyncio.Queue()
if done_event is None:
done_event = asyncio.Event()
super().__init__(queue, done_event)
self._iterator = self._iter_queue_events()
self.loop = loop or asyncio.get_event_loop()

def send_to_queue(self, event: StreamingEventMessage):
"""Send the event to the queue."""
asyncio.run_coroutine_threadsafe(self.queue.put(event), self.loop)

async def _iter_queue_events(self) -> AsyncIterator[StreamingEventMessage]:
"""Async iterate over queue events.
Expand Down
Loading