Huỳnh Triệu Vĩ
commited on
Commit
·
5dea338
1
Parent(s):
a19b3c4
fix this event loop is already running
Browse files- lightrag/lightrag.py +20 -5
lightrag/lightrag.py
CHANGED
|
@@ -404,16 +404,31 @@ class LightRAG:
|
|
| 404 |
|
| 405 |
self._storages_status = StoragesStatus.CREATED
|
| 406 |
|
| 407 |
-
# Initialize storages
|
| 408 |
if self.auto_manage_storages_states:
|
| 409 |
-
|
| 410 |
-
loop.run_until_complete(self.initialize_storages())
|
| 411 |
|
| 412 |
def __del__(self):
|
| 413 |
-
# Finalize storages
|
| 414 |
if self.auto_manage_storages_states:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
loop = always_get_an_event_loop()
|
| 416 |
-
loop.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 417 |
|
| 418 |
async def initialize_storages(self):
|
| 419 |
"""Asynchronously initialize the storages"""
|
|
|
|
| 404 |
|
| 405 |
self._storages_status = StoragesStatus.CREATED
|
| 406 |
|
|
|
|
| 407 |
if self.auto_manage_storages_states:
|
| 408 |
+
self._run_async_safely(self.initialize_storages, "Storage Initialization")
|
|
|
|
| 409 |
|
| 410 |
def __del__(self):
|
|
|
|
| 411 |
if self.auto_manage_storages_states:
|
| 412 |
+
self._run_async_safely(self.finalize_storages, "Storage Finalization")
|
| 413 |
+
|
| 414 |
+
def _run_async_safely(self, async_func, action_name=""):
|
| 415 |
+
"""Safely execute an async function, avoiding event loop conflicts."""
|
| 416 |
+
try:
|
| 417 |
loop = always_get_an_event_loop()
|
| 418 |
+
if loop.is_running():
|
| 419 |
+
task = loop.create_task(async_func())
|
| 420 |
+
task.add_done_callback(
|
| 421 |
+
lambda t: logger.info(f"✅ {action_name} completed!")
|
| 422 |
+
)
|
| 423 |
+
else:
|
| 424 |
+
loop.run_until_complete(async_func())
|
| 425 |
+
except RuntimeError:
|
| 426 |
+
logger.warning(
|
| 427 |
+
f"No running event loop, creating a new loop for {action_name}."
|
| 428 |
+
)
|
| 429 |
+
loop = asyncio.new_event_loop()
|
| 430 |
+
loop.run_until_complete(async_func())
|
| 431 |
+
loop.close()
|
| 432 |
|
| 433 |
async def initialize_storages(self):
|
| 434 |
"""Asynchronously initialize the storages"""
|