OpenAI 的 tools schema 就是用一段 JSON 来"告诉模型有哪些函数可以调用、每个函数有什么参数" ,参数部分用 JSON Schema 描述。模型只在 prompt 里看到这段描述,不会真的执行函数;你拿到 tool_calls 后再自己跑函数,把结果回喂给模型。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
{
  "model": "gpt-4o-2024-11-20",
  "messages": [
    {"role": "system", "content": "You are a helpful assistant. Use tools whenever they apply."},
    {"role": "user",   "content": "What's the weather in Paris in celsius right now?"}
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "...",
        "parameters": { "type": "object", "properties": {...}, "required": [...] }
      }
    },
    { ...get_horoscope... }
  ],
  "tool_choice": "auto",
  "temperature": 0
}

resp = client.chat.completions.create(...) 返回一个 ChatCompletion 对象。 resp.model_dump() 得到的 dict:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
{
  "id": "chatcmpl-AbCDeF...",                 # 这次调用的唯一 id
  "object": "chat.completion",
  "created": 1730000000,                      # unix 时间戳
  "model": "gpt-4o-2024-11-20",

  "choices": [                                # 一般只有 1 个,n>1 时多个
    {
      "index": 0,
      "finish_reason": "tool_calls",          # stop / length / tool_calls / content_filter
      "message": {                            #  真正的"模型说了什么"
        "role": "assistant",
        "content": null,                      # 调工具时 content  null
        "tool_calls": [
          {
            "id": "call_abc123",              # 该工具调用的唯一 id
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"location\":\"Paris\",\"units\":\"celsius\"}"
              #             ^ 注意:是 JSON 字符串,不是 dict
            }
          }
        ],
        "refusal": null                       # 4o 系列才有
      },
      "logprobs": null
    }
  ],

  "usage": {                                  # token 计费
    "prompt_tokens": 78,
    "completion_tokens": 23,
    "total_tokens": 101,
    "prompt_tokens_details": {"cached_tokens": 0, ...},
    "completion_tokens_details": {"reasoning_tokens": 0, ...}
  },
  "system_fingerprint": "fp_..."              # 后端版本指纹
}

参考资料