利用本地模型使用 RAGAS 评估检索增强系统效果

1,379 阅读4分钟

大家好,我是雨飞。之前有写过一篇关于 RAGAS 的文章,由于 RAGAS 官方代码的更新,原来的代码有一些不合适的地方。而且,之前的代码只提供了本地 API 调用的方式,这次给大家提供一个使用本地模型评估系统效果的代码。有不清楚的地方,可以加 1060687688 沟通交流。

RAGAS 安装

我们目前使用的版本是 0.1.1, 直接使用 pip 进行安装就可以。

pip install ragas

新建数据集

RAGAS 需要使用 HuggingFace 标准的 dataset 的格式,因此我们可以根据现有的格式去构建自己的数据集或者读取 HF 上现有的数据集。

读取 HF 上的数据集

from datasets import load_dataset
 
fiqa_eval = load_dataset("explodinggradients/fiqa", "ragas_eval")['baseline']
fiqa_eval

自己定义数据集

数据集包含下面四个列:

question: list[str], 这个是 RAG 系统中希望评测的问题。

answer: list[str],由 RAG 系统生成,并提供给用户的答案,也就是需要评测的答案。

contexts: list[list[str]], 传入 LLM 并回答问题的上下文。

ground_truths: list[list[str]]],问题的真实答案,这个在线评估的时候,可以忽略,因为我们无法有效获取真实的答案数据。

from datasets import Dataset

questions, answers, contexts, ground_truths = [], [], [], []
# The dataset in the format of ragas which the metrics will use to score the RAG pipeline with
evalsets = {
              "question": questions,
              "answer": answers,
              "contexts": contexts,
              "ground_truths": ground_truths
            }
evalsets = Dataset.from_dict(evalsets)

自定义本地的 LLM

RAGAS 高版本,需要实现 generate_text 以及 agenerate_text 这两个方法,其中,generate_text是一个同步的方法,而 agenerate_text 是一个异步的方法。

本地的 LLM,我们可以使用 transformers 这个库去调用,这里需要把 trust_remote_code 参数设置为 True。

class MyLLM(BaseRagasLLM):

    def __init__(self, llm_path):
        self.tokenizer = AutoTokenizer.from_pretrained(llm_path, trust_remote_code=True)
        self.base_llm = AutoModel.from_pretrained(llm_path, trust_remote_code=True).cuda()
        self.base_llm = self.base_llm.eval()

    @property
    def llm(self):
        return self.base_llm

    def get_llm_result(self, prompt):
        generations = []
        llm_output = {}
        token_total = 0
        content = prompt.to_string()
        text, history = self.base_llm.chat(self.tokenizer, content, history=[])
        generations.append([Generation(text=text)])
        token_total += len(text)
        llm_output['token_total'] = token_total
        return LLMResult(generations=generations, llm_output=llm_output)

    def generate_text(
            self,
            prompt: PromptValue,
            n: int = 1,
            temperature: float = 1e-8,
            stop: t.Optional[t.List[str]] = None,
            callbacks: Callbacks = [],
    ):
        result = self.get_llm_result(prompt)
        return result

    async def agenerate_text(
            self,
            prompt: PromptValue,
            n: int = 1,
            temperature: float = 1e-8,
            stop: t.Optional[t.List[str]] = None,
            callbacks: Callbacks = [],
    ) -> LLMResult:
        generations = []
        llm_output = {}
        token_total = 0
        content = prompt.to_string()
        text, history = await asyncio.get_event_loop().run_in_executor(None, self.base_llm.chat, self.tokenizer,
                                                                       content, [])

        generations.append([Generation(text=text)])
        token_total += len(text)
        llm_output['token_total'] = token_total
        result = LLMResult(generations=generations, llm_output=llm_output)
        return result

最终代码

最终代码示例如下,只需要加载自己的数据,将 LLM 的路径和 embedding 的路径修改成自己本地的路径就可以。

import typing as t
import asyncio
from typing import List
from datasets import load_dataset, load_from_disk
from ragas.metrics import faithfulness, context_recall, context_precision
from ragas.metrics import AnswerRelevancy
from ragas import evaluate
from ragas.llms import BaseRagasLLM
from langchain.schema import LLMResult
from langchain.schema import Generation
from langchain.callbacks.base import Callbacks
from langchain.schema.embeddings import Embeddings
from FlagEmbedding import FlagModel
from transformers import AutoModel, AutoTokenizer
from ragas.llms.prompt import PromptValue


class MyLLM(BaseRagasLLM):

    def __init__(self, llm_path):
        self.tokenizer = AutoTokenizer.from_pretrained(llm_path, trust_remote_code=True)
        self.base_llm = AutoModel.from_pretrained(llm_path, trust_remote_code=True).cuda()
        self.base_llm = self.base_llm.eval()

    @property
    def llm(self):
        return self.base_llm

    def get_llm_result(self, prompt):
        generations = []
        llm_output = {}
        token_total = 0
        content = prompt.to_string()
        text, history = self.base_llm.chat(self.tokenizer, content, history=[])
        generations.append([Generation(text=text)])
        token_total += len(text)
        llm_output['token_total'] = token_total
        return LLMResult(generations=generations, llm_output=llm_output)

    def generate_text(
            self,
            prompt: PromptValue,
            n: int = 1,
            temperature: float = 1e-8,
            stop: t.Optional[t.List[str]] = None,
            callbacks: Callbacks = [],
    ):
        result = self.get_llm_result(prompt)
        return result

    async def agenerate_text(
            self,
            prompt: PromptValue,
            n: int = 1,
            temperature: float = 1e-8,
            stop: t.Optional[t.List[str]] = None,
            callbacks: Callbacks = [],
    ) -> LLMResult:
        generations = []
        llm_output = {}
        token_total = 0
        content = prompt.to_string()
        text, history = await asyncio.get_event_loop().run_in_executor(None, self.base_llm.chat, self.tokenizer,
                                                                       content, [])

        generations.append([Generation(text=text)])
        token_total += len(text)
        llm_output['token_total'] = token_total
        result = LLMResult(generations=generations, llm_output=llm_output)
        return result


class MyEmbedding(Embeddings):

    def __init__(self, path, max_length=512, batch_size=256):
        self.model = FlagModel(path, query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:")
        self.max_length = max_length
        self.batch_size = batch_size

    def embed_documents(self, texts: List[str]) -> List[List[float]]:
        return self.model.encode_corpus(texts, self.batch_size, self.max_length).tolist()

    def embed_query(self, text: str) -> List[float]:
        return self.model.encode_queries(text, self.batch_size, self.max_length).tolist()


data_path = "./fiqa_eval"
fiqa_eval = load_from_disk(data_path)
print(fiqa_eval)
llm_path = "/app/examples/pytorch/llm/output/chatglm3-6b"
emb_path = "/app/bge-large-zh"

embedding_model = MyEmbedding(emb_path)
my_llm = MyLLM(llm_path)

ans_relevancy = AnswerRelevancy()
faithfulness.llm = my_llm
context_recall.llm = my_llm
context_precision.llm = my_llm
ans_relevancy.llm = my_llm
ans_relevancy.embeddings = embedding_model

result = evaluate(
    fiqa_eval["baseline"].select(range(5)),
    metrics=[context_recall, context_precision, ans_relevancy, faithfulness]

)

df = result.to_pandas()
print(df.head())
df.to_csv("result.csv", index=False)

雨飞同行

  • 雨飞
  • 主业是推荐算法
  • 希望通过自媒体开启自己不上班只工作的美好愿景
  • 微信:1060687688
  • 欢迎和我交朋友🫰