Function Calling API

最后更新:

用现代 tools.function 结构定义函数参数,解析 arguments 并校验白名单、类型和权限,区分 schema 与业务校验。

使用 tools 中的 function 描述函数

现代 Chat Completions 用 tools: [{type: function, function: ...}] 描述函数。函数 schema 定义输入,arguments 是待解析的 JSON 字符串;是否支持严格 schema 或强制调用需要按具体模型验证。不要把旧 functions 字段与 tools 混在一起。

阶段结构字段
声明tools[].function.name / parameters
返回choices[].message.tool_calls
解析tool_calls[].function.arguments
回传role: tool + tool_call_id + content

最小请求示例

凭据从 KKAI_API_KEY 环境变量读取。示例是请求合同,运行后需核对实际响应和用量。

import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["KKAI_API_KEY"],
                base_url="https://api.kkaiapi.com/v1", max_retries=0, timeout=120)
r = client.chat.completions.create(
    model="gpt-6.1-sol",
    messages=[{"role": "user", "content": "请用 add 计算 2 加 3"}],
    tools=[{"type": "function", "function": {"name": "add", "description": "相加两个整数", "parameters": {"type": "object", "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}, "required": ["a", "b"], "additionalProperties": False}}}], tool_choice="auto",
)
for call in r.choices[0].message.tool_calls or []:
    print(call.id, call.function.name, call.function.arguments)

schema 与业务校验分别负责

例子中的 additionalProperties=false 限制 schema 字段,但应用仍须验证 arguments 是对象、a/b 为整数并只允许 add。strict、并行调用和 tool_choice 的支持边界不能由协议名称推定。

独立验证模型工具能力

公开 endpoint 表证明可用路径,不证明每个模型、客户端版本都支持相同工具语义。先在目标模型完成一次声明、返回、执行与回传,再启用真实业务工具。

常见问题

本页示例代表已经实测成功吗?

示例说明当前请求结构与配置方式。请在自己的运行环境核对响应、模型 ID 与用量;模型快照和文档不能替代一次真实业务验收。