Skip to content
开发指南

工具调用与结构化输出 ​

借助严格的 JSON Schema 工具定义与受约束的结构化输出能力,将大语言模型稳定接入内部 API、数据库与外部业务工作流。

函数 / 工具调用闭环 ​

  1. 发送用户消息,同时附带 tools(JSON Schema 参数定义)。
  2. 解析响应中的 message.tool_calls(Anthropic Messages 协议中对应 tool_use 块)。
  3. 在应用侧本地执行目标函数,并将结果以 role: "tool" 消息追加回上下文,同时关联对应的 tool_call_id。
  4. 将更新后的消息数组再次发送给模型,获取基于工具执行结果的最终回答。
python
import json, os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["VANIX_API_KEY"],
    base_url="https://api.vanix.io/v1",
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_order_status",
            "description": "Retrieve live shipment status by order ID.",
            "parameters": {
                "type": "object",
                "properties": {
                    "order_id": {"type": "string", "description": "Order ID such as ORD-9042"}
                },
                "required": ["order_id"],
                "additionalProperties": False,
            },
            "strict": True,
        },
    }
]

resp = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Where is order ORD-9042?"}],
    tools=tools,
    tool_choice="auto",
)

for call in resp.choices[0].message.tool_calls or []:
    print(call.function.name, json.loads(call.function.arguments))

严格结构化输出(json_schema) ​

直接确保模型返回严格符合 Schema 约束的 JSON,告别脆弱的正则提取:

bash
curl https://api.vanix.io/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $VANIX_API_KEY" \
  -d '{
    "model": "gpt-4o-mini",
    "messages": [
      {"role": "user", "content": "Classify ticket: Billing invoice PDF returns 403 after login."}
    ],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "ticket_triage",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "category": {"type": "string", "enum": ["billing", "auth", "api", "other"]},
            "severity": {"type": "string", "enum": ["p1", "p2", "p3"]},
            "summary": {"type": "string"}
          },
          "required": ["category", "severity", "summary"],
          "additionalProperties": false
        }
      }
    }
  }'

严格模式检查清单

在 OpenAI Schema 中开启 "strict": true 时,每一层对象都必须显式声明 "additionalProperties": false,并将该层所有字段列入 "required" 数组。

Vanix AI 统一模型网关 · https://api.vanix.io