ruslanmv commited on
Commit
cdfa6da
·
verified ·
1 Parent(s): 4e809a7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -27
app.py CHANGED
@@ -1,11 +1,138 @@
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,
@@ -15,38 +142,46 @@ def respond(
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(
@@ -59,6 +194,5 @@ demo = gr.ChatInterface(
59
  ],
60
  )
61
 
62
-
63
  if __name__ == "__main__":
64
- demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
+ from transformers import AutoTokenizer # Import the tokenizer
4
 
5
+ # Use the appropriate tokenizer for your model.
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 = """[INST] <<SYS>>
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
+
93
+ **Please respond with:**
94
+ 1. Your internal reasoning wrapped in <think> tags
95
+ 2. Your NVC-formatted response after </think>
96
+ <</SYS>>
97
+
98
+ **User Input:**
99
+ {user_input}
100
+
101
+ [/INST]"""
102
+
103
+
104
+ def count_tokens(text: str) -> int:
105
+ """Counts the number of tokens in a given string."""
106
+ return len(tokenizer.encode(text))
107
+
108
+ def truncate_history(history: list[tuple[str, str]], system_message: str, max_length: int) -> list[tuple[str, str]]:
109
+ """Truncates the conversation history to fit within the maximum token limit.
110
+
111
+ Args:
112
+ history: The conversation history (list of user/assistant tuples).
113
+ system_message: The system message.
114
+ max_length: The maximum number of tokens allowed.
115
+
116
+ Returns:
117
+ The truncated history.
118
+ """
119
+ truncated_history = []
120
+ system_message_tokens = count_tokens(system_message)
121
+ current_length = system_message_tokens
122
+
123
+ # Iterate backwards through the history (newest to oldest)
124
+ for user_msg, assistant_msg in reversed(history):
125
+ user_tokens = count_tokens(user_msg) if user_msg else 0
126
+ assistant_tokens = count_tokens(assistant_msg) if assistant_msg else 0
127
+ turn_tokens = user_tokens + assistant_tokens
128
+
129
+ if current_length + turn_tokens <= max_length:
130
+ truncated_history.insert(0, (user_msg, assistant_msg)) # Add to the beginning
131
+ current_length += turn_tokens
132
+ else:
133
+ break # Stop adding turns if we exceed the limit
134
+
135
+ return truncated_history
136
 
137
  def respond(
138
  message,
 
142
  temperature,
143
  top_p,
144
  ):
145
+ """Responds to a user message, maintaining conversation history."""
146
 
147
+ # Format the system message with the user input
148
+ formatted_system_message = nvc_prompt_template.format(user_input="") # User input is inserted later
 
 
 
149
 
150
+ truncated_history = truncate_history(history, formatted_system_message, MAX_CONTEXT_LENGTH - max_tokens - 100) # Reserve space for the new message and some generation
151
 
152
+ messages = [{"role": "system", "content": formatted_system_message}]
153
+ for user_msg, assistant_msg in truncated_history:
154
+ if user_msg:
155
+ messages.append({"role": "user", "content": user_msg})
156
+ if assistant_msg:
157
+ messages.append({"role": "assistant", "content": assistant_msg})
158
 
159
+ # Format the user message with the user input template
160
+ formatted_user_message = nvc_prompt_template.format(user_input=message)
161
+ messages.append({"role": "user", "content": formatted_user_message})
 
 
 
 
 
162
 
 
 
163
 
164
+ response = ""
165
+ try:
166
+ for chunk in client.chat_completion(
167
+ messages,
168
+ max_tokens=max_tokens,
169
+ stream=True,
170
+ temperature=temperature,
171
+ top_p=top_p,
172
+ ):
173
+ token = chunk.choices[0].delta.content
174
+ response += token
175
+ yield response
176
+ except Exception as e:
177
+ print(f"An error occurred: {e}") # It's a good practice add a try-except block
178
+ yield "I'm sorry, I encountered an error. Please try again."
179
 
180
+ # --- Gradio Interface ---
 
 
181
  demo = gr.ChatInterface(
182
  respond,
183
  additional_inputs=[
184
+ gr.Textbox(value=nvc_prompt_template.split("<<SYS>>")[1].split("<</SYS>>")[0].strip(), label="System message", visible=False), # Set the NVC prompt as default and hide the system message box
185
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
186
  gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
187
  gr.Slider(
 
194
  ],
195
  )
196
 
 
197
  if __name__ == "__main__":
198
+ demo.launch()