AutoPercenty3/test/openrouter/p.py

90 lines
3.3 KiB
Python

import requests
import json
def get_openrouter_models_pricing(api_key: str = None):
"""
OpenRouter Models API를 호출하여 모든 모델의 상세 정보(가격 포함)를 조회합니다.
:param api_key: OpenRouter API 키. 대부분의 OpenRouter API는 키 없이도 모델 정보를 조회할 수 있지만,
인증이 필요한 경우를 대비해 파라미터로 남겨둡니다.
:return: 모델 정보(dict) 리스트 또는 오류 메시지(str).
"""
url = "https://openrouter.ai/api/v1/models"
headers = {
"Content-Type": "application/json",
}
# API 키가 제공되면 헤더에 추가 (일반적으로 Models API는 키 없이 조회 가능)
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
print(f"➡️ OpenRouter Models API 호출 시작: {url}")
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # 4xx, 5xx 에러 시 예외 발생
data = response.json()
models = data.get('data', [])
print(f"✅ 총 {len(models)}개의 모델 정보 로드 완료.")
return models
except requests.exceptions.RequestException as e:
return f"❌ OpenRouter API 요청 실패: {e}"
except json.JSONDecodeError:
return "❌ JSON 응답 디코딩 실패."
def display_model_prices(models_data):
"""
조회된 모델 데이터에서 주요 모델의 가격 정보를 추출하여 출력합니다.
"""
if isinstance(models_data, str):
print(models_data)
return
print("\n--- 주요 모델의 가격 정보 (100만 토큰당) ---\n")
# 주요 모델 필터링 및 출력 (예시)
featured_models = [
"openai/gpt-4o",
"anthropic/claude-3-opus",
"google/gemini-2.5-flash",
"mistralai/mistral-large-2402"
]
count = 0
for model in models_data:
model_id = model.get('id')
model_name = model.get('name')
pricing = model.get('pricing', {})
# 'pricing' 키가 존재하고, 토큰 가격 정보가 있을 때
if pricing and pricing.get('input') is not None and pricing.get('output') is not None:
input_cost = pricing['input'] * 1_000_000
output_cost = pricing['output'] * 1_000_000
context_length = model.get('context_length')
# 주요 모델이거나, 상위 몇 개만 출력하고 싶을 때
if model_id in featured_models or count < 5:
print(f"**{model_name}** ({model_id})")
print(f" - 입력 (Input): ${input_cost:.4f} / 1M 토큰")
print(f" - 출력 (Output): ${output_cost:.4f} / 1M 토큰")
print(f" - Context: {context_length:,} 토큰\n")
if model_id not in featured_models:
count += 1
print("\n💡 전체 모델 목록은 'models_data' 변수에 저장되어 있습니다.")
# --- 실행 ---
# OpenRouter API 키를 여기에 입력하세요 (필요 없는 경우 None 유지)
OPENROUTER_API_KEY = "YOUR_OPENROUTER_KEY_HERE" # 실제 사용 시 자신의 키로 교체하세요.
# 모델 정보 조회
all_models = get_openrouter_models_pricing(api_key=None)
# 결과 출력
display_model_prices(all_models)