@@ -77,12 +77,42 @@ def __init__(
7777 def __del__ (self ) -> None :
7878 """Clean up the resources used by the task."""
7979 logger .trace ("Cleaning up the resources used by the task..." )
80- asyncio .run_coroutine_threadsafe (
81- self .openai_api_client .close (),
82- self .event_loop ,
83- ).result ()
80+
81+ # Cancel all pending tasks in the event loop
82+ async def _cancel_all_tasks () -> None :
83+ """Cancel all pending tasks in the event loop."""
84+ tasks = [
85+ task
86+ for task in asyncio .all_tasks (self .event_loop )
87+ if not task .done ()
88+ ]
89+ for task in tasks :
90+ task .cancel ()
91+ # Wait briefly for tasks to cancel
92+ if tasks :
93+ await asyncio .gather (* tasks , return_exceptions = True )
94+
95+ try :
96+ # Cancel any pending tasks first
97+ asyncio .run_coroutine_threadsafe (
98+ _cancel_all_tasks (),
99+ self .event_loop ,
100+ ).result (timeout = 5.0 )
101+ except Exception as e :
102+ logger .trace ("Error cancelling tasks during cleanup: {}" , e )
103+
104+ # Try to close the OpenAI client gracefully
105+ try :
106+ asyncio .run_coroutine_threadsafe (
107+ self .openai_api_client .close (),
108+ self .event_loop ,
109+ ).result (timeout = 5.0 )
110+ except Exception as e :
111+ logger .trace ("Error closing OpenAI client during cleanup: {}" , e )
112+
113+ # Stop the event loop and join the thread
84114 self .event_loop .call_soon_threadsafe (self .event_loop .stop )
85- self .event_loop_thread .join ()
115+ self .event_loop_thread .join (timeout = 5.0 )
86116
87117 @staticmethod
88118 def _create_event_loop_in_separate_thread () -> (
0 commit comments