Add clear_cache

This commit is contained in:
zrguo
2025-03-01 18:30:58 +08:00
parent a923ee89b0
commit a8f4385c05
2 changed files with 83 additions and 0 deletions

View File

@@ -1588,3 +1588,52 @@ class LightRAG:
f"Storage implementation '{storage_name}' requires the following "
f"environment variables: {', '.join(missing_vars)}"
)
async def aclear_cache(self, modes: list[str] | None = None) -> None:
"""Clear cache data from the LLM response cache storage.
Args:
modes (list[str] | None): Modes of cache to clear. Options: ["default", "naive", "local", "global", "hybrid", "mix"].
"default" represents extraction cache.
If None, clears all cache.
Example:
# Clear all cache
await rag.aclear_cache()
# Clear local mode cache
await rag.aclear_cache(modes=["local"])
# Clear extraction cache
await rag.aclear_cache(modes=["default"])
"""
if not self.llm_response_cache:
logger.warning("No cache storage configured")
return
valid_modes = ["default", "naive", "local", "global", "hybrid", "mix"]
# Validate input
if modes and not all(mode in valid_modes for mode in modes):
raise ValueError(f"Invalid mode. Valid modes are: {valid_modes}")
try:
# Reset the cache storage for specified mode
if modes:
await self.llm_response_cache.delete(modes)
logger.info(f"Cleared cache for modes: {modes}")
else:
# Clear all modes
await self.llm_response_cache.delete(valid_modes)
logger.info("Cleared all cache")
await self.llm_response_cache.index_done_callback()
except Exception as e:
logger.error(f"Error while clearing cache: {e}")
def clear_cache(self, modes: list[str] | None = None) -> None:
"""Synchronous version of aclear_cache."""
return always_get_an_event_loop().run_until_complete(
self.aclear_cache(modes)
)