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 Optimizedanthropic/claude-3.5-sonnet- Anthropic 的 Claude 3.5 Sonnetgoogle/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 讀取特定的參考檔案。
使用此技能
初學者
- 從基本聊天補全範例開始(上面的 Python/JavaScript/cURL)
- 使用標準的 OpenAI SDK 輕鬆整合
- 嘗試簡單的模型名稱,例如
openai/gpt-4o或anthropic/claude-3.5-sonnet - 初期保持參數簡單(僅使用 model 和 messages)
中階使用者
- 實作模型備援陣列以提高可靠性
- 嘗試採樣參數 (temperature、top_p)
- 在對話式應用程式中使用串流以獲得更好的使用者體驗
- 嘗試
openrouter/auto進行自動模型選擇 - 實作 JSON 模式以提取結構化資料
進階使用者
- 同時微調多個採樣參數
- 使用備援鏈實作自訂路由邏輯
- 使用 logprobs 進行信心評分
- 善用工具/函式呼叫功能
- 為每個任務選擇適當的模型以最佳化成本
- 實作提示快取策略
- 使用 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"}]
)
資源
官方文件
- API 參考:https://openrouter.ai/docs/api-reference/overview
- 快速入門指南:https://openrouter.ai/docs/quickstart
- 模型列表:https://openrouter.ai/docs/models
- 參數指南:https://openrouter.ai/docs/api-reference/parameters
主要端點
- 聊天補全:
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 等)
最佳實務
- 在生產應用程式中務必實作備援
- 根據任務類型使用適當的 temperature(事實性任務用低值,創意工作用高值)
- 設定 max_tokens 以控制成本與回應長度
- 啟用串流以在聊天應用程式中獲得更好的使用者體驗
- 需要保證結構化輸出時使用 JSON 模式
- 在開發期間使用 seed 參數測試以獲得可重現結果
- 監控成本,為每個任務選擇適當的模型
- 不確定哪個模型表現最好時使用自動路由
- 針對速率限制與故障實作適當的錯誤處理
- 快取重複請求的提示詞以降低成本