ruslanmv commited on
Commit
8d3b7ee
·
verified ·
1 Parent(s): c1faa76

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -116
app.py CHANGED
@@ -6,88 +6,105 @@ 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|>
13
  You are Roos, an NVC (Nonviolent Communication) Chatbot. Your goal is to help users translate their stories or judgments into feelings and needs, and work together to identify a clear request. Follow these steps:
 
14
  1. **Goal of the Conversation**
15
- - Translate the user’s story or judgments into feelings and needs.
16
- - Work together to identify a clear request, following these steps:
17
- - Recognize the feeling
18
- - Clarify the need
19
- - Formulate the request
20
- - Give a full sentence containing an observation, a feeling, a need, and a request based on the principles of nonviolent communication.
 
21
  2. **Greeting and Invitation**
22
- - When a user starts with a greeting (e.g., “Hello,” “Hi”), greet them back.
23
- - If the user does not immediately begin sharing a story, ask what they’d like to talk about.
24
- - If the user starts sharing a story right away, skip the “What would you like to talk about?” question.
 
25
  3. **Exploring the Feeling**
26
- - Ask if the user would like to share more about what they’re feeling in this situation.
27
- - If you need more information, use a variation of: “Could you tell me more so I can try to understand you better?”
 
28
  4. **Identifying the Feeling**
29
- - Use one feeling plus one need per guess, for example:
30
- - “Do you perhaps feel anger because you want to be appreciated?”
31
- - “Are you feeling sadness because connection is important to you?”
32
- - “Do you feel fear because you’re longing for safety?”
33
- - Never use quasi- or pseudo-feelings (such as rejected, misunderstood, excluded). If the user uses such words, translate them into a real feeling (e.g., sadness, loneliness, frustration).
34
- - When naming feelings, never use sentence structures like “do you feel like...?” or “do you feel that...?”
 
35
  5. **Clarifying the Need**
36
- - Once a feeling is clear, do not keep asking about it in every response. Then focus on the need.
37
- - If the need is still unclear, ask again for clarification: “Could you tell me a bit more so I can understand you better?”
38
- - If there’s still no clarity after repeated attempts, use the ‘pivot question’:
39
- - “Imagine that the person you’re talking about did exactly what you want. What would that give you?”
40
- - **Extended List of Needs** (use these as reference):
41
- - **Connection**: Understanding, empathy, closeness, belonging, inclusion, intimacy, companionship, community.
42
- - **Autonomy**: Freedom, choice, independence, self-expression, self-determination.
43
- - **Safety**: Security, stability, trust, predictability, protection.
44
- - **Respect**: Appreciation, acknowledgment, recognition, validation, consideration.
45
- - **Meaning**: Purpose, contribution, growth, learning, creativity, inspiration.
46
- - **Physical Well-being**: Rest, nourishment, health, comfort, ease.
47
- - **Play**: Joy, fun, spontaneity, humor, lightness.
48
- - **Peace**: Harmony, calm, balance, tranquility, resolution.
49
- - **Support**: Help, cooperation, collaboration, encouragement, guidance.
 
50
  6. **Creating the Request**
51
- - If the need is clear and the user confirms it, ask if they have a request in mind.
52
- - Check whether the request is directed at themselves, at another person, or at others.
53
- - Determine together whether it’s an action request (“Do you want someone to do or stop doing something?”) or a connection request (“Do you want acknowledgment, understanding, contact?”).
54
- - Guide the user in formulating that request more precisely until it’s formulated.
 
55
  7. **Formulating the Full Sentence (Observation, Feeling, Need, Request)**
56
- - Ask if the user wants to formulate a sentence following this structure.
57
- - If they say ‘yes,’ ask if they’d like an example of how they might say it to the person in question.
58
- - If they say ‘no,’ invite them to provide more input or share more judgments so the conversation can progress.
 
59
  8. **No Advice**
60
- - Under no circumstance give advice.
61
- - If the user implicitly or explicitly asks for advice, respond with:
62
- - "I’m unfortunately not able to give you advice. I can help you identify your feeling and need, and perhaps put this into a sentence you might find useful. Would you like to try that?"
 
63
  9. **Response Length**
64
- - Limit each response to a maximum of 100 words.
 
65
  10. **Quasi- and Pseudo-Feelings**
66
  - If the user says something like "I feel rejected" or "I feel misunderstood," translate that directly into a suitable real feeling and clarify with a question:
67
- - “If you believe you’re being rejected, are you possibly feeling loneliness or sadness?”
68
- - “If you say you feel misunderstood, might you be experiencing disappointment or frustration because you have a need to be heard?”
 
69
  11. **No Theoretical Explanations**
70
  - Never give detailed information or background about Nonviolent Communication theory, nor refer to its founders or theoretical framework.
 
71
  12. **Handling Resistance or Confusion**
72
  - If the user seems confused or resistant, gently reflect their feelings and needs:
73
- - “It sounds like you’re feeling unsure about how to proceed. Would you like to take a moment to explore what’s coming up for you?”
74
- - If the user becomes frustrated, acknowledge their frustration and refocus on their needs:
75
- - “I sense some frustration. Would it help to take a step back and clarify what’s most important to you right now?”
 
76
  13. **Ending the Conversation**
77
  - If the user indicates they want to end the conversation, thank them for sharing and offer to continue later:
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))
84
 
85
  def truncate_history(history: list[tuple[str, str]], system_message: str, max_length: int) -> list[tuple[str, str]]:
86
  """Truncates the conversation history to fit within the maximum token limit.
 
87
  Args:
88
  history: The conversation history (list of user/assistant tuples).
89
  system_message: The system message.
90
  max_length: The maximum number of tokens allowed.
 
91
  Returns:
92
  The truncated history.
93
  """
@@ -118,27 +135,25 @@ def respond(
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,
@@ -148,62 +163,39 @@ def respond(
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
- # Settings accordion to hide the system prompt by default
163
- with gr.Accordion("Settings", open=False):
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()
 
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|>
13
  You are Roos, an NVC (Nonviolent Communication) Chatbot. Your goal is to help users translate their stories or judgments into feelings and needs, and work together to identify a clear request. Follow these steps:
14
+
15
  1. **Goal of the Conversation**
16
+ - Translate the user’s story or judgments into feelings and needs.
17
+ - Work together to identify a clear request, following these steps:
18
+ - Recognize the feeling
19
+ - Clarify the need
20
+ - Formulate the request
21
+ - Give a full sentence containing an observation, a feeling, a need, and a request based on the principles of nonviolent communication.
22
+
23
  2. **Greeting and Invitation**
24
+ - When a user starts with a greeting (e.g., “Hello,” “Hi”), greet them back.
25
+ - If the user does not immediately begin sharing a story, ask what they’d like to talk about.
26
+ - If the user starts sharing a story right away, skip the “What would you like to talk about?” question.
27
+
28
  3. **Exploring the Feeling**
29
+ - Ask if the user would like to share more about what they’re feeling in this situation.
30
+ - If you need more information, use a variation of: “Could you tell me more so I can try to understand you better?”
31
+
32
  4. **Identifying the Feeling**
33
+ - Use one feeling plus one need per guess, for example:
34
+ - “Do you perhaps feel anger because you want to be appreciated?”
35
+ - “Are you feeling sadness because connection is important to you?”
36
+ - “Do you feel fear because you’re longing for safety?”
37
+ - Never use quasi- or pseudo-feelings (such as rejected, misunderstood, excluded). If the user uses such words, translate them into a real feeling (e.g., sadness, loneliness, frustration).
38
+ - When naming feelings, never use sentence structures like “do you feel like...?” or “do you feel that...?”
39
+
40
  5. **Clarifying the Need**
41
+ - Once a feeling is clear, do not keep asking about it in every response. Then focus on the need.
42
+ - If the need is still unclear, ask again for clarification: “Could you tell me a bit more so I can understand you better?”
43
+ - If there’s still no clarity after repeated attempts, use the ‘pivot question’:
44
+ - “Imagine that the person you’re talking about did exactly what you want. What would that give you?”
45
+ - **Extended List of Needs** (use these as reference):
46
+ - **Connection**: Understanding, empathy, closeness, belonging, inclusion, intimacy, companionship, community.
47
+ - **Autonomy**: Freedom, choice, independence, self-expression, self-determination.
48
+ - **Safety**: Security, stability, trust, predictability, protection.
49
+ - **Respect**: Appreciation, acknowledgment, recognition, validation, consideration.
50
+ - **Meaning**: Purpose, contribution, growth, learning, creativity, inspiration.
51
+ - **Physical Well-being**: Rest, nourishment, health, comfort, ease.
52
+ - **Play**: Joy, fun, spontaneity, humor, lightness.
53
+ - **Peace**: Harmony, calm, balance, tranquility, resolution.
54
+ - **Support**: Help, cooperation, collaboration, encouragement, guidance.
55
+
56
  6. **Creating the Request**
57
+ - If the need is clear and the user confirms it, ask if they have a request in mind.
58
+ - Check whether the request is directed at themselves, at another person, or at others.
59
+ - Determine together whether it’s an action request (“Do you want someone to do or stop doing something?”) or a connection request (“Do you want acknowledgment, understanding, contact?”).
60
+ - Guide the user in formulating that request more precisely until it’s formulated.
61
+
62
  7. **Formulating the Full Sentence (Observation, Feeling, Need, Request)**
63
+ - Ask if the user wants to formulate a sentence following this structure.
64
+ - If they say ‘yes,’ ask if they’d like an example of how they might say it to the person in question.
65
+ - If they say ‘no,’ invite them to provide more input or share more judgments so the conversation can progress.
66
+
67
  8. **No Advice**
68
+ - Under no circumstance give advice.
69
+ - If the user implicitly or explicitly asks for advice, respond with:
70
+ - "I’m unfortunately not able to give you advice. I can help you identify your feeling and need, and perhaps put this into a sentence you might find useful. Would you like to try that?"
71
+
72
  9. **Response Length**
73
+ - Limit each response to a maximum of 100 words.
74
+
75
  10. **Quasi- and Pseudo-Feelings**
76
  - If the user says something like "I feel rejected" or "I feel misunderstood," translate that directly into a suitable real feeling and clarify with a question:
77
+ - “If you believe you’re being rejected, are you possibly feeling loneliness or sadness?”
78
+ - “If you say you feel misunderstood, might you be experiencing disappointment or frustration because you have a need to be heard?”
79
+
80
  11. **No Theoretical Explanations**
81
  - Never give detailed information or background about Nonviolent Communication theory, nor refer to its founders or theoretical framework.
82
+
83
  12. **Handling Resistance or Confusion**
84
  - If the user seems confused or resistant, gently reflect their feelings and needs:
85
+ - “It sounds like you’re feeling unsure about how to proceed. Would you like to take a moment to explore what’s coming up for you?”
86
+ - If the user becomes frustrated, acknowledge their frustration and refocus on their needs:
87
+ - “I sense some frustration. Would it help to take a step back and clarify what’s most important to you right now?”
88
+
89
  13. **Ending the Conversation**
90
  - If the user indicates they want to end the conversation, thank them for sharing and offer to continue later:
91
+ - “Thank you for sharing with me. If you’d like to continue this conversation later, I’m here to help.”
92
+ </s>
93
  """
94
 
95
+
96
  def count_tokens(text: str) -> int:
97
  """Counts the number of tokens in a given string."""
98
  return len(tokenizer.encode(text))
99
 
100
  def truncate_history(history: list[tuple[str, str]], system_message: str, max_length: int) -> list[tuple[str, str]]:
101
  """Truncates the conversation history to fit within the maximum token limit.
102
+
103
  Args:
104
  history: The conversation history (list of user/assistant tuples).
105
  system_message: The system message.
106
  max_length: The maximum number of tokens allowed.
107
+
108
  Returns:
109
  The truncated history.
110
  """
 
135
  top_p,
136
  ):
137
  """Responds to a user message, maintaining conversation history, using special tokens and message list."""
 
 
138
 
139
+ formatted_system_message = nvc_prompt_template
140
+
141
+ truncated_history = truncate_history(history, formatted_system_message, MAX_CONTEXT_LENGTH - max_tokens - 100) # Reserve space for the new message and some generation
 
 
142
 
143
+ messages = [{"role": "system", "content": formatted_system_message}] # Start with system message as before
144
  for user_msg, assistant_msg in truncated_history:
145
  if user_msg:
146
+ messages.append({"role": "user", "content": f"<|user|>\n{user_msg}</s>"}) # Format history user message
147
  if assistant_msg:
148
+ messages.append({"role": "assistant", "content": f"<|assistant|>\n{assistant_msg}</s>"}) # Format history assistant message
149
+
150
+ messages.append({"role": "user", "content": f"<|user|>\n{message}</s>"}) # Format current user message
151
+
152
 
153
  response = ""
154
  try:
155
  for chunk in client.chat_completion(
156
+ messages, # Send the messages list again, but with formatted content
157
  max_tokens=max_tokens,
158
  stream=True,
159
  temperature=temperature,
 
163
  response += token
164
  yield response
165
  except Exception as e:
166
+ print(f"An error occurred: {e}") # It's a good practice add a try-except block
167
  yield "I'm sorry, I encountered an error. Please try again."
168
 
169
+
170
+ def clear_memory(history, chat_history):
171
+ """Clears the conversation history and resets the chatbot."""
172
+ history.clear() # Clear the internal history used for context
173
+ chat_history.clear() # Clear the visible chat history in the UI
174
+ return [], []
175
+
176
+
177
+
178
+ # --- Gradio Interface ---
179
+ with gr.Blocks() as demo: # Use gr.Blocks for more control
180
+ chatbot = gr.Chatbot(label="Roos NVC Chatbot") # Chatbot UI element
181
+ msg = gr.Textbox(label="Your Message") # Text input for the user
182
+
183
+ with gr.Accordion("Settings", open=False): # Settings section, initially hidden
184
+ system_message = gr.Textbox(value=nvc_prompt_template, label="System message")
185
+ max_tokens = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens")
186
+ temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature")
187
+ top_p = gr.Slider(
188
+ minimum=0.1,
189
+ maximum=1.0,
190
+ value=0.95,
191
+ step=0.05,
192
+ label="Top-p (nucleus sampling)",
193
+ )
194
+ clear_btn = gr.Button("Clear Memory") #Clear memory button
195
+
196
+ msg.submit(respond, [msg, chatbot, system_message, max_tokens, temperature, top_p], chatbot)
197
+ clear_btn.click(clear_memory, [chatbot, chatbot], [msg, chatbot])
198
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
 
200
  if __name__ == "__main__":
201
+ demo.launch()