Nymbo commited on
Commit
69b4a5f
·
verified ·
1 Parent(s): 880ced6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -202
app.py CHANGED
@@ -16,9 +16,9 @@ print("OpenAI client initialized.")
16
  def respond(
17
  message,
18
  history: list[tuple[str, str]],
19
- system_message,
20
- custom_model,
21
  model,
 
 
22
  max_tokens,
23
  temperature,
24
  top_p,
@@ -26,66 +26,43 @@ def respond(
26
  seed
27
  ):
28
  """
29
- This function handles the chatbot response. It takes in:
30
- - message: the user's new message
31
- - history: the list of previous messages, each as a tuple (user_msg, assistant_msg)
32
- - system_message: the system prompt
33
- - custom_model: custom model path (if any)
34
- - model: selected model from featured models
35
- - max_tokens: the maximum number of tokens to generate in the response
36
- - temperature: sampling temperature
37
- - top_p: top-p (nucleus) sampling
38
- - frequency_penalty: penalize repeated tokens in the output
39
- - seed: a fixed seed for reproducibility; -1 will mean 'random'
40
  """
41
-
42
  print(f"Received message: {message}")
43
  print(f"History: {history}")
44
- print(f"System message: {system_message}")
45
  print(f"Custom model: {custom_model}")
46
- print(f"Selected model: {model}")
47
- print(f"Max tokens: {max_tokens}, Temperature: {temperature}, Top-P: {top_p}")
48
  print(f"Frequency Penalty: {frequency_penalty}, Seed: {seed}")
49
 
50
- # Convert seed to None if -1 (meaning random)
51
  if seed == -1:
52
  seed = None
53
 
54
- # Construct the messages array required by the API
 
 
 
55
  messages = [{"role": "system", "content": system_message}]
56
 
57
- # Add conversation history to the context
58
  for val in history:
59
  user_part = val[0]
60
  assistant_part = val[1]
61
  if user_part:
62
  messages.append({"role": "user", "content": user_part})
63
- print(f"Added user message to context: {user_part}")
64
  if assistant_part:
65
  messages.append({"role": "assistant", "content": assistant_part})
66
- print(f"Added assistant message to context: {assistant_part}")
67
 
68
- # Append the latest user message
69
  messages.append({"role": "user", "content": message})
70
 
71
- # Start with an empty string to build the response as tokens stream in
72
  response = ""
73
- print("Sending request to OpenAI API.")
74
 
75
- # Determine which model to use
76
- if custom_model.strip():
77
- selected_model = custom_model.strip()
78
- else:
79
- # Map the display names to actual model paths
80
- model_mapping = {
81
- "Llama 2 70B": "meta-llama/Llama-2-70b-chat-hf",
82
- "Mixtral 8x7B": "mistralai/Mixtral-8x7B-Instruct-v0.1",
83
- "Zephyr 7B": "HuggingFaceH4/zephyr-7b-beta",
84
- "OpenChat 3.5": "openchat/openchat-3.5-0106",
85
- }
86
- selected_model = model_mapping.get(model, "meta-llama/Llama-2-70b-chat-hf")
87
-
88
- # Make the streaming request to the HF Inference API via openai-like client
89
  for message_chunk in client.chat.completions.create(
90
  model=selected_model,
91
  max_tokens=max_tokens,
@@ -96,7 +73,6 @@ def respond(
96
  seed=seed,
97
  messages=messages,
98
  ):
99
- # Extract the token text from the response chunk
100
  token_text = message_chunk.choices[0].delta.content
101
  print(f"Received token: {token_text}")
102
  response += token_text
@@ -104,181 +80,135 @@ def respond(
104
 
105
  print("Completed response generation.")
106
 
107
- # Create a Chatbot component with a specified height
108
  chatbot = gr.Chatbot(height=600)
109
  print("Chatbot interface created.")
110
 
 
 
 
 
 
 
 
 
 
111
  # Create the Gradio interface with tabs
112
  with gr.Blocks(theme="Nymbo/Nymbo_Theme") as demo:
113
- with gr.Row():
114
- with gr.Column():
115
- # Basic Settings Tab
116
- with gr.Tab("Settings"):
117
- # System Message
118
- system_message = gr.Textbox(
119
- value="",
120
- label="System message",
121
- placeholder="Enter a system message to guide the model's behavior"
122
- )
123
-
124
- # Model Selection Section
125
  with gr.Accordion("Featured Models", open=True):
126
- # Model Search
127
  model_search = gr.Textbox(
128
  label="Filter Models",
129
- placeholder="Search for a featured model...",
130
  lines=1
131
  )
132
-
133
- # Featured Models List
134
- models_list = [
135
- "Llama 2 70B",
136
- "Mixtral 8x7B",
137
- "Zephyr 7B",
138
- "OpenChat 3.5"
139
- ]
140
-
141
  model = gr.Radio(
142
  label="Select a model",
143
  choices=models_list,
144
- value="Llama 2 70B"
145
- )
146
-
147
- # Custom Model Input
148
- custom_model = gr.Textbox(
149
- label="Custom Model",
150
- info="Hugging Face model path (optional)",
151
- placeholder="meta-llama/Llama-2-70b-chat-hf"
152
- )
153
-
154
- # Function to filter models
155
- def filter_models(search_term):
156
- filtered_models = [m for m in models_list if search_term.lower() in m.lower()]
157
- return gr.update(choices=filtered_models)
158
-
159
- # Update model list when search box is used
160
- model_search.change(filter_models, inputs=model_search, outputs=model)
161
-
162
- # Generation Parameters
163
- with gr.Row():
164
- max_tokens = gr.Slider(
165
- minimum=1,
166
- maximum=4096,
167
- value=512,
168
- step=1,
169
- label="Max new tokens"
170
- )
171
- temperature = gr.Slider(
172
- minimum=0.1,
173
- maximum=4.0,
174
- value=0.7,
175
- step=0.1,
176
- label="Temperature"
177
- )
178
-
179
- with gr.Row():
180
- top_p = gr.Slider(
181
- minimum=0.1,
182
- maximum=1.0,
183
- value=0.95,
184
- step=0.05,
185
- label="Top-P"
186
- )
187
- frequency_penalty = gr.Slider(
188
- minimum=-2.0,
189
- maximum=2.0,
190
- value=0.0,
191
- step=0.1,
192
- label="Frequency Penalty"
193
- )
194
-
195
- with gr.Row():
196
- seed = gr.Slider(
197
- minimum=-1,
198
- maximum=65535,
199
- value=-1,
200
- step=1,
201
- label="Seed (-1 for random)"
202
- )
203
-
204
- # Information Tab
205
- with gr.Tab("Information"):
206
- # Featured Models Table
207
- with gr.Accordion("Featured Models", open=True):
208
- gr.HTML(
209
- """
210
- <p><a href="https://huggingface.co/models?inference=warm&pipeline_tag=text-to-text">See all available models</a></p>
211
- <table style="width:100%; text-align:center; margin:auto;">
212
- <tr>
213
- <th>Model Name</th>
214
- <th>Size</th>
215
- <th>Notes</th>
216
- </tr>
217
- <tr>
218
- <td>Llama 2 70B</td>
219
- <td>70B</td>
220
- <td>Meta's flagship model</td>
221
- </tr>
222
- <tr>
223
- <td>Mixtral 8x7B</td>
224
- <td>47B</td>
225
- <td>Mistral AI's MoE model</td>
226
- </tr>
227
- <tr>
228
- <td>Zephyr 7B</td>
229
- <td>7B</td>
230
- <td>Efficient fine-tuned model</td>
231
- </tr>
232
- <tr>
233
- <td>OpenChat 3.5</td>
234
- <td>7B</td>
235
- <td>High performance chat model</td>
236
- </tr>
237
- </table>
238
- """
239
  )
240
 
241
- # Parameters Overview
242
- with gr.Accordion("Parameters Overview", open=False):
243
- gr.Markdown(
244
- """
245
- ## System Message
246
- A message that sets the context and behavior for the model. This helps guide the model's responses.
247
-
248
- ## Max New Tokens
249
- Controls the maximum length of the generated response. Higher values allow for longer outputs but may take more time.
250
-
251
- ## Temperature
252
- Controls randomness in the output:
253
- - Lower values (0.1-0.5): More focused and deterministic
254
- - Higher values (0.7-1.0): More creative and diverse
255
- - Very high values (>1.0): More random and potentially chaotic
256
-
257
- ## Top-P (Nucleus Sampling)
258
- Controls the cumulative probability threshold for token selection:
259
- - Lower values: More focused on highly likely tokens
260
- - Higher values: Considers a wider range of possibilities
261
-
262
- ## Frequency Penalty
263
- Adjusts the likelihood of token repetition:
264
- - Negative values: May encourage repetition
265
- - Zero: Neutral
266
- - Positive values: Discourages repetition
267
-
268
- ## Seed
269
- A number that controls the randomness in generation:
270
- - -1: Random seed each time
271
- - Fixed value: Reproducible outputs with same parameters
272
- """
273
- )
274
-
275
- # Set up the chat interface
276
- chatbot = gr.Chatbot(height=600)
277
- msg = gr.Textbox(label="Message")
278
-
279
- clear = gr.ClearButton([msg, chatbot])
280
-
281
- msg.submit(respond, [msg, chatbot, system_message, custom_model, model, max_tokens, temperature, top_p, frequency_penalty, seed], [chatbot, msg])
282
 
283
- print("Launching the demo application.")
284
- demo.launch(show_api=False, share=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  def respond(
17
  message,
18
  history: list[tuple[str, str]],
 
 
19
  model,
20
+ custom_model,
21
+ system_message,
22
  max_tokens,
23
  temperature,
24
  top_p,
 
26
  seed
27
  ):
28
  """
29
+ This function handles the chatbot response.
 
 
 
 
 
 
 
 
 
 
30
  """
 
31
  print(f"Received message: {message}")
32
  print(f"History: {history}")
33
+ print(f"Model: {model}")
34
  print(f"Custom model: {custom_model}")
35
+ print(f"System message: {system_message}")
36
+ print(f"Parameters - Max tokens: {max_tokens}, Temperature: {temperature}, Top-P: {top_p}")
37
  print(f"Frequency Penalty: {frequency_penalty}, Seed: {seed}")
38
 
39
+ # Convert seed to None if -1
40
  if seed == -1:
41
  seed = None
42
 
43
+ # Set the model based on selection or custom input
44
+ selected_model = custom_model.strip() if custom_model.strip() != "" else model
45
+
46
+ # Construct messages array
47
  messages = [{"role": "system", "content": system_message}]
48
 
49
+ # Add conversation history
50
  for val in history:
51
  user_part = val[0]
52
  assistant_part = val[1]
53
  if user_part:
54
  messages.append({"role": "user", "content": user_part})
 
55
  if assistant_part:
56
  messages.append({"role": "assistant", "content": assistant_part})
 
57
 
58
+ # Append latest message
59
  messages.append({"role": "user", "content": message})
60
 
61
+ # Start with empty response
62
  response = ""
63
+ print("Sending request to API.")
64
 
65
+ # Make the streaming request
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  for message_chunk in client.chat.completions.create(
67
  model=selected_model,
68
  max_tokens=max_tokens,
 
73
  seed=seed,
74
  messages=messages,
75
  ):
 
76
  token_text = message_chunk.choices[0].delta.content
77
  print(f"Received token: {token_text}")
78
  response += token_text
 
80
 
81
  print("Completed response generation.")
82
 
83
+ # Create Chatbot component
84
  chatbot = gr.Chatbot(height=600)
85
  print("Chatbot interface created.")
86
 
87
+ # Define available models
88
+ models_list = [
89
+ "meta-llama/Llama-2-70b-chat-hf",
90
+ "meta-llama/Llama-2-13b-chat-hf",
91
+ "mistralai/Mixtral-8x7B-Instruct-v0.1",
92
+ "mistralai/Mistral-7B-Instruct-v0.2",
93
+ "HuggingFaceH4/zephyr-7b-beta",
94
+ ]
95
+
96
  # Create the Gradio interface with tabs
97
  with gr.Blocks(theme="Nymbo/Nymbo_Theme") as demo:
98
+ with gr.Tab("Chat"):
99
+ with gr.Row():
100
+ with gr.Column():
101
+ # Model selection accordion
 
 
 
 
 
 
 
 
102
  with gr.Accordion("Featured Models", open=True):
 
103
  model_search = gr.Textbox(
104
  label="Filter Models",
105
+ placeholder="Search for a model...",
106
  lines=1
107
  )
 
 
 
 
 
 
 
 
 
108
  model = gr.Radio(
109
  label="Select a model",
110
  choices=models_list,
111
+ value="meta-llama/Llama-2-70b-chat-hf"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  )
113
 
114
+ # Custom model input
115
+ custom_model = gr.Textbox(
116
+ label="Custom Model",
117
+ info="Enter Hugging Face model path (optional)",
118
+ placeholder="organization/model-name"
119
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
+ # System message and parameters
122
+ system_message = gr.Textbox(label="System message")
123
+ max_tokens = gr.Slider(minimum=1, maximum=4096, value=512, step=1, label="Max new tokens")
124
+ temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature")
125
+ top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-P")
126
+ frequency_penalty = gr.Slider(minimum=-2.0, maximum=2.0, value=0.0, step=0.1, label="Frequency Penalty")
127
+ seed = gr.Slider(minimum=-1, maximum=65535, value=-1, step=1, label="Seed (-1 for random)")
128
+
129
+ with gr.Tab("Information"):
130
+ with gr.Accordion("Featured Models", open=False):
131
+ gr.HTML("""
132
+ <p><a href="https://huggingface.co/models?pipeline_tag=text-generation&sort=trending">See all available models</a></p>
133
+ <table style="width:100%; text-align:center; margin:auto;">
134
+ <tr>
135
+ <th>Model Name</th>
136
+ <th>Parameters</th>
137
+ <th>Notes</th>
138
+ </tr>
139
+ <tr>
140
+ <td>Llama-2-70b-chat</td>
141
+ <td>70B</td>
142
+ <td>Meta's largest chat model</td>
143
+ </tr>
144
+ <tr>
145
+ <td>Mixtral-8x7B</td>
146
+ <td>47B</td>
147
+ <td>Mixture of Experts architecture</td>
148
+ </tr>
149
+ <tr>
150
+ <td>Mistral-7B</td>
151
+ <td>7B</td>
152
+ <td>Efficient base model</td>
153
+ </tr>
154
+ </table>
155
+ """)
156
+
157
+ with gr.Accordion("Parameters Overview", open=False):
158
+ gr.Markdown("""
159
+ ## System Message
160
+ The system message sets the context and behavior for the AI assistant. It's like giving it a role or specific instructions.
161
+
162
+ ## Max New Tokens
163
+ Controls the maximum length of the generated response. Higher values allow for longer responses but take more time.
164
+
165
+ ## Temperature
166
+ Controls randomness in the response:
167
+ - Lower (0.1-0.5): More focused and deterministic
168
+ - Higher (0.7-1.0): More creative and varied
169
+
170
+ ## Top-P
171
+ Nucleus sampling parameter:
172
+ - Lower values: More focused on likely tokens
173
+ - Higher values: More diverse vocabulary usage
174
+
175
+ ## Frequency Penalty
176
+ Discourages repetition:
177
+ - Negative: May allow more repetition
178
+ - Positive: Encourages more diverse word choice
179
+
180
+ ## Seed
181
+ Controls randomness initialization:
182
+ - -1: Random seed each time
183
+ - Fixed value: Reproducible outputs
184
+ """)
185
+
186
+ # Function to filter models based on search
187
+ def filter_models(search_term):
188
+ filtered_models = [m for m in models_list if search_term.lower() in m.lower()]
189
+ return gr.update(choices=filtered_models)
190
+
191
+ # Connect the search box to the model filter function
192
+ model_search.change(filter_models, inputs=model_search, outputs=model)
193
+
194
+ # Create the chat interface
195
+ chat_interface = gr.ChatInterface(
196
+ respond,
197
+ additional_inputs=[
198
+ model,
199
+ custom_model,
200
+ system_message,
201
+ max_tokens,
202
+ temperature,
203
+ top_p,
204
+ frequency_penalty,
205
+ seed,
206
+ ],
207
+ chatbot=chatbot,
208
+ )
209
+
210
+ print("Gradio interface initialized.")
211
+
212
+ if __name__ == "__main__":
213
+ print("Launching the demo application.")
214
+ demo.launch(show_api=False, share=False)