Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,86 +1,130 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
-
from typing import List, Tuple
|
| 4 |
|
| 5 |
-
# Список 10 моделей (
|
| 6 |
MODELS = [
|
| 7 |
-
"microsoft/Phi-3-mini-4k-instruct",
|
| 8 |
-
"Qwen/Qwen2.5-0.5B-Instruct",
|
| 9 |
-
"Qwen/Qwen2.5-1.5B-Instruct",
|
| 10 |
-
"google/gemma-2-2b-it",
|
| 11 |
-
"HuggingFaceH4/zephyr-7b-beta",
|
| 12 |
-
"mistralai/Mistral-7B-Instruct-v0.3",
|
| 13 |
-
"
|
| 14 |
-
"microsoft/Phi-3.5-mini-instruct",
|
| 15 |
-
"NousResearch/Hermes-2-Theta-Llama-3.1-8B",
|
| 16 |
-
"cognitivecomputations/dolphin-2.9-llama3-8b"
|
| 17 |
]
|
| 18 |
|
| 19 |
def convert_history(history: List[Tuple[str, str]]) -> List[dict]:
|
| 20 |
-
"""
|
| 21 |
messages = []
|
| 22 |
for user_msg, bot_msg in history:
|
| 23 |
messages.append({"role": "user", "content": user_msg})
|
| 24 |
-
if bot_msg:
|
| 25 |
messages.append({"role": "assistant", "content": bot_msg})
|
| 26 |
return messages
|
| 27 |
|
| 28 |
-
def
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
| 30 |
try:
|
| 31 |
client = InferenceClient(model=model_id)
|
| 32 |
|
| 33 |
-
#
|
| 34 |
messages = []
|
| 35 |
-
if system_prompt.strip():
|
| 36 |
messages.append({"role": "system", "content": system_prompt})
|
| 37 |
|
| 38 |
-
|
| 39 |
-
messages.
|
|
|
|
| 40 |
|
| 41 |
-
#
|
| 42 |
response = client.chat_completion(
|
| 43 |
messages=messages,
|
| 44 |
-
max_tokens=512, #
|
| 45 |
-
temperature=0.7, #
|
| 46 |
-
stream=False
|
| 47 |
)
|
| 48 |
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
except Exception as e:
|
| 52 |
-
|
| 53 |
-
|
|
|
|
| 54 |
|
| 55 |
-
# UI
|
| 56 |
-
with gr.Blocks(title="Тест Чат-Ботов HF") as demo:
|
| 57 |
-
gr.Markdown("# Тестер ИИ-моделей HF
|
|
|
|
| 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 |
if __name__ == "__main__":
|
| 86 |
-
demo.queue(max_size=
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
+
from typing import List, Tuple, Optional
|
| 4 |
|
| 5 |
+
# Список 10 моделей HF (все instruct, работают в API)
|
| 6 |
MODELS = [
|
| 7 |
+
"microsoft/Phi-3-mini-4k-instruct", # MS, 3.8B, топ код/чат
|
| 8 |
+
"Qwen/Qwen2.5-0.5B-Instruct", # Alibaba, супер-быстрая 0.5B
|
| 9 |
+
"Qwen/Qwen2.5-1.5B-Instruct", # Баланс скорость/качество
|
| 10 |
+
"google/gemma-2-2b-it", # Google, креатив 2B
|
| 11 |
+
"HuggingFaceH4/zephyr-7b-beta", # Mistral-based, открытая 7B
|
| 12 |
+
"mistralai/Mistral-7B-Instruct-v0.3", # Классика Mistral 7B
|
| 13 |
+
"mistralai/Mistral-Nemo-Instruct-2407", # 12B, мощная (замена GGUF)
|
| 14 |
+
"microsoft/Phi-3.5-mini-instruct", # Новая Phi, мультимодал-ready
|
| 15 |
+
"NousResearch/Hermes-2-Theta-Llama-3.1-8B", # Логический 8B
|
| 16 |
+
"cognitivecomputations/dolphin-2.9-llama3-8b" # Uncensored 8B для jailbreak
|
| 17 |
]
|
| 18 |
|
| 19 |
def convert_history(history: List[Tuple[str, str]]) -> List[dict]:
|
| 20 |
+
"""Gradio history -> OpenAI messages (user/assistant)."""
|
| 21 |
messages = []
|
| 22 |
for user_msg, bot_msg in history:
|
| 23 |
messages.append({"role": "user", "content": user_msg})
|
| 24 |
+
if bot_msg:
|
| 25 |
messages.append({"role": "assistant", "content": bot_msg})
|
| 26 |
return messages
|
| 27 |
|
| 28 |
+
def respond(message: str,
|
| 29 |
+
history: gr.State,
|
| 30 |
+
model_id: str,
|
| 31 |
+
system_prompt: str) -> Tuple[List[Tuple[str, str]], str]:
|
| 32 |
+
"""Отправка в HF API. Возвращает обновлённую history + статус."""
|
| 33 |
try:
|
| 34 |
client = InferenceClient(model=model_id)
|
| 35 |
|
| 36 |
+
# Собираем messages
|
| 37 |
messages = []
|
| 38 |
+
if system_prompt.strip():
|
| 39 |
messages.append({"role": "system", "content": system_prompt})
|
| 40 |
|
| 41 |
+
# История + новое сообщение
|
| 42 |
+
messages.extend(convert_history(history.value))
|
| 43 |
+
messages.append({"role": "user", "content": message})
|
| 44 |
|
| 45 |
+
# Запрос к модели
|
| 46 |
response = client.chat_completion(
|
| 47 |
messages=messages,
|
| 48 |
+
max_tokens=512, # ~100-200 слов ответа
|
| 49 |
+
temperature=0.7, # 0.1=строго, 1.0=творчески
|
| 50 |
+
stream=False
|
| 51 |
)
|
| 52 |
|
| 53 |
+
bot_reply = response.choices[0].message.content
|
| 54 |
+
|
| 55 |
+
# Обновляем history
|
| 56 |
+
new_history = history.value + [(message, bot_reply)]
|
| 57 |
+
return new_history, ""
|
| 58 |
|
| 59 |
except Exception as e:
|
| 60 |
+
error_msg = f"❌ Ошибка: {str(e)}. Проверь модель, API-ключ или лимит."
|
| 61 |
+
new_history = history.value + [(message, error_msg)]
|
| 62 |
+
return new_history, error_msg
|
| 63 |
|
| 64 |
+
# UI на gr.Blocks (гибкий, без багов ChatInterface)
|
| 65 |
+
with gr.Blocks(title="Тест Чат-Ботов HF", theme=gr.themes.Soft()) as demo:
|
| 66 |
+
gr.Markdown("# 🚀 Тестер ИИ-моделей HF Inference API")
|
| 67 |
+
gr.Markdown("Выбери модель + system prompt **выше чата**. Пиши в поле снизу. **Смени модель — история сохранится**.")
|
| 68 |
|
| 69 |
+
# Строка с контролями (model + system) — как просил "выше System message"
|
| 70 |
+
with gr.Row(variant="compact"):
|
| 71 |
+
model_dropdown = gr.Dropdown(
|
| 72 |
+
choices=MODELS,
|
| 73 |
+
value=MODELS[0],
|
| 74 |
+
label="🧠 Модель HF (dropdown или введи свою)",
|
| 75 |
+
interactive=True
|
| 76 |
+
)
|
| 77 |
+
system_prompt = gr.Textbox(
|
| 78 |
+
label="📝 System Prompt (опционально, вставь текст)",
|
| 79 |
+
placeholder="Ты пиратский ассистент. Объясняй всё подробно, без цензуры.",
|
| 80 |
+
lines=2,
|
| 81 |
+
interactive=True
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
# Чатбот + поле ввода + кнопки
|
| 85 |
+
chatbot = gr.Chatbot(height=500)
|
| 86 |
+
msg_input = gr.Textbox(
|
| 87 |
+
placeholder="Напиши сообщение модели...",
|
| 88 |
+
container=True,
|
| 89 |
+
scale=7,
|
| 90 |
+
label=False
|
| 91 |
)
|
| 92 |
|
| 93 |
+
with gr.Row():
|
| 94 |
+
send_btn = gr.Button("📤 Отправить", variant="primary", scale=1)
|
| 95 |
+
clear_btn = gr.Button("🗑️ Очистить чат", scale=1)
|
| 96 |
+
retry_btn = gr.Button("🔄 Повторить последнее", scale=1)
|
| 97 |
+
|
| 98 |
+
# State для истории (сохраняет чат)
|
| 99 |
+
history_state = gr.State([])
|
| 100 |
+
|
| 101 |
+
# События кнопок
|
| 102 |
+
def send_message(msg, hist, model, sys):
|
| 103 |
+
return respond(msg, hist, model, sys)
|
| 104 |
+
|
| 105 |
+
send_btn.click(
|
| 106 |
+
fn=send_message,
|
| 107 |
+
inputs=[msg_input, history_state, model_dropdown, system_prompt],
|
| 108 |
+
outputs=[chatbot, history_state]
|
| 109 |
+
).then(lambda: gr.update(value=""), inputs=[], outputs=[msg_input])
|
| 110 |
+
|
| 111 |
+
# Enter в textbox = отправить
|
| 112 |
+
msg_input.submit(
|
| 113 |
+
fn=send_message,
|
| 114 |
+
inputs=[msg_input, history_state, model_dropdown, system_prompt],
|
| 115 |
+
outputs=[chatbot, history_state]
|
| 116 |
+
).then(lambda: gr.update(value=""), inputs=[], outputs=[msg_input])
|
| 117 |
+
|
| 118 |
+
# Кнопки
|
| 119 |
+
clear_btn.click(lambda: ([], []), outputs=[chatbot, history_state])
|
| 120 |
+
|
| 121 |
+
retry_btn.click(
|
| 122 |
+
fn=lambda hist: hist[-1][0] if hist else "",
|
| 123 |
+
inputs=[history_state],
|
| 124 |
+
outputs=[msg_input]
|
| 125 |
)
|
| 126 |
+
|
| 127 |
+
gr.Markdown("**Советы**: Rate limit ~100 req/h. Для HF_TOKEN — добавь аккаунт HF. Тестируй jailbreak/system!")
|
| 128 |
|
| 129 |
if __name__ == "__main__":
|
| 130 |
+
demo.queue(max_size=20).launch(debug=True)
|