第 18 期:Agent 基础 — Function Calling 与 ReAct
什么是 Agent?
Agent 与普通 Chatbot 的区别:普通 Chatbot 只会"说",Agent 不仅会"说",还会"做"——它能主动调用工具(搜索、计算、API 调用)来完成任务。
graph TB
subgraph "普通 Chatbot"
Q1[用户提问] --> LLM1[LLM 回答]
end
subgraph "Agent 智能体"
Q2[用户提问] --> Think[LLM 思考]
Think --> Decision{需要工具?}
Decision -->|是| Tool[调用工具]
Tool --> Observe[观察结果]
Observe --> Think
Decision -->|否| Answer[生成回答]
endFunction Calling 模式
直接利用 LLM 原生的函数调用能力(如 OpenAI Function Calling),让模型决定调用哪个工具。
sequenceDiagram
participant U as 用户
participant LLM as LLM
participant Tool as 工具
U->>LLM: "北京今天天气怎么样?"
LLM->>LLM: 分析意图,决定调用天气工具
LLM->>Tool: get_weather(city="北京")
Tool->>LLM: {"temp": 25, "desc": "晴"}
LLM->>U: "北京今天天气晴朗,气温25°C"# Function Calling 格式
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询指定城市的天气信息",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名称,如'北京'"
}
},
"required": ["city"]
}
}
}
]
ReAct 模式
Reasoning + Acting 的循环:LLM 先推理(Thought),再行动(Action),然后观察结果(Observation),反复迭代。
graph TB
Input[用户输入] --> Thought1["Thought: 用户想知道天气
我需要先查城市"]
Thought1 --> Action1["Action: search('北京天气')"]
Action1 --> Obs1["Observation: 返回天气数据..."]
Obs1 --> Thought2["Thought: 我已获得天气数据
可以回答了"]
Thought2 --> Answer["Final Answer: 北京今天..."]模式对比
| 特性 | Function Calling | ReAct |
|---|---|---|
| 推理过程 | 隐式 (模型内部) | 显式 (可追踪 Thought) |
| 多步推理 | 支持但较弱 | 强 (迭代推理) |
| 模型要求 | 支持 FC 的模型 | 任意 LLM |
| 速度 | 快 | 较慢 (多轮推理) |
| 可解释性 | 低 | 高 (每步有 Thought) |
| 推荐场景 | 简单工具调用 | 复杂多步推理 |
在 Dify 中创建 Agent
# Agent 配置
agent_mode: "function_calling" # 或 "react"
model:
provider: openai
name: gpt-4o
max_iterations: 5 # 最大推理轮次
tools:
- google_search # 内置搜索
- calculator # 计算器
- web_scraper # 网页抓取
prompt:
system: |
你是一个全能研究助手。
当需要最新信息时,使用搜索工具。
当需要精确计算时,使用计算器。
先思考,再行动。