Update app.py
Browse files
app.py
CHANGED
@@ -1,148 +1,60 @@
|
|
1 |
import gradio as gr
|
2 |
from huggingface_hub import InferenceClient
|
3 |
-
from transformers import AutoTokenizer
|
4 |
|
5 |
-
# Load
|
6 |
-
tokenizer =
|
7 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
|
9 |
-
# Define
|
10 |
-
MAX_CONTEXT_LENGTH = 4096
|
11 |
|
12 |
-
|
13 |
-
default_nvc_prompt_template = r"""<|system|>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.”"""
|
79 |
|
80 |
def count_tokens(text: str) -> int:
|
81 |
-
"""Counts the number of tokens in a given string
|
82 |
return len(tokenizer.encode(text))
|
83 |
|
84 |
def truncate_history(history: list[tuple[str, str]], system_message: str, max_length: int) -> list[tuple[str, str]]:
|
85 |
-
"""
|
86 |
-
Truncates the conversation history to fit within the maximum token limit.
|
87 |
-
|
88 |
-
Args:
|
89 |
-
history: The conversation history (list of (user_msg, assistant_msg) tuples).
|
90 |
-
system_message: The system message.
|
91 |
-
max_length: The maximum number of tokens allowed.
|
92 |
-
|
93 |
-
Returns:
|
94 |
-
The truncated history as a list of (user_msg, assistant_msg) tuples.
|
95 |
-
"""
|
96 |
truncated_history = []
|
97 |
system_message_tokens = count_tokens(system_message)
|
98 |
current_length = system_message_tokens
|
99 |
|
100 |
-
# Iterate backwards (from the newest to the oldest)
|
101 |
for user_msg, assistant_msg in reversed(history):
|
102 |
user_tokens = count_tokens(user_msg) if user_msg else 0
|
103 |
assistant_tokens = count_tokens(assistant_msg) if assistant_msg else 0
|
104 |
turn_tokens = user_tokens + assistant_tokens
|
105 |
|
106 |
if current_length + turn_tokens <= max_length:
|
107 |
-
truncated_history.insert(0, (user_msg, assistant_msg))
|
108 |
current_length += turn_tokens
|
109 |
else:
|
110 |
-
break
|
111 |
|
112 |
return truncated_history
|
113 |
|
114 |
-
def respond(message, history
|
115 |
-
"""
|
116 |
-
|
117 |
-
Uses standard role-based messaging rather than explicit <|user|> tokens.
|
118 |
-
"""
|
119 |
-
|
120 |
-
# Clear memory command
|
121 |
if message.lower() == "clear memory":
|
122 |
-
return "", []
|
123 |
|
124 |
-
|
125 |
-
truncated_history = truncate_history(
|
126 |
-
history,
|
127 |
-
system_message,
|
128 |
-
MAX_CONTEXT_LENGTH - max_tokens - 100 # Reserve space for the new message
|
129 |
-
)
|
130 |
-
|
131 |
-
# Prepare the messages list in a standard chat format
|
132 |
-
messages = [{"role": "system", "content": system_message}]
|
133 |
|
|
|
|
|
134 |
for user_msg, assistant_msg in truncated_history:
|
135 |
if user_msg:
|
136 |
messages.append({"role": "user", "content": user_msg})
|
137 |
if assistant_msg:
|
138 |
messages.append({"role": "assistant", "content": assistant_msg})
|
139 |
|
140 |
-
# Add the new user message
|
141 |
messages.append({"role": "user", "content": message})
|
142 |
|
143 |
response = ""
|
144 |
try:
|
145 |
-
# Stream the response
|
146 |
for chunk in client.chat_completion(
|
147 |
messages,
|
148 |
max_tokens=max_tokens,
|
@@ -153,42 +65,18 @@ def respond(message, history: list[tuple[str, str]], system_message, max_tokens,
|
|
153 |
token = chunk.choices[0].delta.content
|
154 |
response += token
|
155 |
yield response
|
156 |
-
|
157 |
except Exception as e:
|
158 |
-
print(f"
|
159 |
yield "I'm sorry, I encountered an error. Please try again."
|
160 |
|
161 |
-
# Build
|
162 |
demo = gr.ChatInterface(
|
163 |
fn=respond,
|
164 |
additional_inputs=[
|
165 |
-
gr.Textbox(
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
lines=10,
|
170 |
-
),
|
171 |
-
gr.Slider(
|
172 |
-
minimum=1,
|
173 |
-
maximum=2048,
|
174 |
-
value=512,
|
175 |
-
step=1,
|
176 |
-
label="Max new tokens",
|
177 |
-
),
|
178 |
-
gr.Slider(
|
179 |
-
minimum=0.1,
|
180 |
-
maximum=4.0,
|
181 |
-
value=0.7,
|
182 |
-
step=0.1,
|
183 |
-
label="Temperature",
|
184 |
-
),
|
185 |
-
gr.Slider(
|
186 |
-
minimum=0.1,
|
187 |
-
maximum=1.0,
|
188 |
-
value=0.95,
|
189 |
-
step=0.05,
|
190 |
-
label="Top-p (nucleus sampling)",
|
191 |
-
),
|
192 |
],
|
193 |
)
|
194 |
|
|
|
1 |
import gradio as gr
|
2 |
from huggingface_hub import InferenceClient
|
3 |
+
from transformers import LlamaTokenizer # Use LlamaTokenizer instead of AutoTokenizer
|
4 |
|
5 |
+
# Load the correct tokenizer
|
6 |
+
tokenizer = LlamaTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta")
|
7 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
|
9 |
+
# Define max context length (tokens)
|
10 |
+
MAX_CONTEXT_LENGTH = 4096
|
11 |
|
12 |
+
default_nvc_prompt_template = """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..."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
def count_tokens(text: str) -> int:
|
15 |
+
"""Counts the number of tokens in a given string."""
|
16 |
return len(tokenizer.encode(text))
|
17 |
|
18 |
def truncate_history(history: list[tuple[str, str]], system_message: str, max_length: int) -> list[tuple[str, str]]:
|
19 |
+
"""Truncates the conversation history to fit within the maximum token limit."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
truncated_history = []
|
21 |
system_message_tokens = count_tokens(system_message)
|
22 |
current_length = system_message_tokens
|
23 |
|
|
|
24 |
for user_msg, assistant_msg in reversed(history):
|
25 |
user_tokens = count_tokens(user_msg) if user_msg else 0
|
26 |
assistant_tokens = count_tokens(assistant_msg) if assistant_msg else 0
|
27 |
turn_tokens = user_tokens + assistant_tokens
|
28 |
|
29 |
if current_length + turn_tokens <= max_length:
|
30 |
+
truncated_history.insert(0, (user_msg, assistant_msg)) # Add to the beginning
|
31 |
current_length += turn_tokens
|
32 |
else:
|
33 |
+
break # Stop if limit exceeded
|
34 |
|
35 |
return truncated_history
|
36 |
|
37 |
+
def respond(message, history, system_message, max_tokens, temperature, top_p):
|
38 |
+
"""Handles user message and generates a response."""
|
39 |
+
|
|
|
|
|
|
|
|
|
40 |
if message.lower() == "clear memory":
|
41 |
+
return "", [] # Reset chat history
|
42 |
|
43 |
+
formatted_system_message = system_message
|
44 |
+
truncated_history = truncate_history(history, formatted_system_message, MAX_CONTEXT_LENGTH - max_tokens - 100)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
+
messages = [{"role": "system", "content": formatted_system_message}]
|
47 |
+
|
48 |
for user_msg, assistant_msg in truncated_history:
|
49 |
if user_msg:
|
50 |
messages.append({"role": "user", "content": user_msg})
|
51 |
if assistant_msg:
|
52 |
messages.append({"role": "assistant", "content": assistant_msg})
|
53 |
|
|
|
54 |
messages.append({"role": "user", "content": message})
|
55 |
|
56 |
response = ""
|
57 |
try:
|
|
|
58 |
for chunk in client.chat_completion(
|
59 |
messages,
|
60 |
max_tokens=max_tokens,
|
|
|
65 |
token = chunk.choices[0].delta.content
|
66 |
response += token
|
67 |
yield response
|
|
|
68 |
except Exception as e:
|
69 |
+
print(f"Error: {e}")
|
70 |
yield "I'm sorry, I encountered an error. Please try again."
|
71 |
|
72 |
+
# Build Gradio UI
|
73 |
demo = gr.ChatInterface(
|
74 |
fn=respond,
|
75 |
additional_inputs=[
|
76 |
+
gr.Textbox(value=default_nvc_prompt_template, label="System message", lines=10),
|
77 |
+
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
78 |
+
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
79 |
+
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
],
|
81 |
)
|
82 |
|