AI Agent / 系统课时
解析工具调用请求
解析工具调用请求
模型决定使用工具后,应用不能直接把整段响应交给执行器,而要先拆出工具名称、调用编号和参数。本节用一个最小解析器把候选调用转换成稳定结构,并在执行前检查名称与参数,避免错误请求进入真实工具。
学习目标
- 识别工具调用中的名称、调用编号和参数三类核心字段
- 将模型生成的参数安全解析为应用可验证的数据结构
- 理解调用编号在“请求—执行结果”配对中的作用
识别调用编号、函数和参数
Chat Completions 的调用位于助手消息的 tool_calls 数组。函数名和 JSON 参数字符串在调用项的 function 对象中,使用调用项的 id 匹配结果。Responses 从 output 里读取 type: "function_call" 的项,函数名和参数在顶层,配对时使用 call_id。Responses 中的 id 是输出项 ID,和配对使用的 call_id 是两个字段。
读取完成的调用后再解析参数。若用流式接口,应按协议聚合参数增量,拿到完整调用后才能验证。
解析两种接口的天气调用
把代码保存为 tool_parser.py,与上一课的 tool_specs.py 放在同一目录。解析器检查消息形状、调用编号、JSON 字符串长度和重复键,再复用注册工具的参数校验。它返回应用内部的数据结构,不执行工具。
python
import json
from tool_specs import validate_weather
VALIDATORS = {"get_weather": validate_weather}
def unique_object(pairs):
data = {}
for key, value in pairs:
if key in data:
raise ValueError("duplicate JSON key")
data[key] = value
return data
def parse_tool_call(item, protocol):
if not isinstance(item, dict):
raise ValueError("invalid tool call")
if protocol == "chat" and item.get("type") == "function":
call_id, function = item.get("id"), item.get("function")
elif protocol == "responses" and item.get("type") == "function_call":
call_id, function = item.get("call_id"), item
else:
raise ValueError("unsupported tool call")
if not isinstance(call_id, str) or not call_id.strip() or not isinstance(function, dict):
raise ValueError("invalid tool call envelope")
name, raw = function.get("name"), function.get("arguments")
if not isinstance(name, str) or name not in VALIDATORS:
raise ValueError("unknown tool")
if not isinstance(raw, str) or len(raw) > 4096:
raise ValueError("invalid argument encoding")
arguments = json.loads(raw, object_pairs_hook=unique_object)
return {"id": call_id, "name": name, "arguments": VALIDATORS[name](arguments)}
def parse_batch(items, protocol):
calls = [parse_tool_call(item, protocol) for item in items]
if len({call["id"] for call in calls}) != len(calls):
raise ValueError("duplicate tool call ID")
return calls
if __name__ == "__main__":
function = {"name": "get_weather", "arguments": '{"city":"上海","unit":null}'}
chat = {"type": "function", "id": "call_1", "function": function}
responses = {"type": "function_call", "id": "fc_1", "call_id": "call_1", **function}
parsed = parse_batch([chat], "chat")[0]
assert parsed == parse_batch([responses], "responses")[0]
print(parsed)预期输出
text
{'id': 'call_1', 'name': 'get_weather', 'arguments': {'city': '上海', 'unit': 'celsius'}}应用需要为调用数量和请求体大小设上限。未知工具、损坏的 JSON 或重复编号都应阻止执行。若调用编号可靠,可以按协议返回固定错误码。缺失或重复的编号无法安全配对,应停止该轮并记录错误分类,避免回显含敏感数据的模型参数。合法结构仍需业务授权。下一课会把验证通过的调用交给处理函数。
按自己的节奏,确认真正理解。