Skip to content

OpenRouter API 与 OpenAI Chat API 非常相似,跨模型和提供商统一了 schema。本页涵盖请求和响应的完整 TypeScript 类型定义,包括 messages 格式(文本/图片)、结构化输出(json_object/json_schema)、插件(web search/response-healing)、HTTP 请求头、Assistant 预填充,以及响应中的 usage 字段(含费用信息)。

OpenRouter API 参考

OpenRouter 的请求和响应 schema 与 OpenAI Chat API 非常相似,有少量差异。核心设计是跨模型和提供商统一 schema,只需学一套即可。

OpenAPI 规范

完整 OpenRouter API 以 OpenAPI 规范记录,可通过 YAML 或 JSON 格式访问,并与 Swagger UI、Postman 等工具兼容。


请求格式

/api/v1/chat/completions 发送 POST 请求,完整参数说明见参数文档

完整请求 Schema

typescript
type Request = {
  messages?: Message[];
  prompt?: string;
  model?: string;
  response_format?: ResponseFormat;
  stop?: string | string[];
  stream?: boolean;
  plugins?: Plugin[];
  max_tokens?: number;
  temperature?: number;
  tools?: Tool[];
  tool_choice?: ToolChoice;
  seed?: number;
  top_p?: number;
  top_k?: number;
  frequency_penalty?: number;
  presence_penalty?: number;
  repetition_penalty?: number;
  logit_bias?: { [key: number]: number };
  top_logprobs?: number;
  min_p?: number;
  top_a?: number;
  prediction?: { type: 'content'; content: string };
  models?: string[];      // 多模型 fallback 列表
  route?: 'fallback';
  provider?: ProviderPreferences;
  user?: string;
};

Message 类型

typescript
type TextContent = {
  type: 'text';
  text: string;
};

type ImageContentPart = {
  type: 'image_url';
  image_url: {
    url: string;    // 图片 URL 或 base64 data URL
    detail?: string;
  };
};

type ContentPart = TextContent | ImageContentPart;

type Message =
  | {
      role: 'user' | 'assistant' | 'system';
      content: string | ContentPart[];
      name?: string;
    }
  | {
      role: 'tool';
      content: string;
      tool_call_id: string;
      name?: string;
    };

HTTP 请求头

在请求头中添加你的应用信息,可以让你的应用出现在 OpenRouter 排行榜上:

typescript
fetch('https://openrouter.ai/api/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer <OPENROUTER_API_KEY>',
    'HTTP-Referer': '<YOUR_SITE_URL>',        // 可选,用于排行榜
    'X-OpenRouter-Title': '<YOUR_SITE_NAME>', // 可选,用于排行榜
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'openai/gpt-4o',
    messages: [{ role: 'user', content: '你好' }],
  }),
});

结构化输出

使用 response_format 强制模型输出 JSON:

json
// JSON 对象模式(保证返回有效 JSON)
{ "type": "json_object" }

// JSON Schema 模式(返回匹配你的 schema 的 JSON)
{
  "type": "json_schema",
  "json_schema": { ... }
}

使用 JSON 模式时,还需在 system 或 user message 中指示模型输出 JSON。


插件

在请求中启用额外功能:

json
{
  "plugins": [
    { "id": "web" },             // 网页搜索
    { "id": "response-healing" } // 响应修复
  ]
}

Assistant 预填充

通过在 messages 末尾添加 assistant role 的消息来预填充部分响应:

json
{
  "model": "openai/gpt-4o",
  "messages": [
    { "role": "user", "content": "生命的意义是什么?" },
    { "role": "assistant", "content": "我认为" }
  ]
}

响应格式

响应 Schema

typescript
type Response = {
  id: string;
  choices: (NonStreamingChoice | StreamingChoice | NonChatChoice)[];
  created: number;
  model: string;
  object: 'chat.completion' | 'chat.completion.chunk';
  system_fingerprint?: string;
  usage?: ResponseUsage;
};

Usage 字段

包含 token 计数和费用信息:

typescript
type ResponseUsage = {
  prompt_tokens: number;
  completion_tokens: number;
  total_tokens: number;
  prompt_tokens_details?: {
    cached_tokens: number;
    cache_write_tokens?: number;
    audio_tokens?: number;
  };
  completion_tokens_details?: {
    reasoning_tokens?: number;
    audio_tokens?: number;
    image_tokens?: number;
  };
  cost?: number;         // 本次请求的费用(美元)
  is_byok?: boolean;     // 是否使用了 BYOK key
};

响应示例

json
{
  "id": "gen-xxxxxxxxxxxxxx",
  "choices": [
    {
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": "你好!"
      }
    }
  ],
  "usage": {
    "prompt_tokens": 10,
    "completion_tokens": 4,
    "total_tokens": 14,
    "cost": 0.00014
  },
  "model": "openai/gpt-4o"
}

Finish Reason 值

含义
stop正常完成
length达到 max_tokens 限制
tool_calls模型调用了工具
content_filter内容被过滤
error发生错误

常见问题

Q: 如果选择的模型不支持某个参数会怎样?

A: OpenRouter 会忽略不支持的参数,不会报错。建议通过 Models API 的 supported_parameters 字段提前确认。

Q: 如何查询某次请求的详细统计信息?

A: 使用 /api/v1/generation?id=<GENERATION_ID> 端点(需要带 Authorization header)。

Q: OpenRouter 支持哪些流式输出格式?

A: 使用 SSE(Server-Sent Events),设置 stream: true 即可。详见 streaming 文档