
模型不知道今天的天气,查不了你的订单,也发不了邮件。Function Calling(工具调用) 的思路是:你把能用的函数「描述」给模型,模型在需要时告诉你「请帮我调用某个函数,参数是这些」;你的程序去执行,再把结果交给模型,由它组织成最终回答。
真正执行函数的永远是你的代码,模型只负责决定调哪个、传什么。
一次完整的流程
text
用户:明天上海要带伞吗?
│
▼ ① 发送:问题 + 工具描述(get_weather)
模型:我需要调用 get_weather(city="上海", date="明天") ← tool_calls
│
▼ ② 你的代码执行 get_weather,得到「小雨,18–23℃」
│
▼ ③ 发送:之前的对话 + 函数结果
模型:明天上海有小雨,建议带伞,气温 18 到 23 度。 ← 最终回答描述工具

工具用 JSON Schema 描述参数,description 写清楚「什么时候该用它」:
json
[
{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询某个城市某一天的天气预报",
"parameters": {
"type": "object",
"properties": {
"city": { "type": "string", "description": "城市名,如 上海" },
"date": { "type": "string", "description": "日期,如 今天、明天、2026-10-08" }
},
"required": ["city", "date"]
}
}
}
]动手:看模型要调用什么
下面的运行框只演示第 ① 步:模型收到问题和工具描述后,返回它想调用的函数和参数。换几个问题试试,比如问一个和天气无关的问题,模型会直接回答而不调用工具。
▶ 动手试试
登录后运行登录 HiveGPT 后每天有免费运行次数
[
{
"name": "get_weather",
"arguments": { "city": "上海", "date": "明天" }
}
]完整代码:执行函数,再把结果发回去

python
import json, os
from openai import OpenAI
client = OpenAI(base_url="https://hivegpt.cn/v1", api_key=os.environ["HIVEGPT_API_KEY"])
def get_weather(city, date):
# 真实项目里这里去调天气接口;演示用写死的数据
return {"city": city, "date": date, "weather": "小雨", "temp": "18–23℃"}
TOOLS = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询某个城市某一天的天气预报",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"},
"date": {"type": "string"},
},
"required": ["city", "date"],
},
},
}]
messages = [{"role": "user", "content": "明天上海要带伞吗?"}]
# ① 第一次请求:模型决定要不要调用工具
resp = client.chat.completions.create(model="gpt-5.5", messages=messages, tools=TOOLS)
msg = resp.choices[0].message
if msg.tool_calls:
messages.append(msg) # 把「模型要调用工具」这条也放进历史
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = get_weather(**args) # ② 你的代码执行函数
messages.append({
"role": "tool",
"tool_call_id": call.id, # 对应是哪一次调用
"content": json.dumps(result, ensure_ascii=False),
})
# ③ 第二次请求:模型拿到结果,组织最终回答
resp = client.chat.completions.create(model="gpt-5.5", messages=messages, tools=TOOLS)
print(resp.choices[0].message.content)要点:
- 模型返回工具调用时,
finish_reason是tool_calls,content通常为空。 arguments是字符串形式的 JSON,要先解析;解析失败或参数不合理时,可以把错误信息当作函数结果发回去,让模型修正。- 一次可能返回多个工具调用(比如同时查两个城市),要循环处理,每个结果用
tool_call_id对应上。
安全:模型给的参数不可信
参数是模型「生成」出来的,可能被用户的话误导。凡是会改数据、花钱、发消息的函数:
- 在你的代码里做权限检查,不要因为模型说要调就直接执行;
- 金额、收件人这类关键参数,执行前让用户确认;
- 只给模型它需要的工具,不要把「删除数据」这类函数也挂上去。
小结
- 你描述工具,模型决定调用,你的代码执行,再把结果交回模型。
- 读
tool_calls,解析arguments,用tool_call_id回传结果。 - 有副作用的操作,权限和确认都在你的代码里做。
把「调用工具 → 看结果 → 再决定下一步」放进一个循环,就是 Agent。后面的 A6 会从这里继续。下一课 A5 讲 Embedding 和 RAG:让模型基于你自己的资料回答问题。