Communitygithub.com

OpenRouter API 技能

透過單一 API 統一存取超過 400 種 AI 模型,提供智慧路由、自動備援與標準化介面。

OpenRouter API 技能 是什麼?

此技能旨在協助開發者使用 OpenRouter API,透過單一端點統一存取來自多家供應商的數百種 AI 模型。它支援標準的 OpenAI 相容 SDK,因此能與現有程式碼庫無縫整合。技能文件涵蓋了基本聊天補全、模型備援設定、`openrouter/auto` 自動路由、進階採樣參數(如 temperature、top_p、頻率懲罰與存在懲罰)、串流回應與結構化 JSON 輸出。它也說明了模型命名慣例(例如 `openai/gpt-4o` 或 `anthropic/claude-3.5-sonnet`)、支援的功能如工具/函式呼叫、多模態輸入與提示快取。文件提供了 Python、TypeScript 與 cURL 的實用範例,並針對初學者、中階與進階使用者區分使用策略。此外,還包含了模型清單的參考文件(位於 `references/` 資料夾內)與官方文件連結。無論是建構聊天機器人、自動化工作流程或成本最佳化,此技能都能提供必要的指導。

相容平台✓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、懲罰值)
  • 設定串流回應或結構化 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,                 # Nucleus 採樣 (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,            # 相同種子 = 相同輸出 (當支援時)
    temperature=0.0     # 確定性採樣
)

關鍵概念

模型路由

OpenRouter 提供智慧路由功能:

  • 自動路由器 (openrouter/auto):使用 NotDiamond 根據您的提示詞自動選擇最佳模型
  • 備援模型:指定多個模型,當主要模型失敗時自動重試
  • 供應商路由:自動在多個供應商之間路由以確保可靠性

驗證

  • 使用 API 金鑰的 Bearer Token 驗證
  • API 金鑰可透過程式管理
  • 與 OpenAI SDK 驗證模式相容

模型命名慣例

模型使用 供應商/模型名稱 的格式:

  • 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)

  • 頻率:根據使用比例抑制重複 token
  • 存在:較簡單的懲罰,不按計數縮放
  • 正值減少重複,負值鼓勵重複使用

Max Tokens (整數)

  • 設定最大回應長度
  • 不得超過提示詞長度減去上下文長度
  • 用於控制成本與強制回應簡潔

回應格式

  • 標準 JSON:預設聊天補全格式
  • 串流:使用 stream: true 的伺服器發送事件 (SSE)
  • JSON 模式:使用 response_format: {"type": "json_object"} 保證有效的 JSON
  • 結構化輸出:經過 Schema 驗證的 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. 初期保持參數簡單(僅使用 model 和 messages)

中階使用者

  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"}]
)

上下文感知的 Temperature

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

# 創意內容使用高 temperature
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 Schema
  • 使用 OpenAI 相容的 API 格式,便於遷移
  • 若模型遇到速率限制或故障,會自動進行供應商備援
  • 定價基於實際使用的模型(備援時特別重要)
  • 回應中包含處理請求的模型元資料
  • 所有模型都透過伺服器發送事件支援串流
  • 與主流框架相容(LangChain、Vercel AI SDK 等)

最佳實務

  1. 在生產應用程式中務必實作備援
  2. 根據任務類型使用適當的 temperature(事實性任務用低值,創意工作用高值)
  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.

相關技能