模型能力
工具调用
声明工具、验证参数、执行本地函数并回传工具结果。
工作流程
工具调用要求所选模型与线路支持该能力。模型返回调用建议,由你的应用验证并执行,再把结果交回模型;API 不会替你执行任意本地函数。
完整示例
按 OpenAI SDK安装依赖并设置环境变量。以下工具只整理字符串,不访问外部系统。它演示一次工具往返;业务应用需要限制调用轮数。
import json
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["IROUTER_API_KEY"],
base_url="https://gateway.irouter.io/v1", max_retries=0)
model = os.environ["IROUTER_MODEL"]
messages = [{"role": "user", "content": "Use format_label to trim: ' iRouter '."}]
tools = [{"type": "function", "function": {
"name": "format_label", "description": "Trim surrounding whitespace.",
"parameters": {"type": "object", "properties": {
"label": {"type": "string"}}, "required": ["label"],
"additionalProperties": False}
}}]
reply = client.chat.completions.create(model=model, messages=messages, tools=tools)
message = reply.choices[0].message
if message.tool_calls:
messages.append(message.model_dump(exclude_none=True))
for call in message.tool_calls:
if call.function.name != "format_label":
raise ValueError("Unsupported tool")
args = json.loads(call.function.arguments)
if not isinstance(args, dict) or set(args) != {"label"} or not isinstance(args["label"], str):
raise ValueError("Invalid arguments")
result = {"label": args["label"].strip()}
messages.append({"role": "tool", "tool_call_id": call.id,
"content": json.dumps(result)})
reply = client.chat.completions.create(model=model, messages=messages)
print(reply.choices[0].message.content)
else:
print(message.content)执行前检查
只执行白名单中的函数,检查参数类型与业务权限。付款、删除、发信等有副作用的操作应由应用确认授权,并使用业务幂等标识避免重复执行。不要把模型返回的字符串直接交给命令行或 SQL。
一个响应可能包含多个工具调用,回传每个调用对应的 tool_call_id。流式模式下必须先拼接完整参数再解析 JSON,不要执行尚未完整的片段。
其他协议
Messages 使用 tool_use 与 tool_result 内容块;Responses 使用函数调用项与函数输出项。不同协议不能直接共用上面的消息结构。协议字段参考 OpenAI 工具调用,iRouter 兼容性须按线路验证。