File size: 13,196 Bytes
95fa14a f4af6c1 f5cfa88 4e2a4d9 fafebf2 4e2a4d9 ca96a0f 8dcf0c5 3924d4e 8dcf0c5 3924d4e 8dcf0c5 3924d4e 8dcf0c5 3924d4e 8dcf0c5 3924d4e 8dcf0c5 3924d4e 8dcf0c5 3924d4e 8dcf0c5 3924d4e 8dcf0c5 3924d4e 8dcf0c5 3924d4e 8dcf0c5 3924d4e 8dcf0c5 3924d4e 8dcf0c5 3924d4e 8dcf0c5 3924d4e 8dcf0c5 3924d4e 8dcf0c5 96698e9 8dcf0c5 3924d4e 8dcf0c5 3924d4e 8dcf0c5 39df5f0 f5cfa88 3924d4e f5cfa88 ca96a0f e10a386 f5cfa88 e10a386 d266939 fafebf2 95fa14a e10a386 39df5f0 e10a386 be0c985 d266939 cf261e1 0f74716 95fa14a 3924d4e 95fa14a 3924d4e 95fa14a d266939 d8e81ba 95fa14a d266939 39df5f0 95fa14a d266939 f4af6c1 4e2a4d9 0f74716 d266939 0f74716 d266939 fafebf2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | import base64
import mimetypes
import os
import time
import requests
import gradio as gr
from openai import OpenAI, APIError
MODEL_ID = "openrouter/free"
OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY", None)
# μ±ν
λͺ©μ μ λ§μ§ μλ λͺ¨λΈ(κ²μ΄/νμ μ μ©, μ¬λνΉ, μλ² λ© λ±)μ κ±Έλ¬λ΄κΈ°
# μν ν€μλμ
λλ€. μ΄λ° λͺ¨λΈμ ':free'μ΄κ³ ν
μ€νΈ/μ΄λ―Έμ§ μ
λ ₯μ μ§μνλλΌλ
# μ€μ λν μλ΅ λμ νμ λΌλ²¨ λ± μλ±ν μΆλ ₯μ λ΄λκΈ° λλ¬Έμ μ μΈν©λλ€.
# (μ: nvidia/nemotron-3.5-content-safety:free β μ€μ λ‘ κ²ͺμΌμ μ¬λ‘)
_NON_CHAT_MODEL_KEYWORDS = ["content-safety", "guard", "rerank", "embed", "moderation"]
# λ€νΈμν¬ μ€λ₯ λ±μΌλ‘ μ€μκ° μ‘°νκ° μμ ν μ€ν¨νμ λλ§ μ¬μ©νλ
# μ΅νμ μμ λ§(fallback) λͺ©λ‘μ
λλ€. 2026-07-02 κΈ°μ€μΌλ‘ νμΈλ κ°μ
λλ€.
_SAFETY_NET_TEXT_MODELS = [
"meta-llama/llama-4-scout:free",
"deepseek/deepseek-chat-v3.1:free",
]
_SAFETY_NET_VISION_MODELS = [
"google/gemma-4-31b-it:free",
"nvidia/nemotron-nano-12b-v2-vl:free",
]
# ββ μ±ν
μ© λ¬΄λ£ λͺ¨λΈ λͺ©λ‘ μΊμ (ν
μ€νΈ μ μ© / μ΄λ―Έμ§ μ§μ κ°κ°) ββββββββββββ
# OpenRouter 곡μ λ¬Έμ(openrouter.ai/docs/guides/overview/models)μ λ°λ₯΄λ©΄
# /api/v1/models μλ΅μ OpenRouter μͺ½μμλ edgeμ μΊμ±λμ΄ μ 곡λλ―λ‘,
# μ°λ¦¬ μͺ½μμλ λ§€ μμ²λ§λ€ μ‘°ννμ§ μκ³ μΌμ μκ°(TTL) λμ μ¬μ¬μ©ν©λλ€.
_models_cache: dict = {
"text": {"models": [], "fetched_at": 0.0},
"vision": {"models": [], "fetched_at": 0.0},
}
_CACHE_TTL_SECONDS = 60 * 60 # 1μκ°
def _fetch_chat_capable_free_models(require_image: bool) -> list:
"""OpenRouter 곡μ API(/api/v1/models)λ₯Ό νΈμΆν΄, μ§κΈ μ΄ μκ°
μ€μ 'λν μλ΅'μ μμ±νλ 무λ£(:free) λͺ¨λΈ λͺ©λ‘μ κ°μ Έμ΅λλ€.
κ²μ΄/μ¬λνΉ/μλ² λ© λ± λΉμ±ν
λͺ©μ λͺ¨λΈμ νμ μ μΈνλ©°,
require_image=Trueμ΄λ©΄ μ΄λ―Έμ§ μ
λ ₯κΉμ§ μ§μνλ λͺ¨λΈλ§ λ¨κΉλλ€.
"""
resp = requests.get("https://openrouter.ai/api/v1/models", timeout=10)
resp.raise_for_status()
data = resp.json().get("data", [])
result = []
for m in data:
model_id = m.get("id", "")
if not model_id.endswith(":free"):
continue
if any(kw in model_id.lower() for kw in _NON_CHAT_MODEL_KEYWORDS):
continue
modalities = m.get("architecture", {}).get("input_modalities", [])
if require_image and "image" not in modalities:
continue
result.append(model_id)
return result
def get_chat_capable_free_models(require_image: bool = False, force_refresh: bool = False) -> list:
"""μΊμλ 'μ€μ λνμ©' λ¬΄λ£ λͺ¨λΈ λͺ©λ‘μ λ°νν©λλ€.
μΊμκ° μκ±°λ(μ΅μ΄ νΈμΆ), TTL(1μκ°)μ΄ μ§λ¬κ±°λ, force_refresh=Trueμ΄λ©΄
OpenRouter APIλ₯Ό λ€μ νΈμΆν΄ κ°±μ ν©λλ€.
"""
cache_key = "vision" if require_image else "text"
cache = _models_cache[cache_key]
safety_net = _SAFETY_NET_VISION_MODELS if require_image else _SAFETY_NET_TEXT_MODELS
now = time.time()
cache_expired = (now - cache["fetched_at"]) > _CACHE_TTL_SECONDS
if force_refresh or cache_expired or not cache["models"]:
try:
fresh_models = _fetch_chat_capable_free_models(require_image)
if fresh_models:
cache["models"] = fresh_models
cache["fetched_at"] = now
except Exception:
# μ‘°ν μμ²΄κ° μ€ν¨νλ©΄(λ€νΈμν¬ μ€λ₯ λ±), κΈ°μ‘΄ μΊμκ° μμΌλ©΄
# κ·Έλλ‘ μ°κ³ , μΊμμ‘°μ°¨ μμΌλ©΄ μ΅νμ μμ λ§ λͺ©λ‘μ μ¬μ©ν©λλ€.
pass
return cache["models"] or safety_net
# ββ OpenRouter ν΄λΌμ΄μΈνΈ μ΄κΈ°ν βββββββββββββββββββββββββββββββββββββββββ
# Hugging Faceλ₯Ό μ ν κ±°μΉμ§ μκ³ , OpenRouter μ체 μλ²(openrouter.ai)λ‘
# μ§μ μμ²μ 보λ
λλ€. OpenAI SDKμ base_urlλ§ OpenRouter μ£Όμλ‘
# λ°κΎΈλ, OpenRouter 곡μ λ¬Έμκ° μλ΄νλ νμ€ μ¬μ© λ°©μμ
λλ€.
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=OPENROUTER_API_KEY,
)
def _encode_image_to_data_url(path: str) -> str:
"""λ‘컬 μ΄λ―Έμ§ νμΌ κ²½λ‘λ₯Ό OpenRouterκ° μꡬνλ base64 data URL
νμ(data:image/png;base64,...)μΌλ‘ λ³νν©λλ€.
(OpenRouter 곡μ λ¬Έμ: Image Inputs κ°μ΄λ κΈ°μ€)
"""
mime_type, _ = mimetypes.guess_type(path)
mime_type = mime_type or "image/png"
with open(path, "rb") as f:
encoded = base64.b64encode(f.read()).decode("utf-8")
return f"data:{mime_type};base64,{encoded}"
def _build_content(text: str | None, files: list) -> list | str:
"""ν
μ€νΈμ μ΄λ―Έμ§ νμΌλ€μ OpenAI/OpenRouter νΈν content λ°°μ΄λ‘
λ³νν©λλ€. μ΄λ―Έμ§κ° μμΌλ©΄ ν
μ€νΈλ§ λ΄κΈ΄ λ¬Έμμ΄μ κ·Έλλ‘ λ°νν©λλ€.
"""
if not files:
return text or ""
content = []
if text:
content.append({"type": "text", "text": text})
for path in files:
try:
content.append({
"type": "image_url",
"image_url": {"url": _encode_image_to_data_url(path)},
})
except Exception:
# μ΄λ―Έμ§κ° μλκ±°λ μ½μ μ μλ νμΌμ μ‘°μ©ν 건λλλλ€.
continue
return content
# ββ Gradio λ²μ /λ©ν°λͺ¨λ¬ μ¬λΆμ λ°λΌ history νμμ΄ λ€λ₯΄λ―λ‘ λ€μν νμ μ§μ ββ
def _normalize_history(history: list) -> list:
"""historyλ Gradio λ²μ λ° λ©ν°λͺ¨λ¬ μ¬λΆμ λ°λΌ
- μ ν(messages) νμ: [{"role": "user", "content": "..."}, ...]
- ꡬν(tuples) νμ: [["user λ©μμ§", "bot λ©μμ§"], ...]
- μ΄λ―Έμ§ μ²¨λΆ μ: contentκ° νμΌ κ²½λ‘κ° λ΄κΈ΄ νν/리μ€νΈμΈ κ²½μ°λ μμ
λ€μν ννλ‘ λ€μ΄μ¬ μ μμ΅λλ€. μ΄λ€ νμμ΄ μλ OpenAI/OpenRouter
νΈν messages λ°°μ΄λ‘ ν΅μΌν΄μ λ°νν©λλ€.
"""
messages = []
if not history:
return messages
for turn in history:
if isinstance(turn, dict):
role = turn.get("role", "user")
content = turn.get("content", "")
elif isinstance(turn, (list, tuple)) and len(turn) == 2:
user_msg, bot_msg = turn
if user_msg:
messages.append({"role": "user", "content": user_msg})
if bot_msg:
messages.append({"role": "assistant", "content": bot_msg})
continue
else:
role = getattr(turn, "role", "user")
content = getattr(turn, "content", "")
if role == "model":
role = "assistant"
# contentκ° μ΄λ―Έμ§ νμΌ κ²½λ‘(νν/리μ€νΈ)μΈ κ²½μ°, μ΄λ―Έμ§ λ©μμ§λ‘ λ³νν©λλ€.
if isinstance(content, (tuple, list)) and content:
path = content[0]
if isinstance(path, str) and os.path.isfile(path):
messages.append({
"role": role,
"content": _build_content(None, [path]),
})
continue
# contentκ° {"path": "..."} ννλ‘ λ€μ΄μ€λ κ²½μ°λ μ²λ¦¬ν©λλ€.
if isinstance(content, dict) and "path" in content:
messages.append({
"role": role,
"content": _build_content(None, [content["path"]]),
})
continue
messages.append({"role": role, "content": content})
return messages
# ββ λν ν
μ€νΈ μμ± ν¨μ (OpenRouter chat.completions μ€νΈλ¦¬λ° λ°©μ) ββββββββ
def _call_openrouter_stream(request_model: str, messages: list, extra_body: dict):
return client.chat.completions.create(
model=request_model,
messages=messages,
max_tokens=8192,
temperature=0.7,
top_p=0.95,
stream=True, # μλ΅μ ν ν°(κΈμ) λ¨μ μ‘°κ°μΌλ‘ μ€μκ° μμ ν©λλ€.
extra_headers={
# OpenRouter 리λ보λμ μ±μ νμνκ³ μΆμ λ μ¬μ©νλ
# μ ν νλͺ©μ
λλ€. νμλ μλλ―λ‘ λΉμλμ
λ λ©λλ€.
"HTTP-Referer": "https://huggingface.co/spaces",
"X-Title": "GS AI",
},
extra_body=extra_body,
)
def predict_chat(message, history: list):
# multimodal=TrueμΌ λ messageλ {"text": "...", "files": ["κ²½λ‘", ...]}
# ννμ λμ
λλ¦¬λ‘ λ€μ΄μ΅λλ€. (Gradio 곡μ λ¬Έμ κΈ°μ€)
if isinstance(message, dict):
text = message.get("text") or ""
files = message.get("files") or []
else:
text = message
files = []
messages = _normalize_history(history)
messages.append({"role": "user", "content": _build_content(text, files)})
has_image = bool(files)
def _resolve_request_target(force_refresh: bool = False):
# ν
μ€νΈ μ μ©μ΄λ μ΄λ―Έμ§ 첨λΆλ , "κ²μ΄/νμ μ μ© λͺ¨λΈ"μ΄ μ€μ λν
# μλ΅ μ리μ λ½νλ λ¬Έμ λ₯Ό λ§κΈ° μν΄ νμ νν°λ§λ μΊμ λͺ©λ‘μ
# μ¬μ©ν©λλ€. (openrouter/freeλ₯Ό κ·Έλλ‘ μ°λ©΄, μ±ν
λͺ©μ μ λ§μ§ μλ
# λͺ¨λΈμ΄ 무μμλ‘ μ νλ μ μλ€λ κ²μ μ€μ λ‘ νμΈνμ΅λλ€.)
candidate_models = get_chat_capable_free_models(
require_image=has_image, force_refresh=force_refresh
)
# OpenRouterμ fallback κΈ°λ₯μ 'models' λ°°μ΄μ μ΅λ 3κ°κΉμ§λ§ νμ©ν©λλ€.
# (OpenRouter μλ² μλ΅ κΈ°μ€: "'models' array must have 3 items or fewer.")
candidate_models = candidate_models[:3]
return candidate_models[0], {"models": candidate_models}
request_model, extra_body = _resolve_request_target()
try:
try:
stream = _call_openrouter_stream(request_model, messages, extra_body)
except APIError as e:
# "μ§μ λͺ¨λΈμ λͺ» μ°Ύμ(404)" μ€λ₯κ° λλ©΄, μΊμκ° λ‘μμ κ°λ₯μ±μ΄
# μμΌλ―λ‘ κ°μ λ‘ ν λ² λ μλ‘ μ‘°νν΄μ λ± ν λ²λ§ μ¬μλν©λλ€.
if getattr(e, "status_code", None) == 404:
request_model, extra_body = _resolve_request_target(force_refresh=True)
stream = _call_openrouter_stream(request_model, messages, extra_body)
else:
raise
partial_output = ""
resolved_model = request_model
for chunk in stream:
# κ° μ‘°κ°(chunk)μλ μ€μ μλ΅ μ€μΈ λͺ¨λΈλͺ
μ΄ λ΄κ²¨ μμ΄,
# μ€νΈλ¦¬λ° λμ€ κ³μ μ΅μ κ°μΌλ‘ κ°±μ ν©λλ€.
if getattr(chunk, "model", None):
resolved_model = chunk.model
if not chunk.choices:
continue
delta = chunk.choices[0].delta
token = getattr(delta, "content", None)
if token:
partial_output += token
# yieldν λλ§λ€ Gradio νλ©΄μ΄ μ€μκ°μΌλ‘ κ°±μ λ©λλ€.
yield partial_output
# μ€νΈλ¦¬λ°μ΄ λλ λ€, μ€μ μ¬μ© λͺ¨λΈλͺ
μ λ§μ§λ§μ λ§λΆμ¬ μ΅μ’
κ°±μ ν©λλ€.
yield f"{partial_output}\n\n---\n_(μ€μ μ¬μ© λͺ¨λΈ: `{resolved_model}`)_"
except APIError as e:
# λ¬΄λ£ λͺ¨λΈμ λΆλΉ/μΌμΌ μμ² νλ μ΄κ³Ό, μ΄λ―Έμ§ λ―Έμ§μ λͺ¨λΈ μ ν,
# λͺ¨λΈ μΌμ μ€λ¨ λ± OpenRouter μͺ½ μ¬μ λ‘ μ€λ₯κ° λλ κ²½μ°μ
λλ€.
yield f"β OpenRouter API μ€λ₯: {str(e)}"
except Exception as e:
yield f"β λ€νΈμν¬ ν΅μ μ€ μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}"
# ββ UI λΉλ λ° API κ°μ€ ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with gr.Blocks() as demo:
gr.Markdown(
"# π€ GS-AI API Server (OpenRouter Mode)\n"
"λ¬΄λ£ λͺ¨λΈ μ€ μ±ν
μ μ ν©ν λͺ¨λΈμ μλμΌλ‘ κ³¨λΌ μλ΅ν©λλ€.\n\n"
"ν
μ€νΈμ ν¨κ» μ΄λ―Έμ§λ₯Ό 첨λΆν΄μ μ§λ¬Ένμ€ μ μμ΅λλ€. "
"(λ¨, κ·Έ μμ μ μ΄μ© κ°λ₯ν λ¬΄λ£ λͺ¨λΈμ΄ μμΌλ©΄ μ€λ₯κ° λ μ μμ΅λλ€.)"
)
chatbot_ui = gr.Chatbot(height=480)
textbox_ui = gr.MultimodalTextbox(
placeholder="λ©μμ§λ₯Ό μ
λ ₯νκ±°λ μ΄λ―Έμ§λ₯Ό 첨λΆνμΈμ...",
file_types=["image"],
file_count="multiple",
)
gr.ChatInterface(
fn=predict_chat,
chatbot=chatbot_ui,
textbox=textbox_ui,
multimodal=True, # message μΈμκ° {"text": ..., "files": [...]} λμ
λλ¦¬λ‘ μ λ¬λ©λλ€.
api_name="chat", # μΈλΆ μ°λμ μν /chat κ²½λ‘ λͺ
μ νμ±ν
)
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=7860,
theme=gr.themes.Soft(),
) |