Chat Completions
发送一组消息,获取模型的下一条回复。
POST
/v1/chat/completions
使用本站 Key和可用的完整模型 ID。请求头包含 Authorization: Bearer <API Key> 与 Content-Type: application/json。
本页目录
请求示例#
在本机环境中设置 XKRELAY_API_KEY。下面的示例发送「只回复 OK」。
把 YOUR_MODEL_ID 换成模型 ID,在 Bash 或 Zsh 中运行。Windows 用户可用PowerShell 示例。
printf 'Authorization: Bearer %s\n' "$XKRELAY_API_KEY" |
curl -sS --fail-with-body --max-time 60 \
https://xkrelay.com/v1/chat/completions \
-H @- -H 'Content-Type: application/json' \
-d '{
"model": "YOUR_MODEL_ID",
"messages": [{"role":"user","content":"只回复 OK"}]
}'
Python 3.10+。设置 XKRELAY_MODEL,保存为 chat.py,运行 python3 chat.py。
"""Minimal Chat Completions request; standard library only."""
import json
import os
import urllib.error
import urllib.request
URL = "https://xkrelay.com/v1/chat/completions"
def chat(environ=None, opener=None):
env = os.environ if environ is None else environ
key = env.get("XKRELAY_API_KEY", "").strip()
model = env.get("XKRELAY_MODEL", "").strip()
if not key or not model:
raise ValueError("Set XKRELAY_API_KEY and XKRELAY_MODEL")
request = urllib.request.Request(URL, method="POST", headers={
"Authorization": "Bearer " + key, "Content-Type": "application/json",
}, data=json.dumps({"model": model, "messages": [
{"role": "user", "content": "只回复 OK"}
]}).encode())
with (opener or urllib.request.urlopen)(request, timeout=60) as response:
data = json.load(response)
content = data["choices"][0]["message"].get("content")
if not isinstance(content, str):
raise ValueError("Expected a text response; check model/protocol support")
return content
if __name__ == "__main__":
try:
print(chat())
except urllib.error.HTTPError as error:
raise SystemExit(f"HTTP {error.code}: check the troubleshooting table and usage logs")
except (ValueError, KeyError, IndexError, urllib.error.URLError, TimeoutError):
raise SystemExit("Request/configuration error: check environment, protocol and usage logs")
Node.js 22+。设置 XKRELAY_MODEL,保存为 chat.mjs,运行 node chat.mjs。
import { pathToFileURL } from 'node:url';
export async function chat(env = process.env, fetcher = fetch) {
const key = env.XKRELAY_API_KEY?.trim();
const model = env.XKRELAY_MODEL?.trim();
if (!key || !model) throw new Error('Set XKRELAY_API_KEY and XKRELAY_MODEL');
const response = await fetcher('https://xkrelay.com/v1/chat/completions', {
method: 'POST',
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ model, messages: [{ role: 'user', content: '只回复 OK' }] }),
signal: AbortSignal.timeout(60_000),
});
if (!response.ok) throw new Error(`HTTP ${response.status}: check troubleshooting and usage logs`);
const data = await response.json();
const content = data.choices?.[0]?.message?.content;
if (typeof content !== 'string') throw new Error('Expected text; check model/protocol support');
return content;
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
chat().then(console.log).catch(() => {
console.error('Request/configuration error: check environment, protocol and usage logs');
process.exitCode = 1;
});
}
响应示例#
HTTP 200{
"id": "chatcmpl_example",
"object": "chat.completion",
"created": 1795824000,
"model": "YOUR_MODEL_ID",
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "OK"
},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 11,
"completion_tokens": 1,
"total_tokens": 12
}
}
非流式文本在 choices[0].message.content。
finish_reason是停止原因。stop表示模型正常停止,length表示达到长度限制。- 模型发起工具调用时,读取
choices[].message.tool_calls。这时content可能为空。 usage提供输入、输出及合计 Token 数。实际扣费见调用日志。
响应中的 model 是网关回填的模型标识。排查模型或路由问题时,请保留调用日志中的 request id。
请求参数#
| 参数 | 说明 |
|---|---|
modelstring · 必填 | 当前 Key 所属分组可用的完整模型 ID。 |
messagesarray · 必填 | 按顺序传入对话消息,每条包含 role。文本消息在 content 填文本,应用需要的历史消息也要随请求传入。 |
streamboolean · 可选 | 默认为 false。设为 true 可逐步读取 SSE 响应。 |
toolsarray · 可选 | 提供函数定义,供支持工具调用的模型选择。应用读取 tool_calls 后执行相应函数,并把结果作为角色为 tool 的消息传回。 |
流式响应#
请求加入 "stream": true。逐帧读取 SSE,文本增量在 choices[].delta.content,停止原因在 choices[].finish_reason。用 cURL 查看实时输出时加 -N。
data: {"choices":[{"index":0,"delta":{"content":"OK"},"finish_reason":null}]}
data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]
[DONE] 是流结束标记,单独处理即可。HTTP 200 后仍可能收到带 error 的数据帧,再收到 [DONE]。优先处理错误,并在没有完成信息的情况下把连接中断视为未完成。
遇到鉴权失败、路径错误或限流时,见常见报错与求助。