对话补全

创建模型响应,用于处理单轮或多轮对话。这是最常用的端点,兼容 OpenAI Chat Completions 协议。

基本信息

方法POST 端点https://koprouter.kopglobal.com/v1/chat/completions 鉴权Authorization: Bearer sk-...

请求参数

参数 类型 必填 说明
model string 是 要调用的模型 ID,取自 /v1/models 返回的 id
messages array 是 对话消息列表,每条包含 role 与 content
temperature number 否 采样温度,范围 0~2,默认 1
top_p number 否 核采样概率,范围 0~1
max_tokens number 否 生成的最大 token 数
stream boolean 否 是否流式返回,默认 false
stop string/array 否 停止符,命中即停止生成
tools array 否 工具定义列表,用于工具调用
tool_choice string/object 否 工具调用策略,如 auto、none
response_format object 否 输出格式约束,如 JSON 模式
n number 否 一次请求生成的候选数

请求示例

curl https://koprouter.kopglobal.com/v1/chat/completions \
  -H "Authorization: Bearer sk-..." \
  -H "Content-Type: application/json" \
  -d '{
    "model": "MODEL_ID",
    "messages": [
      { "role": "system", "content": "You are a helpful assistant." },
      { "role": "user", "content": "你好,介绍一下你自己。" }
    ],
    "temperature": 0.7
  }'

响应示例

{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1720000000,
  "model": "MODEL_ID",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "你好!我是一个 AI 助手。"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 18,
    "completion_tokens": 12,
    "total_tokens": 30
  }
}

流式响应

设置 stream: true 后,响应以 Server-Sent Events(SSE)形式返回,每段数据形如:

data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"你"},"finish_reason":null}]}

data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"好"},"finish_reason":null}]}

data: [DONE]
使用官方 SDK 时,传入 `stream: true` 即可自动处理 SSE 分片,无需手动解析 `data:` 行。 `usage` 中的 `prompt_tokens` 与 `completion_tokens` 是计费依据,按模型单价乘以对应 token 数结算。