この記事の内容
実際に
Pythonで 使う OpenRout er: 1つの APIキーであらゆる LLMを 利用
AIアプリケーションの

OpenRouterとは?
OpenRouterは、
プロバイダーごとに
OpenRouterを使う理由
すでに
最適な
モデルへの ルーティング:プロンプトに 応じて 異なる モデルに 振り分けるための 複数の 方法が あります。 たとえば、 「model」に 「openrouter/auto」を 指定すると、AutoRouterが プロンプトに 最適な モデルを 選択します。 信頼性と
冗長性:OpenRouterは フェイルオーバー機能を 備えており、 ある プロバイダーが 停止した 場合に、 アプリケーションを 別の プロバイダーに 切り替えられます。 OpenAI互換API:OpenAIの
SDKを すでに お使いの 場合、 コードを ほとんど 変更せずに OpenRouterへ 切り替えられます。
最小限のOpenRouter実装
Pythonでopenrouter_simple.pyの
"""
Minimal example for using OpenRouter with the OpenAI client directly.
This is the simplest way to get started with OpenRouter.
"""
import os
import pathlib
from dotenv import load_dotenv
from openai import OpenAI
# Get the current directory and load .env file
current_dir = pathlib.Path(__file__).parent.absolute()
env_path = current_dir / '.env'
load_dotenv(dotenv_path=env_path)
# Get API key from environment
api_key = os.environ.get("OPENROUTER_API_KEY")
# Check if API key is available
if not api_key:
raise ValueError("OpenRouter API key not found. Please set OPENROUTER_API_KEY in your .env file.")
# Create a client for OpenRouter
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=api_key,
default_headers={"HTTP-Referer": "http://localhost:5000"} # Required by OpenRouter
)
# Send a message to the model
response = client.chat.completions.create(
model="openai/gpt-3.5-turbo", # You can change this to any supported model
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello, who are you?"}
]
)
# Display the response
print(response.choices[0].message.content)この
1. 環境のセットアップ
まず、.envファイルから
# Get the current directory and load .env file
current_dir = pathlib.Path(__file__).parent.absolute()
env_path = current_dir / '.env'
load_dotenv(dotenv_path=env_path)
# Get API key from environment
api_key = os.environ.get("OPENROUTER_API_KEY")
# Check if API key is available
if not api_key:
raise ValueError("OpenRouter API key not found. Please set OPENROUTER_API_KEY in your .env file.")OpenRouterの.envファイルを
OPENROUTER_API_KEY=your_openrouter_api_keyopenrouter.aiで
2. OpenAIクライアントの設定
ポイントと
# Create a client for OpenRouter
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=api_key,
default_headers={"HTTP-Referer": "http://localhost:5000"} # Required by OpenRouter
)標準の
リクエスト元をHTTP-Refererヘッダーが
3. モデルの選択とリクエスト
リクエストを
# Send a message to the model
response = client.chat.completions.create(
model="openai/gpt-3.5-turbo", # You can change this to any supported model
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello, who are you?"}
]
)モデル識別子はprovider/model-nameの
openai/gpt-4o-2024-11-20- 知識のカットオフ日が 指定された OpenAIの GPT-4o (Omni) anthropic/claude-sonnet-4- AnthropicのClaude 4 Sonnet google/gemini-2.5-pro-preview- GoogleのGemini Pro 2.5 (プレビュー版) meta-llama/llama-4-maverick- MetaのLlama 4 17B Instruct
OpenRouterを
4. レスポンスの処理
最後に、
1# Display the response
2print(response.choices[0].message.content)レスポンスの
OpenRouterの機能とオプション
上記の
モデルルーティングの制御
OpenRouterでは、
# Provider preference ordering
response = client.chat.completions.create(
model="meta-llama/llama-3.1-8b-instruct",
messages=[{"role": "user", "content": "Hello!"}],
extra_body={"provider": {"order": ["together", "fireworks", "perplexity"]}}
)
# Quantization preferences (only for open-source models)
response = client.chat.completions.create(
model="meta-llama/llama-3.1-8b-instruct", # Must use open-source model
messages=[{"role": "user", "content": "Hello!"}],
extra_body={"provider": {"quantizations": ["fp8"]}}
)
# Fallback control
response = client.chat.completions.create(
model="meta-llama/llama-3.1-8b-instruct",
messages=[{"role": "user", "content": "Hello!"}],
extra_body={"provider": {"allow_fallbacks": True}}
)
# Data collection control
response = client.chat.completions.create(
model="openai/gpt-3.5-turbo",
messages=[{"role": "user", "content": "Hello!"}],
extra_body={"provider": {"data_collection": "deny"}}
)この
レスポンスのストリーミング
OpenRouterは
stream = client.chat.completions.create(
model="anthropic/claude-3-sonnet",
messages=[
{"role": "user", "content": "Tell me about renewable energy benefits"}
],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)ビジョン言語モデル
OpenRouterは、
import base64
# Method 1: Using local image files
def encode_image_to_base64(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
base64_image = encode_image_to_base64("your_image.png")
response = client.chat.completions.create(
model="openai/gpt-4o", # GPT-4o works reliably for vision
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{base64_image}"}}
]
}
]
)
# Method 2: Using image URLs
response = client.chat.completions.create(
model="openai/gpt-4o",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}
]
}
]
)料金とコスト管理
OpenRouterは
OpenRouterの
クイックスタート
この
openrouter.aiで
OpenRouterアカウントを 作成します openrouter.ai/settings/keysで
APIキーを 作成します
必要な
pip install openai python-dotenv
APIキーを.envファイルを
OPENROUTER_API_KEY=your_openrouter_api_keyサンプルスクリプトを
python openrouter_simple.pyまとめ
OpenRouterは、
AIアプリケーションを
特定の
プロバイダーに 固定される ことなく、 さまざまな モデルを テストする タスクごとに
最適な モデルを 利用する 信頼性を
高める フォールバックを 実装する ユースケースごとに
最も コスト効率の 高い モデルを 選び、 コストを 最適化する
付属のopenrouter_simple.pyスクリプトを
SnykでAIの実装を安全に
OpenRouterなどの
Snyk AI Security Platform
SnykのAI Security Platformは、
AI Security Platformは、
Snyk AI Security Platformを
オープンソース向けSnyk Secure Developer Program
OpenRouterなどの
参加要件を
エンタープライズレベルの
セキュリティツール:Snykの プレミアムセキュリティプラットフォームを 無料で 利用 専門家に
よる サポート:Snykの デベロッパーリレーションズチームに よる 実践的な 支援 コミュニティリソース:Snykの
Discordコミュニティと Partner Connectを 利用 APIアクセス:セキュリティチェックを
自動化する ための 連携機能
Snykは、
OpenRouterの
詳細に