mcpField
O
openrouter-api

openrouter-api

github.com/thatjuan开发141 次安装3 周前更新
代码仓库

关于 openrouter-api

这是面向 OpenRouter API 集成者的技能,介绍通过统一 API 调用多种 LLM,并提供 HTTP、SDK 和 Agent SDK 等接入方式。内容还涵盖模型路由、工具调用、多模态请求及用量管理。

主要功能

  1. 01统一 API 调用多种 LLM
  2. 02提供 HTTP 和多语言 SDK 接入
  3. 03模型路由、回退与预设
  4. 04工具调用和 Agent 循环
  5. 05结构化输出与推理参数
  6. 06多模态输入及用量统计

适用场景

  1. 01在应用中接入不同提供方的模型
  2. 02为请求配置模型回退和提供方路由
  3. 03构建包含工具调用的 Agent 流程
  4. 04处理多模态输入并查看用量

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/thatjuan/agent-skills --skill openrouter-api

安装后在 Claude Code 中输入/openrouter-api确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

README.md
references/
api-reference.md
byok-and-oauth.md
multimodal.md
plugins.md
prompt-caching.md
reasoning.md
routing.md
streaming.md
structured-outputs.md
tool-calling.md
usage-and-limits.md
web-search.md

详细介绍

OpenRouter API

OpenRouter 是一个统一 API,接入了 300 多个大模型。其 /api/v1/chat/completions 接口的 Schema 与 OpenAI 兼容,并提供仅限 OpenRouter 的扩展(models[]、provider、plugins、reasoning、cache_control、预设和 :suffix 快捷方式)。身份验证使用 Authorization: Bearer <OPENROUTER_API_KEY>。

基础 URL 和身份验证

POST https://openrouter.ai/api/v1/chat/completions
Authorization: Bearer $OPENROUTER_API_KEY
Content-Type: application/json

可选归属标头(用于启用排行榜排名):

  • HTTP-Referer: <YOUR_SITE_URL>
  • X-OpenRouter-Title: <YOUR_SITE_NAME>(也接受 X-Title)
  • X-OpenRouter-Categories: <comma,separated>

API 密钥可在 https://openrouter.ai/keys 创建。每个密钥都支持信用额度限制,也可用于 OAuth 流程。OpenRouter 是 GitHub 的机密扫描合作伙伴——泄露的 sk-or-... 密钥会触发邮件通知。

三种集成方式

方式包最适用于
原始 HTTP无任意语言,无依赖
客户端 SDK@openrouter/sdk(npm)/ openrouter(pip)REST 的轻量类型安全封装
Agent SDK@openrouter/agent(仅 npm,TS)多轮循环、工具执行,以及通过 callModel 管理状态
OpenAI SDKopenai,搭配 baseURL: https://openrouter.ai/api/v1可直接用于现有 OpenAI 代码

默认使用 OpenRouter SDK。只有在用户明确要求时才参考 OpenAI SDK。

快速入门(TS SDK)
import OpenRouter from '@openrouter/sdk';

const client = new OpenRouter({ apiKey: process.env.OPENROUTER_API_KEY });

const completion = await client.chat.send({
  model: 'openai/gpt-5.2',
  messages: [{ role: 'user', content: 'What is the meaning of life?' }],
});
console.log(completion.choices[0].message.content);
快速入门(Python SDK)
from openrouter import OpenRouter
import os

with OpenRouter(api_key=os.getenv("OPENROUTER_API_KEY")) as client:
    response = client.chat.send(
        model="openai/gpt-5.2",
        messages=[{"role": "user", "content": "What is the meaning of life?"}],
    )
    print(response.choices[0].message.content)
快速入门(原始 HTTP)
curl https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"openai/gpt-5.2","messages":[{"role":"user","content":"hi"}]}'

模型标识符

格式:<provider>/<model>(例如 anthropic/claude-sonnet-4.6、openai/gpt-5.2、google/gemini-3-flash-preview、meta-llama/llama-3.3-70b-instruct、deepseek/deepseek-v3.2)。浏览全部模型:https://openrouter.ai/models。通过 API 列出模型:GET /api/v1/models?supported_parameters=tools&output_modalities=text。

后缀快捷方式
后缀效果等效设置
:nitro按吞吐量对提供商排序provider.sort = "throughput"
:floor按最低价格对提供商排序provider.sort = "price"
:online启用网络插件(已弃用——建议改用 openrouter:web_search 服务端工具)plugins: [{id: "web"}] 搭配 openrouter/auto
:free免费层变体(有速率限制和每日上限)—

可组合使用:openai/gpt-oss-20b:free:online。

特殊模型标识
  • openrouter/auto — Auto Router(由 NotDiamond 提供支持,可根据提示词选择模型)
  • openrouter/bodybuilder — 将自然语言转换为结构化请求正文,以并行调用多个模型(免费)
  • @preset/<slug> — 按名称调用已保存的预设(系统提示词 + 参数 + 提供商规则)。在 https://openrouter.ai/settings/presets 配置。也可用作 preset: "<slug>" 字段,或使用 model: "openai/gpt-4@preset/<slug>"(组合方式)。每次请求的参数会浅层合并到预设配置中。

请求正文——顶层结构

type Request = {
  // Either messages or prompt
  messages?: Message[];
  prompt?: string;

  model?: string;           // omit = user default
  models?: string[];        // model fallbacks in order

  stream?: boolean;
  stop?: string | string[];
  response_format?: ResponseFormat;       // json_object | json_schema
  tools?: Tool[];
  tool_choice?: ToolChoice;
  parallel_tool_calls?: boolean;          // default true

  // OpenRouter-only
  provider?: ProviderPreferences;         // see references/routing.md
  plugins?: Plugin[];                     // web, file-parser, response-healing, context-compression, auto-router
  reasoning?: ReasoningConfig;            // see references/reasoning.md
  preset?: string;
  user?: string;                          // stable end-user ID for abuse detection
  debug?: { echo_upstream_body?: boolean }; // streaming only

  // Standard sampling — see references/api-reference.md
  max_tokens?: number;
  temperature?: number;
  top_p?: number; top_k?: number; min_p?: number; top_a?: number;
  frequency_penalty?: number; presence_penalty?: number; repetition_penalty?: number;
  seed?: number; logit_bias?: Record<number, number>;
  logprobs?: boolean; top_logprobs?: number;
  prediction?: { type: 'content'; content: string };
  verbosity?: 'low' | 'medium' | 'high' | 'xhigh' | 'max';
};

所选模型不支持的参数会被静默忽略,其余参数会转发至上游。若要要求提供商支持所有参数,请设置 provider.require_parameters: true。

响应结构

{
  "id": "gen-xxxxxxxxxxxxxx",
  "model": "openai/gpt-4o",
  "object": "chat.completion",
  "choices": [{
    "finish_reason": "stop",
    "native_finish_reason": "stop",
    "message": { "role": "assistant", "content": "Hello there!" }
  }],
  "usage": {
    "prompt_tokens": 10,
    "completion_tokens": 4,
    "total_tokens": 14,
    "prompt_tokens_details": { "cached_tokens": 0, "cache_write_tokens": 0 },
    "completion_tokens_details": { "reasoning_tokens": 0 },
    "cost": 0.00014
  }
}

流式传输块使用 delta 而非 message,并且 object: "chat.completion.chunk"。data: [DONE] 之前的最后一个块会携带 usage,且 choices 为空。

finish_reason 会规范化为以下值之一:tool_calls、stop、length、content_filter、error。提供商返回的原始值位于 native_finish_reason 中。响应标头 X-Generation-Id 也会返回生成 ID。

错误

{ "error": { "code": 400, "message": "...", "metadata": { ... } } }
代码含义
400请求错误 / 参数无效 / CORS
401API 密钥无效 / OAuth 已过期
402信用额度不足——请添加额度
403输入被审核系统标记
408请求超时
429触发速率限制
502上游模型不可用 / 响应无效
503没有提供商符合路由要求

流式传输过程中的错误(HTTP 200 已发送)会以最终 SSE 块的形式返回,其中顶层包含 error,并带有一个 finish_reason: "error" 的选项。请参阅 streaming.md。

功能一览

功能触发条件参考资料
采样参数、完整请求/响应架构、调试选项任意聊天调用references/api-reference.md
SSE 流式传输、取消、中途出错stream: truereferences/streaming.md
函数/工具调用、Agent 循环、并行工具、流式工具调用、MCP 到 OpenAI 的转换tools: [...]references/tool-calling.md
结构化输出(json_schema、json_object)response_formatreferences/structured-outputs.md
推理/思考令牌(effort、max_tokens、exclude)reasoning: {...}references/reasoning.md
提示词缓存(自动、cache_control、粘性路由)cache_control 或受支持的提供商references/prompt-caching.md
提供商路由(sort、order、only、ignore、max_price、throughput、ZDR)provider: {...}references/routing.md
模型回退、自动路由器、请求体构建器、预设models[]、openrouter/auto、@preset/...references/routing.md
多模态——图像、PDF、音频、视频、图像生成、TTSimage_url/file/input_audio 内容部分references/multimodal.md
插件——web、file-parser、response-healing、context-compression、auto-routerplugins: [...]references/plugins.md
openrouter:web_search 服务端工具、:online 快捷方式、引用注释tools: [{type:'openrouter:web_search'}]references/web-search.md
用量统计、费用、/generation、密钥/额度、速率限制usage 字段、GET /api/v1/keyreferences/usage-and-limits.md
BYOK 提供商密钥、OAuth PKCE、应用归属信息在 /settings/integrations 配置的 cbat_ 样式提供商密钥references/byok-and-oauth.md

始终获取最新文档

OpenRouter 支持在文档页面的 URL 后追加 .md 来获取 Markdown 格式的页面内容,并为每个章节提供汇总的 llms-full.txt 文件。当此处的参考资料不足以解决特定边缘情况时,请获取最新内容:

在任意文档 URL 后追加 .md,即可获取该页面的纯 Markdown 内容。

常见陷阱

  • prompt 和 messages 不能同时使用——选择其中一个。
  • 在 Agent 循环的每一轮中都必须重复提供 tools 数组。路由器会在每次调用时验证架构。如果在工具结果消息之前,没有将助手的工具调用消息追加到历史记录中,就会导致 Anthropic 模型出错。
  • Anthropic 的自动缓存(顶层 cache_control)只会路由到 Anthropic 提供商——Bedrock 和 Vertex AI 不在支持范围内。按块设置的 cache_control 可用于这三者。
  • max_tokens 上限为 context_length - prompt_length,并非没有上限。
  • OpenAI o 系列和部分推理模型不会返回推理 token,即使这些 token 在内部已生成。reasoning.exclude: true 控制的是可见性,而非内部使用。
  • debug.echo_upstream_body 仅在 stream: true 时有效,且仅用于开发——它可能会泄露请求内部信息。
  • :online 快捷方式使用的是已弃用的 web 插件,并通过 openrouter/auto 路由。新代码使用 openrouter:web_search 服务端工具,由模型决定何时搜索。
  • 流传输过程中的错误仍会返回 HTTP 200,因为响应头已经发送。可通过数据块顶层的 error 字段以及 finish_reason: "error" 检测此类错误。
  • BYOK 密钥始终优先于 OpenRouter 共享容量尝试使用,无论 provider.order 如何设置。
  • 免费层(:free)的速率限制按账户全局计算——增加 API 密钥不会提高配额。
  • usage: { include: true } 和 stream_options: { include_usage: true } 参数已弃用——现在始终会包含用量信息。

评论

支持 Markdown