跳转至

Chat Completions

POST /v1/chat/completions 提供 OpenAI-compatible 的对话文本生成。请求必须包含 modelmessages,并使用 Authorization: Bearer <YOUR_API_KEY>

最小非流式请求

请求体:

{
  "model": "gpt-5.6-terra",
  "messages": [
    {
      "role": "user",
      "content": "Reply with OK"
    }
  ],
  "stream": false
}

如果 gpt-5.6-terra 不在 GET /v1/models 的结果中,请换成该列表中的模型。

=== "cURL"

```bash
curl https://api.yuniversity.cc/v1/chat/completions \
  -H "Authorization: Bearer <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-5.6-terra","messages":[{"role":"user","content":"Reply with OK"}],"stream":false}'
```

=== "Python(标准库)"

```python
import json
import os
from urllib.request import Request, urlopen

payload = {
    "model": "gpt-5.6-terra",
    "messages": [{"role": "user", "content": "Reply with OK"}],
    "stream": False,
}
request = Request(
    "https://api.yuniversity.cc/v1/chat/completions",
    data=json.dumps(payload).encode(),
    headers={
        "Authorization": f"Bearer {os.environ['YUNIVERSITY_API_KEY']}",
        "Content-Type": "application/json",
    },
)
with urlopen(request) as response:
    print(json.load(response))
```

=== "JavaScript"

```javascript
const response = await fetch("https://api.yuniversity.cc/v1/chat/completions", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.YUNIVERSITY_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "gpt-5.6-terra",
    messages: [{ role: "user", content: "Reply with OK" }],
    stream: false,
  }),
});
console.log(await response.json());
```

成功响应示例:

{
  "id": "chatcmpl-example",
  "object": "chat.completion",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "OK"
      },
      "finish_reason": "stop"
    }
  ]
}

客户端通常读取 choices[0].message.content。实际响应还可能包含 createdmodelusage 等字段。

请求参数

参数 类型 说明
model string /v1/models 返回的模型标识。
messages array 按顺序排列的消息;每项至少包含 rolecontent
stream boolean false 或省略时返回一个 JSON;设为 true 时返回 SSE,见流式响应
temperature number 采样随机性。仅在所选模型/上游支持时使用;不确定时省略。
max_tokens integer 生成上限。部分推理模型使用 max_completion_tokens,请以模型能力为准。

role 常用值为 systemuserassistantcontent 可以是文本字符串;多模态内容应遵循所选模型接受的内容结构。不要把同一条消息写成缺失 rolecontent 的对象。

流式请求

只需把 stream 设为 true

{
  "model": "gpt-5.6-terra",
  "messages": [
    {
      "role": "user",
      "content": "Reply with OK one word at a time"
    }
  ],
  "stream": true,
  "temperature": 0.2,
  "max_tokens": 32
}

SSE 不是一个可直接 json() 的完整文档;请按事件增量读取,详见流式响应

常见失败

  • 400:JSON 无法解析、messages 结构错误,或参数不被该模型接受。修正请求后再试。
  • 404:模型或路径不存在;确认路径,并从 /v1/models 选择模型。
  • 401 / 403:令牌缺失、无效、过期或没有相应权限,参阅身份认证
  • 429:配额或速率限制;按响应头和错误处理中的退避规则稍后重试。
  • 502 / 503:上游暂时失败或不可用;仅在请求是否被接受已明确时重试。