返回顶部
热门问答 更多热门问答
技术文章 更多技术文章

Python Milvus Langchain 大语言模型实现智能问答系统

[复制链接]
链载Ai 显示全部楼层 发表于 半小时前 |阅读模式 打印 上一主题 下一主题

今天基于RAG(检索增强生成)架构带大家实现一个智能问答系统。在项目中我们会结合向量数据库、大语言模型和网页内容检索技术,构建一个能够基于网页(或企业私有知识库)内容进行智能问答的端到端解决方案。基于这个方案可以实现传统的搜索引擎无法理解用户意图、无法准确提供上下文回答的核心问题。

一、技术栈分析

在本系统中我们使用了这些核心技术:

    ingFang SC", Cambria, Cochin, Georgia, Times, "Times New Roman", serif;font-size: 16px;font-style: normal;font-variant-ligatures: normal;font-variant-caps: normal;font-weight: 400;letter-spacing: normal;orphans: 2;text-align: justify;text-indent: 0px;text-transform: none;widows: 2;word-spacing: 0px;-webkit-text-stroke-width: 0px;white-space: normal;background-color: rgb(255, 255, 255);text-decoration-thickness: initial;text-decoration-style: initial;text-decoration-color: initial;" class="list-paddingleft-1">
  • 后端框架
    FastAPI - Python异步Web框架
  • 向量数据库
    Milvus - 专业的向量相似性搜索引擎
  • 嵌入模型
    gte-large-zh中文嵌入模型
  • 大语言模型
    Llama-2-13B
  • 文档处理
    LangChain - 文档分割和处理框架
  • 网页解析
    BeautifulSoup - HTML内容提取
  • 容器化
    Docker Compose - 服务编排和部署

二、项目架构剖析

2.1 架构模式

采用微服务架构思想,通过Docker Compose编排了完整的服务栈,这种架构是云原生应用的最佳实践,实现了服务的松耦合和高可用性:
  • etcd: 分布式键值存储,用于Milvus集群元数据管理

  • minio: 对象存储服务,存储向量数据和索引文件

  • milvus-standalone: 向量数据库主服务

  • attu: Milvus的Web管理界面

2.2 架构模式

2.2.1 数据索引阶段

网站URL→网页抓取→HTML解析→文本分割→向量化→存储到Milvus

2.2.2 数据检索阶段

用户查询→向量化→相似性搜索→知识库检索→LLM生成答案

2.3 多索引器设计模式

为了不局限一种向量数据库,我们采用了策略模式支持多向量数据库,增强系统的扩展性:

    ingFang SC", Cambria, Cochin, Georgia, Times, "Times New Roman", serif;font-size: 16px;font-style: normal;font-variant-ligatures: normal;font-variant-caps: normal;font-weight: 400;letter-spacing: normal;orphans: 2;text-align: justify;text-indent: 0px;text-transform: none;widows: 2;word-spacing: 0px;-webkit-text-stroke-width: 0px;white-space: normal;background-color: rgb(255, 255, 255);text-decoration-thickness: initial;text-decoration-style: initial;text-decoration-color: initial;" class="list-paddingleft-1">
  • MilvusIndexer
    专门针对Milvus优化的索引器
  • ElasticIndexer
    支持Elasticsearch的索引器
  • Indexer
    通用索引器基类
fmt="\n==={:30}===\n"search_latency_fmt="searchlatency={:.4f}s"num_entities,dim=8,8milvus_collection_name="ai_answer"classSearchEngine:def__init__(self):connections.connect("default",host="localhost",port="19530")has=utility.has_collection(milvus_collection_name)print(f"Doescollectionmilvus_collection_nameexistinMilvus:{has}")milvus_client=Collection(milvus_collection_name)self.milvus_client=milvus_clientself.milvus_collection_name=milvus_collection_nameopenai.api_key=os.environ["OPENAI_API_KEY"]defquery_milvus(self,embedding):result=self.milvus_client.search([embedding],"vector",{"metric_type":"L2","offset":1},1,None,None,["id","vector","path","text"])list_of_knowledge_base=list(map(lambdamatch:match.entity.text,result[0]))return{'list_of_knowledge_base':list_of_knowledge_base,}defquery_vector_db(self,embedding):returnself.query_milvus(embedding)

三、核心业务逻辑解析

3.1 智能索引

#indexer_by_milvus.pydefadd_html_to_vectordb(self,content,path):text_splitter=RecursiveCharacterTextSplitter(chunk_size=self.MODEL_CHUNK_SIZE,#8192chunk_overlap=math.floor(self.MODEL_CHUNK_SIZE/10)#819)docs=text_splitter.create_documents([content])fordocindocs:embedding=create_embedding(doc.page_content)self.insert_embedding(embedding,doc.page_content,path)definsert_embedding(self,embedding,text,path):try:print(fmt.format("Startinsertingentities"))data=[{"vector":np.array(embedding),"text":text,"path":path},]self.milvus_client.insert(data)exceptExceptionase:print("self.milvus_client.insertexceptione:",e)os._exit(1)

ingFang SC", Cambria, Cochin, Georgia, Times, "Times New Roman", serif;font-style: normal;font-variant-ligatures: normal;font-variant-caps: normal;letter-spacing: normal;orphans: 2;text-align: justify;text-indent: 0px;text-transform: none;widows: 2;word-spacing: 0px;-webkit-text-stroke-width: 0px;white-space: normal;background-color: rgb(255, 255, 255);text-decoration-thickness: initial;text-decoration-style: initial;text-decoration-color: initial;">一些最佳实践说明:

    ingFang SC", Cambria, Cochin, Georgia, Times, "Times New Roman", serif;font-size: 16px;font-style: normal;font-variant-ligatures: normal;font-variant-caps: normal;font-weight: 400;letter-spacing: normal;orphans: 2;text-align: justify;text-indent: 0px;text-transform: none;widows: 2;word-spacing: 0px;-webkit-text-stroke-width: 0px;white-space: normal;background-color: rgb(255, 255, 255);text-decoration-thickness: initial;text-decoration-style: initial;text-decoration-color: initial;" class="list-paddingleft-1">
  • 智能分块策略
    8192字符的分块大小配合10%重叠的设计(819字符重叠),确保重要信息不会在分块边界丢失,既保证了模型处理效率,又维护了上下文的连贯性
  • 语义保持优化
    使用递归字符分割器,按照自然的文本边界(句子、段落)进行分割,
    在8192字符的分块过程中,如何保持语义完整性是一个关键
    挑战:硬切分可能破坏句子和段落的完整性,使用LangChain框架的RecursiveCharacterTextSplitter,按照句子、段落等语义单位进行智能分割
  • 批处理设计
    每个文档片段独立处理,支持大文档的流式处理
  • 数据类型转换
    将Python列表转换为NumPy数组,提高向量计算效率

3.2 向量检索

# search_engine.pydefsearch(self, user_query): print("user_query: ", user_query)
embedding = create_embedding(user_query) result = self.query_vector_db(embedding)
knowledge_base ="\n".join(result['list_of_knowledge_base']) response = self.ask_chatgpt(knowledge_base, user_query)
return{ 'response': response }
defask_chatgpt(self, knowledge_base, user_query): system_content ="""你是一个专业的智能问答助手,请严格遵循以下规则: 1. 只能基于提供的知识库内容回答问题,不得使用知识库以外的信息; 2. 如果知识库中没有相关信息或无法找到准确答案,请明确告知用户"我无法在知识库中找到相关信息来回答这个问题"; 3. 回答时要客观准确,不得编造或推测信息; 4. 尽量使用知识库中的原始表述,确保信息的准确性和权威性。 """
user_content =f""" Knowledge Base! --- {knowledge_base} --- User Query:{user_query} Answer:{user_history_answer} """
system_message = {"role":"system","content": system_content} user_message = {"role":"user","content": user_content}
chatgpt_response = create_llama2_13b(messages=[system_message, user_message]) returnchatgpt_response["choices"][0]["message"]["content"]

一些最佳实践说明:

    ingFang SC", Cambria, Cochin, Georgia, Times, "Times New Roman", serif;font-size: 16px;font-style: normal;font-variant-ligatures: normal;font-variant-caps: normal;font-weight: 400;letter-spacing: normal;orphans: 2;text-align: justify;text-indent: 0px;text-transform: none;widows: 2;word-spacing: 0px;-webkit-text-stroke-width: 0px;white-space: normal;background-color: rgb(255, 255, 255);text-decoration-thickness: initial;text-decoration-style: initial;text-decoration-color: initial;" class="list-paddingleft-1">
  • 完整的RAG工作流
    检索(Retrieval)→ 增强(Augmentation)→ 生成(Generation)的标准流程
  • 防幻觉设计
    明确的系统提示词限制模型只基于知识库回答,避免模型一本正经的胡说八道
  • 上下文构建
    通过结构化的prompt模板,清晰地分离知识库内容和用户查询
  • 错误边界处理
    当知识库中没有相关信息时,明确告知用户"不知道答案"

四、解决的行业难题

4.1 知识库实时问题

传统的FAQ系统和知识库更新困难,本项目通过动态数据爬取和索引,解决了知识库内容实时性问题。我们可以通过简单地更新内容来自动更新知识库。

4.2 语义理解准确性

相比传统的关键词匹配搜索,本项目通过向量语义搜索,能够理解用户查询的真实意图,提供更准确的答案。这对于客服系统、技术文档查询等场景具有重要价值。

4.3 多语言知识处理

项目使用的阿里达摩院gte-large-zh模型专门针对中文优化,解决了中文语义理解的难题。

写在最后

本项目中我们成功地将复杂的AI技术栈整合为一个易于部署和维护的系统,为企业构建智能问答应用提供了完整的技术方案。
本项目架构设计前瞻、工程实践规范,为AI应用的产业化提供了有价值的参考。通过解决知识检索的实时性、准确性和可扩展性问题,为企业AI化转型提供了有力的技术支撑。

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

链载AI是专业的生成式人工智能教程平台。提供Stable Diffusion、Midjourney AI绘画教程,Suno AI音乐生成指南,以及Runway、Pika等AI视频制作与动画生成实战案例。从提示词编写到参数调整,手把手助您从入门到精通。
  • 官方手机版

  • 微信公众号

  • 商务合作

  • Powered by Discuz! X3.5 | Copyright © 2025-2025. | 链载Ai
  • 桂ICP备2024021734号 | 营业执照 | |广西笔趣文化传媒有限公司|| QQ