第 11 期:变量聚合与模板转换节点
Variable Aggregator(变量聚合器)
将多个并行分支的输出合并成一个结构。
graph TB
subgraph "并行分支"
B1[搜索结果] --> |text| Agg
B2[知识库结果] --> |text| Agg
B3[数据库结果] --> |text| Agg
end
Agg[Variable Aggregator] --> LLM[LLM: 综合分析]聚合器会将同名变量收集为数组,下游可以直接引用:
# 引用聚合后的变量
{{#aggregator.text#}}
# 输出: ["搜索结果内容", "知识库结果内容", "数据库结果内容"]
Template Transform(模板转换)
基于 Jinja2 语法的强大文本格式化引擎。
基础语法
{# 变量插值 #}
用户名: {{ username }}
{# 条件判断 #}
{% if score > 0.8 %}
评价: 优秀
{% elif score > 0.6 %}
评价: 良好
{% else %}
评价: 需改进
{% endif %}
{# 循环 #}
{% for item in items %}
- {{ item.title }}: {{ item.score }}分
{% endfor %}
实例:生成结构化报告
# {{ report_title }}
生成时间: {{ timestamp }}
分析师: AI Assistant
## 摘要
{{ summary }}
## 详细分析
{% for section in sections %}
### {{ loop.index }}. {{ section.heading }}
{{ section.content }}
{% if section.code %}
```{{ section.language }}
{{ section.code }}
{% endif %}
{% endfor %}
数据统计
| 指标 | 值 |
|---|---|
| {% for k, v in metrics.items() %} | |
| {{ k }} | {{ v }} |
| {% endfor %} |
本报告由 Dify Workflow 自动生成
### 实例:格式化 API 响应
```jinja2
{% set data = api_response | fromjson %}
共找到 {{ data.total }} 条结果:
{% for item in data.results[:5] %}
{{ loop.index }}. **{{ item.name }}**
- 评分: {{ "%.1f" | format(item.rating) }}/5.0
- 价格: ¥{{ item.price }}
{% if item.in_stock %}✅ 有货{% else %}❌ 缺货{% endif %}
{% endfor %}
组合使用的完整案例
graph TB
Start[输入: 产品列表JSON] --> Code[Code: 解析JSON]
Code --> Iterator[Iterator: 遍历每件产品]
subgraph "Iterator 内部"
LLM[LLM: 生成产品描述]
HTTP[HTTP: 查询库存API]
end
Iterator --> Agg[Aggregator: 汇总所有结果]
Agg --> Template[Template: 格式化为营销邮件]
Template --> End[End]