Skip to Content
文本生成Chat Completions API

Chat Completions API

OpenAI Chat
接口POST /v1/chat/completions

请求参数

参数类型必填说明
modelstring是模型名称,使用 GET /v1/models 返回的值。
messagesarray是按顺序排列的对话消息。
messages[].rolestring是消息角色,例如 system、user 或 assistant。
messages[].contentstring | array是消息内容;纯文本可直接传字符串。
streamboolean否是否以流式方式返回增量结果,默认 false。
stream_optionsobject否流式选项;需要在流末尾返回用量时可设置 include_usage: true。
max_tokensinteger否限制生成 token 数量。
max_completion_tokensinteger否限制生成内容和推理内容的 token 总数。
reasoning_effortstring否推理强度选项,具体取值由模型支持情况决定。
temperaturenumber否采样温度;数值越高,输出随机性越强。
top_pnumber否核采样参数,通常与 temperature 二选一调整。
stopstring | array否触发后停止生成的字符串或字符串数组。
response_formatobject否指定输出格式,例如 {“type”:“json_object”}。
toolsarray否可供模型调用的工具定义。
tool_choicestring | object否控制是否自动调用工具或指定工具。
parallel_tool_callsboolean否是否允许模型并行调用多个工具。
userstring否用于标识终端用户的业务标识。

响应参数

字段类型说明
idstring本次生成的响应 ID。
objectstring非流式响应为 chat.completion,流式响应为 chat.completion.chunk。
createdinteger响应创建时间,Unix 时间戳。
modelstring实际处理请求的模型名称。
choicesarray候选结果列表。
choices[].indexinteger候选结果索引。
choices[].messageobject非流式响应中的完整消息。
choices[].message.rolestring消息角色,通常为 assistant。
choices[].message.contentstring | null生成的文本内容;工具调用时可能为空。
choices[].deltaobject流式响应中的增量消息。
choices[].delta.contentstring | null本次流事件新增的文本片段。
choices[].finish_reasonstring | null生成结束原因,例如 stop、length 或 tool_calls。
usageobject | nulltoken 用量信息;流式请求通常在最后一个事件返回。
usage.prompt_tokensinteger输入 token 数量。
usage.completion_tokensinteger输出 token 数量。
usage.total_tokensinteger输入与输出 token 总数。

调用示例

curl "https://api.example.com/v1/chat/completions" \ -H "Authorization: Bearer <YOUR_API_KEY>" \ -H "Content-Type: application/json" \ -d '{ "model": "glm-5.3", "messages": [ {"role": "system", "content": "你是一个简洁、准确的助手。"}, {"role": "user", "content": "请用一句话介绍你自己"} ], "temperature": 0.7, "top_p": 0.9, "max_tokens": 512, "stream": false }'

响应示例

非流式响应:

{ "id": "chatcmpl_example", "object": "chat.completion", "created": 1710000000, "model": "glm-5.3", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "我是一个文本生成助手。" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 24, "completion_tokens": 12, "total_tokens": 36 } }

流式响应以 SSE 事件逐段返回,文本增量位于 choices[0].delta.content,结束事件为 data: [DONE]:

data: {"id":"chatcmpl_example","object":"chat.completion.chunk","created":1710000000,"model":"glm-5.3","choices":[{"index":0,"delta":{"role":"assistant","content":"我是"},"finish_reason":null}]} data: {"id":"chatcmpl_example","object":"chat.completion.chunk","created":1710000000,"model":"glm-5.3","choices":[{"index":0,"delta":{"content":"一个文本生成助手。"},"finish_reason":null}]} data: [DONE]

部分推理模型会消耗较多输出 token。使用 deepseek-v4-pro 等模型时,建议设置足够的 max_tokens。

切换到其它兼容模型时,只需替换 model。

Last updated on