Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,270 +1,132 @@
|
|
1 |
import gradio as gr
|
2 |
-
import os
|
3 |
-
import logging
|
4 |
from huggingface_hub import InferenceClient
|
5 |
-
from typing import List, Tuple
|
6 |
-
|
7 |
-
# Configure logging
|
8 |
-
logging.basicConfig(
|
9 |
-
level=logging.INFO,
|
10 |
-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
11 |
-
)
|
12 |
-
logger = logging.getLogger(__name__)
|
13 |
|
|
|
14 |
class ChatConfig:
|
15 |
-
"""Configuration settings for the chat application."""
|
16 |
MODEL = "google/gemma-3-27b-it"
|
17 |
DEFAULT_SYSTEM_MSG = "You are a super intelligent and useful Chatbot."
|
18 |
DEFAULT_MAX_TOKENS = 512
|
19 |
DEFAULT_TEMP = 0.3
|
20 |
DEFAULT_TOP_P = 0.95
|
21 |
-
HF_TOKEN = os.environ.get("HF_TOKEN", None) # Get token from environment variable
|
22 |
|
23 |
-
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
)
|
33 |
-
logger.info(f"Successfully initialized InferenceClient for {ChatConfig.MODEL}")
|
34 |
-
except Exception as e:
|
35 |
-
logger.error(f"Failed to initialize InferenceClient: {e}")
|
36 |
-
raise
|
37 |
|
38 |
-
|
39 |
-
self,
|
40 |
-
message: str,
|
41 |
-
history: List[Tuple[str, str]],
|
42 |
-
system_message: str = ChatConfig.DEFAULT_SYSTEM_MSG,
|
43 |
-
max_tokens: int = ChatConfig.DEFAULT_MAX_TOKENS,
|
44 |
-
temperature: float = ChatConfig.DEFAULT_TEMP,
|
45 |
-
top_p: float = ChatConfig.DEFAULT_TOP_P
|
46 |
-
) -> str:
|
47 |
-
"""Generate responses from the model."""
|
48 |
-
if not message.strip():
|
49 |
-
return "请输入消息。"
|
50 |
-
|
51 |
-
messages = [{"role": "system", "content": system_message}]
|
52 |
-
|
53 |
-
# Add conversation history
|
54 |
-
for user_msg, bot_msg in history:
|
55 |
-
if user_msg:
|
56 |
-
messages.append({"role": "user", "content": user_msg})
|
57 |
-
if bot_msg:
|
58 |
-
messages.append({"role": "assistant", "content": bot_msg})
|
59 |
-
|
60 |
-
# Add the current message
|
61 |
-
messages.append({"role": "user", "content": message})
|
62 |
-
|
63 |
-
try:
|
64 |
-
response = ""
|
65 |
-
for chunk in self.client.chat_completion(
|
66 |
-
messages,
|
67 |
-
max_tokens=max_tokens,
|
68 |
-
stream=True,
|
69 |
-
temperature=temperature,
|
70 |
-
top_p=top_p,
|
71 |
-
):
|
72 |
-
token = chunk.choices[0].delta.content or ""
|
73 |
-
response += token
|
74 |
-
return response
|
75 |
-
except Exception as e:
|
76 |
-
logger.error(f"Error generating response: {e}")
|
77 |
-
return f"抱歉,发生了错误: {str(e)}"
|
78 |
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
)
|
159 |
-
temperature = gr.Slider(
|
160 |
-
minimum=0.1,
|
161 |
-
maximum=1.0,
|
162 |
-
value=ChatConfig.DEFAULT_TEMP,
|
163 |
-
step=0.1,
|
164 |
-
label="温度",
|
165 |
-
info="控制随机性"
|
166 |
-
)
|
167 |
-
top_p = gr.Slider(
|
168 |
-
minimum=0.1,
|
169 |
-
maximum=1.0,
|
170 |
-
value=ChatConfig.DEFAULT_TOP_P,
|
171 |
-
step=0.05,
|
172 |
-
label="Top-P",
|
173 |
-
info="控制多样性"
|
174 |
-
)
|
175 |
-
|
176 |
-
with gr.Accordion("示例问题", open=False):
|
177 |
-
gr.Examples(
|
178 |
-
examples=[
|
179 |
-
["讲一讲人工智能的最新进展"],
|
180 |
-
["写一个关于机器人发现情感的短篇故事"],
|
181 |
-
["向10岁的孩子解释量子计算"]
|
182 |
-
],
|
183 |
-
inputs=msg
|
184 |
-
)
|
185 |
-
|
186 |
-
with gr.Accordion("模型信息", open=False):
|
187 |
-
gr.Markdown(f"""
|
188 |
-
- **模型**: {ChatConfig.MODEL}
|
189 |
-
- **提供商**: Hugging Face
|
190 |
-
- **描述**: Gemma 3是Google推出的先进开源大语言模型。
|
191 |
-
""")
|
192 |
-
|
193 |
-
# Define chatbot functions with correct input/output format
|
194 |
-
def add_text(history, text):
|
195 |
-
history = history + [(text, None)]
|
196 |
-
return history, ""
|
197 |
-
|
198 |
-
def bot_response(history, system_message, max_tokens, temperature, top_p):
|
199 |
-
if history and history[-1][1] is None:
|
200 |
-
user_message = history[-1][0]
|
201 |
-
# Remove the last incomplete message pair
|
202 |
-
history_for_model = history[:-1]
|
203 |
-
# Generate response
|
204 |
-
bot_message = self.generate_response(
|
205 |
-
user_message,
|
206 |
-
history_for_model,
|
207 |
-
system_message,
|
208 |
-
max_tokens,
|
209 |
-
temperature,
|
210 |
-
top_p
|
211 |
-
)
|
212 |
-
# Update the history with the complete message pair
|
213 |
-
history[-1] = (user_message, bot_message)
|
214 |
-
return history
|
215 |
-
|
216 |
-
def load_example():
|
217 |
-
return [("介绍一下人工智能研究中最有趣的发展", None)]
|
218 |
-
|
219 |
-
# Set up event handlers
|
220 |
-
submit_click = submit_btn.click(
|
221 |
-
add_text,
|
222 |
-
[chatbot, msg],
|
223 |
-
[chatbot, msg],
|
224 |
-
queue=False
|
225 |
-
).then(
|
226 |
-
bot_response,
|
227 |
-
[chatbot, system_msg, max_tokens, temperature, top_p],
|
228 |
-
chatbot
|
229 |
-
)
|
230 |
-
|
231 |
-
# Submit when pressing Enter
|
232 |
-
msg.submit(
|
233 |
-
add_text,
|
234 |
-
[chatbot, msg],
|
235 |
-
[chatbot, msg],
|
236 |
-
queue=False
|
237 |
-
).then(
|
238 |
-
bot_response,
|
239 |
-
[chatbot, system_msg, max_tokens, temperature, top_p],
|
240 |
-
chatbot
|
241 |
)
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
example_btn.click(load_example, None, chatbot)
|
248 |
-
|
249 |
-
return interface
|
250 |
|
251 |
def main():
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
show_api=False,
|
262 |
-
debug=True,
|
263 |
-
show_error=True
|
264 |
-
)
|
265 |
-
except Exception as e:
|
266 |
-
logger.critical(f"Failed to launch application: {e}")
|
267 |
-
print(f"错误: {e}")
|
268 |
|
269 |
if __name__ == "__main__":
|
270 |
main()
|
|
|
1 |
import gradio as gr
|
|
|
|
|
2 |
from huggingface_hub import InferenceClient
|
3 |
+
from typing import List, Tuple
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
+
# Default settings
|
6 |
class ChatConfig:
|
|
|
7 |
MODEL = "google/gemma-3-27b-it"
|
8 |
DEFAULT_SYSTEM_MSG = "You are a super intelligent and useful Chatbot."
|
9 |
DEFAULT_MAX_TOKENS = 512
|
10 |
DEFAULT_TEMP = 0.3
|
11 |
DEFAULT_TOP_P = 0.95
|
|
|
12 |
|
13 |
+
client = InferenceClient(ChatConfig.MODEL)
|
14 |
+
|
15 |
+
def generate_response(
|
16 |
+
message: str,
|
17 |
+
history: List[Tuple[str, str]],
|
18 |
+
system_message: str = ChatConfig.DEFAULT_SYSTEM_MSG,
|
19 |
+
max_tokens: int = ChatConfig.DEFAULT_MAX_TOKENS,
|
20 |
+
temperature: float = ChatConfig.DEFAULT_TEMP,
|
21 |
+
top_p: float = ChatConfig.DEFAULT_TOP_P
|
22 |
+
) -> str:
|
23 |
+
messages = [{"role": "system", "content": system_message}]
|
24 |
|
25 |
+
# Conversation history
|
26 |
+
for user_msg, bot_msg in history:
|
27 |
+
if user_msg:
|
28 |
+
messages.append({"role": "user", "content": user_msg})
|
29 |
+
if bot_msg:
|
30 |
+
messages.append({"role": "assistant", "content": bot_msg})
|
|
|
|
|
|
|
|
|
|
|
31 |
|
32 |
+
messages.append({"role": "user", "content": message})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
34 |
+
response = ""
|
35 |
+
for chunk in client.chat_completion(
|
36 |
+
messages,
|
37 |
+
max_tokens=max_tokens,
|
38 |
+
stream=True,
|
39 |
+
temperature=temperature,
|
40 |
+
top_p=top_p,
|
41 |
+
):
|
42 |
+
token = chunk.choices[0].delta.content or ""
|
43 |
+
response += token
|
44 |
+
yield response
|
45 |
+
|
46 |
+
|
47 |
+
def create_interface() -> gr.ChatInterface:
|
48 |
+
"""Create and configure the chat interface."""
|
49 |
+
# Custom CSS for a modern look
|
50 |
+
custom_css = """
|
51 |
+
.chatbot .message {
|
52 |
+
border-radius: 12px;
|
53 |
+
margin: 5px;
|
54 |
+
padding: 10px;
|
55 |
+
}
|
56 |
+
.chatbot .user-message {
|
57 |
+
background-color: #e3f2fd;
|
58 |
+
}
|
59 |
+
.chatbot .bot-message {
|
60 |
+
background-color: #f5f5f5;
|
61 |
+
}
|
62 |
+
.gr-button {
|
63 |
+
border-radius: 8px;
|
64 |
+
padding: 8px 16px;
|
65 |
+
}
|
66 |
+
"""
|
67 |
+
|
68 |
+
# Custom chatbot
|
69 |
+
chatbot = gr.Chatbot(
|
70 |
+
label="Gemma Chat",
|
71 |
+
avatar_images=("./user.png", "./botge.png"),
|
72 |
+
height=450,
|
73 |
+
show_copy_button=True
|
74 |
+
)
|
75 |
+
|
76 |
+
# Chat interface
|
77 |
+
interface = gr.ChatInterface(
|
78 |
+
fn=generate_response,
|
79 |
+
chatbot=chatbot,
|
80 |
+
title="欢迎体验 喵哥 Google-Gemma-3大模型",
|
81 |
+
theme=gr.themes.Soft(),
|
82 |
+
css=custom_css,
|
83 |
+
additional_inputs=[
|
84 |
+
gr.Textbox(
|
85 |
+
value=ChatConfig.DEFAULT_SYSTEM_MSG,
|
86 |
+
label="System Prompt",
|
87 |
+
lines=2,
|
88 |
+
placeholder="Enter system message..."
|
89 |
+
),
|
90 |
+
gr.Slider(
|
91 |
+
minimum=1,
|
92 |
+
maximum=8192,
|
93 |
+
value=ChatConfig.DEFAULT_MAX_TOKENS,
|
94 |
+
step=1,
|
95 |
+
label="Max Tokens",
|
96 |
+
info="Controls response length"
|
97 |
+
),
|
98 |
+
gr.Slider(
|
99 |
+
minimum=0.1,
|
100 |
+
maximum=1.0,
|
101 |
+
value=ChatConfig.DEFAULT_TEMP,
|
102 |
+
step=0.1,
|
103 |
+
label="Temperature",
|
104 |
+
info="Controls randomness"
|
105 |
+
),
|
106 |
+
gr.Slider(
|
107 |
+
minimum=0.1,
|
108 |
+
maximum=1.0,
|
109 |
+
value=ChatConfig.DEFAULT_TOP_P,
|
110 |
+
step=0.05,
|
111 |
+
label="Top-P",
|
112 |
+
info="Controls diversity"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
113 |
)
|
114 |
+
],
|
115 |
+
additional_inputs_accordion=gr.Accordion(label="Advanced Settings", open=False)
|
116 |
+
)
|
117 |
+
|
118 |
+
return interface
|
|
|
|
|
|
|
119 |
|
120 |
def main():
|
121 |
+
app = create_interface()
|
122 |
+
app.launch(
|
123 |
+
server_name="0.0.0.0",
|
124 |
+
server_port=7860,
|
125 |
+
share=False,
|
126 |
+
show_api=False,
|
127 |
+
show_error=True,
|
128 |
+
debug=True
|
129 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
130 |
|
131 |
if __name__ == "__main__":
|
132 |
main()
|