主题
Tool Calling(工具调用)
Tool Calling 是 AI Agent 的核心能力,让 LLM 能够调用外部工具来获取信息或执行操作。
什么是 Tool Calling
LLM 本身只能"说话",不能"做事"。Tool Calling 让它能:
- 搜索网络
- 查数据库
- 执行代码
- 调用 API
- 读写文件
没有 Tool Calling:
用户:今天天气怎么样?
LLM:抱歉,我无法获取实时天气信息
有 Tool Calling:
用户:今天天气怎么样?
LLM:调用 get_weather("北京") → 返回:晴,26°C
LLM:今天北京天气晴,气温 26°C工作原理
mermaid
graph LR
A[用户提问] --> B[LLM 判断是否需要工具]
B -->|需要| C[返回工具调用请求]
C --> D[执行工具]
D --> E[将结果返回 LLM]
E --> F[LLM 生成最终回答]
B -->|不需要| F具体流程
- 用户发送消息
- LLM 判断:需要调用哪个工具?参数是什么?
- 应用层执行工具,拿到结果
- 把结果连同历史对话一起发回 LLM
- LLM 基于工具结果生成回答
Function Calling(OpenAI)
OpenAI 的 Function Calling 是最早广泛使用的 Tool Calling 实现:
javascript
// 定义工具
const tools = [
{
type: "function",
function: {
name: "get_weather",
description: "获取指定城市的天气",
parameters: {
type: "object",
properties: {
city: { type: "string", description: "城市名称" }
},
required: ["city"]
}
}
}
]
// 调用 LLM
const response = await openai.chat.completions.create({
model: "gpt-4",
messages: [{ role: "user", content: "北京今天天气怎么样?" }],
tools: tools
})
// LLM 返回工具调用请求
// response.choices[0].message.tool_calls工具设计原则
1. 描述要清晰
javascript
// ❌ 描述不清晰
{
name: "search",
description: "搜索"
}
// ✅ 描述清晰
{
name: "search_web",
description: "使用搜索引擎搜索指定关键词,返回前 5 条结果和摘要"
}2. 参数要明确
javascript
// ✅ 明确的参数定义
parameters: {
type: "object",
properties: {
query: { type: "string", description: "搜索关键词" },
limit: { type: "number", description: "返回结果数量,默认 5" }
},
required: ["query"]
}3. 工具要单一职责
一个工具只做一件事,复杂任务由 Agent 组合多个工具完成。
常用工具类型
| 工具类型 | 示例 |
|---|---|
| 搜索 | Google Search、Bing API |
| 代码执行 | Python REPL、Node.js |
| 数据库 | SQL 查询、MongoDB 查询 |
| API 调用 | 天气 API、股票 API |
| 文件操作 | 读文件、写文件、列目录 |
| 计算器 | 数学计算 |
在 LangChain 中使用
python
from langchain.tools import Tool
from langchain.agents import initialize_agent, AgentType
from langchain_openai import ChatOpenAI
# 定义工具函数
def get_weather(city: str) -> str:
# 实际调用天气 API
return f"{city} 今天晴,26°C"
# 包装成 LangChain Tool
tools = [
Tool(
name="GetWeather",
func=get_weather,
description="获取指定城市的天气信息"
)
]
# 创建 Agent
agent = initialize_agent(
tools,
ChatOpenAI(model="gpt-4"),
agent=AgentType.OPENAI_FUNCTIONS,
verbose=True
)
# 运行
agent.run("北京今天天气怎么样?")注意事项
- 工具执行可能失败,需要处理异常
- 工具可能有副作用(写数据库、发邮件),需要用户确认
- 工具返回内容可能很长,需要截断或总结后再发给 LLM
- 并发调用工具可以提升速度(当一个步骤需要多个独立工具时)