From f0ea55d709f47399bc6682fab6fc0af2119571ce Mon Sep 17 00:00:00 2001 From: Tasha Upchurch Date: Fri, 29 Nov 2024 13:27:08 -0700 Subject: [PATCH] fix for #209 function was returning a closed event loop. --- lightrag/lightrag.py | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/lightrag/lightrag.py b/lightrag/lightrag.py index cec21b2f..6511e61b 100644 --- a/lightrag/lightrag.py +++ b/lightrag/lightrag.py @@ -52,15 +52,28 @@ def always_get_an_event_loop() -> asyncio.AbstractEventLoop: + """ + Ensure that there is always an event loop available. + + This function tries to get the current event loop. If the current event loop is closed or does not exist, + it creates a new event loop and sets it as the current event loop. + + Returns: + asyncio.AbstractEventLoop: The current or newly created event loop. + """ try: - return asyncio.get_event_loop() + # Try to get the current event loop + current_loop = asyncio.get_event_loop() + if current_loop._closed: + raise RuntimeError("Event loop is closed.") + return current_loop except RuntimeError: + # If no event loop exists or it is closed, create a new one logger.info("Creating a new event loop in main thread.") - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - - return loop + new_loop = asyncio.new_event_loop() + asyncio.set_event_loop(new_loop) + return new_loop @dataclass