|

模型能写代码,但不能执行代码。
你问"今天北京天气",它只能说"我不知道"或者编一个。
Function Calling(工具调用)就是让它能"伸手"去查的机制。
一、原理
不是模型真的执行了函数,流程是这样的:

1. 你告诉模型"我有这些工具,参数长这样"
2. 模型判断需要查天气,返回一个"调用意图":`get_weather(city="北京")`
3. 你的代码真正执行这个函数
4. 把结果回传给模型
5. 模型基于结果组织回答
关键:执行永远在你的代码里,模型只负责"决定调什么"。
二、完整示例
以 DeepSeek 为例(OpenAI 格式通用)。
- import json
- from openai import OpenAI
- client = OpenAI(
- api_key="sk-xxx",
- base_url="https://api.deepseek.com"
- )
- # 1. 定义工具(JSON Schema 格式)
- tools = [{
- "type": "function",
- "function": {
- "name": "get_weather",
- "description": "查询指定城市的实时天气",
- "parameters": {
- "type": "object",
- "properties": {
- "city": {
- "type": "string",
- "description": "城市名,如 北京、上海"
- }
- },
- "required": ["city"]
- }
- }
- }]
复制代码
description 写得好不好,直接决定模型会不会正确调用。要写清楚"什么时候用",不只是"是什么"。
- # 2. 第一次调用:模型决定要不要用工具
- messages = [{"role": "user", "content": "北京今天天气怎么样"}]
- resp = client.chat.completions.create(
- model="deepseek-chat",
- messages=messages,
- tools=tools,
- tool_choice="auto"
- )
- msg = resp.choices[0].message
- if msg.tool_calls:
- # 3. 执行函数
- call = msg.tool_calls[0]
- args = json.loads(call.function.arguments)
- result = get_weather(**args) # 你的真实函数
- # 4. 把结果回传
- messages.append(msg)
- messages.append({
- "role": "tool",
- "tool_call_id": call.id,
- "content": json.dumps(result, ensure_ascii=False)
- })
- # 5. 第二次调用:模型基于结果回答
- final = client.chat.completions.create(
- model="deepseek-chat",
- messages=messages,
- tools=tools
- )
- print(final.choices[0].message.content)
- else:
- print(msg.content)
复制代码
三、多工具编排
模型可以一次调多个工具,也可以连续调:
- tools = [
- {"type": "function", "function": {"name": "get_weather", ...}},
- {"type": "function", "function": {"name": "query_database", ...}},
- {"type": "function", "function": {"name": "send_email", ...}},
- ]
复制代码
处理多个调用:
- for call in msg.tool_calls:
- name = call.function.name
- args = json.loads(call.function.arguments)
- if name == "get_weather":
- result = get_weather(**args)
- elif name == "query_database":
- result = query_database(**args)
- else:
- result = {"error": f"未知工具 {name}"}
- messages.append({
- "role": "tool",
- "tool_call_id": call.id,
- "content": json.dumps(result, ensure_ascii=False)
- })
复制代码
注意:每个 tool_call 都必须有对应的 tool 消息回传,漏一个会报错。
四、错误处理
1. 参数解析失败
模型偶尔会生成非法 JSON:
- try:
- args = json.loads(call.function.arguments)
- except json.JSONDecodeError:
- # 把错误告诉模型,让它重试
- messages.append({
- "role": "tool",
- "tool_call_id": call.id,
- "content": "参数解析失败,请重新生成合法的 JSON 参数"
- })
- continue
复制代码
2. 函数执行异常
不要把异常直接抛给用户,要作为工具结果回传,让模型解释:
- try:
- result = get_weather(**args)
- except Exception as e:
- result = {"error": str(e), "hint": "请告知用户天气服务暂时不可用"}
复制代码
3. 死循环
模型可能反复调用同一个工具,加个计数:
- max_rounds = 5
- for _ in range(max_rounds):
- resp = client.chat.completions.create(...)
- if not resp.choices[0].message.tool_calls:
- break
复制代码
五、实用建议
1. 工具描述要写"何时用"
差的写法:`"description": "查询天气"`
好的写法:`"description": "查询指定城市的实时天气。当用户询问天气、温度、是否下雨时使用"`
2. 参数尽量简单
能用 string 就别用嵌套对象。模型对复杂 schema 的准确率会下降。
3. 只暴露必要工具
工具越多,模型选错的概率越大。按场景分不同工具集。
4. 结果要精简
回传的 JSON 别塞整个数据库记录,只给模型需要的字段,省 token。
5. 加日志
记录每次调用的工具名、参数、结果,排查问题时全靠它。
六、典型场景
- 查数据库:自然语言转 SQL 再执行(注意权限,只给只读账号)
- 调用内部 API:查订单、查库存、发通知
- 计算:模型算数不准,交给代码算
- 联网搜索:搜索结果作为工具返回
- 操作文件:读写本地文件(注意路径校验)
小结
Function Calling 的本质是把模型的"意图"翻译成"动作"。
三个关键点:
1. 工具描述决定调用准确率
2. 执行永远在你的代码里,做好校验和兜底
3. 错误也要回传给模型,让它自己修正
掌握这个,AI 才真正从"聊天"变成"干活"。
有问题评论区问。 |
|