Chat Completions
根据提供的对话上下文生成模型回复,是零派智能业务平台中最常用的接口。支持流式和非流式两种响应模式,完全兼容 OpenAI 格式。
Endpoint
POST /v1/chat/completionsMethod
POST
Authentication
需要 Bearer Token 认证:
Authorization: Bearer $API_KEYRequest Headers
| Header | 是否必需 | 说明 |
|---|---|---|
Authorization | 是 | Bearer <API_KEY> |
Content-Type | 是 | application/json |
Request Body
| 参数 | 类型 | 是否必需 | 说明 |
|---|---|---|---|
model | string | 是 | 模型标识,如 gpt-4o、gpt-4o-mini,通过 /v1/models 获取 |
messages | array | 是 | 对话消息数组,包含完整的对话上下文 |
temperature | number | 否 | 采样温度,范围 0-2,默认 1。值越高输出越随机 |
top_p | number | 否 | 核采样概率,默认 1。与 temperature 二选一 |
max_tokens | integer | 否 | 生成 token 数量上限 |
stream | boolean | 否 | 是否流式返回,默认 false |
n | integer | 否 | 生成候选回复数量,默认 1 |
stop | string | array | 否 | 停止生成的标记 |
presence_penalty | number | 否 | 存在惩罚,范围 -2 到 2,默认 0 |
frequency_penalty | number | 否 | 频率惩罚,范围 -2 到 2,默认 0 |
response_format | object | 否 | 指定输出格式,如 {"type": "json_object"} |
messages 数组
每个消息对象包含以下字段:
| 字段 | 类型 | 说明 |
|---|---|---|
role | string | 消息角色:system、user、assistant、tool |
content | string | array | 消息内容,可以是字符串或多模态数组 |
请求示例
{ "model": "gpt-4o-mini", "messages": [ { "role": "system", "content": "你是一个有帮助的助手。" }, { "role": "user", "content": "用一句话介绍零派智能。" } ], "temperature": 0.7, "max_tokens": 1000}Response
非流式响应返回一个 JSON 对象:
{ "id": "chatcmpl-abc123", "object": "chat.completion", "created": 1699999999, "model": "gpt-4o-mini", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "零派智能业务平台一个兼容 OpenAI 格式的 AI 模型聚合平台。" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 25, "completion_tokens": 20, "total_tokens": 45 }}响应字段说明
| 字段 | 类型 | 说明 |
|---|---|---|
id | string | 本次请求的唯一标识 |
object | string | 固定为 chat.completion |
created | integer | 响应创建时间(Unix 时间戳) |
model | string | 实际使用的模型标识 |
choices | array | 生成的候选回复数组 |
usage | object | token 用量统计 |
choices 数组
| 字段 | 类型 | 说明 |
|---|---|---|
index | integer | 候选回复索引 |
message | object | 回复消息,包含 role 和 content |
finish_reason | string | 结束原因:stop、length、content_filter、tool_calls |
usage 对象
| 字段 | 类型 | 说明 |
|---|---|---|
prompt_tokens | integer | 输入 token 数 |
completion_tokens | integer | 输出 token 数 |
total_tokens | integer | 总 token 数 |
Streaming
将 stream 设置为 true 即可启用流式响应。响应以 SSE(Server-Sent Events)格式返回,每个 chunk 包含部分生成内容。
流式响应格式:
data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","created":1699999999,"model":"gpt-4o-mini","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}
data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","created":1699999999,"model":"gpt-4o-mini","choices":[{"index":0,"delta":{"content":"New"},"finish_reason":null}]}
data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","created":1699999999,"model":"gpt-4o-mini","choices":[{"index":0,"delta":{"content":" API"},"finish_reason":null}]}
data: [DONE]流式响应以 data: [DONE] 标记结束。详见 Streaming。
错误码
| 状态码 | 说明 |
|---|---|
| 400 | 请求参数错误 |
| 401 | API Key 无效或缺失 |
| 403 | 无权限访问该模型 |
| 404 | 模型不存在 |
| 429 | 请求频率超限 |
| 500 | 服务器内部错误 |
| 502 | 上游网关错误 |
| 503 | 服务不可用 |
详见 Errors。
代码示例
import { Tabs, TabItem } from ‘@astrojs/starlight/components’;
curl "$BASE_URL/v1/chat/completions" \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "'"$MODEL"'", "messages": [ { "role": "system", "content": "你是一个有帮助的助手。" }, { "role": "user", "content": "用一句话介绍零派智能。" } ], "temperature": 0.7, "max_tokens": 1000 }'import osimport requests
base_url = os.environ.get("BASE_URL")api_key = os.environ.get("API_KEY")model = os.environ.get("MODEL", "gpt-4o-mini")
response = requests.post( f"{base_url}/v1/chat/completions", headers={ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", }, json={ "model": model, "messages": [ {"role": "system", "content": "你是一个有帮助的助手。"}, {"role": "user", "content": "用一句话介绍零派智能。"}, ], "temperature": 0.7, "max_tokens": 1000, },)
result = response.json()print(result["choices"][0]["message"]["content"])const baseURL = process.env.BASE_URL;const apiKey = process.env.API_KEY;const model = process.env.MODEL || "gpt-4o-mini";
const response = await fetch(`${baseURL}/v1/chat/completions`, { method: "POST", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", }, body: JSON.stringify({ model, messages: [ { role: "system", content: "你是一个有帮助的助手。" }, { role: "user", content: "用一句话介绍零派智能。" }, ], temperature: 0.7, max_tokens: 1000, }),});
const result = await response.json();console.log(result.choices[0].message.content);package main
import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os")
func main() { baseURL := os.Getenv("BASE_URL") apiKey := os.Getenv("API_KEY") model := os.Getenv("MODEL") if model == "" { model = "gpt-4o-mini" }
payload, _ := json.Marshal(map[string]interface{}{ "model": model, "messages": []map[string]string{ {"role": "system", "content": "你是一个有帮助的助手。"}, {"role": "user", "content": "用一句话介绍零派智能。"}, }, "temperature": 0.7, "max_tokens": 1000, })
req, _ := http.NewRequest("POST", baseURL+"/v1/chat/completions", bytes.NewReader(payload)) req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result struct { Choices []struct { Message struct { Content string `json:"content"` } `json:"message"` } `json:"choices"` } json.Unmarshal(body, &result)
fmt.Println(result.Choices[0].Message.Content)}