一、整体流程步骤
1. 环境准备
安装依赖(参考引用[2]):
```bash
# 安装PostgreSQL
sudo apt-get install postgresql
# 修改配置文件
vim /etc/postgresql/16/main/postgresql.conf
```
2. 创建报表生成应用
在Dify控制台创建空白应用,类型选择文本生成或Agent模式。
3. Agent核心编排
- 提示词工程:
在`prompt`中定义报表结构,例如:
```python
"你是一个报表生成Agent,按以下步骤工作:
1. 从${database_tool}获取${date_range}的销售数据
2. 计算总销售额、同比增长率
3. 输出Markdown表格:
| 指标 | 值 |
|------------|----------|
| 总销售额 | ${total} |
| 同比增长 | ${rate}% |"
```
- 工具集成:
添加数据库查询工具(如SQL执行器)或API连接器。
4. 变量设置
定义动态参数:
```json
{
"date_range": "2024-Q2",
"metrics": ["sales", "profit"]
}
```
5. 测试与发布
通过测试界面验证输出,发布为API接口供系统调用。
二、关键源码解析
Dify生成报表的核心源码位于以下路径([GitHub仓库](https://github.com/langgenius/dify)):
1. Agent执行引擎
`api/core/agent/agent_runner.py`
```python
def run_agent(prompt: str, tools: list, variables: dict):
# 1. 解析提示词中的工具调用指令
tool_calls = parse_tool_calls(prompt)
# 2. 动态执行工具链(如数据库查询)
tool_results = execute_tools(tool_calls, variables)
# 3. 注入结果到LLM生成阶段
final_prompt = inject_results(prompt, tool_results)
# 4. 调用LLM生成结构化报表
report = llm_generate(final_prompt)
return format_report(report) # 转换为Markdown/HTML
```
2. 工具集成层
`api/core/tools/`目录下的工具实现类:
```python
# SQL执行器示例 (tools/sql_tool.py)
class SQLTool:
def execute(self, query: str, conn_params: dict):
with psycopg2.connect(**conn_params) as conn:
cursor = conn.cursor()
cursor.execute(query)
return cursor.fetchall() # 返回数据集
```
3. 输出格式化
`api/utils/report_formatter.py`的转换逻辑:
```python
def markdown_formatter(data: dict):
table = "| 指标 | 值 |\n|------|----|\n"
for k, v in data.items():
table += f"| {k} | {v} |\n"
return table
```
三、执行流程示意图
```mermaid
graph TD
A[用户请求] --> B{Agent引擎}
B --> C[解析工具调用]
C --> D[执行数据库查询]
D --> E[获取原始数据]
E --> F[LLM分析计算]
F --> G[生成结构化报表]
G --> H[格式转换]
H --> I[返回Markdown/HTML]
```
> 技术原理:Dify通过将工具调用、变量注入和LLM生成封装成标准化Pipeline,使开发者无需编写底层代码即可构建报表生成应用。
1776

被折叠的 条评论
为什么被折叠?



