5 分钟内搭建一个免费问答机器人:Milvus + LangChain

搭建一个好用、便宜又准确的问答机器人需要多长时间?

答案是 5 分钟。只需借助开源的 RAG 技术栈、LangChain 以及好用的向量数据库 Milvus。必须要强调的是,该问答机器人的成本很低,因为我们在召回、评估和开发迭代的过程中不需要调用大语言模型 API。只有在最后一步——生成最终问答结果的时候会调用到 1 次 API。

如有兴趣深入了解问答机器人背后的技术,可以查看 GitHub 上的源代码(https://github.com/zilliztech/akcio)。本文完整代码可通过 Bootcamp (https://github.com/milvus-io/bootcamp/blob/master/bootcamp/RAG/readthedocs_zilliz_langchain.ipynb)获取。

在正式开始前,我们先复习一下 RAG。RAG 的主要用途是为了给生成式 AI 输出的文本提供支撑。换言之,RAG 就是通过事实、自定义数据以减少 LLM 幻觉。具体而言,在 RAG 中,我们可以使用可靠可信的自定义数据文本,如产品文档,随后从向量数据库中检索相似结果。然后,将准确的文本答案作为“上下文”和“问题”一起插入到“Prompt”中,并将其输入到诸如 OpenAI 的 ChatGPT 之类的 LLM 中。最终,LLM 生成一个基于事实的聊天答案。

alt

RAG 的具体流程:

  1. 准备可信的自定义数据和一个 Embeding 模型。

  2. 用 Encoder 对数据进行分块并生成 Embedding 向量,将数据和元数据保存在向量数据库中。

  3. 用户提出一个问题。使用第 1 步中相同的 Encoder 将问题转化为 Embedding 向量。

  4. 用向量数据库进行语义搜索来检索问题的答案。

  5. 将搜索答案文本块作为“上下文”和用户问题结果,形成 Prompt。将 Prompt 发送给 LLM。

  6. LLM 生成答案。

01.获取数据

首先介绍一下本次搭建过程中会用到的工具:

Milvus 是一款开源高性能向量数据库,可简化非结构化数据搜索流程。Milvus 可存储、索引、搜索海量 Embedding 向量数据。

OpenAI 主要开发 AI 模型和工具,其最出名的产品为 GPT。

LangChain 工具和 wrapper 库能够帮助开发人员在传统软件和 LLM 中构建一座桥梁。

我们将用到产品文档页面,ReadTheDocs 是一款开源的免费文档软件,通过 Sphinx 生成文档。

Download readthedocs pages locally.
    DOCS_PAGE="https://pymilvus.readthedocs.io/en/latest/"
    wget -r -A.html -P rtdocs --header="Accept-Charset: UTF-8" $DOCS_PAGE

上述代码将文档页面下载到本地路径rtdocs中。接着,在 LangChain 中读取这些文档:

#!pip install langchain
from langchain.document_loaders import ReadTheDocsLoader
loader = ReadTheDocsLoader(
   "rtdocs/pymilvus.readthedocs.io/en/latest/",
   features="html.parser")
docs = loader.load()

02.使用 HTML 结构切分数据

需要确定分块策略、分块大小、分块重叠(chunk overlap)。本教程中,我们的配置如下所示:

  • 分块策略 = 根据 Markdown 标题结构切分。

  • 分块大小 = 使用 Embedding 模型参数 MAX_SEQ_LENGTH

  • Overlap = 10-15%

  • 函数 =

    Langchain HTMLHeaderTextSplitter 切分markdown 文件标题。

    Langchain RecursiveCharacterTextSplitter 将长文切分。

from langchain.text_splitter import HTMLHeaderTextSplitter, RecursiveCharacterTextSplitter
Define the headers to split on for the HTMLHeaderTextSplitter
headers_to_split_on = [
    ("h1", "Header 1"),
    ("h2", "Header 2"),]
Create an instance of the HTMLHeaderTextSplitter
html_splitter = HTMLHeaderTextSplitter(headers_to_split_on=headers_to_split_on)
Use the embedding model parameters.
chunk_size = MAX_SEQ_LENGTH - HF_EOS_TOKEN_LENGTH
chunk_overlap = np.round(chunk_size * 0.10, 0)
Create an instance of the RecursiveCharacterTextSplitter
child_splitter = RecursiveCharacterTextSplitter(
    chunk_size = chunk_size,
    chunk_overlap = chunk_overlap,
    length_function = len,)
Split the HTML text using the HTMLHeaderTextSplitter.
html_header_splits = []
for doc in docs:
    splits = html_splitter.split_text(doc.page_content)
    for split in splits:
        # Add the source URL and header values to the metadata
        metadata = {}
        new_text = split.page_content
        for header_name, metadata_header_name in headers_to_split_on:
            header_value = new_text.split("¶ ")[0].strip()
            metadata[header_name] = header_value
            try:
                new_text = new_text.split("¶ ")[1].strip()
            except:
                break
        split.metadata = {
            **metadata,
            "source": doc.metadata["source"]}
        # Add the header to the text
        split.page_content = split.page_content
    html_header_splits.extend(splits)
Split the documents further into smaller, recursive chunks.
chunks = child_splitter.split_documents(html_header_splits)
end_time = time.time()
print(f"chunking time: {end_time - start_time}")
print(f"docs: {len(docs)}, split into: {len(html_header_splits)}")
print(f"split into chunks: {len(chunks)}, type: list of {type(chunks[0])}") 
Inspect a chunk.
print()
print("Looking at a sample chunk...")
print(chunks[1].page_content[:100])
print(chunks[1].metadata)
alt

本段文本块都有文档作为支撑。此外,标题和文本块也保存在一起,标题可以后续使用。

03.生成 Embedding 向量

最新的 MTEB 性能测试结果显示,开源 Embedding/召回模型和 OpenAI Embeddings (ada-002)效果相似。下图中分数最高的小模型是bge-large-en-v1.5,本文将选择这个模型。

alt

上图为 Embedding 模型排名表,排名最高的是voyage-lite-01-instruct(size 4.2 GB, and third rankbge-base-en-v1.5(size 1.5 GB)OpenAIEmbeddingtext-embeddings-ada-002 排名第 22。

现在,我们来初始化模型;

#pip install torch, sentence-transformers
import torch
from sentence_transformers import SentenceTransformer
Initialize torch settings
DEVICE = torch.device('cuda:3' 
   if torch.cuda.is_available() 
   else 'cpu')
Load the encoder model from huggingface model hub.
model_name = "BAAI/bge-base-en-v1.5"
encoder = SentenceTransformer(model_name, device=DEVICE)
Get the model parameters and save for later.
MAX_SEQ_LENGTH = encoder.get_max_seq_length() 
EMBEDDING_LENGTH = encoder.get_sentence_embedding_dimension()

接着,使用模型生成 Embedding 向量,将所有数据整合成 dictionary。

chunk_list = []
for chunk in chunks:
    # Generate embeddings using encoder from HuggingFace.
    embeddings = torch.tensor(encoder.encode([chunk.page_content]))
    embeddings = F.normalize(embeddings, p=2, dim=1)
    converted_values = list(map(np.float32, embeddings))[0]
    # Assemble embedding vector, original text chunk, metadata.
    chunk_dict = {
        'vector': converted_values,
        'text': chunk.page_content,
        'source': chunk.metadata['source'],
        'h1': chunk.metadata['h1'][:50],
        'h2': chunk.metadata['h1'][:50],}
    chunk_list.append(chunk_dict)

04.在 Milvus 中创建索引并插入数据

我们将原始文本块以 vectortextsourceh1h2的形式存储在向量数据库中。

alt

启动并连接 Milvus 服务器。如需使用 serverless 集群,你需要在连接时提供ZILLIZ_API_KEY

#pip install pymilvus
from pymilvus import connections
ENDPOINT=”https://xxxx.api.region.zillizcloud.com:443”
connections.connect(
   uri=ENDPOINT,
   token=TOKEN)

创建 Milvus Collection 并命名为 MilvusDocs。Collection 类似于传统数据库中的表,其具备 Schema,定义字段和数据类型。Schema 中的向量维度应该与 Embedding 模型生成向量的维度保持一致。与此同时,创建索引:

from pymilvus import (
   FieldSchema, DataType, 
   CollectionSchema, Collection)
1. Define a minimum expandable schema.
fields = [
   FieldSchema(“pk”, DataType.INT64, is_primary=True, auto_id=True),
   FieldSchema(“vector”, DataType.FLOAT_VECTOR, dim=768),]
schema = CollectionSchema(
   fields,
   enable_dynamic_field=True,)
2. Create the collection.
mc = Collection(“MilvusDocs”, schema)
3. Index the collection.
mc.create_index(
   field_name=”vector”,
   index_params={
       “index_type”: “AUTOINDEX”,
       “metric_type”: “COSINE”,}

在 Milvus/Zilliz 中插入数据的速度比 Pinecone快!

Insert data into the Milvus collection.
insert_result = mc.insert(chunk_list)
After final entity is inserted, call flush
to stop growing segments left in memory.
mc.flush() 
print(mc.partitions)
alt

05.提出问题

接下来,我们就可以用语义搜索的力量来回答有关文档的问题。语义搜索在向量空间中使用最近邻技术来找到最匹配的文档,以回答用户的问题。语义搜索的目标是理解问题和文档背后的含义,而不仅仅是匹配关键词。在检索过程中,Milvus 还可以利用元数据来增强搜索体验(在 Milvus API 选项expr=中使用布尔表达式)。

Define a sample question about your data.
QUESTION = "what is the default distance metric used in AUTOINDEX?"
QUERY = [question]
Before conducting a search, load the data into memory.
mc.load()
Embed the question using the same encoder.
embedded_question = torch.tensor(encoder.encode([QUESTION]))
Normalize embeddings to unit length.
embedded_question = F.normalize(embedded_question, p=2, dim=1)
Convert the embeddings to list of list of np.float32.
embedded_question = list(map(np.float32, embedded_question))
Return top k results with AUTOINDEX.
TOP_K = 5
Run semantic vector search using your query and the vector database.
start_time = time.time()
results = mc.search(
    data=embedded_question, 
    anns_field="vector", 
    # No params for AUTOINDEX
    param={},
    # Boolean expression if any
    expr="",
    output_fields=["h1", "h2", "text", "source"], 
    limit=TOP_K,
    consistency_level="Eventually")
elapsed_time = time.time() - start_time
print(f"Milvus search time: {elapsed_time} sec")
alt

下面是检索结果,我们把这些文本放入 context 字段中:

for n, hits in enumerate(results):
     print(f"{n}th query result")
     for hit in hits:
         print(hit)
Assemble the context as a stuffed string.
context = ""
for r in results[0]:
    text = r.entity.text
    context += f"{text} "
Also save the context metadata to retrieve along with the answer.
context_metadata = {
    "h1": results[0][0].entity.h1,
    "h2": results[0][0].entity.h2,
    "source": results[0][0].entity.source,}
alt

上图显示,检索出了 5 个文本块。其中第一个文本块中包含了问题的答案。因为我们在检索时使用了output_fields=,所以检索返回的输出字段会带上引用和元数据。

id: 445766022949255988, distance: 0.708217978477478, entity: {
  'chunk': "...# Optional, default MetricType.L2 } timeout (float) –
           An optional duration of time in seconds to allow for the
           RPC. …",
  'source': 'https://pymilvus.readthedocs.io/en/latest/api.html',
  'h1': 'API reference',
  'h2': 'Client'}

06.使用 LLM 根据上下文生成用户问题的回答

这一步中,我们将使用一个小型生成式 AI 模型(LLM),该模型可通过 HuggingFace 获取。

#pip install transformers
from transformers import AutoTokenizer, pipeline
tiny_llm = "deepset/tinyroberta-squad2"
tokenizer = AutoTokenizer.from_pretrained(tiny_llm)
context cannot be empty so just put random text in it.
QA_input = {
    'question': question,
    'context': 'The quick brown fox jumped over the lazy dog'}
nlp = pipeline('question-answering', 
               model=tiny_llm, 
               tokenizer=tokenizer)
result = nlp(QA_input)
print(f"Question: {question}")
print(f"Answer: {result['answer']}")
alt

答案不是很准确,我们用召回的文本提出同样的问题试试看:

QA_input = {
    'question': question,
    'context': context,}
nlp = pipeline('question-answering', 
               model=tiny_llm, 
               tokenizer=tokenizer)
result = nlp(QA_input)
Print the question, answer, grounding sources and citations.
Answer = assemble_grounding_sources(result[‘answer’], context_metadata)
print(f"Question: {question}")
print(answer)
alt

答案准确多了!

接下来,我们用 OpenAI 的 GPT 试试,发现回答结果和我们自己搭建的开源机器人相同。

def prepare_response(response):
    return response["choices"][-1]["message"]["content"]
def generate_response(
    llm, 
    temperature=0.0, #0 for reproducible experiments
    grounding_sources=None,
    system_content="", assistant_content="", user_content=""):
    response = openai.ChatCompletion.create(
        model=llm,
        temperature=temperature,
        api_key=openai.api_key,
        messages=[
            {"role": "system", "content": system_content},
            {"role": "assistant", "content": assistant_content},
            {"role": "user", "content": user_content}, ])
        answer = prepare_response(response=response)
    
        # Add the grounding sources and citations.
        answer = assemble_grounding_sources(answer, grounding_sources)
        return answer
Generate response
response = generate_response(
    llm="gpt-3.5-turbo-1106",
    temperature=0.0,
    grounding_sources=context_metadata,
    system_content="Answer the question using the context provided. Be succinct.",
    user_content=f"question: {QUESTION}, context: {context}")
Print the question, answer, grounding sources and citations.
print(f"Question: {QUESTION}")
print(response)
alt

07.总结

本文完整展示了如何针对自定义文档搭建一个 RAG 聊天机器人。得益于 LangChain、Milvus 和开源的 LLM,我们轻而易举实现了对制定数据进行免费问答。在检索过程中,Milvus 提供了数据来源。我们搭建的聊天机器人是个低成本的问答机器人,因为在召回、评估和开发迭代的过程中不需要调用大语言模型 API。只有在最后一步——生成最终问答结果的时候会调用到 1 次 API。

本文由 mdnice 多平台发布

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/261809.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【接口测试】HTTP接口详细验证清单

概述 当我们在构建、测试、发布一套新的HTTP API时,包括我在内的大多数人都不知道他们所构建的每一个组件的复杂性和细微差别。 即使你对每一个组件都有深刻的理解,也可能会有太多的信息在你的脑海中出现。 以至于我们不可能一下把所有的信息进行梳理…

python如何更改代码背景图片,背景主题(黑色护眼)和各类文本颜色(python进阶必看,爱了爱了)

一、在 PyCharm 中设置图片背景的方法如下: 打开 PyCharm 的设置窗口,在设置窗口中找到 "Appearance & Behavior" -> "Appearance" 选项卡。在 "Appearance" 选项卡中,找到 "Background Image&qu…

Python学习之复习MySQL-Day8(事务)

目录 文章声明⭐⭐⭐让我们开始今天的学习吧!事务简介事务操作模拟转账操作开启事务提交事务回滚事务查看/设置事务提交方法实例演示 事务四大特性并发事务问题分类 事务隔离级别分类查看/设置事务隔离级别实例演示 文章声明⭐⭐⭐ 该文章为我(有编程语…

Mysql的SQL优化和锁

👏作者简介:大家好,我是爱吃芝士的土豆倪,24届校招生Java选手,很高兴认识大家📕系列专栏:Spring源码、JUC源码、Kafka原理、分布式技术原理、数据库技术🔥如果感觉博主的文章还不错的…

闫式Dp分析法(一种求解动态规划问题的思路)

最近一直跟着Acwing学习动态规划问题的求解思想,感觉晦涩的算法问题一旦经过闫式Dp分析法的剖析,瞬时迎刃而解,故今天我觉得很有必要再次分享一下闫式Dp分析法(在此默认你对DP问题有了一定的了解)。 闫式Dp分析法 闫式…

前端问题记录

jenkins安装vue依赖报错 jenkins 安装依赖,报错cannot find module ‘/root/.jenkins/workspace/项目路径/node_modules/xxxx’,如图上 解决:执行 npm install vue/cli-service --unsafe-perm,再执行npm i

你以为出现NoClassDefFoundError错误会是什么原因?

你以为出现NoClassDefFoundError错误会是什么原因? 1、概述2、事情经过3、总结 1、概述 大家好,我是欧阳方超,可以关注我的公众号“欧阳方超”,后续内容将在公众号首发。 同样的错误,非一样的解决方式。NoClassDefFou…

【sgDragUploadFolder】自定义组件:自定义拖拽文件夹上传组件,支持上传单个或多个文件/文件夹,右下角上传托盘出现(后续更新...)

特性&#xff1a; 支持在拖拽上传单个文件、多个文件、单个文件夹、多个文件夹可自定义headers可自定义过滤上传格式可自定义上传API接口支持显示/隐藏右下角上传队列托盘 sgDragUploadFolder源码 <template><div :class"$options.name" :dragenter"i…

使用Gitee中的CI/CD来完成代码的自动部署与发布(使用内网穿透把本地电脑当作服务器使用)

&#x1f4da;目录 &#x1f4da;简介:⚙️ 所需工具&#xff1a;&#x1f4a8;内网穿透配置&#x1f4ad;工具介绍✨命令安装&#x1f38a;配置Cpolar&#x1f573;️关闭防火墙&#x1f95b;防火墙端口放行规则&#xff08;关闭防火墙可以忽略&#xff09;&#x1f36c;小章总…

WCF服务总结

前言 WCF,全称为Windows Communication Foundation,是一种用于构建分布式应用程序的微软框架。它提供了一种统一的编程模型,用于构建服务导向的应用程序,这些应用程序可以在本地或远程计算机上运行。WCF 支持多种传输协议和编码格式,并提供了高级安全性、可靠性和事务处理…

微软在 Perforce Helix 核心服务器中发现4个安全漏洞

微软分析师在对Perforce Helix的游戏开发工作室产品进行安全审查时&#xff0c;发现为游戏、政府、军事和技术等部门广泛使用的源代码管理平台 Perforce Helix Core Server 存在四大漏洞&#xff0c;并于今年 8 月底向 Perforce 报告了这些漏洞&#xff0c;其中一个漏洞被评为严…

路径规划之RRT *算法

系列文章目录 路径规划之Dijkstra算法 路径规划之Best-First Search算法 路径规划之A *算法 路径规划之D *算法 路径规划之PRM算法 路径规划之RRT算法 路径规划之RRT *算法 路径规划之RRT*算法 系列文章目录前言一、RRT算法1.起源2.改进2.1 重新选择父节点2.2 重新布线 3.对比…

day44代码训练|动态规划part06

完全背包和01背包问题唯一不同的地方就是&#xff0c;每种物品有无限件。 1. dp数组的含义 dp[i][j] 0-i物品&#xff0c;重量为j的容量时&#xff0c;最大的价值 2. 递推公式 dp[i][j] max(dp[i-1][j],dp[i][j-weight[i]]value[i]); 两种状态&#xff0c;不用物品i的话&…

【数论】质数

试除法判断质数 分解质因数 一个数可以被分解为质因数乘积 n &#xff0c;其中的pi都是质因数 那么怎么求pi及其指数呢&#xff1f; 我们将i一直从2~n/i循环&#xff0c;如果 n%i0&#xff0c;那么i一定是质因数&#xff0c;并且用一个while循环将n除以i&#xff0c;一直到…

蛇梯棋[中等]

一、题目 给你一个大小为n x n的整数矩阵board&#xff0c;方格按从1到n2编号&#xff0c;编号遵循 转行交替方式 &#xff0c;从左下角开始 &#xff08;即&#xff0c;从board[n - 1][0]开始&#xff09;每一行交替方向。玩家从棋盘上的方格1&#xff08;总是在最后一行、第…

礼品企业网站搭建的作用是什么

礼品一般分为企业定制礼品和零售现成礼品&#xff0c;二者都有很强的市场需求度。同时对礼品企业而言&#xff0c;一般主要以批发为主&#xff0c;客户也主要是零售商或企业。 1、拓客难 不同于零售&#xff0c;即使没有引流&#xff0c;入驻商场或街边小摊也总会有自然客户。…

【C++篇】Vector容器 Vector嵌套容器

文章目录 &#x1f354;简述vector&#x1f384;vector存放内置数据类型⭐创建一个vector容器⭐向容器里面插入数据⭐通过迭代器访问容器里面的数据⭐遍历&#x1f388;第一种遍历方式&#x1f388;第二种遍历方式&#x1f388;第三种遍历方式 &#x1f384;vector存放自定义数…

揭秘 Go 中 Goroutines 轻量级并发

理解 Goroutines、它们的效率以及同步挑战 并发是现代软件开发的一个基本概念&#xff0c;使程序能够同时执行多个任务。在 Go 编程领域&#xff0c;理解 Goroutines 是至关重要的。本文将全面概述 Goroutines&#xff0c;它们的轻量级特性&#xff0c;如何使用 go 关键字创建…

FPGA模块——以太网(1)MDIO读写

FPGA模块——以太网MDIO读写 MDIO接口介绍MDIO接口代码&#xff08;1&#xff09;MDIO接口驱动代码&#xff08;2&#xff09;使用MDIO驱动的代码 MDIO接口介绍 MDIO是串行管理接口。MAC 和 PHY 芯片有一个配置接口&#xff0c;即 MDIO 接口&#xff0c;可以配置 PHY 芯片的工…

Ubuntu 常用命令之 ifconfig 命令用法介绍

&#x1f4d1;Linux/Ubuntu 常用命令归类整理 ifconfig 是一个用于配置和显示 Linux 内核中网络接口的系统管理命令。它用于配置&#xff0c;管理和查询 TCP/IP 网络接口参数。 ifconfig 命令的参数有很多&#xff0c;以下是一些常见的参数 up&#xff1a;激活指定的网络接口…
最新文章