[{"data":1,"prerenderedAt":404},["ShallowReactive",2],{"content-query-mogcwHuSt7":3},{"_path":4,"_dir":5,"_draft":6,"_partial":6,"_locale":7,"title":8,"description":9,"date":10,"cover":11,"type":12,"category":13,"body":14,"_type":398,"_id":399,"_source":400,"_file":401,"_stem":402,"_extension":403},"/technology-blogs/zh/3589","zh",false,"","一文读懂什么是RAG？附基于MindSpore NLP实现TinyRAG框架实践","作者：青云遮夜雨          来源：知乎","2025-01-21","https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/01/24/cd17a2a9d7244cd091c97743f77e07aa.png","technology-blogs","开发者分享",{"type":15,"children":16,"toc":392},"root",[17,25,35,43,48,56,64,69,114,119,148,156,164,169,173,178,183,196,200,205,210,228,235,243,248,268,273,283,288,296,301,309,314,322,327,332,340,345,353,358,366,371,379,384],{"type":18,"tag":19,"props":20,"children":22},"element","h1",{"id":21},"一文读懂什么是rag附基于mindspore-nlp实现tinyrag框架实践",[23],{"type":24,"value":8},"text",{"type":18,"tag":26,"props":27,"children":28},"p",{},[29],{"type":18,"tag":30,"props":31,"children":32},"strong",{},[33],{"type":24,"value":34},"作****者：青云遮夜雨 来源：知乎",{"type":18,"tag":26,"props":36,"children":37},{},[38],{"type":18,"tag":30,"props":39,"children":40},{},[41],{"type":24,"value":42},"什么是RAG？",{"type":18,"tag":26,"props":44,"children":45},{},[46],{"type":24,"value":47},"首先我们给出RAG的定义：RAG（Retrieval-Augmented Generation）技术是一种结合了信息检索（Retrieval）和生成式模型（Generation）的人工智能方法。对于用户的Query，它首先通过检索系统从大规模知识库中提取相关信息，然后将这些信息输入到生成式模型中，以生成更加准确和上下文相关的文本。RAG技术在自然语言处理任务中表现出色，特别是在需要结合外部知识来生成文本的场景，如问答系统、对话生成和文档摘要等。通过这种方式，RAG能够有效地利用外部知识来增强生成模型的性能，从而提供更高质量的输出。",{"type":18,"tag":26,"props":49,"children":50},{},[51],{"type":18,"tag":30,"props":52,"children":53},{},[54],{"type":24,"value":55},"简单来说：RAG（检索增强生成） = 检索技术 + LLM 提示",{"type":18,"tag":26,"props":57,"children":58},{},[59],{"type":18,"tag":30,"props":60,"children":61},{},[62],{"type":24,"value":63},"为什么使用RAG？",{"type":18,"tag":26,"props":65,"children":66},{},[67],{"type":24,"value":68},"要理解RAG为什么会出现，我们要先看看大模型的局限性：",{"type":18,"tag":70,"props":71,"children":72},"ul",{},[73,88,101],{"type":18,"tag":74,"props":75,"children":76},"li",{},[77,82,86],{"type":18,"tag":30,"props":78,"children":79},{},[80],{"type":24,"value":81},"知识的局限性：",{"type":18,"tag":83,"props":84,"children":85},"br",{},[],{"type":24,"value":87},"模型自身的知识完全源于它的训练数据，而现有的主流大模型（ChatGPT、文心一言、通义千问…）的训练集基本都是构建于网络公开的数据，对于一些实时性的、非公开的或离线的数据是无法获取到的，这部分知识也就无从具备。",{"type":18,"tag":74,"props":89,"children":90},{},[91,96,99],{"type":18,"tag":30,"props":92,"children":93},{},[94],{"type":24,"value":95},"幻觉问题不可避免：",{"type":18,"tag":83,"props":97,"children":98},{},[],{"type":24,"value":100},"所有的AI模型的底层原理都是基于数学概率，其模型输出实质上是一系列数值运算，大模型也不例外，所以它有时候会一本正经地胡说八道，尤其是在大模型自身不具备某一方面的知识或不擅长的场景。而这种幻觉问题的区分是比较困难的，因为它要求使用者自身具备相应领域的知识。论文《Calibrated Language Models Must Hallucinate》证明了预训练语言模型对特定类型的事实产生幻觉存在一个固有的统计学原因，而与 Transformer 架构或数据质量无关。",{"type":18,"tag":74,"props":102,"children":103},{},[104,109,112],{"type":18,"tag":30,"props":105,"children":106},{},[107],{"type":24,"value":108},"数据安全性：",{"type":18,"tag":83,"props":110,"children":111},{},[],{"type":24,"value":113},"对于企业来说，数据安全至关重要，没有企业愿意承担数据泄露的风险，将自身的私域数据上传第三方平台进行训练。这也导致完全依赖通用大模型自身能力的应用方案不得不在数据安全和效果方面进行取舍。",{"type":18,"tag":26,"props":115,"children":116},{},[117],{"type":24,"value":118},"为了克服这些限制，提高模型的能力，有两种主要途径：一种是微调（Fine Tune）来更新模型，另一种是让他们能够与外部世界互动，以不同的形式和方式获取知识。",{"type":18,"tag":70,"props":120,"children":121},{},[122,135],{"type":18,"tag":74,"props":123,"children":124},{},[125,130,133],{"type":18,"tag":30,"props":126,"children":127},{},[128],{"type":24,"value":129},"微调(Fine Tuning)：",{"type":18,"tag":83,"props":131,"children":132},{},[],{"type":24,"value":134},"微调固然效果好，可以让模型真正的“学会”一些私域知识。但是微调也会带来几个问题：首先，由于生成模型依赖于内在知识（权重），因此模型还是无法摆脱幻觉的产生，在对理解门槛高且准确性要求严格的场景下，这就是完全无法接受的，因为用户很难从回答的表面看出模型是否是在胡说八道。其次，在真实场景中，每时每刻都在产生大量数据，对一个事物的概念会迭代的飞快，如某个政策的解读、某个指标的调整等。而模型微调并不是一个简单的工作，无论是从数据准备、算力资源、微调效果、训练时间等各个角度来看，随时用新产生的数据来进行微调都是不现实的，且最终微调的效果也无法保证，能够做到每月更新一次都已经是很理想的状态。最后，对于超大型的大语言模型来说，频繁微调的成本是难以承受的。",{"type":18,"tag":74,"props":136,"children":137},{},[138,143,146],{"type":18,"tag":30,"props":139,"children":140},{},[141],{"type":24,"value":142},"检索增强生成(RAG)：",{"type":18,"tag":83,"props":144,"children":145},{},[],{"type":24,"value":147},"RAG的主要作用类似搜索引擎，找到用户提问最相关的知识或者是相关的对话历史，并结合原始提问（查询），创造信息丰富的prompt，指导模型生成准确输出。其本质上应用了情境学习（In-Context Learning）的原理。RAG（Retrieval Augmented Generation）为生成式模型提供了与外部世界互动提供了一个很有前景的解决方案。",{"type":18,"tag":26,"props":149,"children":150},{},[151],{"type":18,"tag":30,"props":152,"children":153},{},[154],{"type":24,"value":155},"RAG的工作流程",{"type":18,"tag":26,"props":157,"children":158},{},[159],{"type":18,"tag":160,"props":161,"children":163},"img",{"alt":7,"src":162},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/01/24/7698c5a869de49a58ad8fb719a8f18c8.png",[],{"type":18,"tag":26,"props":165,"children":166},{},[167],{"type":24,"value":168},"RAG（Retrieval-Augmented Generation）流程是一种结合信息检索与生成模型的技术，旨在提高生成模型的准确性与效果，尤其在处理开放域问题时，能利用外部知识库或文档增强模型的回答质量。其流程通常分为以下几个步骤：",{"type":18,"tag":170,"props":171,"children":172},"h2",{"id":7},[],{"type":18,"tag":26,"props":174,"children":175},{},[176],{"type":24,"value":177},"01",{"type":18,"tag":26,"props":179,"children":180},{},[181],{"type":24,"value":182},"构建知识库",{"type":18,"tag":70,"props":184,"children":185},{},[186,191],{"type":18,"tag":74,"props":187,"children":188},{},[189],{"type":24,"value":190},"在构建一个高效的RAG系统时，首要步骤是准备知识文档。接着执行一项关键步骤：文档切片。我们需要将长篇文档分割成多个文本块，以便更高效地处理和检索信息。这不仅有助于减轻模型的负担，还能提高信息检索的准确性。",{"type":18,"tag":74,"props":192,"children":193},{},[194],{"type":24,"value":195},"向量化：将文档切片转化为向量是RAG系统中至关重要的一步。一般来说，使用各种Embedding模型来将每个文档切片转化为高维向量表示。这个过程的目的是为了使文本可以在高维空间中进行高效的相似度比较和检索。文档切片的向量可以存储在向量数据库（如FAISS、Pinecone、Weaviate等）中，供后续的检索使用。",{"type":18,"tag":170,"props":197,"children":199},{"id":198},"_1",[],{"type":18,"tag":26,"props":201,"children":202},{},[203],{"type":24,"value":204},"02",{"type":18,"tag":26,"props":206,"children":207},{},[208],{"type":24,"value":209},"用户检索",{"type":18,"tag":70,"props":211,"children":212},{},[213,218,223],{"type":18,"tag":74,"props":214,"children":215},{},[216],{"type":24,"value":217},"用户提出问题时，首先将问题文本进行同样的向量化处理，得到问题的向量表示。然后，通过向量数据库进行相似度检索，从知识库中找到与用户问题最相关的文档切片。常用的相似度度量方法包括余弦相似度、欧几里得距离等。通常，检索系统会返回多个与问题最相关的文档或文档片段。",{"type":18,"tag":74,"props":219,"children":220},{},[221],{"type":24,"value":222},"一旦检索到相关文档切片，接下来，生成模型（如GPT、Qwen等）会根据这些文档切片与用户的问题生成答案。生成过程不仅依赖于模型本身的语言理解和生成能力，还可以借助检索到的相关信息，增强回答的准确性与丰富性。这一过程是RAG的核心，生成模型会将检索到的文本块作为额外的上下文，提升其回答的质量。",{"type":18,"tag":74,"props":224,"children":225},{},[226],{"type":24,"value":227},"生成的答案可能需要一些后处理步骤，比如去除不必要的内容，确保语言流畅性，以及在某些情况下对答案进行事实检查。最终，生成的答案将返回给用户。",{"type":18,"tag":26,"props":229,"children":230},{},[231],{"type":18,"tag":160,"props":232,"children":234},{"alt":7,"src":233},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/01/24/b147f181ffb140869d885070106af573.png",[],{"type":18,"tag":26,"props":236,"children":237},{},[238],{"type":18,"tag":30,"props":239,"children":240},{},[241],{"type":24,"value":242},"基于MindSpore NLP实践",{"type":18,"tag":26,"props":244,"children":245},{},[246],{"type":24,"value":247},"有了上述知识，接下来就可以实现一个基于MindSpore NLP的RAG简易架构。",{"type":18,"tag":249,"props":250,"children":251},"blockquote",{},[252,257],{"type":18,"tag":26,"props":253,"children":254},{},[255],{"type":24,"value":256},"基于MindSpore NLP实现开源代码：",{"type":18,"tag":26,"props":258,"children":259},{},[260],{"type":18,"tag":261,"props":262,"children":266},"a",{"href":263,"rel":264},"https://github.com/ResDream/MindTinyRAG",[265],"nofollow",[267],{"type":24,"value":263},{"type":18,"tag":26,"props":269,"children":270},{},[271],{"type":24,"value":272},"首先我们需要一个阅读数据的Reader：",{"type":18,"tag":274,"props":275,"children":277},"pre",{"code":276},"import os\nimport PyPDF2\nimport markdown\nimport json\nimport tiktoken\nfrom bs4 import BeautifulSoup\nimport re\n\nenc = tiktoken.get_encoding(\"cl100k_base\")\n\n\nclass ReadFiles:\n    \"\"\"\n    class to read files\n    \"\"\"\n\n    def __init__(self, path: str) -> None:\n        self._path = path\n        self.file_list = self.get_files()\n\n    def get_files(self):\n        # args：dir_path，目标文件夹路径\n        file_list = []\n        for filepath, dirnames, filenames in os.walk(self._path):\n            # os.walk 函数将递归遍历指定文件夹\n            for filename in filenames:\n                # 通过后缀名判断文件类型是否满足要求\n                if filename.endswith(\".md\"):\n                    # 如果满足要求，将其绝对路径加入到结果列表\n                    file_list.append(os.path.join(filepath, filename))\n                elif filename.endswith(\".txt\"):\n                    file_list.append(os.path.join(filepath, filename))\n                elif filename.endswith(\".pdf\"):\n                    file_list.append(os.path.join(filepath, filename))\n        return file_list\n\n    def get_content(self, max_token_len: int = 600, cover_content: int = 150):\n        docs = []\n        # 读取文件内容\n        for file in self.file_list:\n            content = self.read_file_content(file)\n            chunk_content = self.get_chunk(\n                content, max_token_len=max_token_len, cover_content=cover_content)\n            docs.extend(chunk_content)\n        return docs\n\n    @classmethod\n    def get_chunk(cls, text: str, max_token_len: int = 600, cover_content: int = 150):\n        chunk_text = []\n\n        curr_len = 0\n        curr_chunk = ''\n\n        token_len = max_token_len - cover_content\n        lines = text.splitlines()  # 假设以换行符分割文本为行\n\n        for line in lines:\n            line = line.replace(' ', '')\n            line_len = len(enc.encode(line))\n            if line_len > max_token_len:\n                # 如果单行长度就超过限制，则将其分割成多个块\n                num_chunks = (line_len + token_len - 1) // token_len\n                for i in range(num_chunks):\n                    start = i * token_len\n                    end = start + token_len\n                    # 避免跨单词分割\n                    while not line[start:end].rstrip().isspace():\n                        start += 1\n                        end += 1\n                        if start >= line_len:\n                            break\n                    curr_chunk = curr_chunk[-cover_content:] + line[start:end]\n                    chunk_text.append(curr_chunk)\n                # 处理最后一个块\n                start = (num_chunks - 1) * token_len\n                curr_chunk = curr_chunk[-cover_content:] + line[start:end]\n                chunk_text.append(curr_chunk)\n                \n            if curr_len + line_len \u003C= token_len:\n                curr_chunk += line\n                curr_chunk += '\\n'\n                curr_len += line_len\n                curr_len += 1\n            else:\n                chunk_text.append(curr_chunk)\n                curr_chunk = curr_chunk[-cover_content:]+line\n                curr_len = line_len + cover_content\n\n        if curr_chunk:\n            chunk_text.append(curr_chunk)\n\n        return chunk_text\n\n    @classmethod\n    def read_file_content(cls, file_path: str):\n        # 根据文件扩展名选择读取方法\n        if file_path.endswith('.pdf'):\n            return cls.read_pdf(file_path)\n        elif file_path.endswith('.md'):\n            return cls.read_markdown(file_path)\n        elif file_path.endswith('.txt'):\n            return cls.read_text(file_path)\n        else:\n            raise ValueError(\"Unsupported file type\")\n\n    @classmethod\n    def read_pdf(cls, file_path: str):\n        # 读取PDF文件\n        with open(file_path, 'rb') as file:\n            reader = PyPDF2.PdfReader(file)\n            text = \"\"\n            for page_num in range(len(reader.pages)):\n                text += reader.pages[page_num].extract_text()\n            return text\n\n    @classmethod\n    def read_markdown(cls, file_path: str):\n        # 读取Markdown文件\n        with open(file_path, 'r', encoding='utf-8') as file:\n            md_text = file.read()\n            html_text = markdown.markdown(md_text)\n            # 使用BeautifulSoup从HTML中提取纯文本\n            soup = BeautifulSoup(html_text, 'html.parser')\n            plain_text = soup.get_text()\n            # 使用正则表达式移除网址链接\n            text = re.sub(r'http\\S+', '', plain_text) \n            return text\n\n    @classmethod\n    def read_text(cls, file_path: str):\n        # 读取文本文件\n        with open(file_path, 'r', encoding='utf-8') as file:\n            return file.read()\n\n\nclass Documents:\n    \"\"\"\n        获取已分好类的json格式文档\n    \"\"\"\n    def __init__(self, path: str = '') -> None:\n        self.path = path\n    \n    def get_content(self):\n        with open(self.path, mode='r', encoding='utf-8') as f:\n            content = json.load(f)\n        return content\n",[278],{"type":18,"tag":279,"props":280,"children":281},"code",{"__ignoreMap":7},[282],{"type":24,"value":276},{"type":18,"tag":26,"props":284,"children":285},{},[286],{"type":24,"value":287},"接下来我们实现一个Embedding类",{"type":18,"tag":274,"props":289,"children":291},{"code":290},"import os\nfrom copy import copy\nfrom typing import Dict, List, Optional, Tuple, Union\nimport numpy as np\n\n\nclass BaseEmbeddings:\n    \"\"\"\n    Base class for embeddings\n    \"\"\"\n\n    def __init__(self, path: str, is_api: bool) -> None:\n        self.path = path\n        self.is_api = is_api\n\n    def get_embedding(self, text: str, model: str) -> List[float]:\n        raise NotImplementedError\n\n    @classmethod\n    def cosine_similarity(cls, vector1: List[float], vector2: List[float]) -> float:\n        \"\"\"\n        calculate cosine similarity between two vectors\n        \"\"\"\n        dot_product = np.dot(vector1, vector2)\n        magnitude = np.linalg.norm(vector1) * np.linalg.norm(vector2)\n        if not magnitude:\n            return 0\n        return dot_product / magnitude\n\n# 使用MindNLP的SentenceTransformer实现\nclass MindNLPEmbedding(BaseEmbeddings):\n    \"\"\"\n    class for MindNLP embeddings\n    \"\"\"\n    def __init__(self, path: str = 'BAAI/bge-base-zh-v1.5', is_api: bool = False) -> None:\n        super().__init__(path, is_api)\n        self._model = self.load_model(path)\n\n    def get_embedding(self, text: str):\n        sentence_embedding = self._model.encode([text], normalize_embeddings=True)\n        return sentence_embedding\n\n    def load_model(self, path: str):\n        from mindnlp.sentence import SentenceTransformer\n        model = SentenceTransformer(path)\n        return model\n\n    @classmethod\n    def cosine_similarity(cls, sentence_embedding_1, sentence_embedding_2):\n        \"\"\"\n        calculate cosine similarity between two vectors\n        \"\"\"\n        similarity = sentence_embedding_1 @ sentence_embedding_2.T\n        return similarity\n",[292],{"type":18,"tag":279,"props":293,"children":294},{"__ignoreMap":7},[295],{"type":24,"value":290},{"type":18,"tag":26,"props":297,"children":298},{},[299],{"type":24,"value":300},"接着实现一个LLM类用于接收不同的模型进行生成：",{"type":18,"tag":274,"props":302,"children":304},{"code":303},"import os\nfrom typing import Dict, List, Optional, Tuple, Union\n\nPROMPT_TEMPLATE = dict(\n    RAG_PROMPT_TEMPALTE=\"\"\"使用以上下文来回答用户的问题。如果你不知道答案，请输出我不知道。总是使用中文回答。\n        问题: {question}\n        可参考的上下文：\n        ···\n        {context}\n        ···\n        如果给定的上下文无法让你做出回答，请回答数据库中没有这个内容，你不知道。\n        有用的回答:\"\"\",\n    MindNLP_PROMPT_TEMPALTE=\"\"\"先对上下文进行内容总结,再使用上下文来回答用户的问题。如果你不知道答案，请输出我不知道。总是使用中文回答。\n        问题: {question}\n        可参考的上下文：\n        ···\n        {context}\n        ···\n        如果给定的上下文无法让你做出回答，请回答数据库中没有这个内容，你不知道。\n        有用的回答:\"\"\"\n)\n\n\nclass BaseModel:\n    def __init__(self, path: str = '') -> None:\n        self.path = path\n\n    def chat(self, prompt: str, history: List[dict], content: str) -> str:\n        pass\n\n    def load_model(self):\n        pass\n\n\nclass OpenAIChat(BaseModel):\n    def __init__(self, path: str = '', model: str = \"gpt-3.5-turbo-1106\") -> None:\n        super().__init__(path)\n        self.model = model\n\n    def chat(self, prompt: str, history: List[dict], content: str) -> str:\n        from openai import OpenAI\n        client = OpenAI()\n        client.api_key = os.getenv(\"OPENAI_API_KEY\")\n        client.base_url = os.getenv(\"OPENAI_BASE_URL\")\n        history.append({'role': 'user',\n                        'content': PROMPT_TEMPLATE['RAG_PROMPT_TEMPALTE'].format(question=prompt, context=content)})\n        response = client.chat.completions.create(\n            model=self.model,\n            messages=history,\n            max_tokens=150,\n            temperature=0.1\n        )\n        return response.choices[0].message.content\n\n\nclass MindNLPChat(BaseModel):\n    def __init__(self, path: str = '') -> None:\n        super().__init__(path)\n        self.load_model()\n\n    def chat(self, prompt: str, history: List = [], content: str = '') -> str:\n        prompt = PROMPT_TEMPLATE['MindNLP_PROMPT_TEMPALTE'].format(question=prompt, context=content)\n        response, history = self.model.chat(self.tokenizer, prompt, history, max_length=512)\n        return response\n\n    def load_model(self):\n        import mindspore\n        from mindnlp.transformers import AutoTokenizer, AutoModelForCausalLM\n        self.tokenizer = AutoTokenizer.from_pretrained(self.path, mirror=\"huggingface\")\n        self.model = AutoModelForCausalLM.from_pretrained(self.path, ms_dtype=mindspore.float16, mirror=\"huggingface\")\n",[305],{"type":18,"tag":279,"props":306,"children":307},{"__ignoreMap":7},[308],{"type":24,"value":303},{"type":18,"tag":26,"props":310,"children":311},{},[312],{"type":24,"value":313},"最后实现一个简单的知识库：",{"type":18,"tag":274,"props":315,"children":317},{"code":316},"import os\nfrom typing import Dict, List, Optional, Tuple, Union\nimport json\nimport numpy as np\nfrom tqdm import tqdm\nfrom RAG.Embeddings import BaseEmbeddings, MindNLPEmbedding\n\n\n# MindNLP的SentenceTransformer实现\nclass VectorStore:\n    def __init__(self, document: List[str] = ['']) -> None:\n        self.document = document\n\n    def get_vector(self, EmbeddingModel: BaseEmbeddings):\n        self.vectors = []\n        for doc in tqdm(self.document, desc=\"Calculating embeddings\"):\n            self.vectors.append(EmbeddingModel.get_embedding(doc))\n        return self.vectors\n\n    def persist(self, path: str = 'storage'):\n        if not os.path.exists(path):\n            os.makedirs(path)\n        with open(f\"{path}/document.json\", 'w', encoding='utf-8') as f:\n            json.dump(self.document, f, ensure_ascii=False)\n        if self.vectors:\n            # 将 numpy.ndarray 转换为列表\n            vectors_list = [vector.tolist() for vector in self.vectors]\n            with open(f\"{path}/vectors.json\", 'w', encoding='utf-8') as f:\n                json.dump(vectors_list, f)\n\n    def load_vector(self, EmbeddingModel: BaseEmbeddings, path: str = 'storage'):\n        with open(f\"{path}/vectors.json\", 'r', encoding='utf-8') as f:\n            vectors_list = json.load(f)\n        with open(f\"{path}/document.json\", 'r', encoding='utf-8') as f:\n            self.document = json.load(f)\n\n        # 查询 EmbeddingModel 的类别\n        if isinstance(EmbeddingModel, MindNLPEmbedding):\n            # 将列表重新变为 numpy.ndarray\n            self.vectors = [np.array(vector) for vector in vectors_list]\n        else:\n            self.vectors = vectors_list\n\n    def get_similarity(self, vector1, vector2, EmbeddingModel: BaseEmbeddings):\n        return EmbeddingModel.cosine_similarity(vector1, vector2)\n\n    def query(self, query: str, EmbeddingModel: BaseEmbeddings, k: int = 1):\n        # 获取查询字符串的嵌入向量\n        query_vector = EmbeddingModel.get_embedding(query)\n\n        # 计算查询向量与数据库中每个向量的相似度\n        similarities = [self.get_similarity(query_vector, vector, EmbeddingModel) for vector in self.vectors]\n\n        # 将相似度、向量和文档存储在一个列表中\n        results = []\n        for similarity, vector, document in zip(similarities, self.vectors, self.document):\n            results.append({\n                'similarity': similarity,\n                'vector': vector,\n                'document': document\n            })\n        # 按相似度从高到低排序\n        results.sort(key=lambda x: x['similarity'], reverse=True)\n        # 获取最相似的 k 个文档\n        top_k_documents = [result['document'] for result in results[:k]]\n\n        return top_k_documents\n",[318],{"type":18,"tag":279,"props":319,"children":320},{"__ignoreMap":7},[321],{"type":24,"value":316},{"type":18,"tag":26,"props":323,"children":324},{},[325],{"type":24,"value":326},"完成上述代码的编写，我们就可以使用这个框架了：",{"type":18,"tag":26,"props":328,"children":329},{},[330],{"type":24,"value":331},"导入对应包",{"type":18,"tag":274,"props":333,"children":335},{"code":334},"from RAG.VectorBase import VectorStore\nfrom RAG.utils import ReadFiles\nfrom RAG.LLM import MindNLPChat\nfrom RAG.Embeddings import MindNLPEmbedding\nfrom RAG.Reranker import MindNLPReranker\n",[336],{"type":18,"tag":279,"props":337,"children":338},{"__ignoreMap":7},[339],{"type":24,"value":334},{"type":18,"tag":26,"props":341,"children":342},{},[343],{"type":24,"value":344},"建立知识库",{"type":18,"tag":274,"props":346,"children":348},{"code":347},"docs = ReadFiles('./data').get_content(max_token_len=600, cover_content=150)  # 获得data目录下的所有文件内容并分割\nvector = VectorStore(docs)\nembedding = MindNLPEmbedding(\"BAAI/bge-base-zh-v1.5\")  # 创建EmbeddingModel\nvector.get_vector(EmbeddingModel=embedding)\nvector.persist(path='storage')  # 将向量和文档内容保存到storage目录下，下次再用就可以直接加载本地的数据库\n",[349],{"type":18,"tag":279,"props":350,"children":351},{"__ignoreMap":7},[352],{"type":24,"value":347},{"type":18,"tag":26,"props":354,"children":355},{},[356],{"type":24,"value":357},"读取知识库并完成RAG",{"type":18,"tag":274,"props":359,"children":361},{"code":360},"vector = VectorStore()\nembedding = MindNLPEmbedding(\"BAAI/bge-base-zh-v1.5\") # 创建EmbeddingModel\nvector.load_vector(EmbeddingModel=embedding, path='./storage')  # 加载本地的数据库\nquestion = 'git如何新建分支？'\ncontent = vector.query(question, EmbeddingModel=embedding, k=1)[0]\nprint(content)\nchat = MindNLPChat(path='openbmb/MiniCPM-2B-dpo-bf16')\nprint(chat.chat(question, [], content))\n",[362],{"type":18,"tag":279,"props":363,"children":364},{"__ignoreMap":7},[365],{"type":24,"value":360},{"type":18,"tag":26,"props":367,"children":368},{},[369],{"type":24,"value":370},"我们也可以实现一个简单的Reranker来增强RAG的能力",{"type":18,"tag":274,"props":372,"children":374},{"code":373},"from typing import List\nimport numpy as np\n\n\nclass BaseReranker:\n    \"\"\"\n    Base class for reranker\n    \"\"\"\n\n    def __init__(self, path: str) -> None:\n        self.path = path\n\n    def rerank(self, text: str, content: List[str], k: int) -> List[str]:\n        raise NotImplementedError\n\n\nclass MindNLPReranker(BaseReranker):\n    \"\"\"\n    class for MindNLP reranker\n    \"\"\"\n\n    def __init__(self, path: str = 'BAAI/bge-reranker-base') -> None:\n        super().__init__(path)\n        self._model= self.load_model(path)\n\n    def rerank(self, text: str, content: List[str], k: int) -> List[str]:\n        query_embedding = self._model.encode(text, normalize_embeddings=True)\n        sentences_embedding = self._model.encode(sentences=content, normalize_embeddings=True)\n        similarity = query_embedding @ sentences_embedding.T\n        # 获取按相似度排序后的索引\n        ranked_indices = np.argsort(similarity)[::-1]  # 按相似度降序排序\n        # 选择前 k 个最相关的候选内容\n        top_k_sentences = [content[i] for i in ranked_indices[:k]]\n        return top_k_sentences\n\n    def load_model(self, path: str):\n        from mindnlp.sentence import SentenceTransformer\n        model = SentenceTransformer(path)\n        return model\n",[375],{"type":18,"tag":279,"props":376,"children":377},{"__ignoreMap":7},[378],{"type":24,"value":373},{"type":18,"tag":26,"props":380,"children":381},{},[382],{"type":24,"value":383},"使用Reranker",{"type":18,"tag":274,"props":385,"children":387},{"code":386},"embedding = MindNLPEmbedding(\"BAAI/bge-base-zh-v1.5\") # 创建EmbeddingModel\n\n# 创建RerankerModel\nreranker = MindNLPReranker('BAAI/bge-reranker-base')\n\nif have_created_db:\n    # 保存数据库之后\n    vector = VectorStore()\n    vector.load_vector(EmbeddingModel=embedding, path='./storage')  # 加载本地的数据库\nelse:\n    # 没有保存数据库\n    docs = ReadFiles('./data').get_content(max_token_len=600, cover_content=150)  # 获得data目录下的所有文件内容并分割\n    vector = VectorStore(docs)\n    vector.get_vector(EmbeddingModel=embedding)\n    vector.persist(path='storage')  # 将向量和文档内容保存到storage目录下，下次再用就可以直接加载本地的数据库\n\nquestion = '远程仓库的协作与贡献有哪些？'\n\n# 从向量数据库中查询出最相似的3个文档\ncontent = vector.query(question, EmbeddingModel=embedding, k=3)\nprint(content)\n# 从一阶段查询结果中用Reranker再次筛选出最相似的2个文档\nrerank_content = reranker.rerank(question, content, k=2)\nprint(rerank_content)\n# 最后选择最相似的文档, 交给LLM作为可参考上下文\nbest_content = rerank_content[0]\nchat = MindNLPChat(path='openbmb/MiniCPM-2B-dpo-bf16')\nprint(chat.chat(question, [], best_content))\n",[388],{"type":18,"tag":279,"props":389,"children":390},{"__ignoreMap":7},[391],{"type":24,"value":386},{"title":7,"searchDepth":393,"depth":393,"links":394},4,[395,397],{"id":7,"depth":396,"text":7},2,{"id":198,"depth":396,"text":7},"markdown","content:technology-blogs:zh:3589.md","content","technology-blogs/zh/3589.md","technology-blogs/zh/3589","md",1776506131693]