Spaces:
Running
Running
File size: 10,283 Bytes
8930085 1c834ab 8930085 1c834ab 8930085 1c834ab 8930085 1c834ab 2147fdd 8930085 1c834ab 8930085 1c834ab 8930085 1c834ab 2147fdd 1c834ab 2147fdd 1c834ab 2147fdd 1c834ab 2147fdd 1c834ab 2147fdd 1c834ab 2147fdd 1c834ab 2147fdd 1c834ab 2147fdd 1c834ab 2147fdd 1c834ab 2147fdd 1c834ab 2147fdd 1c834ab 2147fdd 1c834ab 2147fdd 1c834ab 2147fdd 1c834ab 2147fdd 1c834ab 2147fdd 1c834ab 98da9fc 1c834ab 8930085 2147fdd 1c834ab 2147fdd 1c834ab 2147fdd 1c834ab 8930085 1c834ab 2147fdd 1c834ab 8930085 1c834ab 8930085 1c834ab 8930085 1c834ab 8930085 2147fdd |
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 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |
import gradio as gr
import requests
import json
import os
from typing import Iterator
# Model list
MODELS = [
"anthropic/claude-opus-4",
"anthropic/claude-sonnet-4",
"deepseek/deepseek-r1-0528",
"deepseek/deepseek-chat-v3-0324",
"openai/gpt-4.1",
"openai/gpt-4.1-mini",
"google/gemini-2.5-pro-preview",
"microsoft/phi-4-reasoning-plus",
"qwen/qwen3-30b-a3b",
"meta-llama/llama-guard-4-12b",
"meta-llama/llama-4-maverick",
"meta-llama/llama-4-scout",
"x-ai/grok-2-vision-1212"
]
def get_openrouter_response(message: str, history: list, model: str, api_key: str) -> Iterator[str]:
"""Stream response from OpenRouter API"""
if not api_key:
yield "β Please enter your OpenRouter API key in the settings below."
return
# Prepare messages for API
messages = []
# Add conversation history
for user_msg, assistant_msg in history:
messages.append({"role": "user", "content": user_msg})
if assistant_msg:
messages.append({"role": "assistant", "content": assistant_msg})
# Add current message
messages.append({"role": "user", "content": message})
# API request
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"HTTP-Referer": "https://huggingface.co",
"X-Title": "HuggingFace OpenRouter Chat"
}
data = {
"model": model,
"messages": messages,
"stream": True
}
try:
response = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers=headers,
json=data,
stream=True
)
if response.status_code != 200:
yield f"β Error: {response.status_code} - {response.text}"
return
# Stream the response
full_response = ""
for line in response.iter_lines():
if line:
line_text = line.decode('utf-8')
if line_text.startswith('data: '):
if line_text.strip() == 'data: [DONE]':
break
try:
json_data = json.loads(line_text[6:])
if 'choices' in json_data and len(json_data['choices']) > 0:
delta = json_data['choices'][0].get('delta', {})
if 'content' in delta:
content = delta['content']
full_response += content
yield full_response
except json.JSONDecodeError:
continue
except Exception as e:
yield f"β Error: {str(e)}"
# Custom CSS
custom_css = """
/* Modern Dark Theme */
.gradio-container {
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
font-family: 'Inter', 'Segoe UI', sans-serif;
}
/* Header Styling */
.main-header {
text-align: center;
padding: 2rem 0;
margin-bottom: 2rem;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}
.main-header h1 {
color: white;
font-size: 2.5rem;
font-weight: 700;
margin: 0;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}
.main-header p {
color: rgba(255, 255, 255, 0.9);
font-size: 1.1rem;
margin-top: 0.5rem;
}
/* Chat Interface */
#chatbot {
/* Changed from important declarations for better compatibility */
background-color: rgba(30, 30, 50, 0.8);
border-radius: 15px;
border: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}
#chatbot .user {
background-color: rgba(102, 126, 234, 0.2);
border-left: 4px solid #667eea;
border-radius: 10px;
padding: 10px;
margin: 5px;
}
#chatbot .bot {
background-color: rgba(118, 75, 162, 0.2);
border-left: 4px solid #764ba2;
border-radius: 10px;
padding: 10px;
margin: 5px;
}
/* Input Areas */
#msg-input {
background-color: rgba(30, 30, 50, 0.8);
border: 2px solid rgba(102, 126, 234, 0.5);
border-radius: 10px;
color: white;
font-size: 16px;
transition: all 0.3s ease;
}
#msg-input:focus {
border-color: #667eea;
box-shadow: 0 0 15px rgba(102, 126, 234, 0.3);
}
/* Buttons */
.submit-btn, .clear-btn, .settings-btn {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
border-radius: 10px;
color: white;
font-weight: 600;
padding: 12px 24px;
transition: all 0.3s ease;
cursor: pointer;
}
.submit-btn:hover, .clear-btn:hover, .settings-btn:hover {
transform: translateY(-2px);
box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
}
/* Dropdown */
#model-dropdown {
background-color: rgba(30, 30, 50, 0.9);
border: 2px solid rgba(102, 126, 234, 0.5);
border-radius: 10px;
color: white;
padding: 10px;
font-size: 14px;
}
#model-dropdown:focus {
border-color: #667eea;
outline: none;
}
/* Settings Panel */
.settings-panel {
background: rgba(30, 30, 50, 0.8);
border-radius: 15px;
padding: 20px;
margin-top: 20px;
border: 1px solid rgba(255, 255, 255, 0.1);
}
/* API Key Input */
#api-key-input {
background-color: rgba(20, 20, 40, 0.8);
border: 2px solid rgba(102, 126, 234, 0.3);
border-radius: 10px;
color: white;
font-family: monospace;
}
/* Info Box */
.info-box {
background: rgba(102, 126, 234, 0.1);
border-left: 4px solid #667eea;
border-radius: 8px;
padding: 15px;
margin: 10px 0;
}
/* Model List */
.model-info {
background: rgba(30, 30, 50, 0.6);
border-radius: 10px;
padding: 15px;
margin: 10px 0;
}
/* Labels */
label {
color: rgba(255, 255, 255, 0.9);
font-weight: 600;
margin-bottom: 5px;
}
/* Dark theme for gradio components */
.dark {
--block-background-fill: rgba(30, 30, 50, 0.8);
--body-background-fill: transparent;
--color-accent: #667eea;
}
"""
# Create interface
with gr.Blocks(css=custom_css, theme=gr.themes.Soft(primary_hue="violet", neutral_hue="slate").set(
loader_color="#667eea",
slider_color="#667eea",
)) as demo:
# Header
gr.HTML("""
<div class="main-header">
<h1>πTry my bestπ</h1>
<p>Learn by doing </p>
</div>
""")
# State for API key
api_key_state = gr.State("")
with gr.Row():
with gr.Column(scale=3):
# Chat interface
chatbot = gr.Chatbot(
label="Chat",
elem_id="chatbot",
height=500,
bubble_full_width=False
)
with gr.Row():
msg = gr.Textbox(
label="Type your message",
placeholder="Ask me anything...",
lines=2,
max_lines=4,
elem_id="msg-input"
)
with gr.Row():
submit = gr.Button("π Send", variant="primary", elem_classes="submit-btn")
clear = gr.Button("ποΈ Clear", variant="secondary", elem_classes="clear-btn")
with gr.Column(scale=1):
# Model selection
model_dropdown = gr.Dropdown(
choices=MODELS,
value=MODELS[0],
label="π€ Select Model",
interactive=True,
elem_id="model-dropdown"
)
gr.HTML("""
<div class="info-box">
<p><strong>Available Models:</strong></p>
<ul style="margin: 5px 0; padding-left: 20px;">
<li>Claude (Anthropic)</li>
<li>DeepSeek</li>
<li>GPT-4 (OpenAI)</li>
<li>Gemini (Google)</li>
<li>Phi-4 (Microsoft)</li>
<li>Qwen</li>
<li>LLaMA (Meta)</li>
<li>Grok (xAI)</li>
</ul>
</div>
""")
# Settings
with gr.Accordion("βοΈ Settings", open=False):
api_key_input = gr.Textbox(
label="OpenRouter API Key",
placeholder="sk-or-v1-...",
type="password",
elem_id="api-key-input"
)
gr.HTML("""
<div class="info-box">
<p>Get your API key from <a href="https://openrouter.ai/keys" target="_blank" style="color: #667eea;">OpenRouter</a></p>
</div>
""")
# Event handlers
def update_api_key(key):
return key
api_key_input.change(update_api_key, inputs=[api_key_input], outputs=[api_key_state])
def user_submit(message, history, model, api_key):
return "", history + [[message, None]]
def bot_response(history, model, api_key):
if not history:
return history
user_message = history[-1][0]
bot_message = ""
for chunk in get_openrouter_response(user_message, history[:-1], model, api_key):
bot_message = chunk
history[-1][1] = bot_message
yield history
msg.submit(
user_submit,
[msg, chatbot, model_dropdown, api_key_state],
[msg, chatbot]
).then(
bot_response,
[chatbot, model_dropdown, api_key_state],
chatbot
)
submit.click(
user_submit,
[msg, chatbot, model_dropdown, api_key_state],
[msg, chatbot]
).then(
bot_response,
[chatbot, model_dropdown, api_key_state],
chatbot
)
clear.click(lambda: None, None, chatbot)
# Footer
gr.HTML("""
<div style="text-align: center; margin-top: 30px; color: rgba(255, 255, 255, 0.6);">
<p>Built with AHMAD ANUGERAH using Gradio & OpenRouter</p>
</div>
""")
if __name__ == "__main__":
demo.launch()
|