Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,60 +5,79 @@ import gradio as gr
|
|
| 5 |
import spaces
|
| 6 |
|
| 7 |
OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY", "")
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
"
|
| 12 |
-
"
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
"Microsoft Phi-4": "microsoft/phi-4",
|
| 16 |
-
"
|
| 17 |
}
|
| 18 |
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
headers = {
|
| 21 |
-
"Authorization": f"Bearer {
|
| 22 |
"Content-Type": "application/json"
|
| 23 |
}
|
| 24 |
-
payload = {
|
| 25 |
-
|
| 26 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
}
|
|
|
|
|
|
|
| 28 |
try:
|
| 29 |
-
res = requests.post(
|
| 30 |
-
"https://openrouter.ai/api/v1/chat/completions",
|
| 31 |
-
headers=headers,
|
| 32 |
-
json=payload,
|
| 33 |
-
timeout=40
|
| 34 |
-
)
|
| 35 |
if res.status_code == 200:
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
else:
|
| 39 |
-
return f"### 🤖 **{model_name}**\n\n⚠️ *Помилка API ({res.status_code}):* {res.text}"
|
| 40 |
except Exception as e:
|
| 41 |
return f"### 🤖 **{model_name}**\n\n❌ *Помилка з'єднання:* {str(e)}"
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
@spaces.GPU
|
| 44 |
def group_chat_fn(user_message, history, selected_models):
|
| 45 |
if history is None:
|
| 46 |
history = []
|
| 47 |
|
| 48 |
-
if not OPENROUTER_API_KEY:
|
| 49 |
-
history.append({"role": "user", "content": user_message})
|
| 50 |
-
history.append({"role": "assistant", "content": "❌ **Помилка:** `OPENROUTER_API_KEY` не знайдено в Settings -> Secrets."})
|
| 51 |
-
return "", history
|
| 52 |
-
|
| 53 |
if not selected_models:
|
| 54 |
history.append({"role": "user", "content": user_message})
|
| 55 |
-
history.append({"role": "assistant", "content": "⚠️
|
| 56 |
return "", history
|
| 57 |
|
| 58 |
-
messages = []
|
| 59 |
-
for msg in history:
|
| 60 |
-
if isinstance(msg, dict):
|
| 61 |
-
messages.append({"role": msg.get("role", "user"), "content": msg.get("content", "")})
|
| 62 |
messages.append({"role": "user", "content": user_message})
|
| 63 |
|
| 64 |
history.append({"role": "user", "content": user_message})
|
|
@@ -66,7 +85,7 @@ def group_chat_fn(user_message, history, selected_models):
|
|
| 66 |
responses = []
|
| 67 |
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 68 |
futures = [
|
| 69 |
-
executor.submit(query_single_model, m_name,
|
| 70 |
for m_name in selected_models
|
| 71 |
]
|
| 72 |
for future in concurrent.futures.as_completed(futures):
|
|
@@ -81,78 +100,45 @@ custom_css = """
|
|
| 81 |
body, .gradio-container {
|
| 82 |
background-color: #0f172a !important;
|
| 83 |
color: #f8fafc !important;
|
| 84 |
-
font-family: 'Inter', system-ui, -apple-system, sans-serif !important;
|
| 85 |
}
|
| 86 |
#sidebar {
|
| 87 |
background: #1e293b !important;
|
| 88 |
-
border-right: 1px solid #334155 !important;
|
| 89 |
border-radius: 12px;
|
| 90 |
padding: 16px;
|
| 91 |
}
|
| 92 |
#chatbot {
|
| 93 |
background: #0f172a !important;
|
| 94 |
-
border: 1px solid #334155 !important;
|
| 95 |
border-radius: 12px;
|
| 96 |
}
|
| 97 |
-
.message {
|
| 98 |
-
border-radius: 10px !important;
|
| 99 |
-
padding: 12px !important;
|
| 100 |
-
}
|
| 101 |
-
pre {
|
| 102 |
-
background-color: #1e293b !important;
|
| 103 |
-
border: 1px solid #475569 !important;
|
| 104 |
-
border-radius: 8px !important;
|
| 105 |
-
}
|
| 106 |
-
code {
|
| 107 |
-
font-family: 'Fira Code', 'Consolas', monospace !important;
|
| 108 |
-
}
|
| 109 |
"""
|
| 110 |
|
| 111 |
-
force_dark_js = "() => { document.body.classList.add('dark'); }"
|
| 112 |
-
|
| 113 |
with gr.Blocks() as demo:
|
| 114 |
gr.Markdown("# ⚡ **Multi-AI Studio**")
|
| 115 |
-
gr.Markdown("Груповий чат із кількома нейромережами одночасно.")
|
| 116 |
|
| 117 |
with gr.Row():
|
| 118 |
with gr.Column(scale=1, elem_id="sidebar"):
|
| 119 |
-
gr.Markdown("### 🎛️ **
|
| 120 |
model_selector = gr.CheckboxGroup(
|
| 121 |
-
choices=list(
|
| 122 |
-
value=["
|
| 123 |
-
label="Обери
|
| 124 |
)
|
| 125 |
clear_btn = gr.Button("🗑️ Очистити чат", variant="secondary")
|
| 126 |
|
| 127 |
with gr.Column(scale=3):
|
| 128 |
-
chatbot = gr.Chatbot(
|
| 129 |
-
elem_id="chatbot",
|
| 130 |
-
height=600
|
| 131 |
-
)
|
| 132 |
|
| 133 |
with gr.Row():
|
| 134 |
msg_input = gr.Textbox(
|
| 135 |
-
placeholder="
|
| 136 |
show_label=False,
|
| 137 |
scale=4,
|
| 138 |
container=False
|
| 139 |
)
|
| 140 |
send_btn = gr.Button("Надіслати 🚀", variant="primary", scale=1)
|
| 141 |
|
| 142 |
-
msg_input.submit(
|
| 143 |
-
|
| 144 |
-
inputs=[msg_input, chatbot, model_selector],
|
| 145 |
-
outputs=[msg_input, chatbot]
|
| 146 |
-
)
|
| 147 |
-
send_btn.click(
|
| 148 |
-
group_chat_fn,
|
| 149 |
-
inputs=[msg_input, chatbot, model_selector],
|
| 150 |
-
outputs=[msg_input, chatbot]
|
| 151 |
-
)
|
| 152 |
clear_btn.click(lambda: [], outputs=[chatbot])
|
| 153 |
|
| 154 |
-
demo.launch(
|
| 155 |
-
theme=gr.themes.Soft(primary_hue="indigo"),
|
| 156 |
-
css=custom_css,
|
| 157 |
-
js=force_dark_js
|
| 158 |
-
)
|
|
|
|
| 5 |
import spaces
|
| 6 |
|
| 7 |
OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY", "")
|
| 8 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 9 |
|
| 10 |
+
# Список моделей за провайдерами
|
| 11 |
+
OPENROUTER_MODELS = {
|
| 12 |
+
"Gemma 4 26B": "google/gemma-4-26b-a4b-it:free",
|
| 13 |
+
"Nemotron 3 Ultra 550B": "nvidia/nemotron-3-ultra-550b-a55b:free"
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
HF_MODELS = {
|
| 17 |
+
"Qwen 3.8 2.4T": "Qwen/Qwen3.8-2.4T-A95B",
|
| 18 |
+
"GPT OSS 120B": "openai/gpt-oss-120b",
|
| 19 |
+
"Llama 3.1 8B Instruct": "meta-llama/Llama-3.1-8B-Instruct",
|
| 20 |
+
"Xiaomi MiMo V2.6 Flash": "XiaomiMiMo/MiMo-V2.6-Flash-RL",
|
| 21 |
+
"DeepSeek V4 Flash": "deepseek-ai/DeepSeek-V4-Flash-0731",
|
| 22 |
"Microsoft Phi-4": "microsoft/phi-4",
|
| 23 |
+
"Hermes 3 Llama 3.1 8B": "NousResearch/Hermes-3-Llama-3.1-8B"
|
| 24 |
}
|
| 25 |
|
| 26 |
+
ALL_MODELS = {**OPENROUTER_MODELS, **HF_MODELS}
|
| 27 |
+
|
| 28 |
+
def query_openrouter(model_name, model_id, messages):
|
| 29 |
+
if not OPENROUTER_API_KEY:
|
| 30 |
+
return f"### 🤖 **{model_name}**\n\n❌ *Помилка:* `OPENROUTER_API_KEY` відсутній у Secrets."
|
| 31 |
+
|
| 32 |
headers = {
|
| 33 |
+
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
|
| 34 |
"Content-Type": "application/json"
|
| 35 |
}
|
| 36 |
+
payload = {"model": model_id, "messages": messages}
|
| 37 |
+
try:
|
| 38 |
+
res = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload, timeout=40)
|
| 39 |
+
if res.status_code == 200:
|
| 40 |
+
return f"### 🤖 **{model_name}**\n\n{res.json()['choices'][0]['message']['content']}"
|
| 41 |
+
return f"### 🤖 **{model_name}**\n\n⚠️ *Помилка OpenRouter ({res.status_code}):* {res.text}"
|
| 42 |
+
except Exception as e:
|
| 43 |
+
return f"### 🤖 **{model_name}**\n\n❌ *Помилка з'єднання:* {str(e)}"
|
| 44 |
+
|
| 45 |
+
def query_huggingface(model_name, model_id, messages):
|
| 46 |
+
if not HF_TOKEN:
|
| 47 |
+
return f"### 🤖 **{model_name}**\n\n❌ *Помилка:* `HF_TOKEN` відсутній у Secrets."
|
| 48 |
+
|
| 49 |
+
headers = {
|
| 50 |
+
"Authorization": f"Bearer {HF_TOKEN}",
|
| 51 |
+
"Content-Type": "application/json"
|
| 52 |
}
|
| 53 |
+
url = f"https://router.huggingface.co/hf-inference/v1/chat/completions"
|
| 54 |
+
payload = {"model": model_id, "messages": messages, "max_tokens": 1024}
|
| 55 |
try:
|
| 56 |
+
res = requests.post(url, headers=headers, json=payload, timeout=40)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
if res.status_code == 200:
|
| 58 |
+
return f"### 🤖 **{model_name}**\n\n{res.json()['choices'][0]['message']['content']}"
|
| 59 |
+
return f"### 🤖 **{model_name}**\n\n⚠️ *Помилка HF API ({res.status_code}):* {res.text}"
|
|
|
|
|
|
|
| 60 |
except Exception as e:
|
| 61 |
return f"### 🤖 **{model_name}**\n\n❌ *Помилка з'єднання:* {str(e)}"
|
| 62 |
|
| 63 |
+
def query_single_model(model_name, messages):
|
| 64 |
+
if model_name in OPENROUTER_MODELS:
|
| 65 |
+
return query_openrouter(model_name, OPENROUTER_MODELS[model_name], messages)
|
| 66 |
+
elif model_name in HF_MODELS:
|
| 67 |
+
return query_huggingface(model_name, HF_MODELS[model_name], messages)
|
| 68 |
+
return f"### 🤖 **{model_name}**\n\n❌ Невідома модель."
|
| 69 |
+
|
| 70 |
@spaces.GPU
|
| 71 |
def group_chat_fn(user_message, history, selected_models):
|
| 72 |
if history is None:
|
| 73 |
history = []
|
| 74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
if not selected_models:
|
| 76 |
history.append({"role": "user", "content": user_message})
|
| 77 |
+
history.append({"role": "assistant", "content": "⚠️ Обери хоча б одну модель зі списку."})
|
| 78 |
return "", history
|
| 79 |
|
| 80 |
+
messages = [{"role": msg.get("role", "user"), "content": msg.get("content", "")} for msg in history if isinstance(msg, dict)]
|
|
|
|
|
|
|
|
|
|
| 81 |
messages.append({"role": "user", "content": user_message})
|
| 82 |
|
| 83 |
history.append({"role": "user", "content": user_message})
|
|
|
|
| 85 |
responses = []
|
| 86 |
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 87 |
futures = [
|
| 88 |
+
executor.submit(query_single_model, m_name, messages)
|
| 89 |
for m_name in selected_models
|
| 90 |
]
|
| 91 |
for future in concurrent.futures.as_completed(futures):
|
|
|
|
| 100 |
body, .gradio-container {
|
| 101 |
background-color: #0f172a !important;
|
| 102 |
color: #f8fafc !important;
|
|
|
|
| 103 |
}
|
| 104 |
#sidebar {
|
| 105 |
background: #1e293b !important;
|
|
|
|
| 106 |
border-radius: 12px;
|
| 107 |
padding: 16px;
|
| 108 |
}
|
| 109 |
#chatbot {
|
| 110 |
background: #0f172a !important;
|
|
|
|
| 111 |
border-radius: 12px;
|
| 112 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
"""
|
| 114 |
|
|
|
|
|
|
|
| 115 |
with gr.Blocks() as demo:
|
| 116 |
gr.Markdown("# ⚡ **Multi-AI Studio**")
|
|
|
|
| 117 |
|
| 118 |
with gr.Row():
|
| 119 |
with gr.Column(scale=1, elem_id="sidebar"):
|
| 120 |
+
gr.Markdown("### 🎛️ **Моделі OpenRouter & HF**")
|
| 121 |
model_selector = gr.CheckboxGroup(
|
| 122 |
+
choices=list(ALL_MODELS.keys()),
|
| 123 |
+
value=["Gemma 4 26B", "Llama 3.1 8B Instruct"],
|
| 124 |
+
label="Обери нейромережі:"
|
| 125 |
)
|
| 126 |
clear_btn = gr.Button("🗑️ Очистити чат", variant="secondary")
|
| 127 |
|
| 128 |
with gr.Column(scale=3):
|
| 129 |
+
chatbot = gr.Chatbot(elem_id="chatbot", height=600)
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
with gr.Row():
|
| 132 |
msg_input = gr.Textbox(
|
| 133 |
+
placeholder="Введіть запит...",
|
| 134 |
show_label=False,
|
| 135 |
scale=4,
|
| 136 |
container=False
|
| 137 |
)
|
| 138 |
send_btn = gr.Button("Надіслати 🚀", variant="primary", scale=1)
|
| 139 |
|
| 140 |
+
msg_input.submit(group_chat_fn, inputs=[msg_input, chatbot, model_selector], outputs=[msg_input, chatbot])
|
| 141 |
+
send_btn.click(group_chat_fn, inputs=[msg_input, chatbot, model_selector], outputs=[msg_input, chatbot])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
clear_btn.click(lambda: [], outputs=[chatbot])
|
| 143 |
|
| 144 |
+
demo.launch(css=custom_css)
|
|
|
|
|
|
|
|
|
|
|
|