ruslanmv commited on
Commit
e1561c7
·
verified ·
1 Parent(s): fb3f4e3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -40
app.py CHANGED
@@ -6,7 +6,7 @@ from transformers import AutoTokenizer # Import the tokenizer
6
  tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta")
7
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
9
- # Define a maximum context length (tokens). Check your model's documentation!
10
  MAX_CONTEXT_LENGTH = 4096 # Example: Adjust this based on your model!
11
 
12
  nvc_prompt_template = r"""<|system|>
@@ -78,7 +78,6 @@ You are Roos, an NVC (Nonviolent Communication) Chatbot. Your goal is to help us
78
  - “Thank you for sharing with me. If you’d like to continue this conversation later, I’m here to help.”</s>
79
  """
80
 
81
-
82
  def count_tokens(text: str) -> int:
83
  """Counts the number of tokens in a given string."""
84
  return len(tokenizer.encode(text))
@@ -119,53 +118,92 @@ def respond(
119
  top_p,
120
  ):
121
  """Responds to a user message, maintaining conversation history, using special tokens and message list."""
 
 
122
 
123
- formatted_system_message = nvc_prompt_template
124
-
125
- truncated_history = truncate_history(history, formatted_system_message, MAX_CONTEXT_LENGTH - max_tokens - 100) # Reserve space for the new message and some generation
 
 
126
 
127
- messages = [{"role": "system", "content": formatted_system_message}] # Start with system message as before
128
  for user_msg, assistant_msg in truncated_history:
129
  if user_msg:
130
- messages.append({"role": "user", "content": f"<|user|>\n{user_msg}</s>"}) # Format history user message
131
  if assistant_msg:
132
- messages.append({"role": "assistant", "content": f"<|assistant|>\n{assistant_msg}</s>"}) # Format history assistant message
133
-
134
- messages.append({"role": "user", "content": f"<|user|>\n{message}</s>"}) # Format current user message
135
-
136
 
137
  response = ""
138
  try:
139
- for chunk in client.chat_completion(
140
- messages, # Send the messages list again, but with formatted content
141
- max_tokens=max_tokens,
142
- stream=True,
143
- temperature=temperature,
144
- top_p=top_p,
145
- ):
146
- token = chunk.choices[0].delta.content
147
- response += token
148
- yield response
149
  except Exception as e:
150
- print(f"An error occurred: {e}") # It's a good practice add a try-except block
151
- yield "I'm sorry, I encountered an error. Please try again."
152
-
153
- # --- Gradio Interface ---
154
- demo = gr.ChatInterface(
155
- respond,
156
- additional_inputs=[
157
- gr.Textbox(value=nvc_prompt_template, label="System message", visible=False), # Set the NVC prompt as default and hide the system message box
158
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
159
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
160
- gr.Slider(
161
- minimum=0.1,
162
- maximum=1.0,
163
- value=0.95,
164
- step=0.05,
165
- label="Top-p (nucleus sampling)",
166
- ),
167
- ],
168
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
  if __name__ == "__main__":
171
  demo.launch()
 
6
  tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta")
7
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
9
+ # Define a maximum context length (tokens). Check your model's documentation!
10
  MAX_CONTEXT_LENGTH = 4096 # Example: Adjust this based on your model!
11
 
12
  nvc_prompt_template = r"""<|system|>
 
78
  - “Thank you for sharing with me. If you’d like to continue this conversation later, I’m here to help.”</s>
79
  """
80
 
 
81
  def count_tokens(text: str) -> int:
82
  """Counts the number of tokens in a given string."""
83
  return len(tokenizer.encode(text))
 
118
  top_p,
119
  ):
120
  """Responds to a user message, maintaining conversation history, using special tokens and message list."""
121
+ # Allow a modifiable system prompt; if none is provided, fall back to the default.
122
+ formatted_system_message = system_message if system_message else nvc_prompt_template
123
 
124
+ truncated_history = truncate_history(
125
+ history,
126
+ formatted_system_message,
127
+ MAX_CONTEXT_LENGTH - max_tokens - 100 # Reserve space for the new message and some generation
128
+ )
129
 
130
+ messages = [{"role": "system", "content": formatted_system_message}] # Start with system message
131
  for user_msg, assistant_msg in truncated_history:
132
  if user_msg:
133
+ messages.append({"role": "user", "content": f"<|user|>\n{user_msg}</s>"})
134
  if assistant_msg:
135
+ messages.append({"role": "assistant", "content": f"<|assistant|>\n{assistant_msg}</s>"})
136
+ messages.append({"role": "user", "content": f"<|user|>\n{message}</s>"})
 
 
137
 
138
  response = ""
139
  try:
140
+ for chunk in client.chat_completion(
141
+ messages, # Send the messages list with the formatted content
142
+ max_tokens=max_tokens,
143
+ stream=True,
144
+ temperature=temperature,
145
+ top_p=top_p,
146
+ ):
147
+ token = chunk.choices[0].delta.content
148
+ response += token
149
+ yield response
150
  except Exception as e:
151
+ print(f"An error occurred: {e}")
152
+ yield "I'm sorry, I encountered an error. Please try again."
153
+
154
+ # --- Gradio Interface using Blocks ---
155
+ with gr.Blocks() as demo:
156
+ # State to hold conversation history
157
+ state = gr.State([])
158
+
159
+ # Chatbot display
160
+ chatbot = gr.Chatbot(label="NVC Chatbot")
161
+
162
+ # System prompt textbox (modifiable)
163
+ with gr.Row():
164
+ system_prompt = gr.Textbox(value=nvc_prompt_template, label="System Prompt (modifiable)")
165
+
166
+ # Controls for generation parameters
167
+ with gr.Row():
168
+ max_tokens_slider = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens")
169
+ temperature_slider = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature")
170
+ top_p_slider = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)")
171
+
172
+ # Button to clear conversation memory
173
+ with gr.Row():
174
+ clear_button = gr.Button("Clear Memory")
175
+
176
+ # User input area and send button
177
+ with gr.Row():
178
+ user_input = gr.Textbox(label="Your Message", placeholder="Type your message here...")
179
+ send_button = gr.Button("Send")
180
+
181
+ def chat_step(message, history, system_message, max_tokens, temperature, top_p):
182
+ # Call the respond generator and accumulate the final response.
183
+ gen = respond(message, history, system_message, max_tokens, temperature, top_p)
184
+ response = ""
185
+ for r in gen:
186
+ response = r # In a streaming scenario, you might update the UI incrementally.
187
+ history.append((message, response))
188
+ return history, history
189
+
190
+ # Trigger the chat step on button click or when submitting the textbox.
191
+ send_button.click(
192
+ chat_step,
193
+ inputs=[user_input, state, system_prompt, max_tokens_slider, temperature_slider, top_p_slider],
194
+ outputs=[chatbot, state],
195
+ )
196
+ user_input.submit(
197
+ chat_step,
198
+ inputs=[user_input, state, system_prompt, max_tokens_slider, temperature_slider, top_p_slider],
199
+ outputs=[chatbot, state],
200
+ )
201
+
202
+ # Clear memory: resets both the chatbot display and the state.
203
+ def clear_history():
204
+ return [], []
205
+
206
+ clear_button.click(clear_history, inputs=[], outputs=[chatbot, state])
207
 
208
  if __name__ == "__main__":
209
  demo.launch()