关于 openrouter-api
这是面向 OpenRouter API 集成者的技能,介绍通过统一 API 调用多种 LLM,并提供 HTTP、SDK 和 Agent SDK 等接入方式。内容还涵盖模型路由、工具调用、多模态请求及用量管理。
主要功能
- 01统一 API 调用多种 LLM
- 02提供 HTTP 和多语言 SDK 接入
- 03模型路由、回退与预设
- 04工具调用和 Agent 循环
- 05结构化输出与推理参数
- 06多模态输入及用量统计
适用场景
- 01在应用中接入不同提供方的模型
- 02为请求配置模型回退和提供方路由
- 03构建包含工具调用的 Agent 流程
- 04处理多模态输入并查看用量
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ thatjuan/ agent-skills --skill openrouter-api安装后在 Claude Code 中输入/openrouter-api确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
README.mdreferences/api-reference.mdbyok-and-oauth.mdmultimodal.mdplugins.mdprompt-caching.mdreasoning.mdrouting.mdstreaming.mdstructured-outputs.mdtool-calling.mdusage-and-limits.mdweb-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 SDK | openai,搭配 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 |
| 401 | API 密钥无效 / OAuth 已过期 |
| 402 | 信用额度不足——请添加额度 |
| 403 | 输入被审核系统标记 |
| 408 | 请求超时 |
| 429 | 触发速率限制 |
| 502 | 上游模型不可用 / 响应无效 |
| 503 | 没有提供商符合路由要求 |
流式传输过程中的错误(HTTP 200 已发送)会以最终 SSE 块的形式返回,其中顶层包含 error,并带有一个 finish_reason: "error" 的选项。请参阅 streaming.md。
功能一览
| 功能 | 触发条件 | 参考资料 |
|---|---|---|
| 采样参数、完整请求/响应架构、调试选项 | 任意聊天调用 | references/api-reference.md |
| SSE 流式传输、取消、中途出错 | stream: true | references/streaming.md |
| 函数/工具调用、Agent 循环、并行工具、流式工具调用、MCP 到 OpenAI 的转换 | tools: [...] | references/tool-calling.md |
结构化输出(json_schema、json_object) | response_format | references/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、音频、视频、图像生成、TTS | image_url/file/input_audio 内容部分 | references/multimodal.md |
插件——web、file-parser、response-healing、context-compression、auto-router | plugins: [...] | references/plugins.md |
openrouter:web_search 服务端工具、:online 快捷方式、引用注释 | tools: [{type:'openrouter:web_search'}] | references/web-search.md |
用量统计、费用、/generation、密钥/额度、速率限制 | usage 字段、GET /api/v1/key | references/usage-and-limits.md |
| BYOK 提供商密钥、OAuth PKCE、应用归属信息 | 在 /settings/integrations 配置的 cbat_ 样式提供商密钥 | references/byok-and-oauth.md |
始终获取最新文档
OpenRouter 支持在文档页面的 URL 后追加 .md 来获取 Markdown 格式的页面内容,并为每个章节提供汇总的 llms-full.txt 文件。当此处的参考资料不足以解决特定边缘情况时,请获取最新内容:
- 快速入门:https://openrouter.ai/docs/quickstart/llms-full.txt
- API 参考:https://openrouter.ai/docs/api/reference/llms-full.txt
- 功能:https://openrouter.ai/docs/guides/features/llms-full.txt
- 路由:https://openrouter.ai/docs/guides/routing/llms-full.txt
- 插件:https://openrouter.ai/docs/guides/features/plugins/llms-full.txt
- 多模态:https://openrouter.ai/docs/guides/overview/multimodal/llms-full.txt
- 最佳实践(缓存、推理):https://openrouter.ai/docs/guides/best-practices/llms-full.txt
- 身份验证(BYOK、OAuth):https://openrouter.ai/docs/guides/overview/auth/llms-full.txt
- 管理(用量统计):https://openrouter.ai/docs/guides/administration/llms-full.txt
- 服务端工具(网络搜索):https://openrouter.ai/docs/guides/features/server-tools/llms-full.txt
- OpenAPI 规范:
https://openrouter.ai/openapi.yaml或.json
在任意文档 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 }参数已弃用——现在始终会包含用量信息。