Skip to content

Chat Completions ​

OpenAI Chat Completions 兼容接口,适用于绝大多数聊天、Agent、RAG 与多模态场景。

还要接 Claude 或 Gemini?

本页只讲 OpenAI Chat 协议。Claude 的 /v1/messages、Gemini 的 /v1beta/models/{model}:generateContent 的请求头、SDK 配置、字段差异和参数映射,见聊天协议总览。

POSThttps://YOUR_API_BASE_URL/v1/chat/completions
鉴权:Bearer TokenContent-Type:application/json
messages 为必填对话列表;stream 为 true 时返回 SSE 流。

请求头 ​

请求头必填值
Authorization是Bearer sk-xxxxxxxx
Content-Type是application/json

请求体参数 ​

核心参数 ​

字段类型必填说明
modelstring是模型 ID,来自 GET /v1/models
messagesarray是对话消息列表,按时间顺序排列
streamboolean否true 时以 SSE 返回,默认 false
stream_optionsobject否流式选项,如 {"include_usage": true}
max_tokensinteger否最大生成 token 数;不要与 max_completion_tokens 同时使用
max_completion_tokensinteger否生成 token 上限,部分模型包含推理 token
ninteger否生成候选数量,默认 1
stopstring | string[]否遇到指定字符串时停止,最多 4 个
temperaturenumber否采样温度,通常 0–2,默认值由模型决定
top_pnumber否核采样,通常 0–1
presence_penaltynumber否话题新鲜度惩罚,-2–2
frequency_penaltynumber否频率惩罚,-2–2
logit_biasobject否token 级偏置,键为 token ID
logprobsboolean否是否返回对数概率
top_logprobsinteger否返回概率最高的 token 数,0–20
userstring否终端用户标识,用于风控与统计
seedinteger否随机种子;不保证所有模型可复现

输出格式 ​

字段类型说明
response_formatobject指定输出格式
response_format.typestringtext、json_object 或 json_schema
response_format.json_schemaobjecttype=json_schema 时的结构定义
response_format.json_schema.namestring结构名称
response_format.json_schema.schemaobjectJSON Schema
response_format.json_schema.strictboolean是否严格遵循 Schema

TIP

使用 json_object 时,提示词中仍需明确要求输出 JSON。使用 json_schema 可配合 strict: true 获得更稳定的结构,但需要模型支持。

工具调用 ​

字段类型说明
toolsarray可用工具列表
tools[].typestring目前常用 function
tools[].function.namestring函数名
tools[].function.descriptionstring函数说明,影响模型选择
tools[].function.parametersobjectJSON Schema 参数定义
tools[].function.strictboolean是否严格遵循参数结构
tool_choicestring | objectnone、auto、required 或指定函数
parallel_tool_callsboolean是否允许并行调用多个工具

指定函数:

json
{
  "tool_choice": {
    "type": "function",
    "function": { "name": "get_weather" }
  }
}

其他参数(模型相关) ​

字段类型说明
reasoning_effortstring推理强度,常见 low / medium / high
modalitiesstring[]输出模态,例如 ["text"]、["text","audio"]
audioobject音频输出配置,如 {"voice":"alloy","format":"mp3"}
service_tierstring服务等级,如 auto / default / flex / priority
storeboolean是否允许服务端存储请求,部分模型不接受 true
metadataobject自定义元数据,键值对
predictionobject预测输出以降低延迟(模型相关)

WARNING

上表部分参数只有特定模型支持。传入不支持的参数时,网关或模型可能返回 400 unsupported_parameter,也可能忽略。生产环境请做好兼容。

messages 结构 ​

每条消息的基本结构:

json
{
  "role": "user",
  "content": "你好"
}
字段类型说明
rolestringsystem、developer、user、assistant、tool
contentstring | array | null文本,或多模态内容块数组
namestring可选的参与者名称
tool_callsarray助手消息中的工具调用
tool_call_idstringtool 消息对应的调用 ID

内容块 ​

content 为数组时,支持以下块(是否支持由模型决定):

type结构说明
text{"type":"text","text":"..."}文本
image_url{"type":"image_url","image_url":{"url":"...","detail":"auto"}}图片 URL 或 Data URI
input_audio{"type":"input_audio","input_audio":{"data":"<base64>","format":"wav"}}音频输入
file{"type":"file","file":{"file_id":"file_xxx"}}文件引用,字段随模型而定

图片示例:

json
{
  "role": "user",
  "content": [
    { "type": "text", "text": "请描述这张图片。" },
    {
      "type": "image_url",
      "image_url": {
        "url": "https://media.example.com/reference.jpg",
        "detail": "auto"
      }
    }
  ]
}

图片 URL 必须是公网可访问的 http / https 地址,或合法的 Data URI。私有地址、需要登录的页面通常无法被服务读取。

基础调用 ​

bash
curl "https://YOUR_API_BASE_URL/v1/chat/completions" \
  -H "Authorization: Bearer sk-xxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "YOUR_MODEL",
    "messages": [
      {"role": "system", "content": "你是一个简洁的助手。"},
      {"role": "user", "content": "用一句话解释什么是向量数据库。"}
    ],
    "temperature": 0.7,
    "stream": false
  }'
python
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ["API_KEY"],
    base_url=os.environ["API_BASE"] + "/v1",
)

resp = client.chat.completions.create(
    model="YOUR_MODEL",
    messages=[
        {"role": "system", "content": "你是一个简洁的助手。"},
        {"role": "user", "content": "用一句话解释什么是向量数据库。"},
    ],
    temperature=0.7,
)
print(resp.choices[0].message.content)
print(resp.usage)
javascript
import OpenAI from 'openai'

const client = new OpenAI({
  apiKey: process.env.API_KEY,
  baseURL: process.env.API_BASE + '/v1'
})

const resp = await client.chat.completions.create({
  model: 'YOUR_MODEL',
  messages: [
    { role: 'system', content: '你是一个简洁的助手。' },
    { role: 'user', content: '用一句话解释什么是向量数据库。' }
  ],
  temperature: 0.7
})
console.log(resp.choices[0].message.content)

成功响应 ​

HTTP 200:

json
{
  "id": "chatcmpl-example",
  "object": "chat.completion",
  "created": 1788566400,
  "model": "YOUR_MODEL",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "向量数据库是一种专门存储和检索向量表示的数据库。"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 28,
    "completion_tokens": 24,
    "total_tokens": 52
  },
  "system_fingerprint": null
}
字段说明
id响应 ID
object固定为 chat.completion
createdUnix 秒时间戳
model实际使用的模型名,可能是实际模型名
choices[].index候选序号
choices[].message.content生成的文本
choices[].message.tool_calls工具调用列表,可能不存在
choices[].finish_reasonstop、length、tool_calls、content_filter 等
usage.prompt_tokens输入 token
usage.completion_tokens输出 token
usage.total_tokens总 token

部分推理模型会在消息中额外返回 reasoning_content 字段,属于模型相关行为。

流式调用 ​

bash
curl -N "https://YOUR_API_BASE_URL/v1/chat/completions" \
  -H "Authorization: Bearer sk-xxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "YOUR_MODEL",
    "messages": [{"role": "user", "content": "写两句关于秋天的诗。"}],
    "stream": true,
    "stream_options": {"include_usage": true}
  }'

返回:

text
data: {"id":"chatcmpl-example","object":"chat.completion.chunk","created":1788566400,"model":"YOUR_MODEL","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}

data: {"id":"chatcmpl-example","object":"chat.completion.chunk","created":1788566400,"model":"YOUR_MODEL","choices":[{"index":0,"delta":{"content":"秋风"},"finish_reason":null}]}

data: {"id":"chatcmpl-example","object":"chat.completion.chunk","created":1788566400,"model":"YOUR_MODEL","choices":[{"index":0,"delta":{"content":"起"},"finish_reason":null}]}

data: {"id":"chatcmpl-example","object":"chat.completion.chunk","created":1788566400,"model":"YOUR_MODEL","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: {"id":"chatcmpl-example","object":"chat.completion.chunk","created":1788566400,"model":"YOUR_MODEL","choices":[],"usage":{"prompt_tokens":20,"completion_tokens":12,"total_tokens":32}}

data: [DONE]
字段说明
choices[].delta.content本次增量文本
choices[].delta.tool_calls增量工具调用,需按 index 拼接
choices[].finish_reason最后一个内容块给出结束原因
usage仅在 include_usage: true 时,最后一个数据块返回
[DONE]流结束标记,不是 JSON

Python SDK:

python
stream = client.chat.completions.create(
    model="YOUR_MODEL",
    messages=[{"role": "user", "content": "写两句关于秋天的诗。"}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

工具调用 ​

第一次请求让模型决定调用哪个函数:

json
{
  "model": "YOUR_MODEL",
  "messages": [
    {"role": "user", "content": "北京今天天气怎么样?"}
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "查询指定城市的天气",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {"type": "string", "description": "城市名称"}
          },
          "required": ["city"]
        }
      }
    }
  ],
  "tool_choice": "auto"
}

模型返回工具调用:

json
{
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_example",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"city\":\"北京\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}

执行函数后,把结果作为 tool 消息追加,再次请求:

json
{
  "model": "YOUR_MODEL",
  "messages": [
    {"role": "user", "content": "北京今天天气怎么样?"},
    {
      "role": "assistant",
      "content": null,
      "tool_calls": [
        {
          "id": "call_example",
          "type": "function",
          "function": {"name": "get_weather", "arguments": "{\"city\":\"北京\"}"}
        }
      ]
    },
    {
      "role": "tool",
      "tool_call_id": "call_example",
      "content": "{\"temperature\":26,\"weather\":\"晴\"}"
    }
  ],
  "tools": [ ... ]
}

结构化输出 ​

json
{
  "model": "YOUR_MODEL",
  "messages": [
    {"role": "system", "content": "从文本中抽取人物信息。"},
    {"role": "user", "content": "张三,32 岁,住在杭州。"}
  ],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "person",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "name": {"type": "string"},
          "age": {"type": "integer"},
          "city": {"type": "string"}
        },
        "required": ["name", "age", "city"],
        "additionalProperties": false
      }
    }
  }
}

错误 ​

状态码常见原因
400JSON 错误、缺少 messages、参数不支持、图片格式错误
401Key 无效或过期
403模型不在分组 / 白名单,或额度不足
404模型不存在
429频率或额度超限
500 / 502 / 503服务异常,可退避重试

完整错误结构见错误与重试。

相关阅读 ​

接口以实际网关配置与模型能力为准。