作为一名长期从事AI应用开发的工程师,我发现大语言模型的工具调用能力正在彻底改变我们构建智能系统的方式。不同于传统的单一文本生成,工具调用让模型具备了与现实世界交互的能力,这就像给一位博学的学者配上了可以实际操作的工具箱。
工具调用的核心价值在于它打破了语言模型的封闭性。想象一下,你正在和一个知识渊博但被关在玻璃房里的专家对话——他能给你建议,但无法亲自操作任何工具。而通过函数调用,我们终于打开了这扇玻璃门,让模型能够直接操作系统资源、调用API、执行代码,真正实现了"知行合一"。
ReAct(Reasoning and Acting)框架和工具调用代表了两种不同的AI交互范式。在我的项目实践中,ReAct更像是一位需要详细指导的实习生——你必须通过精心设计的提示词模板(如"Think -> Act -> Observe"循环)来引导它的每一步操作。这种方式在复杂任务中表现出色,比如需要多步推理的信息抽取场景。
而工具调用则像是一位专业的技术员——你只需要告诉它有哪些工具可用,它就能自主决定何时使用哪个工具。这种结构化方法特别适合以下场景:
从实现难度来看,ReAct通常需要:
而工具调用主要涉及:
实际经验:在最近的一个客服自动化项目中,我们混合使用了两种方法——用ReAct处理开放性问题,用工具调用执行具体的订单查询操作,取得了不错的效果。
工具调用的核心是三个关键数据结构:
json复制{
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
}
}
]
}
一个完整的工具调用包含四个阶段:
mermaid复制sequenceDiagram
participant User
participant System
participant LLM
participant Tool
User->>System: 输入请求
System->>LLM: 发送请求+工具定义
LLM->>System: 返回工具调用请求
System->>Tool: 执行工具
Tool->>System: 返回结果
System->>LLM: 发送结果
LLM->>System: 生成最终响应
System->>User: 返回答案
首先确保安装最新版openai库:
bash复制pip install --upgrade openai
设置API密钥:
python复制import openai
openai.api_key = "你的API密钥"
下面实现一个数学计算工具:
python复制def calculate(expression: str) -> float:
"""执行数学表达式计算"""
try:
return eval(expression)
except:
return None
tools = [
{
"type": "function",
"function": {
"name": "calculate",
"description": "执行数学表达式计算",
"parameters": {
"properties": {
"expression": {"type": "string"}
},
"required": ["expression"]
}
}
}
]
def run_conversation():
messages = [{"role": "user", "content": "计算(3.14 + 2.718) * 1.618等于多少?"}]
# 第一轮:获取工具调用请求
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
tools=tools,
tool_choice="auto"
)
# 解析工具调用
tool_call = response.choices[0].message.tool_calls[0]
func_name = tool_call.function.name
args = json.loads(tool_call.function.arguments)
# 执行工具
if func_name == "calculate":
result = calculate(args["expression"])
# 第二轮:发送结果给模型
messages.append({
"role": "tool",
"content": str(result),
"tool_call_id": tool_call.id
})
final_response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
print(final_response.choices[0].message.content)
run_conversation()
在实际项目中,我们经常需要组合多个工具:
json复制{
"tools": [
{
"type": "function",
"function": {
"name": "get_user_info",
"description": "获取用户基本信息",
"parameters": {
"properties": {
"user_id": {"type": "string"}
}
}
}
},
{
"type": "function",
"function": {
"name": "get_order_history",
"description": "获取用户订单历史",
"parameters": {
"properties": {
"user_id": {"type": "string"},
"limit": {"type": "integer"}
}
}
}
}
]
}
实战经验:在电商客服系统中,通过缓存用户信息查询结果,我们将平均响应时间从1.2秒降低到了0.6秒。
检查要点:
建议添加参数验证逻辑:
python复制def validate_args(func_name, args):
if func_name == "calculate":
if not isinstance(args.get("expression"), str):
return False
return True
python复制def safe_calculate(expression: str) -> float:
allowed_chars = set("0123456789+-*/.() ")
if not all(c in allowed_chars for c in expression):
raise ValueError("非法字符")
return eval(expression)
在实际项目中,我发现工具调用特别适合以下场景:
最后分享一个实用技巧:在定义工具时,可以加入使用示例,这能显著提高模型调用准确性:
json复制{
"function": {
"name": "search_products",
"description": "搜索商品信息(示例:红色运动鞋 under 500元)",
"parameters": {
"properties": {
"keywords": {"type": "string"},
"max_price": {"type": "number"}
}
}
}
}