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
28 changes: 24 additions & 4 deletions src/agents/realtime/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -758,10 +758,20 @@ def _on_guardrail_task_done(self, task: asyncio.Task[Any]) -> None:
)
)

def _cleanup_guardrail_tasks(self) -> None:
async def _cleanup_guardrail_tasks(self) -> None:
"""Cancel all pending guardrail tasks and wait for them to complete.

This ensures that any exceptions raised by the tasks are properly handled
and prevents warnings about unhandled task exceptions.
"""
for task in self._guardrail_tasks:
if not task.done():
task.cancel()

# Wait for all tasks to complete and collect any exceptions
if self._guardrail_tasks:
await asyncio.gather(*self._guardrail_tasks, return_exceptions=True)

self._guardrail_tasks.clear()

def _enqueue_tool_call_task(
Expand Down Expand Up @@ -796,17 +806,27 @@ def _on_tool_call_task_done(self, task: asyncio.Task[Any]) -> None:
)
)

def _cleanup_tool_call_tasks(self) -> None:
async def _cleanup_tool_call_tasks(self) -> None:
"""Cancel all pending tool call tasks and wait for them to complete.

This ensures that any exceptions raised by the tasks are properly handled
and prevents warnings about unhandled task exceptions.
"""
for task in self._tool_call_tasks:
if not task.done():
task.cancel()

# Wait for all tasks to complete and collect any exceptions
if self._tool_call_tasks:
await asyncio.gather(*self._tool_call_tasks, return_exceptions=True)

self._tool_call_tasks.clear()

async def _cleanup(self) -> None:
"""Clean up all resources and mark session as closed."""
# Cancel and cleanup guardrail tasks
self._cleanup_guardrail_tasks()
self._cleanup_tool_call_tasks()
await self._cleanup_guardrail_tasks()
await self._cleanup_tool_call_tasks()

# Remove ourselves as a listener
self._model.remove_listener(self)
Expand Down
Loading