在 Ragas 中的缓存
您可以使用缓存,通过避免冗余计算来加速评估和测试集生成。我们使用 Exact Match Caching 来缓存来自 LLM 和 Embedding 模型的响应。
您可以使用 DiskCacheBackend,它使用本地磁盘缓存来存储缓存的响应。您也可以通过实现 CacheInterface 来实现您自己的自定义缓存器。
使用 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)
创建一个带缓存器的 LLM 和嵌入模型,这里我使用来自 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分钟。现在让我们再运行一次以查看缓存的实际效果。
几乎瞬间完成。
您也可以将其用于 testset generation,通过将 generator_llm 替换为它的缓存版本。有关更多详细信息,请参阅 testset generation 部分。