文档 · 核心 API

工具调用 / JSON 模式

工具调用与 response_format=json_object 在所有上游间归一化。OpenAI、Anthropic、Google、DeepSeek 与 Qwen 的差异由网关消化,业务侧只看到 OpenAI 形状。

§ 01

声明工具

curl https://api.cdgo.ai/v1/chat/completions \
  -H "Authorization: Bearer sk-cdgo-..." \
  -H "Content-Type: application/json" \
  -d '{
    "model": "auto",
    "messages": [{"role":"user","content":"weather in Hangzhou tomorrow"}],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_weather",
        "parameters": {
          "type":"object",
          "properties":{"city":{"type":"string"},"date":{"type":"string"}},
          "required":["city"]
        }
      }
    }]
  }'

§ 02

回喂工具结果

# After running get_weather() locally:
messages.append(resp.choices[0].message)        # the assistant tool_call message
messages.append({
    "role": "tool",
    "tool_call_id": call.id,
    "content": '{"city":"Hangzhou","forecast":"rain","high_c":18}',
})
final = client.chat.completions.create(model="auto", messages=messages)
print(final.choices[0].message.content)

§ 03

JSON 模式

response_format = { type: "json_object" } 强制返回合法 JSON。系统会同时校验: 如果上游返回非法 JSON,网关会自动重试一次再失败。

resp = client.chat.completions.create(
    model="gpt-4o-mini",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Reply with JSON: {city: str, lat: float, lon: float}."},
        {"role": "user", "content": "Hangzhou"},
    ],
)
import json
print(json.loads(resp.choices[0].message.content))