Chat Completions

使用 OpenAI 兼容的 Chat Completions 接口进行消息式文本生成。

POST https://getrouter.ai/v1/chat/completions

基础请求

curl https://getrouter.ai/v1/chat/completions \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "MODEL_ID",
    "messages": [
      {"role": "system", "content": "请清晰、简洁地回答。"},
      {"role": "user", "content": "API 网关有什么作用?"}
    ]
  }'

非流式响应的生成内容位于:

choices[0].message.content

模型返回用量时,Token 用量位于 usage 对象中。

Python

from openai import OpenAI

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://getrouter.ai/v1",
)

response = client.chat.completions.create(
    model="MODEL_ID",
    messages=[
        {"role": "system", "content": "请清晰、简洁地回答。"},
        {"role": "user", "content": "API 网关有什么作用?"},
    ],
)

print(response.choices[0].message.content)

Node.js / TypeScript

import OpenAI from 'openai'

const client = new OpenAI({
  apiKey: 'YOUR_API_KEY',
  baseURL: 'https://getrouter.ai/v1',
})

const response = await client.chat.completions.create({
  model: 'MODEL_ID',
  messages: [
    { role: 'system', content: '请清晰、简洁地回答。' },
    { role: 'user', content: 'API 网关有什么作用?' },
  ],
})

console.log(response.choices[0]?.message.content)

消息角色

接口 Schema 支持以下角色:

角色用途
system高层行为或上下文
developer支持该角色的模型所使用的开发者指令
user用户输入
assistant历史 Assistant 输出
toolTool Call 的执行结果

常用请求字段

字段说明
model必填的模型 ID
messages必填的有序消息列表
stream设置为 true 时返回增量数据
temperature所选模型支持的采样控制参数
top_p核采样参数
max_tokens兼容模型的最大生成 Token 数
max_completion_tokens兼容模型的补全长度限制
tools支持 Tool Calling 的模型所使用的工具定义
tool_choice控制工具选择
response_format兼容模型的结构化响应配置
reasoning_effort兼容推理模型的 lowmediumhigh

不要向模型发送其不支持的可选字段。

多模态输入

消息内容支持文本、图片 URL、输入音频、文件和视频 URL 等类型,实际可用性取决于模型。

图片输入示例:

{
  "model": "MODEL_ID",
  "messages": [
    {
      "role": "user",
      "content": [
        {"type": "text", "text": "描述这张图片。"},
        {
          "type": "image_url",
          "image_url": {"url": "https://example.com/image.jpg"}
        }
      ]
    }
  ]
}

Tool Calling

兼容模型返回 tool_calls 后,应用需要执行对应函数,并追加带有相同 tool_call_idtool 消息。Tool 支持和具体行为取决于模型。

流式输出

stream 设置为 true,从各个 Chunk 的 choices[0].delta.content 读取文本。完整示例请查看流式输出

错误

  • 400 — 请求字段无效或参数不支持
  • 401 — API Key 缺失或无效
  • 429 — 触发频率、额度或容量限制
  • 模型错误 — 模型 ID 不正确或接口不匹配

下一步