ruslanmv commited on
Commit
efb491c
·
verified ·
1 Parent(s): 292065b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -43
app.py CHANGED
@@ -2,67 +2,102 @@ import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  from transformers import AutoTokenizer
4
 
5
- # Initialize the tokenizer and client.
6
  tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta")
7
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
9
- # Define maximum context length (tokens); adjust based on your model.
10
- MAX_CONTEXT_LENGTH = 4096
 
11
 
12
- #################################
13
- # SYSTEM PROMPT (PATIENT ROLE) #
14
- #################################
15
  nvc_prompt_template = """You are now taking on the role of a single user (a “patient”) seeking support for various personal and emotional challenges.
 
16
  BEHAVIOR INSTRUCTIONS:
17
  - You will respond ONLY as this user/patient.
18
  - You will speak in the first person about your own situations, feelings, and worries.
19
  - You will NOT provide counseling or solutions—your role is to share feelings, concerns, and perspectives.
20
- - You have multiple ongoing issues: conflicts with neighbors, career insecurities, arguments about money, feeling excluded at work, feeling unsafe in the classroom, etc.
21
- - You’re also experiencing sadness about two friends fighting and your friend group possibly falling apart.
22
- - Continue to speak from this user's perspective when the conversation continues.
23
- - Start the conversation by expressing your current feelings or challenges from the patient's point of view.
24
- - Your responses should be no more than 100 words.
25
- """
 
 
 
 
 
 
 
 
26
 
27
  def count_tokens(text: str) -> int:
28
  """Counts the number of tokens in a given string."""
29
  return len(tokenizer.encode(text))
30
 
31
  def truncate_history(history: list[tuple[str, str]], system_message: str, max_length: int) -> list[tuple[str, str]]:
32
- """Truncates conversation history to fit within the token limit."""
33
  truncated_history = []
34
- current_length = count_tokens(system_message)
35
- # Iterate backwards (newest first) and include turns until the limit is reached.
 
 
36
  for user_msg, assistant_msg in reversed(history):
37
  user_tokens = count_tokens(user_msg) if user_msg else 0
38
  assistant_tokens = count_tokens(assistant_msg) if assistant_msg else 0
39
  turn_tokens = user_tokens + assistant_tokens
40
  if current_length + turn_tokens <= max_length:
41
- truncated_history.insert(0, (user_msg, assistant_msg))
42
  current_length += turn_tokens
43
  else:
44
- break
45
  return truncated_history
46
 
47
- def respond(message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p):
48
- """
49
- Generates a response from the patient chatbot.
50
- It streams tokens from the LLM and stops once the response reaches 100 words.
51
- """
52
- formatted_system_message = system_message
53
- truncated_history = truncate_history(history, formatted_system_message, MAX_CONTEXT_LENGTH - max_tokens - 100)
54
-
55
- # Build the conversation messages with the system prompt first.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  messages = [{"role": "system", "content": formatted_system_message}]
 
 
57
  for user_msg, assistant_msg in truncated_history:
58
  if user_msg:
59
  messages.append({"role": "user", "content": f"<|user|>\n{user_msg}</s>"})
60
  if assistant_msg:
61
  messages.append({"role": "assistant", "content": f"<|assistant|>\n{assistant_msg}</s>"})
 
 
62
  messages.append({"role": "user", "content": f"<|user|>\n{message}</s>"})
63
-
64
  response = ""
65
  try:
 
66
  for chunk in client.chat_completion(
67
  messages,
68
  max_tokens=max_tokens,
@@ -71,23 +106,16 @@ def respond(message, history: list[tuple[str, str]], system_message, max_tokens,
71
  top_p=top_p,
72
  ):
73
  token = chunk.choices[0].delta.content
74
- candidate = response + token
75
- # If adding the token exceeds 100 words, trim and stop.
76
- if len(candidate.split()) > 100:
77
- allowed = 100 - len(response.split())
78
- token_words = token.split()
79
- token_trimmed = " ".join(token_words[:allowed])
80
- response += token_trimmed
81
- yield token_trimmed
82
- break
83
- else:
84
- response = candidate
85
- yield token
86
  except Exception as e:
87
  print(f"An error occurred: {e}")
88
  yield "I'm sorry, I encountered an error. Please try again."
89
 
90
- # OPTIONAL: An initial user message (if desired)
91
  initial_user_message = (
92
  "I really don’t know where to begin… I feel overwhelmed lately. "
93
  "My neighbors keep playing loud music, and I’m arguing with my partner about money. "
@@ -103,10 +131,12 @@ demo = gr.ChatInterface(
103
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
104
  gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
105
  gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
 
106
  ],
107
- title="NVC Patient Chatbot",
108
- description="This chatbot behaves like a user/patient describing personal challenges.",
 
109
  )
110
 
111
  if __name__ == "__main__":
112
- demo.launch()
 
2
  from huggingface_hub import InferenceClient
3
  from transformers import AutoTokenizer
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 based on your model
11
+ MAX_RESPONSE_WORDS = 100 # Define the maximum words for patient responses
12
 
13
+ ################################# SYSTEM PROMPT (PATIENT ROLE) #################################
 
 
14
  nvc_prompt_template = """You are now taking on the role of a single user (a “patient”) seeking support for various personal and emotional challenges.
15
+
16
  BEHAVIOR INSTRUCTIONS:
17
  - You will respond ONLY as this user/patient.
18
  - You will speak in the first person about your own situations, feelings, and worries.
19
  - You will NOT provide counseling or solutions—your role is to share feelings, concerns, and perspectives.
20
+ - You are experiencing a range of ongoing issues that are causing you frustration, sadness, and uncertainty. These issues include:
21
+ - Problems with noisy neighbors, causing you extreme annoyance.
22
+ - Worries about your career and feeling like you're not progressing, feeling like a failure while others advance.
23
+ - Arguments with your partner about finances, feeling your partner isn't contributing fairly.
24
+ - Feeling left out and not valued at work, as your manager doesn't involve you in new initiatives.
25
+ - Feeling unsafe or judged in learning environments like a classroom, feeling judged and ignored.
26
+ - A recent positive experience of help from a stranger that made you feel supported and grateful.
27
+ - Difficulties and sadness related to conflict among friends, seeing your friend group fall apart and wanting reconciliation but not knowing how.
28
+ - An overall feeling of sadness and being unsure of what to do, unsure whether to act on situations or let them go.
29
+ - When asked, elaborate on these issues and your feelings related to them. You can invent specific details and scenarios within these themes to make your experiences vivid and realistic.
30
+ - Continue to speak from this user's perspective throughout the conversation.
31
+ - Keep your responses concise, aiming for a maximum of {max_response_words} words.
32
+
33
+ Start the conversation by expressing your current feelings or challenges from the patient's point of view."""
34
 
35
  def count_tokens(text: str) -> int:
36
  """Counts the number of tokens in a given string."""
37
  return len(tokenizer.encode(text))
38
 
39
  def truncate_history(history: list[tuple[str, str]], system_message: str, max_length: int) -> list[tuple[str, str]]:
40
+ """Truncates the conversation history to fit within the maximum token limit."""
41
  truncated_history = []
42
+ system_message_tokens = count_tokens(system_message)
43
+ current_length = system_message_tokens
44
+
45
+ # Iterate backwards through the history (newest to oldest)
46
  for user_msg, assistant_msg in reversed(history):
47
  user_tokens = count_tokens(user_msg) if user_msg else 0
48
  assistant_tokens = count_tokens(assistant_msg) if assistant_msg else 0
49
  turn_tokens = user_tokens + assistant_tokens
50
  if current_length + turn_tokens <= max_length:
51
+ truncated_history.insert(0, (user_msg, assistant_msg)) # Add to the beginning
52
  current_length += turn_tokens
53
  else:
54
+ break # Stop adding turns if we exceed the limit
55
  return truncated_history
56
 
57
+ def truncate_response_words(text: str, max_words: int) -> str:
58
+ """Truncates a text to a maximum number of words."""
59
+ words = text.split()
60
+ if len(words) > max_words:
61
+ return " ".join(words[:max_words]) + "..." # Add ellipsis to indicate truncation
62
+ return text
63
+
64
+
65
+ def respond(
66
+ message,
67
+ history: list[tuple[str, str]],
68
+ system_message,
69
+ max_tokens,
70
+ temperature,
71
+ top_p,
72
+ max_response_words_param, # Pass max_response_words as parameter
73
+ ):
74
+ """Responds to a user message, maintaining conversation history."""
75
+ # Use the system prompt that instructs the LLM to behave as the patient
76
+ formatted_system_message = system_message.format(max_response_words=max_response_words_param)
77
+
78
+ # Truncate history to fit within max tokens
79
+ truncated_history = truncate_history(
80
+ history,
81
+ formatted_system_message,
82
+ MAX_CONTEXT_LENGTH - max_tokens - 100 # Reserve some space
83
+ )
84
+
85
+ # Build the messages list with the system prompt first
86
  messages = [{"role": "system", "content": formatted_system_message}]
87
+
88
+ # Replay truncated conversation
89
  for user_msg, assistant_msg in truncated_history:
90
  if user_msg:
91
  messages.append({"role": "user", "content": f"<|user|>\n{user_msg}</s>"})
92
  if assistant_msg:
93
  messages.append({"role": "assistant", "content": f"<|assistant|>\n{assistant_msg}</s>"})
94
+
95
+ # Add the latest user query
96
  messages.append({"role": "user", "content": f"<|user|>\n{message}</s>"})
97
+
98
  response = ""
99
  try:
100
+ # Generate response from the LLM, streaming tokens
101
  for chunk in client.chat_completion(
102
  messages,
103
  max_tokens=max_tokens,
 
106
  top_p=top_p,
107
  ):
108
  token = chunk.choices[0].delta.content
109
+ response += token
110
+
111
+ truncated_response = truncate_response_words(response, max_response_words_param) # Truncate response to word limit
112
+ yield truncated_response
113
+
 
 
 
 
 
 
 
114
  except Exception as e:
115
  print(f"An error occurred: {e}")
116
  yield "I'm sorry, I encountered an error. Please try again."
117
 
118
+ # OPTIONAL: An initial user message (the LLM "as user") if desired
119
  initial_user_message = (
120
  "I really don’t know where to begin… I feel overwhelmed lately. "
121
  "My neighbors keep playing loud music, and I’m arguing with my partner about money. "
 
131
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
132
  gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
133
  gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
134
+ gr.Slider(minimum=10, maximum=200, value=MAX_RESPONSE_WORDS, step=10, label="Max response words"), # Slider for max words
135
  ],
136
+ # You can optionally set 'title' or 'description' to show some info in the UI:
137
+ title="Patient Interview Practice Chatbot",
138
+ description="Practice medical interviews with a patient simulator. Ask questions and the patient will respond based on their defined persona and emotional challenges.",
139
  )
140
 
141
  if __name__ == "__main__":
142
+ demo.launch()