ruslanmv commited on
Commit
f52eb65
·
verified ·
1 Parent(s): b40b6be

Create patient2.py

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