Communitygithub.com

ASoudy/AGS

OpenRouter API - 通过一个 API 统一访问 400+ 种 AI 模型

AGS 是什么?

此技能为开发者提供对 OpenRouter API 的全面支持,该 API 作为一个统一网关,通过单个端点即可访问来自多个提供商的数百种 AI 模型。其核心优势在于智能路由功能,包括自动选择最佳模型的 `openrouter/auto` 模式、用于故障转移的模型回退列表,以及跨提供商的自动故障切换,从而显著提升应用程序的可靠性。该技能完全兼容 OpenAI SDK,因此开发者可以无缝迁移现有代码。它还支持广泛的自定义,涵盖各种采样参数(如 temperature、top_p)、流式响应(SSE)、JSON 结构化输出模式、函数/工具调用,以及通过 seed 参数实现的可重现输出。此技能涵盖了从基础聊天补全到高级实施策略(如成本优化路由和上下文感知的温度调整)的所有内容,并引用了详细的参考文件,为使用 OpenRouter 构建健壮的 AI 应用提供了必要的指导。

兼容平台✓Claude Code✓Codex CLI~Cursor✓Gemini CLI
npx skills add https://github.com/ASoudy/AGS/tree/HEAD/claude_skills_libraries/landing-page-mastery/skills/openrouter

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

OpenRouter 技能

针对 OpenRouter API 开发的全面助手,通过一个端点提供对数百种 AI 模型的统一访问,支持智能路由、自动回退和标准化接口。

何时使用该技能

当出现以下情况时应触发该技能:

  • 通过统一接口向多个 AI 模型提供商发起 API 调用
  • 实施模型回退策略或自动路由
  • 使用兼容 OpenAI 的 SDK,但目标是多个提供商
  • 配置高级采样参数(temperature、top_p、penalties)
  • 设置流式响应或结构化 JSON 输出
  • 比较不同 AI 模型之间的成本
  • 构建需要自动提供商故障转移的应用程序
  • 跨不同模型实现函数/工具调用
  • 关于 OpenRouter 特定功能的问题(路由、回退、零补全保险)

快速参考

基础聊天补全 (Python)

from openai import OpenAI

client = OpenAI(
  base_url="https://openrouter.ai/api/v1",
  api_key="<OPENROUTER_API_KEY>",
)

completion = client.chat.completions.create(
  model="openai/gpt-4o",
  messages=[{"role": "user", "content": "What is the meaning of life?"}]
)
print(completion.choices[0].message.content)

基础聊天补全 (JavaScript/TypeScript)

import OpenAI from 'openai';

const openai = new OpenAI({
  baseURL: 'https://openrouter.ai/api/v1',
  apiKey: '<OPENROUTER_API_KEY>',
});

const completion = await openai.chat.completions.create({
  model: 'openai/gpt-4o',
  messages: [{"role": 'user', "content": 'What is the meaning of life?'}],
});
console.log(completion.choices[0].message);

cURL 请求

curl https://openrouter.ai/api/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -d '{
    "model": "openai/gpt-4o",
    "messages": [{"role": "user", "content": "What is the meaning of life?"}]
  }'

模型回退配置 (Python)

completion = client.chat.completions.create(
    model="openai/gpt-4o",
    extra_body={
        "models": ["anthropic/claude-3.5-sonnet", "gryphe/mythomax-l2-13b"],
    },
    messages=[{"role": "user", "content": "Your prompt here"}]
)

模型回退配置 (TypeScript)

const completion = await client.chat.completions.create({
    model: 'openai/gpt-4o',
    models: ['anthropic/claude-3.5-sonnet', 'gryphe/mythomax-l2-13b'],
    messages: [{ role: 'user', content: 'Your prompt here' }],
});

自动路由器(动态模型选择)

completion = client.chat.completions.create(
    model="openrouter/auto",  # 根据提示自动选择最佳模型
    messages=[{"role": "user", "content": "Your prompt here"}]
)

高级参数示例

completion = client.chat.completions.create(
    model="openai/gpt-4o",
    messages=[{"role": "user", "content": "Write a creative story"}],
    temperature=0.8,           # 值越高越有创造性 (0.0-2.0)
    max_tokens=500,            # 限制响应长度
    top_p=0.9,                 # 核采样 (0.0-1.0)
    frequency_penalty=0.5,     # 减少重复 (-2.0-2.0)
    presence_penalty=0.3       # 鼓励主题多样性 (-2.0-2.0)
)

流式响应

stream = client.chat.completions.create(
    model="openai/gpt-4o",
    messages=[{"role": "user", "content": "Tell me a story"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end='')

JSON 模式(结构化输出)

completion = client.chat.completions.create(
    model="openai/gpt-4o",
    messages=[{
        "role": "user",
        "content": "Extract person's name, age, and city from: John is 30 and lives in NYC"
    }],
    response_format={"type": "json_object"}
)

使用 Seed 实现确定性输出

completion = client.chat.completions.create(
    model="openai/gpt-4o",
    messages=[{"role": "user", "content": "Generate a random number"}],
    seed=42,            # 相同的 seed = 相同的输出(当支持时)
    temperature=0.0     # 确定性采样
)

关键概念

模型路由

OpenRouter 提供智能路由能力:

  • 自动路由器 (openrouter/auto):使用 NotDiamond 根据您的提示自动选择最佳模型
  • 回退模型:指定多个模型,如果主模型失败则自动重试
  • 提供商路由:自动跨提供商路由以确保可靠性

身份验证

  • 使用带有 API 密钥的 Bearer token 认证
  • 可以以编程方式管理 API 密钥
  • 兼容 OpenAI SDK 认证模式

模型命名约定

模型使用 provider/model-name 格式:

  • openai/gpt-4o - OpenAI 的 GPT-4 Optimized
  • anthropic/claude-3.5-sonnet - Anthropic 的 Claude 3.5 Sonnet
  • google/gemini-2.0-flash-exp:free - Google 的免费 Gemini 模型
  • openrouter/auto - 自动路由系统

采样参数

Temperature (0.0-2.0, 默认: 1.0)

  • 值越低 = 响应越可预测、越专注
  • 值越高 = 响应越有创造性、越多样化
  • 对于事实性任务使用低值 (0.0-0.3),对于创造性工作使用高值 (0.8-1.5)

Top P (0.0-1.0, 默认: 1.0)

  • 将选择范围限制在可能 token 的百分比内
  • 动态过滤不太可能出现的选项
  • 在一致性和多样性之间取得平衡

频率/存在惩罚 (-2.0-2.0, 默认: 0.0)

  • Frequency: 根据使用比例劝阻重复 tokens
  • Presence: 简单的惩罚,不按计数缩放
  • 正值减少重复,负值鼓励重复

Max Tokens (整数)

  • 设置最大响应长度
  • 不能超过上下文长度减去提示长度
  • 用于控制成本和强制简洁回复

响应格式

  • 标准 JSON:默认的聊天补全格式
  • 流式响应:使用 stream: true 的服务端推送事件 (SSE)
  • JSON 模式:使用 response_format: {"type": "json_object"} 保证有效的 JSON
  • 结构化输出:经过模式验证的 JSON 响应

高级功能

  • 工具/函数调用:将模型连接到外部 API
  • 多模态输入:支持图像、PDF、音频
  • 提示缓存:降低重复提示的成本
  • 网络搜索集成:使用网络数据增强响应
  • 零补全保险:防止响应失败
  • Logprobs:访问 token 概率以进行置信度分析

参考文件

此技能在 references/ 中包含全面的文档:

  • llms-full.md - 包含元数据的完整可用模型列表
  • llms-small.md - 精选的流行模型子集
  • llms.md - 标准模型列表

当需要详细的模型信息时,请使用 view 读取特定的参考文件。

使用此技能

对于初学者

  1. 从基础的聊天补全示例开始(上面的 Python/JavaScript/cURL)
  2. 使用标准的 OpenAI SDK 实现轻松集成
  3. 尝试简单的模型名称,如 openai/gpt-4o 或 anthropic/claude-3.5-sonnet
  4. 初始时保持参数简单(仅模型和消息)

对于中级用户

  1. 为实现可靠性实施模型回退数组
  2. 尝试采样参数(temperature、top_p)
  3. 在会话应用中使用流式响应以获得更好的用户体验
  4. 尝试使用 openrouter/auto 进行自动模型选择
  5. 使用 JSON 模式进行结构化数据提取

对于高级用户

  1. 同时微调多个采样参数
  2. 使用回退链实现自定义路由逻辑
  3. 使用 logprobs 进行置信度评分
  4. 利用工具/函数调用能力
  5. 通过为每个任务选择合适的模型来优化成本
  6. 实施提示缓存策略
  7. 使用 seed 参数进行可重现的测试

常见模式

包含回退的错误处理

try:
    completion = client.chat.completions.create(
        model="openai/gpt-4o",
        extra_body={
            "models": [
                "anthropic/claude-3.5-sonnet",
                "google/gemini-2.0-flash-exp:free"
            ]
        },
        messages=[{"role": "user", "content": "Your prompt"}]
    )
except Exception as e:
    print(f"All models failed: {e}")

成本优化路由

# 对简单任务使用更便宜的模型
simple_completion = client.chat.completions.create(
    model="google/gemini-2.0-flash-exp:free",
    messages=[{"role": "user", "content": "Simple question"}]
)

# 对复杂任务使用高级模型
complex_completion = client.chat.completions.create(
    model="openai/o1",
    messages=[{"role": "user", "content": "Complex reasoning task"}]
)

上下文感知的温度

# 低温度用于事实性响应
factual = client.chat.completions.create(
    model="openai/gpt-4o",
    temperature=0.2,
    messages=[{"role": "user", "content": "What is the capital of France?"}]
)

# 高温度用于创造性内容
creative = client.chat.completions.create(
    model="openai/gpt-4o",
    temperature=1.2,
    messages=[{"role": "user", "content": "Write a unique story opening"}]
)

资源

官方文档

关键端点

  • 聊天补全:POST https://openrouter.ai/api/v1/chat/completions
  • 列出模型:GET https://openrouter.ai/api/v1/models
  • 生成信息:GET https://openrouter.ai/api/v1/generation

备注

  • OpenRouter 标准化所有提供商的 API 模式
  • 使用兼容 OpenAI 的 API 格式,方便迁移
  • 如果模型受到速率限制或宕机,自动进行提供商回退
  • 定价基于实际使用的模型(对回退很重要)
  • 响应中包含有关哪个模型处理了请求的元数据
  • 所有模型都支持通过服务端推送事件进行流式传输
  • 与流行的框架兼容(LangChain、Vercel AI SDK 等)

最佳实践

  1. 始终为生产应用程序实施回退
  2. 根据任务类型使用适当的温度(事实性任务低,创造性任务高)
  3. 设置 max_tokens 以控制成本和响应长度
  4. 启用流式传输以获得更好的聊天应用用户体验
  5. 在需要保证结构化输出时使用 JSON 模式
  6. 在开发期间使用 seed 参数测试以获得可重现的结果
  7. 通过为每个任务选择合适的模型来监控成本
  8. 在不确定哪个模型性能最佳时使用自动路由
  9. 针对速率限制和失败实施适当的错误处理
  10. 为重复请求缓存提示以降低成本

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ASoudy/AGS

Advanced JavaScript animation library skill for creating complex, high-performance web animations.

ASoudy/AGS

Astropy is the core Python package for astronomy, providing essential functionality for astronomical research and data analysis.

ASoudy/AGS

Build content-focused websites with Astro — zero JS by default, islands architecture, multi-framework components, and Markdown/MDX support.

ASoudy/AGS

One sentence - what this skill does and when to invoke it

ASoudy/AGS

Audit and fix animation performance issues including layout thrashing, compositor properties, scroll-linked motion, and blur effects. Use when animations stutter, transitions jank, or reviewing CSS/JS animation performance.

ASoudy/AGS

Internationalization and localization patterns. Detecting hardcoded strings, managing translations, locale files, RTL support.

ASoudy/AGS

Pull a YouTube video transcript into a queryable markdown vault with yt-dlp subtitle discovery, VTT cleanup, metadata frontmatter, and capture-seed stubs.

ASoudy/AGS

Expert in building portfolios that actually land jobs and clients - not just showing work, but creating memorable experiences. Covers developer portfolios, designer portfolios, creative portfolios, and portfolios that convert visitors into opportunities.

ASoudy/AGS

Generates high-converting Next.js/React landing pages with Tailwind CSS. Uses PAS, AIDA, and BAB frameworks for optimized copy/components (Heroes, Features, Pricing). Focuses on Core Web Vitals/SEO.

ASoudy/AGS

AI-powered animation tool for creating motion in logos, UI, icons, and social media assets.

ASoudy/AGS

CRITICAL: Use for Makepad animation system. Triggers on: makepad animation, makepad animator, makepad hover, makepad state, makepad transition, "from: { all: Forward", makepad pressed, makepad 动画, makepad 状态, makepad 过渡, makepad 悬停效果

ASoudy/AGS

Comprehensive patterns for Next.js 14+ App Router architecture, Server Components, and modern full-stack React development.

ASoudy/AGS

Next.js App Router principles. Server Components, data fetching, routing patterns.

ASoudy/AGS

Expert integration of Supabase Auth with Next.js App Router

ASoudy/AGS

React and Next.js 14+ application development with App Router, Server Components, TypeScript, Tailwind CSS, and modern frontend patterns.

ASoudy/AGS

Best practices for Remotion - Video creation in React

ASoudy/AGS

Generate walkthrough videos from Stitch projects using Remotion with smooth transitions, zooming, and text overlays

ASoudy/AGS

Seek and analyze video content using Memories.ai Large Visual Memory Model for persistent video intelligence

ASoudy/AGS

Writes complete, structured landing pages optimized for SEO ranking, AEO citation, and visitor conversion. Activate when the user wants to write or generate a landing page for a product, service, or offer.

ASoudy/AGS

Skill for discovering and researching autonomous AI agents, tools, and ecosystems using the AgentFolio directory.

相关技能