Chat Completions
POST /v1/chat/completions 提供 OpenAI-compatible 的对话文本生成。请求必须包含 model 和 messages,并使用 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。实际响应还可能包含 created、model 和 usage 等字段。
请求参数
| 参数 | 类型 | 说明 |
|---|---|---|
model |
string | /v1/models 返回的模型标识。 |
messages |
array | 按顺序排列的消息;每项至少包含 role 与 content。 |
stream |
boolean | false 或省略时返回一个 JSON;设为 true 时返回 SSE,见流式响应。 |
temperature |
number | 采样随机性。仅在所选模型/上游支持时使用;不确定时省略。 |
max_tokens |
integer | 生成上限。部分推理模型使用 max_completion_tokens,请以模型能力为准。 |
role 常用值为 system、user 和 assistant。content 可以是文本字符串;多模态内容应遵循所选模型接受的内容结构。不要把同一条消息写成缺失 role 或 content 的对象。
流式请求
只需把 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() 的完整文档;请按事件增量读取,详见流式响应。