工具调用(function calling / tool calls)是所有 AI 接口里最容易「看起来能用、线上天天炸」的能力。根因集中在两处:把增量参数当完整 JSON 用,以及没处理被截断的 JSON。
流式返回里,工具参数以片段形式到达:第一段可能是 {"city":,第二段是 "杭州"}。非流式虽然一次给全,但也仍然是字符串,不是对象。
{
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": "call_abc123",
"type": "function",
"function": {"name": "get_weather", "arguments": "{\"city\":\"杭州\",\"unit\":\"c\"}"}
}]
},
"finish_reason": "tool_calls"
}]
}finish_reason 必须是 tool_calls;如果是 length,说明参数被输出上限截断了。② 拿到的 arguments 要 json.loads 并做 schema 校验,不能直接当 dict 用。| 现象 | 原因 | 处置 |
|---|---|---|
JSONDecodeError: Expecting value | 参数被截断(finish_reason=length) | 调大 max_tokens;简化 schema;失败重试一次 |
| 参数缺字段 / 类型不对 | 模型自由发挥,schema 未强约束 | schema 里写 required 与 enum,并在描述里给示例 |
tool_call_id 对不上 | 回传 tool 消息时 id 丢了或被重写 | 原样回传上一个 id |
| 连续调用同一工具死循环 | 模型看不到工具结果,或结果格式不符合预期 | tool 消息里给结构化结果 + 一句明确结论 |
| 并行调用只返回了一个结果 | parallel_tool_calls 开着但只处理了第一个 | 遍历全部 tool_calls,逐个回填 |
| 模型不调用工具,直接编答案 | 提示词里没说清「必须查」,或工具描述太模糊 | 系统提示加约束;工具 description 写清「什么时候用」 |
400 tools[0].function.parameters | schema 不是合法 JSON Schema | 校验:type: object + properties |
import json
def run_tool_loop(client, model, messages, tools, handlers, max_steps=5):
for _ in range(max_steps):
resp = client.chat.completions.create(
model=model, messages=messages, tools=tools, tool_choice="auto")
msg = resp.choices[0].message
reason = resp.choices[0].finish_reason
if reason == "length":
raise RuntimeError("工具参数被截断:调大 max_tokens 或简化 schema")
if not msg.tool_calls:
return msg.content or ""
messages.append(msg.model_dump(exclude_none=True)) # 先把 assistant 的调用意图放回历史
for call in msg.tool_calls: # 并行调用要全部处理
fn = handlers.get(call.function.name)
try:
args = json.loads(call.function.arguments or "{}")
result = fn(**args) if fn else {"error": "unknown tool"}
except Exception as e:
result = {"error": str(e)} # 把错误回给模型,让它自我修正
messages.append({"role": "tool", "tool_call_id": call.id,
"content": json.dumps(result, ensure_ascii=False)})
return "步骤过多,已中止"注意最后那个 except:把工具执行错误回传给模型,比直接抛给用户有效得多,模型通常能换个参数重试。但要在提示词里明确「最多重试两次」。
enum 列全,别用 any 这种模糊类型。description 写「城市名,如 杭州」比写「城市」高一个档次的准确率。很多人把 response_format 当工具调用的替代。两者目标不同:前者约束回答的形状,后者让模型去执行动作。如果只是要一个固定结构的 JSON,用 response_format 更省 token;如果需要多步、需要外部数据,就用工具调用。各厂商对 json_schema 的支持程度不同,只支持 json_object 时,字段结构要靠提示词 + 本地校验兜住。