跳转到主内容

5 篇带有 "Tutorials" 标签的文章

查看所有标签

RAGFlow 的无缝升级 - 从 0.21 到 0.22 及更高版本

阅读时长 3 分钟

背景

从 0.22.0 版本开始,RAGFlow 不再提供内置 Embedding 模型的完整 Docker 镜像。此前,部分用户依赖该镜像中捆绑的 Embedding 模型来构建数据集。

升级到 0.22.0 后,这些模型不再可用,导致了几个问题:数据集原先使用的 Embedding 模型丢失;无法添加新文档;数据集中的检索功能无法正常工作;并且由于旧的逻辑限制,无法切换到新的 Embedding 模型。为了解决升级后的这些兼容性问题,我们在 0.22.1 版本中引入了重要的改进。

0.22.1 版本功能

包含已解析数据的知识库现支持更换嵌入模型

从 RAGFlow 0.22.1 开始,引入了更安全、自动化的 Embedding 兼容性检查,允许用户在已有数据的数据集上切换 Embedding 模型。为确保新的 Embedding 模型不会破坏原有的向量空间结构,RAGFlow 会执行以下检查:

  1. 样本提取:从当前数据集中随机选择几个(例如 5-10 个)chunk 作为代表性样本。
  2. 重新编码:使用用户选择的新 Embedding 模型为抽样的 chunk 生成新向量。
  3. 相似度计算:对每个 chunk,计算新旧向量之间的余弦相似度。
  4. 切换决策:如果平均相似度达到 0.9 或以上,则认为新旧模型在向量空间上足够一致,允许切换。如果低于 0.9,则拒绝模型切换请求。

为何使用 0.9 阈值?

阈值设为 0.9,是因为来自不同模型提供商的同名模型可能存在微小的版本差异,并且 RAGFlow 的 Embedding 也会因策略和参数而异,因此新模型无法完美复现旧的 Embedding 环境。这些“微小差异”通常仍能得到 0.9 以上的平均相似度,所以 0.9 可以很好地作为“可安全替换”模型的临界值。相比之下,来自完全不同模型家族的 Embedding(例如,从 MiniLM 到 BGE-M3)的相似度往往在 0.3–0.6 之间,因此它们会低于此阈值并被正确阻止,从而防止向量空间被打乱。

如何更换嵌入模型

  1. 在模型设置界面配置一个新模型,以替换无法使用的默认模型。

  1. 进入数据集的配置页面,从新的提供商中选择相同的模型名称,并等待模型切换完成。

如果切换 Embedding 模型失败,将出现错误消息。

  1. 进入检索测试,自行评估新的 Embedding 模型。

现在,聊天应用中涉及数据集检索的功能等已能正常工作。

我们未来的版本将提供更完善的升级工具和自动化功能,简化从旧版本的迁移过程,并减轻用户的维护负担。

Google Drive 数据源指南

阅读时间 4 分钟

1. 创建 Google Cloud 项目

您可以为 RAGFlow 创建一个专用项目,也可以使用现有的 Google Cloud 外部项目。

步骤

  1. 打开项目创建页面
    https://console.cloud.google.com/projectcreate placeholder-image
  2. 在 Audience 中选择 External placeholder-image
  3. 点击 Create placeholder-image

  1. 前往 API 和服务 → OAuth 同意屏幕
  2. 确保 User Type = External placeholder-image
  3. 通过输入电子邮件地址,在 Test Users(测试用户)下添加您的测试用户 placeholder-image placeholder-image

3. 创建 OAuth 客户端凭据

  1. 导航至
    https://console.cloud.google.com/auth/clients
  2. 创建一个 Web Application placeholder-image
  3. 为客户端输入一个名称
  4. 添加以下 已获授权的重定向 URI
https://:9380/v1/connector/google-drive/oauth/web/callback

如果使用 Docker 部署:

已获授权的 JavaScript 来源

https://:80

placeholder-image

如果从源码运行:

已获授权的 JavaScript 来源

https://:9222

placeholder-image 5. 保存后,点击 Download JSON。该文件稍后将上传到 RAGFlow 中。

placeholder-image


4. 添加作用域(Scopes)

  1. 打开 数据访问 → 添加或移除范围

  2. 粘贴并添加以下条目

https://www.googleapis.com/auth/drive.readonly
https://www.googleapis.com/auth/drive.metadata.readonly
https://www.googleapis.com/auth/admin.directory.group.readonly
https://www.googleapis.com/auth/admin.directory.user.readonly

placeholder-image 3. 更新并保存更改

placeholder-image placeholder-image


5. 启用所需的 API

导航到 Google API 库
https://console.cloud.google.com/apis/library placeholder-image

启用以下 API

  • Google Drive API
  • Admin SDK API
  • Google Sheets API
  • Google Docs API

placeholder-image

placeholder-image

placeholder-image

placeholder-image

placeholder-image

placeholder-image


6. 在 RAGFlow 中添加 Google Drive 作为数据源

  1. 在 RAGFlow 中进入 数据源

  2. 选择 Google Drive

  3. 上传先前下载的 JSON 凭据 placeholder-image

  4. 输入共享的 Google Drive 文件夹链接 (https://drive.google.com/drive),例如: placeholder-image

  5. 点击 Authorize with Google(通过 Google 授权),将弹出一个浏览器窗口。placeholder-image 点击: - Continue(继续) - Select All → Continue(全选 → 继续) - 授权应成功 - 选择 OK 以添加数据源 placeholder-image placeholder-image placeholder-image placeholder-image

RAGFlow 实践 - 构建用于公司研究报告深度分析的 Agent

阅读时长 16 分钟

在金融机构投研部门的实际工作中,分析师每天都会接触海量的行业和公司分析报告、第三方研究数据以及实时市场动态,信息来源既多样又分散。金融分析师的工作是根据上述信息迅速制定清晰的投资建议,例如具体推荐购买哪些股票、如何调整投资组合配置,或预测行业的下一个走向。因此,我们开发了“智能投研助手”来帮助金融分析师快速整理信息。它可以自动抓取公司数据、整合财务指标并汇编研报观点,使分析师能够在几分钟内确定某只股票是否值得购买,无需在成堆的材料中筛选,从而让他们能够将时间集中在真正的投资决策上。为了实现这一目标,我们设计了一套完整的技术流程。

技术方案围绕一个核心业务流程展开

当分析师提出问题时,系统会从问题中识别公司名称或简称,并借助搜索引擎检索出相应的股票代码。如果识别失败,则直接返回公司代码的提示。成功获取股票代码后,系统从数据接口中调取该公司的核心财务指标,对数据进行整理和格式化,生成一张清晰的财务表格。在此基础上,智能分析进一步整合研报信息:一方面,它会采集最新的权威研报和市场观点;另一方面,它会从内部知识库中检索相关的研报内容。最终,这些整理好的财务数据和研报信息被组合成一份全面的回复,方便分析师快速审阅关键指标和核心观点。

编排后的工作流如下

本案例利用 RAGFlow 实现了一套完整的工作流程,从股票代码的提取,到公司财务报表的生成,再到最终研报信息的整合输出。

下文将详细介绍本方案的实现过程。

1. 准备数据集

1.1 创建数据集

本示例所需的数据集可以从 Hugging Face Datasets 下载1

创建一个名为“内部股票研究报告”的数据集,并导入相应的数据集文档。

1.2 解析文档

对于“内部股票研究报告”数据集中的文档,我们选择了名为 Paper 的解析和切片方法。

研究报告文档通常包括摘要、核心观点、专题分析、财务预测表和风险提示等模块。整体结构更遵循论文式的逻辑递进,而非严格的层级目录。如果根据最低级别的标题进行切片,很容易破坏段落和表格之间的连贯性。

因此,RAGFlow 更适合采用“Paper”切片方法,以章节或逻辑段落为基本单位。这种方法不仅保留了研究报告结构的完整性,还有助于模型在检索时快速定位关键信息。

切片后的财务报告预览如下

2. 构建智能代理

2.1 创建应用程序

创建成功后,系统将在画布上自动生成一个“开始”节点。

在“开始”节点中,您可以设置助手的初始问候语,例如:“您好!我是您的股票研究助理。”

2.2 构建“提取股票代码”功能

2.2.1 Agent 提取股票代码

使用一个 Agent 节点并附加一个 TavilySearch 工具,用于从用户的自然语言输入中识别股票名称或简称,并返回一个唯一的标准股票代码。当未找到匹配项时,统一输出“未找到”。

在金融场景中,用户的自然语言往往是模糊的。例如:

  • “帮我查一下苹果公司的研究报告。”
  • “英伟达的财务表现如何?”
  • “今天上证指数的情况怎么样?”

这些请求都包含与股票相关的信息,但系统只有在准确识别出股票代码后,才能进一步查询财务报告、研究报告或市场数据。

这就是为什么我们需要一个具有“提取股票代码”功能的 Agent。

以下是此 Agent 的系统提示词

<role> 

Your responsibility is: to identify and extract the stock name or abbreviation from the user's natural language query and return the corresponding unique stock code.

</role>



<rules>

1. Only one result is allowed: - If a stock is identified → return the corresponding stock code only; - If no stock is identified → return “Not Found” only.

2. **Do not** output any extra words, punctuation, explanations, prefixes, suffixes, or newline prompts. 3. The output must strictly follow the <response_format>. </rules>


<response_format>
Output only the stock code (e.g., AAPL or 600519)
Or output “Not Found”
</response_format>


<response_examples>
User input: “Please check the research report for Apple Inc.” → Output: AAPL
User input: “How is the financial performance of Moutai?” → Output: 600519
User input: “How is the Shanghai Composite Index performing today?” → Output: Not Found
</response_examples>


<tools> - Tavily Search: You may use this tool to query when you're uncertain about the stock code. - If you're confident, there's no need to use the tool.

</tools>



<Strict Output Requirements> - Only output the result, no explanations, prompts, or instructions allowed. - The output can only be the stock code or “Not Found,” otherwise, it will be considered an incorrect answer.

</Strict Output Requirements>

2.2.2 识别股票代码的条件节点

使用一个条件节点来评估前一个 Agent 节点的输出结果,并根据不同的结果引导流程走向

  • 如果输出是股票代码:表示成功识别了股票,流程将进入“Case1”分支。
  • 如果输出包含“未找到”:表示未从用户输入中识别出有效的股票名称,流程将进入“Else”分支,执行一个回复无关消息的节点,输出“您的查询不支持”。

2.3 构建“公司财务报表”功能

此功能的数据来源于雅虎财经提供的财务数据。通过调用此 API,我们获取指定股票的核心财务数据,包括营业收入、净利润等,从而驱动“公司财务报表”的生成。

2.3.1 Yahoo Finance 工具:请求财务数据

通过使用“雅虎财经工具”节点,选择“资产负债表”并将上游 Agent 输出的 stockCode 作为参数传递。这使您能够获取相应公司的核心财务指标。

返回的结果包含总资产、总权益和有形账面价值等关键数据,用于生成“公司财务报表”功能。

2.3.2 Code 节点生成财务表格

利用代码节点,通过 Python 脚本对雅虎财经工具返回的财务数据进行字段映射和数值格式化,最终生成一个带有双语指标对比的 Markdown 表格,从而实现“公司财务报表”的清晰直观展示。

代码

import re

def format_number(value: str) -> str:
"""Convert scientific notation or floating-point numbers to comma-separated numbers"""
try:
num = float(value)
if num.is_integer():
return f"{int(num):,}" # If it's an integer, format without decimal places
else:
return f"{num:,.2f}" # Otherwise, keep two decimal places and add commas
except:
return value # Return the original value if it's not a number (e.g., — or empty)

def extract_md_table_single_column(input_text: str) -> str:
# Use English indicators directly
indicators = [
"Total Assets", "Total Equity", "Tangible Book Value", "Total Debt",
"Net Debt", "Cash And Cash Equivalents", "Working Capital",
"Long Term Debt", "Common Stock Equity", "Ordinary Shares Number"
]

# Core indicators and their corresponding units
unit_map = {
"Total Assets": "USD",
"Total Equity": "USD",
"Tangible Book Value": "USD",
"Total Debt": "USD",
"Net Debt": "USD",
"Cash And Cash Equivalents": "USD",
"Working Capital": "USD",
"Long Term Debt": "USD",
"Common Stock Equity": "USD",
"Ordinary Shares Number": "Shares"
}

lines = input_text.splitlines()

# Automatically detect the date column, keeping only the first one
date_pattern = r"\d{4}-\d{2}-\d{2}"
header_line = ""
for line in lines:
if re.search(date_pattern, line):
header_line = line
break

if not header_line:
raise ValueError("Date column header row not found")

dates = re.findall(date_pattern, header_line)
first_date = dates[0] # Keep only the first date
header = f"| Indicator | {first_date} |"
divider = "|------------------------|------------|"

rows = []
for ind in indicators:
unit = unit_map.get(ind, "")
display_ind = f"{ind} ({unit})" if unit else ind

found = False
for line in lines:
if ind in line:
# Match numbers and possible units
pattern = r"(nan|[0-9\.]+(?:[eE][+-]?\d+)?)"
values = re.findall(pattern, line)
# Replace 'nan' with '—' and format the number
first_value = values[0].strip() if values and values[0].strip().lower() != "nan" else "—"
first_value = format_number(first_value) if first_value != "—" else "—"
rows.append(f"| {display_ind} | {first_value} |")
found = True
break
if not found:
rows.append(f"| {display_ind} | — |")

md_table = "\n".join([header, divider] + rows)
return md_table

def main(input_text: str):
return extract_md_table_single_column(input_text)

我们也收到了大家希望不通过编码提取 JSON 字段的请求,我们将在未来的版本中逐步提供解决方案。

2.4 构建“研报信息提取”功能

利用信息提取代理,根据 stockCode 调用 AlphaVantage API 提取最新的权威研究报告和见解。同时,它调用内部研究报告检索代理以获取完整研究报告的全文。最后,它以固定结构分别输出这两部分内容,从而实现高效的信息提取功能。

系统提示词

<role> 

You are the information extraction agent. You understand the user’s query and delegate tasks to alphavantage and the internal research report retrieval agent.

</role>

<requirements>

1. Based on the stock code output by the "Extract Stock Code" agent, call alphavantage's EARNINGS_CALL_TRANSCRIPT to retrieve the latest information that can be used in a research report, and store all publicly available key details.


2. Call the "Internal Research Report Retrieval Agent" and save the full text of the research report output.

3. Output the content retrieved from alphavantage and the Internal Research Report Retrieval Agent in full.

</requirements>


<report_structure_requirements>
The output must be divided into two sections:
#1. Title: “alphavantage”
Directly output the content collected from alphavantage without any additional processing.
#2. Title: "Internal Research Report Retrieval Agent"
Directly output the content provided by the Internal Research Report Retrieval Agent.
</report_structure_requirements>

2.4.1 配置 MCP 工具

添加 MCP 工具

在代理下添加 MCP 工具并选择所需的方法,例如“EARNINGS_CALL_TRANSCRIPT”。

2.4.2 内部研报检索 Agent

构建内部研究报告检索代理的关键在于准确识别用户查询中的公司或股票代码。然后,它调用检索工具从数据集中搜索研究报告并输出全文,确保数据、观点、结论、表格和风险提示等信息不被遗漏。这实现了研究报告内容的高保真提取。

系统提示词

<Task Objective> 

Read user input → Identify the involved company/stock (supports abbreviations, full names, codes, and aliases) → Retrieve the most relevant research reports from the dataset → Output the full text of the research report, retaining the original format, data, chart descriptions, and risk warnings.

</Task Objective>



<Execution Rules>

1. Exact Match: Prioritize exact matches of company full names and stock codes.

2. Content Fidelity: Fully retain the research report text stored in the dataset without deletion, modification, or omission of paragraphs.

3. Original Data: Retain table data, dates, units, etc., in their original form.

4. Complete Viewpoints: Include investment logic, financial analysis, industry comparisons, earnings forecasts, valuation methods, risk warnings, etc.

5. Merging Multiple Reports: If there are multiple relevant research reports, output them in reverse chronological order.

6. No Results Feedback: If no matching reports are found, output “No related research reports available in the dataset.”



</Execution Rules>

2.5 添加研报生成 Agent

研究报告生成代理自动提取并结构化组织财务和经济信息,为投资银行分析师生成专业、保留差异化且可直接用于投资研究报告的基础数据和内容。

<role> 

You are a senior investment banking (IB) analyst with years of experience in capital market research. You excel at writing investment research reports covering publicly listed companies, industries, and macroeconomics. You possess strong financial analysis skills and industry insights, combining quantitative and qualitative analysis to provide high-value references for investment decisions.

**You are able to retain and present differentiated viewpoints from various reports and sources in your research, and when discrepancies arise, you do not merge them into a single conclusion. Instead, you compare and analyze the differences.**


</role>




<input>

You will receive financial information extracted by the information extraction agent.

</input>


<core_task>
Based on the content returned by the information extraction agent (no fabrication of data), write a professional, complete, and structured investment research report. The report must be logically rigorous, clearly organized, and use professional language, suitable for reference by fund managers, institutional investors, and other professional readers.
When there are differences in analysis or forecasts between different reports or institutions, you must list and identify the sources in the report. You should not select only one viewpoint. You need to point out the differences, their possible causes, and their impact on investment judgments.
</core_task>


<report_structure_requirements>
##1. Summary
Provide a concise overview of the company’s core business, recent performance, industry positioning, and major investment highlights.
Summarize key conclusions in 3-5 sentences.
Highlight any discrepancies in core conclusions and briefly describe the differing viewpoints and areas of disagreement.
##2. Company Overview
Describe the company's main business, core products/services, market share, competitive advantages, and business model.
Highlight any differences in the description of the company’s market position or competitive advantages from different sources. Present and compare these differences.
##3. Recent Financial Performance
Summarize key metrics from the latest financial report (e.g., revenue, net profit, gross margin, EPS).
Highlight the drivers behind the trends and compare the differential analyses from different reports. Present this comparison in a table.
##4. Industry Trends & Opportunities
Overview of industry development trends, market size, and major drivers.
If different sources provide differing forecasts for industry growth rates, technological trends, or competitive landscape, list these and provide background information. Present this comparison in a table.
##5. Investment Recommendation
Provide a clear investment recommendation based on the analysis above (e.g., "Buy/Hold/Neutral/Sell"), presented in a table.
Include investment ratings or recommendations from all sources, with the source and date clearly noted.
If you provide a combined recommendation based on different viewpoints, clearly explain the reasoning behind this integration.
##6. Appendix & References
List the data sources, analysis methods, important formulas, or chart descriptions used.
All references must come from the information extraction agent and the company financial data table provided, or publicly noted sources.
For differentiated viewpoints, provide full citation information (author, institution, date) and present this in a table.
</report_structure_requirements>


<output_requirements>
Language Style: Financial, professional, precise, and analytical.
Viewpoint Retention: When there are multiple viewpoints and conclusions, all must be retained and compared. You cannot choose only one.
Citations: When specific data or viewpoints are referenced, include the source in parentheses (e.g., Source: Morgan Stanley Research, 2024-05-07).
Facts: All data and conclusions must come from the information extraction agent or their noted legitimate sources. No fabrication is allowed.
Readability: Use short paragraphs and bullet points to make it easy for professional readers to grasp key information and see the differences in viewpoints.
</output_requirements>


<output_goal>
Generate a complete investment research report that meets investment banking industry standards, which can be directly used for institutional investment internal reference, while faithfully retaining differentiated viewpoints from various reports and providing the corresponding analysis.
</output_goal>



<heading_format_requirements>
All section headings in the investment research report must be formatted as N. Section Title (e.g., 1. Summary, 2. Company Overview), where:
The heading number is followed by a period and the section title.
The entire heading (number, period, and title) is rendered in bold text (e.g., using <b> in HTML or equivalent bold formatting, without relying on Markdown ** syntax).
Do not use ##, **, or any other prefix before the heading number.
Apply this format consistently to all section headings (Summary, Company Overview, Recent Financial Performance, Industry Trends & Opportunities, Investment Recommendation, Appendix & References).
</heading_format_requirements>

2.6 添加回复消息节点

回复消息节点用于输出工作流程最终产出的“财务报表”和“研究报告内容”。

2.7 保存并测试

点击“保存”-“运行”- 并查看执行结果。整个过程大约需要 5 分钟才能运行。执行结果

日志:整个过程大约需要 5 分钟才能运行。

总结与展望

本案例研究使用 RAGFlow 构建了一个完整的股票研究报告工作流程,包含三个核心步骤

  1. 利用 Agent 节点从用户输入中提取股票代码。
  2. 通过雅虎财经工具和代码节点获取并格式化公司财务数据,以生成清晰的财务报表。
  3. 调用信息提取代理和内部研究报告检索代理,并使用研究报告生成代理分别输出最新的研究报告见解和完整研究报告的全文。

整个过程实现了从股票代码识别到财务和研究报告信息整合的自动化处理。

我们观察到几个可持续发展的方向:可以纳入更多的数据源,使分析结果更全面,同时提供一种无代码的数据处理方法以降低入门门槛。该系统还有潜力分析同一行业内的多家公司,跟踪行业趋势,甚至覆盖更广泛的投资工具,如期货和基金,从而协助分析师形成更优的投资组合。随着这些功能的逐步实现,智能投研助手不仅能帮助分析师更快地做出判断,还能建立一套高效、可复用的研究方法论,使团队能够持续产出高质量的分析成果。

教程 - 使用 RAGFlow 构建电商客服 Agent

阅读时间 7 分钟

目前,电商零售平台广泛使用智能客服系统来处理大量的用户咨询。然而,传统的智能客服往往难以满足用户日益复杂多样的需求。例如,客户在购买前可能需要详细比较不同型号产品的功能;由于丢失了说明书,他们可能无法使用某些功能;或者,对于家居产品,他们可能需要通过客服安排上门安装预约。

为了解决这些挑战,我们识别了几种常见的需求场景,包括产品型号功能差异查询、使用帮助请求以及上门安装服务预约。基于 RAGFlow 最近推出的 Agent 框架,本博客介绍了一种通过将工作流编排与大语言模型相结合,实现用户咨询自动识别和分支处理的方法。

工作流编排如下

Image

以下章节将详细解释该解决方案的实现过程。

1. 准备数据集

1.1 创建数据集

您可以从 Hugging Face Datasets 下载示例数据集。

创建“产品信息”和“用户指南”知识库,并上传相关的数据集文档。

1.2 解析文档

对于“产品信息”和“用户指南”知识库中的文档,我们选择使用手动分块。

Image

产品手册通常图文并茂,信息量大,结构复杂。仅仅依靠文本长度进行分割可能会破坏内容的完整性。RAGFlow 假定这类文档遵循层级结构,因此使用“最小标题”作为分割的基本单位,确保每段文本及其附图在单个块中保持完整。以下是用户手册分割后的预览

Image

2. 构建工作流

2.1 创建应用

成功创建后,系统将在画布上自动生成一个开始组件。

Image

在开始组件中,可以配置客服的开场问候语,例如

Hi! I'm your assistant. 

Image

2.2 添加分类(Categorize)组件

分类组件使用大语言模型(LLM)进行意图识别。它对用户输入进行分类,并根据类别的名称、描述和提供的示例,将其路由到适当的处理工作流。

Image

2.3 构建产品特性对比工作流

检索组件连接到“产品信息”知识库,以获取与用户查询相关的内容,然后将其传递给 Agent 组件以生成响应。

Image

添加一个名为“功能比较知识库”的检索组件,并将其链接到“产品信息”知识库。

Image

在检索组件后添加一个 Agent 组件,命名为“功能比较 Agent”,并按如下方式配置系统提示

## Role
You are a product specification comparison assistant.
## Goal
Help the user compare two or more products based on their features and specifications. Provide clear, accurate, and concise comparisons to assist the user in making an informed decision.
---
## Instructions
- Start by confirming the product models or options the user wants to compare.
- If the user has not specified the models, politely ask for them.
- Present the comparison in a structured way (e.g., bullet points or a table format if supported).
- Highlight key differences such as size, capacity, performance, energy efficiency, and price if available.
- Maintain a neutral and professional tone without suggesting unnecessary upselling.
---

配置用户提示

User's query is /(Begin Input) sys.query 

Schema is /(Feature Comparison Knowledge Base) formalized_content

配置完 Agent 组件后,结果如下

Image

2.4 构建产品用户指南工作流

检索组件查询“用户指南”知识库中与用户问题相关的内容,然后将结果传递给 Agent 组件以制定响应。

Image

添加一个名为“使用指南知识库”的检索组件,并将其链接到“用户指南”知识库。

Image

在检索组件后添加一个 Agent 组件,命名为“使用指南 Agent”,并按如下方式配置其系统提示

## Role
You are a product usage guide assistant.
## Goal
Provide clear, step-by-step instructions to help the user set up, operate, and maintain their product. Answer questions about functions, settings, and troubleshooting.
---
## Instructions
- If the user asks about setup, provide easy-to-follow installation or configuration steps.
- If the user asks about a feature, explain its purpose and how to activate it.
- For troubleshooting, suggest common solutions first, then guide through advanced checks if needed.
- Keep the response simple, clear, and actionable for a non-technical user.
---

编写用户提示

User's query is /(Begin Input) sys.query 

Schema is / (Usage Guide Knowledge Base) formalized_content

配置完 Agent 组件后,结果如下

Image

2.5 构建安装预约助手

Agent 与用户进行多轮对话,以收集三个关键信息:联系电话、安装时间和安装地址。创建一个名为“安装预约 Agent”的 Agent 组件,并按如下方式配置其系统提示

# Role
You are an Installation Booking Assistant.
## Goal
Collect the following three pieces of information from the user
1. Contact Number
2. Preferred Installation Time
3. Installation Address
Once all three are collected, confirm the information and inform the user that a technician will contact them later by phone.
## Instructions
1. **Check if all three details** (Contact Number, Preferred Installation Time, Installation Address) have been provided.
2. **If some details are missing**, acknowledge the ones provided and only ask for the missing information.
3. Do **not repeat** the full request once some details are already known.
4. Once all three details are collected, summarize and confirm them with the user.

编写用户提示

User's query is /(Begin Input) sys.query 

配置完 Agent 组件后,结果如下

Image

如果需要注册用户信息,可以在 Agent 组件后连接一个 HTTP 请求组件,将数据传输到 Google Sheets 或 Notion 等平台。开发者可以根据具体需求实现此功能;本博客文章不涉及实现细节。

Image

2.6 添加消息回复(Reply)组件

对于这三个工作流,使用单个消息组件来接收 Agent 组件的输出,然后向用户显示处理后的结果。

Image

2.7 保存并测试

点击保存 → 运行 → 查看执行结果。当询问产品型号和功能时,系统正确返回了比较结果

Image

当询问使用说明时,系统提供了准确的指导

Image

当预约安装时,系统收集并确认了所有必要信息

Image

小结

这个用例也可以使用基于 Agent 的工作流来实现,其优点是能灵活处理复杂问题。然而,由于 Agent 会主动进行规划和反思,它们通常会显著增加响应时间,导致客户体验下降。因此,这种方法不太适合像电商售后客服这样要求高响应性和任务相对直接的场景。对于涉及复杂问题的应用,我们之前分享过深度研究(Deep Research)多 Agent 框架。相关模板可在我们的模板库中找到。

Image

本文介绍的客服工作流是为电子商务设计的,但该领域还有更多适合工作流自动化的场景——例如用户评论分析和个性化邮件营销——本文并未涉及。通过遵循所提供的实践指南,您也可以轻松地将这种方法应用于其他客服环境。我们鼓励您使用 RAGFlow 构建此类应用。用大语言模型重塑客户服务,使支持超越了“机械式回应”,将能力从单纯的“检索与匹配”提升到“认知推理”。通过深度理解和实时知识生成,它提供了前所未有的“懂人话”的体验,从而重新定义了智能服务的上限,并将支持转变为企业的核心价值引擎。

教程 - 构建 SQL 助手工作流

阅读时间 7 分钟

工作流概览

本教程展示了如何创建一个 SQL 助手工作流,该工作流支持使用自然语言查询 SQL 数据库。市场营销人员和产品经理等非技术用户可以使用此工具独立查询业务数据,减少对数据分析师的依赖。它还可以作为学校和编程课程中 SQL 的教学辅助工具。完成的工作流操作如下

Image

数据库结构、字段描述和 SQL 示例作为知识库存储在 RAGFlow 中。当用户查询时,系统会从这些来源检索相关信息,并将其传递给一个 Agent,由该 Agent 生成 SQL 语句。然后,这些语句由一个 SQL 执行器组件执行,以返回查询结果。

操作步骤

1. 创建三个知识库

1.1 准备数据集文件

您可以从 Hugging Face Datasets 下载示例数据集。

以下是预定义的示例文件

  1. Schema.txt
CREATE TABLE `users` (
`id` INT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(50) NOT NULL,
`password` VARCHAR(50) NOT NULL,
`email` VARCHAR(100),
`mobile` VARCHAR(20),
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_username` (`username`),
UNIQUE KEY `uk_email` (`email`),
UNIQUE KEY `uk_mobile` (`mobile`)
);

...

注意:在定义 schema 字段时,避免使用下划线等特殊字符,因为它们可能导致 LLM 生成的 SQL 语句出错。 2. Question to SQL.csv

What are the names of all the Cities in Canada
SELECT geo_name, id FROM data_commons_public_data.cybersyn.geo_index WHERE iso_name ilike '%can%

What is average Fertility Rate measure of Canada in 2002 ?
SELECT variable_name, avg(value) as average_fertility_rate FROM data_commons_public_data.cybersyn.timeseries WHERE variable_name = 'Fertility Rate' and geo_id = 'country/CAN' and date >= '2002-01-01' and date < '2003-01-01' GROUP BY 1;

What 5 countries have the highest life expectancy ?
SELECT geo_name, value FROM data_commons_public_data.cybersyn.timeseries join data_commons_public_data.cybersyn.geo_index ON timeseries.geo_id = geo_index.id WHERE variable_name = 'Life Expectancy' and date = '2020-01-01' ORDER BY value desc limit 5;


...
  1. Database Description EN.txt
### Users Table (users)
The users table stores user information for the website or application. Below are the definitions of each column in this table:
- `id`: INTEGER, an auto-incrementing field that uniquely identifies each user (primary key). It automatically increases with every new user added, guaranteeing a distinct ID for every user.
- `username`: VARCHAR, stores the user’s login name; this value is typically the unique identifier used during authentication.
- `password`: VARCHAR, holds the user’s password; for security, the value must be encrypted (hashed) before persistence.
- `email`: VARCHAR, stores the user’s e-mail address; it can serve as an alternate login credential and is used for notifications or password-reset flows.
- `mobile`: VARCHAR, stores the user’s mobile phone number; it can be used for login, receiving SMS notifications, or identity verification.
- `create_time`: TIMESTAMP, records the timestamp when the user account was created; defaults to the current timestamp.
- `update_time`: TIMESTAMP, records the timestamp of the last update to the user’s information; automatically refreshed to the current timestamp on every update.

...

1.2 在 RAGFlow 中创建知识库

Schema 知识库

创建一个名为“Schema”的知识库,并上传 Schema.txt 文件。

数据库中的表长度各不相同,每个表都以分号(;)结尾。

CREATE TABLE `users` (
`id` INT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(50) NOT NULL,
`password` VARCHAR(50) NOT NULL,
...
UNIQUE KEY `uk_mobile` (`mobile`)
);

CREATE TABLE `products` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`description` TEXT,
`price` DECIMAL(10, 2) NOT NULL,
`stock` INT NOT NULL,
...
FOREIGN KEY (`merchant_id`) REFERENCES `merchants` (`id`)
);

CREATE TABLE `merchants` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`description` TEXT,
`email` VARCHAR(100),
...
UNIQUE KEY `uk_mobile` (`mobile`)
);

为了将每个表隔离为独立的块且内容不重叠,按如下方式配置知识库参数

  • 分块方法:通用
  • 块大小:2 个 token(隔离的最小尺寸)
  • 分隔符:分号 (;) RAGFlow 将根据此工作流解析并生成块

以下是 Schema.txt 解析结果的预览

我们现在通过检索测试来验证检索到的结果

Question to SQL 知识库

创建一个名为“Question to SQL”的新知识库,并上传“Question to SQL.csv”文件。

将分块方法设置为 Q&A,然后解析 Question_to_SQL.csv 以预览结果。

我们现在通过检索测试来验证检索到的结果

数据库描述知识库 创建一个名为“Database Description”的新知识库,并上传“Database_Description_EN.txt”文件。

配置(与 Schema 知识库相同)

  • 分块方法:通用
  • 块大小:2 个 token(隔离的最小尺寸)
  • 分隔符:分号 `###` 以下是配置后解析 Database_Description_EN.txt 的预览。

我们现在通过检索测试来验证检索到的结果

注意:这三个知识库是分开维护和查询的。Agent 组件在生成输出前会整合所有来源的结果。

2. 编排工作流

2.1 创建工作流应用

成功创建后,开始组件会自动出现在画布上。

您可以在开始组件中配置欢迎消息。例如

Hi! I'm your SQL assistant, what can I do for you?

2.2 配置三个检索(Retrieval)组件

在开始组件后添加三个并行的检索组件,命名如下

  • Schema
  • Question to SQL
  • Database Description 配置每个检索组件
  1. 查询变量:sys.query
  2. 知识库选择:选择名称与当前组件名称匹配的知识库。

2.3 配置 Agent 组件

在检索组件后添加一个名为“SQL 生成器”的 Agent 组件,并将所有三个检索组件连接到它。

编写系统提示

### ROLE
You are a Text-to-SQL assistant.
Given a relational database schema and a natural-language request, you must produce a **single, syntactically-correct MySQL query** that answers the request.
Return **nothing except the SQL statement itself**—no code fences, no commentary, no explanations, no comments, no trailing semicolon if not required.

### EXAMPLES
-- Example 1
User: List every product name and its unit price.
SQL:
SELECT name, unit_price FROM Products;

-- Example 2
User: Show the names and emails of customers who placed orders in January 2025.
SQL:
SELECT DISTINCT c.name, c.email
FROM Customers c
JOIN Orders o ON o.customer_id = c.id
WHERE o.order_date BETWEEN '2025-01-01' AND '2025-01-31';

-- Example 3
User: How many orders have a status of "Completed" for each month in 2024?
SQL:
SELECT DATE_FORMAT(order_date, '%Y-%m') AS month,
COUNT(*) AS completed_orders
FROM Orders
WHERE status = 'Completed'
AND YEAR(order_date) = 2024
GROUP BY month
ORDER BY month;

-- Example 4
User: Which products generated at least \$10 000 in total revenue?
SQL:
SELECT p.id, p.name, SUM(oi.quantity * oi.unit_price) AS revenue
FROM Products p
JOIN OrderItems oi ON oi.product_id = p.id
GROUP BY p.id, p.name
HAVING revenue >= 10000
ORDER BY revenue DESC;

### OUTPUT GUIDELINES
1. Think through the schema and the request.
2. Write **only** the final MySQL query.
3. Do **not** wrap the query in back-ticks or markdown fences.
4. Do **not** add explanations, comments, or additional text—just the SQL.

编写用户提示

User's query: /(Begin Input) sys.query  
Schema: /(Schema) formalized_content
Samples about question to SQL: /(Question to SQL) formalized_content
Description about meanings of tables and files: /(Database Description) formalized_content

插入变量后,填充的结果如下所示

2.4 配置 ExeSQL 组件

在 SQL 生成器后追加一个名为“SQL 执行器”的 ExeSQL 组件。

为 SQL 执行器组件配置数据库,指定其查询输入来自 SQL 生成器的输出。

2.5 配置消息(Message)组件

在 SQL 执行器后追加一个消息组件。

在“消息”字段中插入变量,使消息组件能够显示 SQL 执行器的输出(formalized_content)

2.6 保存并测试

点击保存 → 运行 → 输入一个自然语言问题 → 查看执行结果。

结语

最后,与目前的 Copilot 技术一样,NL2SQL 无法实现完全准确。对于结构化数据的标准化处理,我们建议将其操作整合到特定的 API 中,然后将这些 API 封装为 RAGFlow 的 MCP(托管内容包)。我们将在即将发布的博客中演示这种方法。

© . This site is unofficial and not affiliated with InfiniFlow.