今天基于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">二、项目架构剖析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">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">检索(Retrieval)→ 增强(Augmentation)→ 生成(Generation)的标准流程明确的系统提示词限制模型只基于知识库回答,避免模型一本正经的胡说八道通过结构化的prompt模板,清晰地分离知识库内容和用户查询当知识库中没有相关信息时,明确告知用户"不知道答案"四、解决的行业难题4.1 知识库实时问题传统的FAQ系统和知识库更新困难,本项目通过动态数据爬取和索引,解决了知识库内容实时性问题。我们可以通过简单地更新内容来自动更新知识库。4.2 语义理解准确性相比传统的关键词匹配搜索,本项目通过向量语义搜索,能够理解用户查询的真实意图,提供更准确的答案。这对于客服系统、技术文档查询等场景具有重要价值。4.3 多语言知识处理项目使用的阿里达摩院gte-large-zh模型专门针对中文优化,解决了中文语义理解的难题。写在最后本项目中我们成功地将复杂的AI技术栈整合为一个易于部署和维护的系统,为企业构建智能问答应用提供了完整的技术方案。本项目架构设计前瞻、工程实践规范,为AI应用的产业化提供了有价值的参考。通过解决知识检索的实时性、准确性和可扩展性问题,为企业AI化转型提供了有力的技术支撑。 |