From a8f4385c0517a724eed5ee6ce1ba510affcf1c3a Mon Sep 17 00:00:00 2001 From: zrguo Date: Sat, 1 Mar 2025 18:30:58 +0800 Subject: [PATCH] Add clear_cache --- README.md | 34 ++++++++++++++++++++++++++++++ lightrag/lightrag.py | 49 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) diff --git a/README.md b/README.md index 84b35654..86211b35 100644 --- a/README.md +++ b/README.md @@ -751,6 +751,40 @@ rag.delete_by_entity("Project Gutenberg") rag.delete_by_doc_id("doc_id") ``` +## Cache + +
+ Clear Cache + +You can clear the LLM response cache with different modes: + +```python +# 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"]) + +# Clear multiple modes +await rag.aclear_cache(modes=["local", "global", "hybrid"]) + +# Synchronous version +rag.clear_cache(modes=["local"]) +``` + +Valid modes are: +- `"default"`: Extraction cache +- `"naive"`: Naive search cache +- `"local"`: Local search cache +- `"global"`: Global search cache +- `"hybrid"`: Hybrid search cache +- `"mix"`: Mix search cache + +
+ ## LightRAG init parameters
diff --git a/lightrag/lightrag.py b/lightrag/lightrag.py index ea87d188..0f08f20e 100644 --- a/lightrag/lightrag.py +++ b/lightrag/lightrag.py @@ -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) + )