Update app.py
Browse files
app.py
CHANGED
@@ -1,15 +1,14 @@
|
|
1 |
import gradio as gr
|
2 |
from huggingface_hub import InferenceClient
|
3 |
-
from transformers import AutoTokenizer
|
4 |
|
5 |
-
#
|
6 |
tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta")
|
7 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
|
9 |
-
# Define a maximum context length (tokens).
|
10 |
-
MAX_CONTEXT_LENGTH = 4096
|
11 |
|
12 |
-
# Default system prompt
|
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.
|
@@ -82,8 +81,13 @@ def count_tokens(text: str) -> int:
|
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
87 |
"""
|
88 |
truncated_history = []
|
89 |
system_message_tokens = count_tokens(system_message)
|
@@ -106,66 +110,65 @@ def truncate_history(history: list[tuple[str, str]], system_message: str, max_le
|
|
106 |
def respond(
|
107 |
message,
|
108 |
history: list[tuple[str, str]],
|
109 |
-
system_message,
|
110 |
max_tokens,
|
111 |
temperature,
|
112 |
top_p,
|
113 |
):
|
114 |
-
"""
|
115 |
-
Responds to a user message, maintaining conversation history.
|
116 |
-
"""
|
117 |
|
118 |
-
|
119 |
-
|
120 |
-
return "", []
|
121 |
|
122 |
-
|
123 |
-
truncated_history = truncate_history(history,
|
124 |
|
125 |
-
#
|
126 |
-
messages = [{"role": "system", "content": system_message}]
|
127 |
for user_msg, assistant_msg in truncated_history:
|
128 |
if user_msg:
|
129 |
-
messages.append({"role": "user", "content": user_msg})
|
130 |
if assistant_msg:
|
131 |
-
messages.append({"role": "assistant", "content": assistant_msg})
|
132 |
|
133 |
-
#
|
134 |
-
messages.append({"role": "user", "content": message})
|
135 |
|
136 |
response = ""
|
137 |
try:
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
response += token
|
149 |
-
yield response
|
150 |
except Exception as e:
|
151 |
-
|
152 |
-
|
153 |
|
154 |
# --- Gradio Interface ---
|
155 |
demo = gr.ChatInterface(
|
156 |
-
|
157 |
additional_inputs=[
|
158 |
gr.Textbox(
|
159 |
value=default_nvc_prompt_template,
|
160 |
label="System message",
|
161 |
visible=True,
|
162 |
-
lines=10,
|
163 |
),
|
164 |
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
165 |
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
166 |
-
gr.Slider(
|
|
|
|
|
|
|
|
|
|
|
|
|
167 |
],
|
168 |
)
|
169 |
|
170 |
if __name__ == "__main__":
|
171 |
-
demo.launch(share=True)
|
|
|
1 |
import gradio as gr
|
2 |
from huggingface_hub import InferenceClient
|
3 |
+
from transformers import AutoTokenizer # Import the tokenizer
|
4 |
|
5 |
+
# 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 |
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:
|
13 |
1. **Goal of the Conversation**
|
14 |
- Translate the user’s story or judgments into feelings and needs.
|
|
|
81 |
return len(tokenizer.encode(text))
|
82 |
|
83 |
def truncate_history(history: list[tuple[str, str]], system_message: str, max_length: int) -> list[tuple[str, str]]:
|
84 |
+
"""Truncates the conversation history to fit within the maximum token limit.
|
85 |
+
Args:
|
86 |
+
history: The conversation history (list of user/assistant tuples).
|
87 |
+
system_message: The system message.
|
88 |
+
max_length: The maximum number of tokens allowed.
|
89 |
+
Returns:
|
90 |
+
The truncated history.
|
91 |
"""
|
92 |
truncated_history = []
|
93 |
system_message_tokens = count_tokens(system_message)
|
|
|
110 |
def respond(
|
111 |
message,
|
112 |
history: list[tuple[str, str]],
|
113 |
+
system_message, # System message is now an argument
|
114 |
max_tokens,
|
115 |
temperature,
|
116 |
top_p,
|
117 |
):
|
118 |
+
"""Responds to a user message, maintaining conversation history, using special tokens and message list."""
|
|
|
|
|
119 |
|
120 |
+
if message.lower() == "clear memory": # Check for the clear memory command
|
121 |
+
return "", [] # Return empty message and empty history to reset the chat
|
|
|
122 |
|
123 |
+
formatted_system_message = system_message # Use the system_message argument
|
124 |
+
truncated_history = truncate_history(history, formatted_system_message, MAX_CONTEXT_LENGTH - max_tokens - 100) # Reserve space for the new message and some generation
|
125 |
|
126 |
+
messages = [{"role": "system", "content": formatted_system_message}] # Start with system message as before
|
|
|
127 |
for user_msg, assistant_msg in truncated_history:
|
128 |
if user_msg:
|
129 |
+
messages.append({"role": "user", "content": f"<|user|>\n{user_msg}</s>"}) # Format history user message
|
130 |
if assistant_msg:
|
131 |
+
messages.append({"role": "assistant", "content": f"<|assistant|>\n{assistant_msg}</s>"}) # Format history assistant message
|
132 |
|
133 |
+
messages.append({"role": "user", "content": f"<|user|>\n{message}</s>"}) # Format current user message
|
|
|
134 |
|
135 |
response = ""
|
136 |
try:
|
137 |
+
for chunk in client.chat_completion(
|
138 |
+
messages, # Send the messages list again, but with formatted content
|
139 |
+
max_tokens=max_tokens,
|
140 |
+
stream=True,
|
141 |
+
temperature=temperature,
|
142 |
+
top_p=top_p,
|
143 |
+
):
|
144 |
+
token = chunk.choices[0].delta.content
|
145 |
+
response += token
|
146 |
+
yield response
|
|
|
|
|
147 |
except Exception as e:
|
148 |
+
print(f"An error occurred: {e}") # It's a good practice add a try-except block
|
149 |
+
yield "I'm sorry, I encountered an error. Please try again."
|
150 |
|
151 |
# --- Gradio Interface ---
|
152 |
demo = gr.ChatInterface(
|
153 |
+
respond,
|
154 |
additional_inputs=[
|
155 |
gr.Textbox(
|
156 |
value=default_nvc_prompt_template,
|
157 |
label="System message",
|
158 |
visible=True,
|
159 |
+
lines=10, # Increased height for more space to read the prompt
|
160 |
),
|
161 |
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
162 |
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
163 |
+
gr.Slider(
|
164 |
+
minimum=0.1,
|
165 |
+
maximum=1.0,
|
166 |
+
value=0.95,
|
167 |
+
step=0.05,
|
168 |
+
label="Top-p (nucleus sampling)",
|
169 |
+
),
|
170 |
],
|
171 |
)
|
172 |
|
173 |
if __name__ == "__main__":
|
174 |
+
demo.launch(share=True)
|