MrAlexGov commited on
Commit
5d83c2a
·
verified ·
1 Parent(s): 2ccd460

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -53
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
- "unsloth/Mistral-Nemo-Instruct-2407-12B-GGUF",
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
- """Конвертирует Gradio history [[user_msg, bot_msg]] в OpenAI messages."""
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 chat_response(message: str, history: List[Tuple[str, str]], model_id: str, system_prompt: str):
29
- """Главная функция: отправляет чат в HF Inference API."""
 
 
 
30
  try:
31
  client = InferenceClient(model=model_id)
32
 
33
- # Строим messages
34
  messages = []
35
- if system_prompt.strip(): # Если system не пустой
36
  messages.append({"role": "system", "content": system_prompt})
37
 
38
- messages.extend(convert_history(history)) # История чата
39
- messages.append({"role": "user", "content": message}) # Текущее сообщение
 
40
 
41
- # Генерируем ответ (max_new_tokens=512 для скорости)
42
  response = client.chat_completion(
43
  messages=messages,
44
- max_tokens=512, # Лимит токенов ответа (токены ~ слова/4)
45
- temperature=0.7, # Креативность (0=детерминировано, 1=случайно)
46
- stream=False # Без стриминга для простоты
47
  )
48
 
49
- return response.choices[0].message.content
 
 
 
 
50
 
51
  except Exception as e:
52
- # Обработка ошибок (rate limit, модель не найдена)
53
- return f"Ошибка: {str(e)}. Проверь модель или подожди (API лимит)."
 
54
 
55
- # UI: ChatInterface с доп. полями
56
- with gr.Blocks(title="Тест Чат-Ботов HF") as demo:
57
- gr.Markdown("# Тестер ИИ-моделей HF\nВыбери модель, system prompt (опционально), чатай!")
 
58
 
59
- # Дополнительные inputs (выше чата)
60
- model_dropdown = gr.Dropdown(
61
- choices=MODELS,
62
- value=MODELS[0], # По умолчанию Phi-3
63
- label="Модель HF (выбери или замени на свою)",
64
- interactive=True
65
- )
66
- system_input = gr.Textbox(
67
- label="System Prompt (системное сообщение, опционально)",
68
- placeholder="Пример: Ты полезный ассистент. Отвечай кратко.",
69
- lines=2
 
 
 
 
 
 
 
 
 
 
 
70
  )
71
 
72
- # Чат
73
- chat = gr.ChatInterface(
74
- fn=chat_response,
75
- additional_inputs=[model_dropdown, system_input],
76
- title="Чат с моделью",
77
- description="Тестируй промпты, jailbreak, код. Смени модель — чат обновится.",
78
- examples=None, # Добавь свои примеры позже
79
- cache_examples=False,
80
- retry_btn="🔄 Повторить",
81
- undo_btn="↶ Назад",
82
- clear_btn="🗑️ Очистить"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  )
 
 
84
 
85
  if __name__ == "__main__":
86
- demo.queue(max_size=10).launch(share=True, debug=True) # share=True для публичной ссылки
 
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)