Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,123 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
-
from
|
|
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
|
|
|
|
|
9 |
|
10 |
-
def
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
)
|
18 |
-
|
|
|
|
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
-
|
|
|
|
|
|
|
|
|
27 |
|
28 |
-
|
|
|
|
|
29 |
|
30 |
-
|
31 |
-
messages,
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
)
|
37 |
-
token = message.choices[0].delta.content
|
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 |
if __name__ == "__main__":
|
64 |
-
demo.launch()
|
|
|
1 |
+
import os
|
2 |
import gradio as gr
|
3 |
+
from gradio import ChatMessage
|
4 |
+
from typing import Iterator
|
5 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
6 |
+
import torch
|
7 |
|
8 |
+
# Загрузка модели и токенизатора
|
9 |
+
model_name = "FractalGPT/RuQwen2.5-3B-Instruct-AWQ"
|
10 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
11 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")
|
12 |
|
13 |
+
# Создание пайплайна для генерации текста
|
14 |
+
text_generator = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0)
|
15 |
|
16 |
+
def format_chat_history(messages: list) -> str:
|
17 |
+
"""
|
18 |
+
Форматирует историю чата в строку, которую модель может понять.
|
19 |
+
"""
|
20 |
+
formatted_history = ""
|
21 |
+
for message in messages:
|
22 |
+
if message.get("role") == "user":
|
23 |
+
formatted_history += f"User: {message.get('content', '')}\n"
|
24 |
+
elif message.get("role") == "assistant":
|
25 |
+
formatted_history += f"Assistant: {message.get('content', '')}\n"
|
26 |
+
return formatted_history
|
27 |
|
28 |
+
def stream_model_response(user_message: str, messages: list) -> Iterator[list]:
|
29 |
+
"""
|
30 |
+
Генерирует ответ модели с поддержкой истории чата.
|
31 |
+
"""
|
32 |
+
try:
|
33 |
+
print(f"\n=== New Request ===")
|
34 |
+
print(f"User message: {user_message}")
|
35 |
+
|
36 |
+
# Форматируем историю чата
|
37 |
+
chat_history = format_chat_history(messages)
|
38 |
+
|
39 |
+
# Формируем входной текст для модели
|
40 |
+
input_text = f"{chat_history}User: {user_message}\nAssistant:"
|
41 |
+
|
42 |
+
# Генерируем ответ модели
|
43 |
+
response = text_generator(input_text, max_length=512, do_sample=True, temperature=0.7, top_p=0.9)
|
44 |
+
model_response = response[0]['generated_text'].split("Assistant:")[-1].strip()
|
45 |
+
|
46 |
+
# Добавляем ответ модели в историю чата
|
47 |
+
messages.append(
|
48 |
+
ChatMessage(
|
49 |
+
role="assistant",
|
50 |
+
content=model_response
|
51 |
+
)
|
52 |
+
)
|
53 |
+
|
54 |
+
yield messages
|
55 |
+
|
56 |
+
print(f"\n=== Final Response ===\n{model_response}")
|
57 |
+
|
58 |
+
except Exception as e:
|
59 |
+
print(f"\n=== Error ===\n{str(e)}")
|
60 |
+
messages.append(
|
61 |
+
ChatMessage(
|
62 |
+
role="assistant",
|
63 |
+
content=f"I apologize, but I encountered an error: {str(e)}"
|
64 |
+
)
|
65 |
+
)
|
66 |
+
yield messages
|
67 |
|
68 |
+
def user_message(msg: str, history: list) -> tuple[str, list]:
|
69 |
+
"""Добавляет сообщение пользователя в историю чата"""
|
70 |
+
history.append(ChatMessage(role="user", content=msg))
|
71 |
+
return "", history
|
72 |
+
|
73 |
|
74 |
+
# Создаем интерфейс Gradio
|
75 |
+
with gr.Blocks(theme=gr.themes.Citrus(), fill_height=True) as demo:
|
76 |
+
gr.Markdown("# Chat with FractalGPT/RuQwen2.5-3B-Instruct-AWQ 💭")
|
77 |
|
78 |
+
chatbot = gr.Chatbot(
|
79 |
+
type="messages",
|
80 |
+
label="FractalGPT Chatbot",
|
81 |
+
render_markdown=True,
|
82 |
+
scale=1,
|
83 |
+
avatar_images=(None, "https://huggingface.co/FractalGPT/RuQwen2.5-3B-Instruct-AWQ/resolve/main/avatar.png")
|
84 |
+
)
|
|
|
85 |
|
86 |
+
with gr.Row(equal_height=True):
|
87 |
+
input_box = gr.Textbox(
|
88 |
+
lines=1,
|
89 |
+
label="Chat Message",
|
90 |
+
placeholder="Type your message here...",
|
91 |
+
scale=4
|
92 |
+
)
|
93 |
|
94 |
+
clear_button = gr.Button("Clear Chat", scale=1)
|
95 |
|
96 |
+
# Настраиваем обработчики событий
|
97 |
+
msg_store = gr.State("") # Хранилище для сохранения сообщения пользователя
|
98 |
+
|
99 |
+
input_box.submit(
|
100 |
+
lambda msg: (msg, msg, ""), # Сохраняем сообщение и очищаем поле ввода
|
101 |
+
inputs=[input_box],
|
102 |
+
outputs=[msg_store, input_box, input_box],
|
103 |
+
queue=False
|
104 |
+
).then(
|
105 |
+
user_message, # Добавляем сообщение пользователя в чат
|
106 |
+
inputs=[msg_store, chatbot],
|
107 |
+
outputs=[input_box, chatbot],
|
108 |
+
queue=False
|
109 |
+
).then(
|
110 |
+
stream_model_response, # Генерируем и передаем ответ модели
|
111 |
+
inputs=[msg_store, chatbot],
|
112 |
+
outputs=chatbot
|
113 |
+
)
|
114 |
|
115 |
+
clear_button.click(
|
116 |
+
lambda: ([], "", ""),
|
117 |
+
outputs=[chatbot, input_box, msg_store],
|
118 |
+
queue=False
|
119 |
+
)
|
120 |
|
121 |
+
# Запускаем интерфейс
|
122 |
if __name__ == "__main__":
|
123 |
+
demo.launch(debug=True)
|