创建聊天补全 (流式)
POST/v1/chat/completions 创建聊天补全(流式)
POST https://www.vortapapi.com/v1/chat/completions
向聊天模型发送一组消息,并以流式方式接收模型生成的回复。启用流式输出时,接口会逐步返回增量内容,适合需要边生成边展示的对话场景。
要使用流式响应,请在请求体中设置
stream: true。
请求头
| 名称 | 必填 | 说明 |
|---|---|---|
Content-Type | 是 | 请求体格式,通常为 application/json |
Accept | 是 | 建议设置为 text/event-stream 以接收流式数据 |
Authorization | 否 | API Key 鉴权信息,格式为 Bearer sk-*** |
X-Forwarded-Host | 否 | 可选的转发主机信息 |
请求示例
curl https://www.vortapapi.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
-H "Authorization: Bearer sk-***" \
-d '{
"model": "gpt-4o-mini",
"messages": [
{
"role": "user",
"content": "你好,请介绍一下 Vortap。"
}
],
"stream": true
}'
流式响应示例
启用 stream: true 后,服务会以 Server-Sent Events(SSE)的形式连续返回数据片段:
data: {
"id": "chatcmpl-123",
"object": "chat.completion.chunk",
"created": 1677652288,
"model": "gpt-4o-mini",
"choices": [
{
"index": 0,
"delta": {
"role": "assistant"
},
"finish_reason": null
}
]
}
data: {
"id": "chatcmpl-123",
"object": "chat.completion.chunk",
"created": 1677652288,
"model": "gpt-4o-mini",
"choices": [
{
"index": 0,
"delta": {
"content": "你好"
},
"finish_reason": null
}
]
}
data: {
"id": "chatcmpl-123",
"object": "chat.completion.chunk",
"created": 1677652288,
"model": "gpt-4o-mini",
"choices": [
{
"index": 0,
"delta": {
"content": ",有什么可以帮你?"
},
"finish_reason": null
}
]
}
data: [DONE]
非流式响应示例
如果未设置 stream: true,接口会在生成完成后一次性返回完整结果:
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1677652288,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "\n\nHello there, how may I assist you today?"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 9,
"completion_tokens": 12,
"total_tokens": 21
}
}