[{"data":1,"prerenderedAt":421},["ShallowReactive",2],{"content-query-PChd5oD99T":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":415,"_id":416,"_source":417,"_file":418,"_stem":419,"_extension":420},"/technology-blogs/zh/3714","zh",false,"","基于MindSpore和DeepSeek打造Agent+RAG问答系统","作者：马泽森   单位：东南大学研一","2025-05-06","https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/05/09/109b924e27404ceeb33eac376744dbc6.png","technology-blogs","开发者分享",{"type":15,"children":16,"toc":412},"root",[17,25,31,36,41,50,58,63,68,73,83,91,99,107,112,117,122,127,132,137,142,147,159,164,172,180,188,196,204,212,220,228,236,241,246,251,259,267,275,283,291,299,307,312,320,328,336,341,346,351,356,364,372,380,388,396,404],{"type":18,"tag":19,"props":20,"children":22},"element","h1",{"id":21},"基于mindspore和deepseek打造agentrag问答系统",[23],{"type":24,"value":8},"text",{"type":18,"tag":26,"props":27,"children":28},"p",{},[29],{"type":24,"value":30},"作者：马泽森",{"type":18,"tag":26,"props":32,"children":33},{},[34],{"type":24,"value":35},"单位：东南大学研一",{"type":18,"tag":26,"props":37,"children":38},{},[39],{"type":24,"value":40},"基于MindSpore和DeepSeek打造Agent+RAG问答系统项目的核心在于将 DeepSeek 应用于实际场景，具体而言，通过处理和解析 MindSpore 的设计概览 PDF 文档，构建一个智能问答系统。这不仅展示了大语言模型在专业领域文档理解和信息提取方面的能力，也为开发者提供了一个范例，说明如何将预训练模型与特定领域知识相结合，构建高效的问答系统。本文将通过实践步骤，教会你如何搭建一个Agent+RAG问答系统。",{"type":18,"tag":26,"props":42,"children":43},{},[44],{"type":18,"tag":45,"props":46,"children":47},"strong",{},[48],{"type":24,"value":49},"# 01",{"type":18,"tag":26,"props":51,"children":52},{},[53],{"type":18,"tag":45,"props":54,"children":55},{},[56],{"type":24,"value":57},"安装依赖包",{"type":18,"tag":26,"props":59,"children":60},{},[61],{"type":24,"value":62},"MindSpore NLP是一个基于MindSpore深度学习框架开发的开源自然语言处理(NLP)库。它为解决各种NLP任务提供了一个强大的平台,包含了许多常用的NLP方法和模型。MindSpore NLP的目标是帮助研究人员和开发者更方便快捷地构建和训练NLP模型。",{"type":18,"tag":26,"props":64,"children":65},{},[66],{"type":24,"value":67},"本项目主要基于MindSpore NLP和MindSpore进行开发。",{"type":18,"tag":26,"props":69,"children":70},{},[71],{"type":24,"value":72},"安装依赖库：",{"type":18,"tag":74,"props":75,"children":77},"pre",{"code":76},"\npip install pymupdf sentence-transformers faiss-cpu mindspore mindnlp newspaper3k lxml[html_clean]\n",[78],{"type":18,"tag":79,"props":80,"children":81},"code",{"__ignoreMap":7},[82],{"type":24,"value":76},{"type":18,"tag":26,"props":84,"children":85},{},[86],{"type":18,"tag":45,"props":87,"children":88},{},[89],{"type":24,"value":90},"# 02",{"type":18,"tag":26,"props":92,"children":93},{},[94],{"type":18,"tag":45,"props":95,"children":96},{},[97],{"type":24,"value":98},"RAG——加载 PDF 文档",{"type":18,"tag":26,"props":100,"children":101},{},[102],{"type":18,"tag":45,"props":103,"children":104},{},[105],{"type":24,"value":106},"RAG介绍",{"type":18,"tag":26,"props":108,"children":109},{},[110],{"type":24,"value":111},"大语言模型在智能交互、语言理解等方面都展现出了强大能力，然而在实际业务场景中，通用的基础语言大模型往往难以满足特定的业务需求。",{"type":18,"tag":26,"props":113,"children":114},{},[115],{"type":24,"value":116},"大模型的知识来源受限于其训练数据，目前主流的大模型，如ChatGPT、文心一言、通义千问等，其训练集主要基于网络公开数据。意味着它们往往难以获取实时、非公开或离线数据中的知识，从而限制了模型在某些专业领域的应用。",{"type":18,"tag":26,"props":118,"children":119},{},[120],{"type":24,"value":121},"同时大模型可能面临幻觉问题，由于所有AI模型的底层原理都基于数学概率，大模型的输出实质上是一系列数值运算的结果。在某些情况下，这可能导致模型在不擅长的场景或缺乏相关知识时产生误导性的回答。这种幻觉问题的识别需要使用者具备相应领域的知识，从而限制了使用的效果。",{"type":18,"tag":26,"props":123,"children":124},{},[125],{"type":24,"value":126},"再者，数据安全性也是现代社会关注的焦点。在利用大模型处理企业数据时，数据泄露的风险不容忽视。因此，许多企业或者个人用户不愿将私域数据上传至第三方平台进行训练，这在一定程度上限制了通用大模型在实际业务中的应用。",{"type":18,"tag":26,"props":128,"children":129},{},[130],{"type":24,"value":131},"为了解决上述问题，检索增强生成（Retrieval Augmented Generation ，RAG）技术应运而生。",{"type":18,"tag":26,"props":133,"children":134},{},[135],{"type":24,"value":136},"RAG技术结合了信息检索与自然语言生成，通过从大量文档中检索相关信息来增强大模型的生成能力。在实际操作中，RAG系统会先依据用户的查询需求，在庞大的知识库中迅速定位并检索到高度相关的文档。随后，系统会精心提炼这些文档中的宝贵知识，将其巧妙地融入用户输入文本之中，一同传递给大模型。这一过程不仅为大模型提供了丰富的可参考背景知识，还大幅提升了生成内容的准确性和针对性。",{"type":18,"tag":26,"props":138,"children":139},{},[140],{"type":24,"value":141},"RAG的核心架构可以概括为“数据检索+智能生成”。在“数据检索”环节，依赖向量数据库技术，利用其高效的数据存储与检索机制，迅速锁定目标知识；而在“智能生成”阶段，则借助大模型和精细的提示工程技术，将检索到的知识精准利用，最终生成符合需求的答案。本课题中任务场景涉及的交通系统场景属于细分领域，基于RAG技术获取相关行业背景知识以及对大语言模型进行辅助，可以帮助大语言模型做出更合理的决策，辅助事故的分析与处理。",{"type":18,"tag":26,"props":143,"children":144},{},[145],{"type":24,"value":146},"文档链接：",{"type":18,"tag":26,"props":148,"children":149},{},[150],{"type":18,"tag":151,"props":152,"children":156},"a",{"href":153,"rel":154},"https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/white%5C_paper/MindSpore%5C_white%5C_paperV1.1.pdf",[155],"nofollow",[157],{"type":24,"value":158},"https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/white\\_paper/MindSpore\\_white\\_paperV1.1.pdf",{"type":18,"tag":26,"props":160,"children":161},{},[162],{"type":24,"value":163},"本项目使用的pdf文档下载链接如上，下载到同目录后改名为如：MindSpore_Design_Overview.pdf，与下方代码相同。",{"type":18,"tag":74,"props":165,"children":167},{"code":166},"\nimport fitz  # PyMuPDF \npdf_path = 'MindSpore_Design_Overview.pdf'  # 需提前下载该文档 \ndoc = fitz.open(pdf_path) \npdf_text = [page.get_text() for page in doc] \n",[168],{"type":18,"tag":79,"props":169,"children":170},{"__ignoreMap":7},[171],{"type":24,"value":166},{"type":18,"tag":26,"props":173,"children":174},{},[175],{"type":18,"tag":45,"props":176,"children":177},{},[178],{"type":24,"value":179},"# 03",{"type":18,"tag":26,"props":181,"children":182},{},[183],{"type":18,"tag":45,"props":184,"children":185},{},[186],{"type":24,"value":187},"清洗 PDF 文本",{"type":18,"tag":74,"props":189,"children":191},{"code":190},"\nimport pandas as pd \ndef clean_text(text): \n    return ' '.join(text.split()) \npdf_df = pd.DataFrame({ \n    'page': list(range(1, len(pdf_text)+1)), \n    'text': [clean_text(t) for t in pdf_text] \n}) \n",[192],{"type":18,"tag":79,"props":193,"children":194},{"__ignoreMap":7},[195],{"type":24,"value":190},{"type":18,"tag":26,"props":197,"children":198},{},[199],{"type":18,"tag":45,"props":200,"children":201},{},[202],{"type":24,"value":203},"# 04",{"type":18,"tag":26,"props":205,"children":206},{},[207],{"type":18,"tag":45,"props":208,"children":209},{},[210],{"type":24,"value":211},"切分为语义块",{"type":18,"tag":74,"props":213,"children":215},{"code":214},"chunks = [] \nfor _, row in pdf_df.iterrows(): \n    text = row['text'] \n    for i in range(0, len(text), 300): \n        chunk = text[i:i+300] \n        chunks.append(chunk) \n",[216],{"type":18,"tag":79,"props":217,"children":218},{"__ignoreMap":7},[219],{"type":24,"value":214},{"type":18,"tag":26,"props":221,"children":222},{},[223],{"type":18,"tag":45,"props":224,"children":225},{},[226],{"type":24,"value":227},"# 05",{"type":18,"tag":26,"props":229,"children":230},{},[231],{"type":18,"tag":45,"props":232,"children":233},{},[234],{"type":24,"value":235},"向量化并构建 FAISS 检索器",{"type":18,"tag":26,"props":237,"children":238},{},[239],{"type":24,"value":240},"由于一般情况下加载的文档字符较多，常常会达到千位万位的数量级，如果大语言模型直接处理整个文档，可能会在分析过长的文本时遇到困难，难以准确抓取苏姚的信息。为有效应对这一挑战，可以需要采取分割策略，将庞大的文档细化为若干小文本块。如此一来，在需要时，我们便可以灵活地调用相关文档片段，从而提升信息处理的准确性和效率。本课题中也将文档切成包含更小数量级的段落，并且每个段落间也有部分字符重叠，确保一个观点的相关背景信息不会因为切分被遗漏。",{"type":18,"tag":26,"props":242,"children":243},{},[244],{"type":24,"value":245},"向量化是一个将文本数据转化为向量矩阵的过程，将每个文本块的内容换成向量，并将这些向量存储在向量数据库中，从而实现索引，方便程序在运行时可以快速检索到相关那内容。向量化的模型众多，Openai的ChatGPT-Embedding、百度的ERNIE-Embedding V1以及北京智源人工智能研究院的BGE模型都是目前主流的开源转换模型。",{"type":18,"tag":26,"props":247,"children":248},{},[249],{"type":24,"value":250},"数据向量化后，构建索引并将其写入数据库的过程，简称为“数据入库”。在RAG场景下，有多种数据库可供选择，例如FAISS、Chromadb、Elasticsearch以及Milvus等。在选择适合的数据库时，应全面考虑业务的具体需求、硬件配置以及性能要求等诸多因素，以确保选出最适合的数据库方案。本项目采用较通用常见的FAISS数据库进行数据入库操作。",{"type":18,"tag":74,"props":252,"children":254},{"code":253},"\n# 建议下载到本地部署，比较快，可以从魔塔下载或者昇思平台 \n!git lfs install \n!git clone https://www.modelscope.cn/Ceceliachenen/paraphrase-multilingual-MiniLM-L12-v2.git \n",[255],{"type":18,"tag":79,"props":256,"children":257},{"__ignoreMap":7},[258],{"type":24,"value":253},{"type":18,"tag":74,"props":260,"children":262},{"code":261},"\nfrom sentence_transformers import SentenceTransformer \nimport faiss \nimport numpy as np \n \nembed_model = SentenceTransformer('./paraphrase-multilingual-MiniLM-L12-v2') \nchunk_embeddings = embed_model.encode(chunks) \n \nindex = faiss.IndexFlatL2(chunk_embeddings.shape[1]) \nindex.add(np.array(chunk_embeddings)) \n",[263],{"type":18,"tag":79,"props":264,"children":265},{"__ignoreMap":7},[266],{"type":24,"value":261},{"type":18,"tag":26,"props":268,"children":269},{},[270],{"type":18,"tag":45,"props":271,"children":272},{},[273],{"type":24,"value":274},"# 06",{"type":18,"tag":26,"props":276,"children":277},{},[278],{"type":18,"tag":45,"props":279,"children":280},{},[281],{"type":24,"value":282},"定义检索接口",{"type":18,"tag":74,"props":284,"children":286},{"code":285},"\ndef query_pdf(query, top_k=3): \n    q_vec = embed_model.encode([query]) \n    D, I = index.search(np.array(q_vec), top_k) \n    return [chunks[i] for i in I[0]] \n",[287],{"type":18,"tag":79,"props":288,"children":289},{"__ignoreMap":7},[290],{"type":24,"value":285},{"type":18,"tag":26,"props":292,"children":293},{},[294],{"type":18,"tag":45,"props":295,"children":296},{},[297],{"type":24,"value":298},"# 07",{"type":18,"tag":26,"props":300,"children":301},{},[302],{"type":18,"tag":45,"props":303,"children":304},{},[305],{"type":24,"value":306},"加载 DeepSeek 模型",{"type":18,"tag":26,"props":308,"children":309},{},[310],{"type":24,"value":311},"本项目使用小规模蒸馏模型，基于MindSpore框架和MindSpore NLP库开发安装具有便捷使用的优势。",{"type":18,"tag":74,"props":313,"children":315},{"code":314},"\nfrom mindnlp.transformers import AutoModelForCausalLM, AutoTokenizer \nimport mindspore as ms \n \ntokenizer = AutoTokenizer.from_pretrained('MindSpore-Lab/DeepSeek-R1-Distill-Qwen-7B', mirror='modelers', ms_dtype=ms.float16) \nmodel = AutoModelForCausalLM.from_pretrained('MindSpore-Lab/DeepSeek-R1-Distill-Qwen-7B', mirror='modelers', ms_dtype=ms.float16) \nmodel.set_train(False) \n \ndef qwen_generate(prompt): \n    messages = [{\"role\": \"user\", \"content\": prompt}] \n    text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) \n    inputs = tokenizer([text], return_tensors=\"ms\") \n    outputs = model.generate(**inputs, max_new_tokens=256) \n    output = [o[len(i):] for i, o in zip(inputs.input_ids, outputs)] \n    return tokenizer.batch_decode(output, skip_special_tokens=True)[0] \n",[316],{"type":18,"tag":79,"props":317,"children":318},{"__ignoreMap":7},[319],{"type":24,"value":314},{"type":18,"tag":26,"props":321,"children":322},{},[323],{"type":18,"tag":45,"props":324,"children":325},{},[326],{"type":24,"value":327},"# 08",{"type":18,"tag":26,"props":329,"children":330},{},[331],{"type":18,"tag":45,"props":332,"children":333},{},[334],{"type":24,"value":335},"集成工具：时间、翻译、网页摘要",{"type":18,"tag":26,"props":337,"children":338},{},[339],{"type":24,"value":340},"在人类历史的长河中，对工具的创造和使用无疑展现了我们的智慧与创新能力。自人类文明出现以来，工具一直是我们生存的本质所不可或缺的一部分。工具是人类能力的扩展，旨在提高人类活动的生产力、效率和解决问题的能力。随着工具的进步，我们可以轻松高效地完成日益复杂的任务，从而解放时间和资源，以追求更宏伟的目标。",{"type":18,"tag":26,"props":342,"children":343},{},[344],{"type":24,"value":345},"大语言模型拥有丰富的社会经验与基础知识，在理解和生成自然语言文本方面表现优异，但由于大模型预训练数据的滞后性以及私域数据的使用限制，再加上大语言模型存在的幻觉问题，有时基于RAG也很难满足所有需求，因此类似于人类发展，大模型也需要借助工具来与外部世界交互或者实现动态功能。",{"type":18,"tag":26,"props":347,"children":348},{},[349],{"type":24,"value":350},"借助工具，不仅可以打破传统静态文本处理的限制，使得模型能够根据实时数据和信息来生成更加准确和有用的输出，还能够与其他先进技术进行无缝集成，例如机器学习算法、图像处理或数据分析工具等，从而提供更加全面和深入的服务。总的来说，工具调用为大语言模型赋予了更强的交互性和实用性，使其能够成为真正意义上的智能助手，帮助人类解决各种复杂问题。",{"type":18,"tag":26,"props":352,"children":353},{},[354],{"type":24,"value":355},"因此，本项目也集成了一些基本工具供LLM调用，构建一个能执行任务的智能体，扩展性更强。",{"type":18,"tag":74,"props":357,"children":359},{"code":358},"\nfrom datetime import datetime \ndef get_time_info(query): \n    now = datetime.now() \n    if \"几点\" in query: \n        return f\"现在是 {now.strftime('%H:%M:%S')}\" \n    elif \"星期\" in query: \n        return f\"今天是星期{now.isoweekday()}\" \n    elif \"几号\" in query or \"日期\" in query: \n        return f\"今天是 {now.strftime('%Y-%m-%d')}\" \n    return \"我可以告诉你时间哦~\" \n \ndef translate(query): \n    if \"翻译\" in query: \n        target = \"英文\" if \"英文\" in query else \"中文\" \n        content = query.replace(\"翻译\", \"\").replace(\"成英文\", \"\").replace(\"成中文\", \"\") \n        return qwen_generate(f\"请将以下内容翻译成{target}：{content}\") \n    return \"翻译请求格式不清晰。\" \n \nfrom newspaper import Article \n \ndef summarize_web(url): \n    try: \n        article = Article(url, language='zh') \n        article.download() \n        article.parse() \n        return qwen_generate(\"请总结以下网页内容：\" + article.text[:2000]) \n    except Exception as e: \n        return f\"❌ 网页摘要失败：{e}\" \n",[360],{"type":18,"tag":79,"props":361,"children":362},{"__ignoreMap":7},[363],{"type":24,"value":358},{"type":18,"tag":26,"props":365,"children":366},{},[367],{"type":18,"tag":45,"props":368,"children":369},{},[370],{"type":24,"value":371},"# 09",{"type":18,"tag":26,"props":373,"children":374},{},[375],{"type":18,"tag":45,"props":376,"children":377},{},[378],{"type":24,"value":379},"Agent 路由控制器",{"type":18,"tag":74,"props":381,"children":383},{"code":382},"\nclass PDFAgent: \n    def answer(self, query): \n        if any(k in query for k in [\"计算\", \"+\", \"-\", \"*\", \"/\"]): \n            return qwen_generate(f\"请计算：{query}\") \n        elif any(k in query for k in [\"几点\", \"星期\", \"几号\"]): \n            return get_time_info(query) \n        elif \"翻译\" in query: \n            return translate(query) \n        elif query.startswith(\"http\"): \n            return summarize_web(query) \n        else: \n            retrieved = \"\\n\".join(query_pdf(query)) \n            return qwen_generate(f\"以下是相关资料：{retrieved}\\n请回答：{query}\") \n \nagent = PDFAgent() \n",[384],{"type":18,"tag":79,"props":385,"children":386},{"__ignoreMap":7},[387],{"type":24,"value":382},{"type":18,"tag":26,"props":389,"children":390},{},[391],{"type":18,"tag":45,"props":392,"children":393},{},[394],{"type":24,"value":395},"# 10",{"type":18,"tag":26,"props":397,"children":398},{},[399],{"type":18,"tag":45,"props":400,"children":401},{},[402],{"type":24,"value":403},"测试示例",{"type":18,"tag":74,"props":405,"children":407},{"code":406},"以下分别是RAG的测试示例以及简单工具调用的示例 \nprint(agent.answer(\"什么是MindSpore？\")) \nprint(agent.answer(\"现在几点？\")) \nprint(agent.answer(\"翻译成英文：你好，我是AI助手\")) \n",[408],{"type":18,"tag":79,"props":409,"children":410},{"__ignoreMap":7},[411],{"type":24,"value":406},{"title":7,"searchDepth":413,"depth":413,"links":414},4,[],"markdown","content:technology-blogs:zh:3714.md","content","technology-blogs/zh/3714.md","technology-blogs/zh/3714","md",1776506133998]