创建向量 RAG 聊天机器人
本教程演示如何使用 Langflow 创建一个聊天机器人应用程序,该应用程序使用检索增强生成 (RAG) 将您的数据作为向量嵌入到向量数据库中,然后与数据聊天。
先决条件
创建向量 RAG flow
-
在 Langflow 中,点击 New Flow,然后选择 Vector Store RAG 模板。
关于 Vector Store RAG 模板
此模板有两个 flow。
工作区底部的 Load Data Flow 使用文件中的数据填充向量存储。 此数据用于响应提交给 Retriever Flow 的查询,后者位于工作区的顶部。
具体来说,Load Data Flow 从本地文件接收数据,将数据分割成块,在您的向量数据库 中加载和索引数据,然后为块计算嵌入。嵌入也与加载的数据一起存储。此 flow 只需要在您需要将数据加载到向量数据库中时运行。
Retriever Flow 接收聊天输入,为输入生成嵌入,然后使用多个组件将块重构为文本,并通过将新嵌入与存储的嵌入进行比较来查找相似数据,从而生成响应。
-
将您的 OpenAI API 密钥添加到两个 OpenAI Embeddings 组件中。
-
可选:将两个 Astra DB 向量存储组件替换为 Chrome DB 或您选择的其他向量存储组件。 本教程使用 Chroma DB。
Load Data Flow 应该包含 File、Split Text、Embedding Model、向量存储(如 Chroma DB)和 Chat Output 组件:
Retriever Flow 应该包含 Chat Input、Embedding Model、向量存储、Parser、Prompt、Language Model 和 Chat Output 组件:
flow 已准备就绪可以使用。 继续教程学习如何使用加载 flow 将数据加载到向量存储中,然后在聊天机器人应用程序中调用聊天 flow。
加载数据并生成嵌入
要加载数据并生成嵌入,您可以使用 Langflow UI 或 /v2/files
端点。
Langflow UI 选项更简单,但仅建议在创建 flow 的用户与将数据加载到数据库中的用户是同一用户的情况下使用。
在许多用户加载数据或您需要以编程方式加载数据的情况下,请使用 Langflow API 选项。
- Langflow UI
- Langflow API
- 在您的 RAG 聊天机器人 flow 中,点击 File component,然后点击 File。
- 选择您要上传的本地文件,然后点击 Open。 文件将加载到您的 Langflow 服务器。
- 要将数据加载到向量存储中,请点击向量存储组件,然后点击 Run component 以运行所选组件及其所有先前的依赖组件。
要以编程方式加载数据,请使用 /v2/files/
和 /v1/run/$FLOW_ID
端点。第一个端点将文件加载到您的 Langflow 服务器,然后返回上传的文件路径。第二个端点运行 Load Data Flow,引用上传的文件路径,对数据进行分块、嵌入并加载到向量存储中。
以下脚本演示了此过程。 如需帮助创建此脚本,请使用 Langflow File Upload Utility。
_37// Node 18+ example using global fetch, FormData, and Blob_37import fs from 'fs/promises';_37_37// 1. Prepare the form data with the file to upload_37const fileBuffer = await fs.readFile('FILE_NAME');_37const data = new FormData();_37data.append('file', new Blob([fileBuffer]), 'FILE_NAME');_37const headers = { 'x-api-key': 'LANGFLOW_API_KEY' };_37_37// 2. Upload the file to Langflow_37const uploadRes = await fetch('LANGFLOW_SERVER_ADDRESS/api/v2/files/', {_37 method: 'POST',_37 headers,_37 body: data_37});_37const uploadData = await uploadRes.json();_37const uploadedPath = uploadData.path;_37_37// 3. Call the Langflow run endpoint with the uploaded file path_37const payload = {_37 input_value: "Analyze this file",_37 output_type: "chat",_37 input_type: "text",_37 tweaks: {_37 'FILE_COMPONENT_NAME': {_37 path: uploadedPath_37 }_37 }_37};_37const runRes = await fetch('LANGFLOW_SERVER_ADDRESS/api/v1/run/FLOW_ID', {_37 method: 'POST',_37 headers: { 'Content-Type': 'application/json', 'x-api-key': 'LANGFLOW_API_KEY' },_37 body: JSON.stringify(payload)_37});_37const langflowData = await runRes.json();_37// Output only the message_37console.log(langflowData.outputs?.[0]?.outputs?.[0]?.results?.message?.data?.text);
当 flow 运行时,flow 会接收选定的文件,对数据进行分块,将数据加载到向量存储数据库中,然后为块生成嵌入,这些嵌入也存储在向量存储中。
您的数据库现在包含带有向量嵌入的数据,LLM 可以使用这些数据作为上下文来响应查询,如教程的下一节所示。
从 JavaScript 应用程序与您的 flow 聊天
要与向量数据库中的数据聊天,请创建一个以编程方式运行 Retriever Flow 的聊天机器人应用程序。
本教程使用 JavaScript 作为演示目的。
-
要构建聊天机器人,请收集以下信息:
LANGFLOW_SERVER_ADDRESS
:您的 Langflow 服务器域名。默认值是127.0.0.1:7860
。您可以从 flow 的 API access 面板 上的代码片段中获取此值。FLOW_ID
:您的 flow 的 UUID 或自定义端点名称。您可以从 flow 的 API access 面板 上的代码片段中获取此值。LANGFLOW_API_KEY
:有效的 Langflow API 密钥。要创建 API 密钥,请参阅 API keys。
-
将以下脚本复制到 JavaScript 文件中,然后用您在上一步中收集的信息替换占位符:
_49const readline = require('readline');_49const { LangflowClient } = require('@datastax/langflow-client');_49_49const API_KEY = 'LANGFLOW_API_KEY';_49const SERVER = 'LANGFLOW_SERVER_ADDRESS';_49const FLOW_ID = 'FLOW_ID';_49_49const rl = readline.createInterface({ input: process.stdin, output: process.stdout });_49_49// Initialize the Langflow client_49const client = new LangflowClient({_49baseUrl: SERVER,_49apiKey: API_KEY_49});_49_49async function sendMessage(message) {_49try {_49const response = await client.flow(FLOW_ID).run(message, {_49session_id: 'user_1'_49});_49_49// Use the convenience method to get the chat output text_49return response.chatOutputText() || 'No response';_49} catch (error) {_49return `Error: ${error.message}`;_49}_49}_49_49function chat() {_49console.log('🤖 Langflow RAG Chatbot (type "quit" to exit)\n');_49_49const ask = () => {_49rl.question('👤 You: ', async (input) => {_49if (['quit', 'exit', 'bye'].includes(input.trim().toLowerCase())) {_49console.log('👋 Goodbye!');_49rl.close();_49return;_49}_49_49const response = await sendMessage(input.trim());_49console.log(`🤖 Assistant: ${response}\n`);_49ask();_49});_49};_49_49ask();_49}_49_49chat();脚本创建一个 Node 应用程序,该应用程序与向量数据库中的内容聊天,使用
chat
输入和输出类型与您的 flow 通信。 聊天在多条消息中维护持续的对话上下文。如果您使用text
类型的输入和输出,每个请求都是一个独立的文本字符串。提示Langflow TypeScript 客户端 有一个
chatOutputText()
便利方法,可简化处理 Langflow 复杂 JSON 响应结构的工作。 该客户端不需要手动导航通过多层嵌套对象data.outputs[0].outputs[0].results.message.data.text
,而是自动提取消息文本并优雅地处理可能未定义的值。 -
保存并运行脚本以发送请求并测试 flow。
结果
以下是本教程 flow 的示例响应。由于 LLM 的性质和您输入的变化,您的响应可能会有所不同。
_10👤 You: Do you have any documents about engines?_10🤖 Assistant: Yes, the provided text contains several warnings and guidelines related to engine installation, maintenance, and selection. It emphasizes the importance of using the correct engine for specific applications, ensuring all components are in good condition, and following safety precautions to prevent fire or explosion. If you need more specific information or details, please let me know!_10_10👤 You: It should be about a Briggs and Stratton engine._10🤖 Assistant: The text provides important safety and installation guidelines for Briggs & Stratton engines. It emphasizes that these engines should not be used on 3-wheel All-Terrain Vehicles (ATVs), motor bikes, aircraft products, or vehicles intended for competitive events, as such uses are not approved by Briggs & Stratton._10_10If you have any specific questions about Briggs & Stratton engines or need further information, feel free to ask!
下一步
有关构建或扩展本教程的更多信息,请参阅以下内容: