第 10 期:HTTP 请求节点与外部 API 集成
[Translation Pending]\n\n## HTTP 请求节点的威力
HTTP 节点让 Workflow 能够与整个互联网交互:查天气、调支付、发邮件、存数据库。
graph LR
LLM[LLM 提取参数] --> HTTP[HTTP 请求节点]
HTTP --> Parse[Code 解析响应]
Parse --> LLM2[LLM 总结结果]
HTTP -.-> ExtAPI[外部 REST API]配置详解
GET 请求:查询天气
# 节点配置
Method: GET
URL: https://api.openweathermap.org/data/2.5/weather
Query Parameters:
q: "{{#start.city#}}"
appid: "{{#env.WEATHER_API_KEY#}}"
units: metric
lang: zh_cn
Headers:
Accept: application/json
Timeout: 10
POST 请求:调用 Slack Webhook
Method: POST
URL: https://hooks.slack.com/services/T00/B00/xxx
Headers:
Content-Type: application/json
Body (JSON):
text: "{{#llm_1.text#}}"
channel: "#ai-notifications"
带 Bearer Token 鉴权
Method: GET
URL: https://api.github.com/repos/langgenius/dify
Headers:
Authorization: "Bearer {{#env.GITHUB_TOKEN#}}"
Accept: application/vnd.github.v3+json
响应解析
# Code 节点:解析 HTTP 响应
import json
def main(http_response: str, status_code: int) -> dict:
if status_code != 200:
return {
"success": False,
"error": f"API returned {status_code}",
"data": None
}
data = json.loads(http_response)
return {
"success": True,
"temperature": data["main"]["temp"],
"description": data["weather"][0]["description"],
"city": data["name"]
}
实战:构建一个新闻聚合 Workflow
graph TB
Start[用户输入关键词] --> HTTP1[HTTP: 新闻API搜索]
HTTP1 --> Code1[Code: 提取前5条]
Code1 --> Iterator[Iterator: 遍历每条新闻]
subgraph "Iterator 内部"
LLM1[LLM: 生成摘要]
LLM2[LLM: 情感分析]
LLM1 --> LLM2
end
Iterator --> Agg[Aggregator: 汇总]
Agg --> LLM3[LLM: 生成综合报告]
LLM3 --> End[End: 输出报告]# 代码节点:提取前 5 条新闻
def main(api_response: str) -> dict:
import json
data = json.loads(api_response)
articles = data.get("articles", [])[:5]
return {
"articles": [
{
"title": a["title"],
"source": a["source"]["name"],
"url": a["url"],
"content": a.get("content", "")[:500]
}
for a in articles
],
"count": len(articles)
}