GeorgeDe commited on
Commit
9bb76c2
·
verified ·
1 Parent(s): 718408d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -50
app.py CHANGED
@@ -1,64 +1,123 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
 
 
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
 
27
 
28
- response = ""
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
 
 
41
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
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)