OpenRouter
OpenRouter
LiteLLM에서 OpenRouter의 텍스트·채팅·비전·임베딩 모델을 모두 사용하는 방법을 알아봐요.
출처: 문서
본문
LiteLLM은 OpenRouter의 모든 텍스트/채팅/비전/임베딩 모델을 지원해요.
사용법
import os
from litellm import completion
os.environ["OPENROUTER_API_KEY"] = ""
os.environ["OPENROUTER_API_BASE"] = "" # [OPTIONAL] defaults to https://openrouter.ai/api/v1
os.environ["OR_SITE_URL"] = "" # [OPTIONAL]
os.environ["OR_APP_NAME"] = "" # [OPTIONAL]
response = completion(
model="openrouter/google/palm-2-chat-bison",
messages=messages,
)
환경 변수로 구성
프로덕션 환경에서는 환경 변수로 base_url을 동적으로 구성할 수 있어요:
import os
from litellm import completion
# Configure with environment variables
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
OPENROUTER_BASE_URL = os.getenv("OPENROUTER_API_BASE", "https://openrouter.ai/api/v1")
# Set environment for LiteLLM
os.environ["OPENROUTER_API_KEY"] = OPENROUTER_API_KEY
os.environ["OPENROUTER_API_BASE"] = OPENROUTER_BASE_URL
response = completion(
model="openrouter/google/palm-2-chat-bison",
messages=messages,
base_url=OPENROUTER_BASE_URL # Explicitly pass base_url for clarity
)
이 방식은 다양한 환경(dev, staging, production) 간 설정 관리에 유연성을 제공하고, 자체 호스팅과 클라우드 엔드포인트 사이를 전환하기 쉬워요.
OpenRouter 완성 모델
🚨 LiteLLM은 모든 OpenRouter 모델을 지원해요. model=openrouter/을 보내면 open router로 전송돼요. 모든 openrouter 모델은 여기에서 볼 수 있어요.
| 모델명 | 함수 호출 |
|---|---|
| openrouter/openai/gpt-3.5-turbo | completion('openrouter/openai/gpt-3.5-turbo', messages) |
| openrouter/openai/gpt-3.5-turbo-16k | completion('openrouter/openai/gpt-3.5-turbo-16k', messages) |
| openrouter/openai/gpt-4 | completion('openrouter/openai/gpt-4', messages) |
| openrouter/openai/gpt-4-32k | completion('openrouter/openai/gpt-4-32k', messages) |
| openrouter/anthropic/claude-2 | completion('openrouter/anthropic/claude-2', messages) |
| openrouter/anthropic/claude-instant-v1 | completion('openrouter/anthropic/claude-instant-v1', messages) |
| openrouter/google/palm-2-chat-bison | completion('openrouter/google/palm-2-chat-bison', messages) |
| openrouter/google/palm-2-codechat-bison | completion('openrouter/google/palm-2-codechat-bison', messages) |
| openrouter/meta-llama/llama-2-13b-chat | completion('openrouter/meta-llama/llama-2-13b-chat', messages) |
| openrouter/meta-llama/llama-2-70b-chat | completion('openrouter/meta-llama/llama-2-70b-chat', messages) |
OpenRouter 파라미터 전달 - transforms, models, route
transforms, models, route를 litellm.completion()의 인자로 전달해요.
import os
from litellm import completion
os.environ["OPENROUTER_API_KEY"] = ""
response = completion(
model="openrouter/google/palm-2-chat-bison",
messages=messages,
transforms = [""],
route= ""
)
임베딩
from litellm import embedding
import os
os.environ["OPENROUTER_API_KEY"] = "your-api-key"
response = embedding(
model="openrouter/openai/text-embedding-3-small",
input=["good morning from litellm", "this is another item"],
)
print(response)
이미지 생성
OpenRouter는 Google Gemini 이미지 생성 모델 같은 일부 모델을 통해 이미지 생성을 지원해요. LiteLLM은 표준 이미지 생성 요청을 OpenRouter의 채팅 완성 형식으로 변환해요.
지원 파라미터
size: OpenRouter의aspect_ratio형식으로 매핑1024x1024→1:1(정사각형)1536x1024→3:2(가로)1024x1536→2:3(세로)1792x1024→16:9(와이드 가로)1024x1792→9:16(롱 세로)
quality: OpenRouter의image_size형식으로 매핑 (Gemini 모델)low또는standard→1Kmedium→2Khigh또는hd→4K
n: 생성할 이미지 수
사용법
from litellm import image_generation
import os
os.environ["OPENROUTER_API_KEY"] = "your-api-key"
# Basic image generation
response = image_generation(
model="openrouter/google/gemini-2.5-flash-image",
prompt="A beautiful sunset over a calm ocean",
)
print(response)
파라미터를 포함한 고급 사용법
from litellm import image_generation
import os
os.environ["OPENROUTER_API_KEY"] = "your-api-key"
# Generate high-quality landscape image
response = image_generation(
model="openrouter/google/gemini-2.5-flash-image",
prompt="A serene mountain landscape with a lake",
size="1536x1024", # Landscape format
quality="high", # High quality (4K)
)
# Access the generated image
image_data = response.data[0]
if image_data.b64_json:
# Base64 encoded image
print(f"Generated base64 image: {image_data.b64_json[:50]}...")
elif image_data.url:
# Image URL
print(f"Generated image URL: {image_data.url}")
OpenRouter 전용 파라미터 사용
image_config를 사용해 OpenRouter 전용 파라미터를 직접 전달할 수도 있어요:
from litellm import image_generation
import os
os.environ["OPENROUTER_API_KEY"] = "your-api-key"
response = image_generation(
model="openrouter/google/gemini-2.5-flash-image",
prompt="A futuristic cityscape at night",
image_config={
"aspect_ratio": "16:9", # OpenRouter native format
"image_size": "4K" # OpenRouter native format
}
)
print(response)
응답 형식
응답은 표준 LiteLLM ImageResponse 형식을 따르며:
{
"created": 1703658209,
"data": [{
"b64_json": "iVBORw0KGgoAAAANSUhEUgAA...", # Base64 encoded image
"url": None,
"revised_prompt": None
}],
"usage": {
"input_tokens": 10,
"output_tokens": 1290,
"total_tokens": 1300
}
}
비용 추적
OpenRouter는 응답에 비용 정보를 제공하며, LiteLLM이 자동으로 추적해요:
response = image_generation(
model="openrouter/google/gemini-2.5-flash-image",
prompt="A cute baby sea otter",
)
# Cost is available in the response metadata
print(f"Request cost: ${response._hidden_params['additional_headers']['llm_provider-x-litellm-response-cost']}")
이미지 편집
OpenRouter는 Google Gemini 이미지 모델 같은 일부 모델을 통해 이미지 편집을 지원해요. LiteLLM은 소스 이미지를 base64 data URL로, modalities: ["image", "text"]로 보내 이미지 편집 요청을 OpenRouter의 채팅 완성 엔드포인트로 라우팅해요.
지원 모델
| 모델 | 설명 |
|---|---|
openrouter/google/gemini-2.5-flash-image |
이미지 편집이 가능한 Gemini 2.5 Flash |
이미지 모델 전체 목록은 OpenRouter의 모델 목록에서 확인할 수 있어요.
지원 파라미터
| 파라미터 | OpenRouter 매핑 | 비고 |
|---|---|---|
size |
image_config.aspect_ratio |
1024x1024 → 1:1, 1536x1024 → 3:2, 1024x1536 → 2:3, 1792x1024 → 16:9, 1024x1792 → 9:16 |
quality |
image_config.image_size |
low/standard → 1K, medium → 2K, high/hd → 4K |
n |
n |
이미지 수 |
note:
quality=high(4K)는google/gemini-3-pro-image-preview와google/gemini-3.1-flash-image-preview만 지원해요.google/gemini-2.5-flash-image모델은medium(2K)까지만 지원해요.
사용법
from litellm import image_edit
import os
os.environ["OPENROUTER_API_KEY"] = "your-api-key"
# Basic image edit
response = image_edit(
model="openrouter/google/gemini-2.5-flash-image",
image=open("original_image.png", "rb"),
prompt="Make the sky a vibrant purple sunset",
)
print(response)
파라미터를 포함한 고급 사용법
from litellm import image_edit
import os
os.environ["OPENROUTER_API_KEY"] = "your-api-key"
# Edit with size and quality parameters
response = image_edit(
model="openrouter/google/gemini-2.5-flash-image",
image=open("photo.png", "rb"),
prompt="Add northern lights to the sky",
size="1536x1024", # Maps to aspect_ratio 3:2
quality="high", # Maps to image_size 4K
)
# Access the edited image
image_data = response.data[0]
if image_data.b64_json:
import base64
with open("edited.png", "wb") as f:
f.write(base64.b64decode(image_data.b64_json))
여러 이미지 편집
from litellm import image_edit
import os
os.environ["OPENROUTER_API_KEY"] = "your-api-key"
response = image_edit(
model="openrouter/google/gemini-2.5-flash-image",
image=[
open("scene.png", "rb"),
open("style_reference.png", "rb"),
],
prompt="Blend the reference style into the scene",
)
print(response)
더 알아보기 (Learn more)
- OpenRouter 모델 목록
- OpenRouter 공식 문서