Ragas 中的缓存
您可以使用缓存来加速您的评估和测试集生成,避免冗余计算。我们使用精确匹配缓存 (Exact Match Caching) 来缓存来自 LLM 和 Embedding 模型的响应。
您可以使用 DiskCacheBackend,它使用本地磁盘缓存来存储缓存的响应。您也可以通过实现 CacheInterface 来实现您自己的自定义 cacher。
使用 DefaultCacher
让我们看看如何使用 DiskCacheBackend LLM 和 Embedding 模型。
from ragas.cache import DiskCacheBackend
cacher = DiskCacheBackend()
# check if the cache is empty and clear it
print(len(cacher.cache))
cacher.cache.clear()
print(len(cacher.cache))
DiskCacheBackend(cache_dir=.cache)
使用 cacher 创建一个 LLM 和 Embedding 模型,这里我以来自 langchain-openai 的 ChatOpenAI
为例。
from langchain_openai import ChatOpenAI
from ragas.llms import LangchainLLMWrapper
cached_llm = LangchainLLMWrapper(ChatOpenAI(model="gpt-4o"), cache=cacher)
# if you want to see the cache in action, set the logging level to debug
import logging
from ragas.utils import set_logging_level
set_logging_level("ragas.cache", logging.DEBUG)
现在我们来运行一个简单的评估。
from ragas import evaluate
from ragas import EvaluationDataset
from ragas.metrics import FactualCorrectness, AspectCritic
from datasets import load_dataset
# Define Answer Correctness with AspectCritic
answer_correctness = AspectCritic(
name="answer_correctness",
definition="Is the answer correct? Does it match the reference answer?",
llm=cached_llm,
)
metrics = [answer_correctness, FactualCorrectness(llm=cached_llm)]
# load the dataset
dataset = load_dataset(
"explodinggradients/amnesty_qa", "english_v3", trust_remote_code=True
)
eval_dataset = EvaluationDataset.from_hf_dataset(dataset["eval"])
# evaluate the dataset
results = evaluate(
dataset=eval_dataset,
metrics=metrics,
)
results
这在我们的本地机器上运行花了将近 2 分钟。现在我们再次运行它,看看缓存的效果。
几乎瞬间运行。
您也可以将其用于测试集生成,方法是将 generator_llm
替换为其缓存版本。有关更多详细信息,请参阅测试集生成部分。