开始使用
什么是 Tool Calling?
Tool Calling(工具调用)是让大语言模型(LLM)能够与外部系统交互的机制。通过 tool calling,AI 不再只是「聊天」,而是能够真正「做事」。
从聊天到行动
json
// 没有工具调用:AI 只能说
{ "content": "我可以帮你查天气,但是...我做不到" }
// 有了工具调用:AI 真正执行
{
"content": null,
"tool_calls": [{
"function": {
"name": "get_weather",
"arguments": "{ \"city\": \"Shanghai\" }"
}
}]
}快速示例
Python + OpenAI
python
from openai import OpenAI
client = OpenAI()
# 定义工具
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名"}
},
"required": ["city"]
}
}
}]
# 发起请求
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "北京今天天气怎么样?"}],
tools=tools
)
# 模型请求调用工具
if response.choices[0].message.tool_calls:
tool_call = response.choices[0].message.tool_calls[0]
print(f"模型想调用: {tool_call.function.name}")
print(f"参数: {tool_call.function.arguments}")核心流程
用户输入 → 模型判断是否需要工具 → 返回 tool_calls → 执行工具 → 返回结果 → 模型生成最终回答