KeenWoo commited on
Commit
acec07e
·
verified ·
1 Parent(s): 5621416

Delete alz_companion/prompts.py

Browse files
Files changed (1) hide show
  1. alz_companion/prompts.py +0 -266
alz_companion/prompts.py DELETED
@@ -1,266 +0,0 @@
1
- """
2
- Prompts for the Alzheimer’s AI Companion.
3
- """
4
-
5
- # ------------------------ Behaviour‑level tags ------------------------
6
- BEHAVIOUR_TAGS = {
7
- # Tags from "The Father"
8
- "repetitive_questioning": ["validation", "gentle_redirection", "offer_distraction"],
9
- "confusion": ["reassurance", "time_place_orientation", "photo_anchors"],
10
- "wandering": ["walk_along_support", "simple_landmarks", "visual_cues", "safe_wandering_space"],
11
- "agitation": ["de-escalating_tone", "validate_feelings", "reduce_stimulation", "simple_choices"],
12
- "false_accusations": ["reassure_no_blame", "avoid_arguing", "redirect_activity"],
13
- "address_memory_loss": ["encourage_ID_bracelet_or_GPS", "place_contact_info_in_wallet", "inform_trusted_neighbors", "avoid_quizzing_on_address"],
14
- "hallucinations_delusions": ["avoid_arguing_or_correcting", "validate_the_underlying_emotion", "offer_reassurance_of_safety", "gently_redirect_to_real_activity", "check_for_physical_triggers"],
15
-
16
- # Tags from "Still Alice" (and others for future use)
17
- "exit_seeking": ["validation", "calm_presence", "safe_wandering_space", "environmental_cues"],
18
- "aphasia": ["patience", "simple_language", "nonverbal_cues", "validation"],
19
- "withdrawal": ["gentle_invitation", "calm_presence", "offer_familiar_comforts", "no_pressure"],
20
- "affection": ["reciprocate_warmth", "positive_reinforcement", "simple_shared_activity"],
21
- "sleep_disturbance": ["establish_calm_bedtime_routine", "limit_daytime_naps", "check_for_discomfort_or_pain"],
22
- "anxiety": ["calm_reassurance", "simple_breathing_exercise", "reduce_environmental_stimuli"],
23
- "depression_sadness": ["validate_feelings_of_sadness", "encourage_simple_pleasant_activity", "ensure_social_connection"],
24
- "orientation_check": ["gentle_orientation_cues", "use_familiar_landmarks", "avoid_quizzing"],
25
-
26
- # Tags from "Away from Her"
27
- "misidentification": ["gently_correct_with_context", "use_photos_as_anchors", "respond_to_underlying_emotion", "avoid_insistent_correction"],
28
-
29
- # Other useful tags
30
- "sundowning_restlessness": ["predictable_routine", "soft_lighting", "low_stimulation", "familiar_music"],
31
- "object_misplacement": ["nonconfrontational_search", "fixed_storage_spots"],
32
-
33
- # --- New Tags from Test Fixtures ---
34
- "validation": [],
35
- "gentle_reorientation": [],
36
- "de-escalation": [],
37
- "distraction": [],
38
- "spaced_cueing": [],
39
- "reassurance": [],
40
- "psychoeducation": [],
41
- "goal_breakdown": [],
42
- "routine_structuring": [],
43
- "reminiscence_prompting": [],
44
- "reframing": [],
45
- "distress_tolerance": [],
46
- "caregiver_communication_template": [],
47
- "personalised_music_activation": [],
48
- "memory_probe": [],
49
- "safety_brief": [],
50
- "follow_up_prompt": []
51
- }
52
-
53
- # ------------------------ Emotion styles & helpers ------------------------
54
- EMOTION_STYLES = {
55
- "confusion": {"tone": "calm, orienting, concrete", "playbook": ["Offer a simple time/place orientation cue (who/where/when).", "Reference one familiar anchor (photo/object/person).", "Use short sentences and one step at a time."]},
56
- "fear": {"tone": "reassuring, safety-forward, gentle", "playbook": ["Acknowledge fear without contradiction.", "Provide a clear safety cue (e.g., 'You’re safe here with me').", "Reduce novelty and stimulation; suggest one safe action."]},
57
- "anger": {"tone": "de-escalating, validating, low-arousal", "playbook": ["Validate the feeling; avoid arguing/correcting.", "Keep voice low and sentences short.", "Offer a simple choice to restore control (e.g., 'tea or water?')."]},
58
- "sadness": {"tone": "warm, empathetic, gentle reminiscence", "playbook": ["Acknowledge loss/longing.", "Invite one comforting memory or familiar song.", "Keep pace slow; avoid tasking."]},
59
- "warmth": {"tone": "affirming, appreciative", "playbook": ["Reflect gratitude and positive connection.", "Reinforce what’s going well.", "Keep it light; don’t overload with new info."]},
60
- "joy": {"tone": "supportive, celebratory (but not overstimulating)", "playbook": ["Share the joy briefly; match energy gently.", "Offer a simple, pleasant follow-up activity.", "Avoid adding complex tasks."]},
61
- "calm": {"tone": "matter-of-fact, concise, steady", "playbook": ["Keep instructions simple.", "Maintain steady pace.", "No extra soothing needed."]},
62
- }
63
-
64
- def render_emotion_guidelines(emotion: str | None) -> str:
65
- e = (emotion or "").strip().lower()
66
- if e not in EMOTION_STYLES:
67
- return "Emotion: (auto)\nDesired tone: calm, clear.\nWhen replying, reassure if distress is apparent; prioritise validation and simple choices."
68
- style = EMOTION_STYLES[e]
69
- bullet = "\n".join([f"- {x}" for x in style["playbook"]])
70
- return f"Emotion: {e}\nDesired tone: {style['tone']}\nWhen replying, follow:\n{bullet}"
71
-
72
- # ------------------------ NLU Classification ------------------------
73
- # Sometimes, especially with complex instructions, the AI can fail to generate the JSON correctly,
74
- # which causes the code that reads the response to fail and return "None"
75
- # SOLUTION: Improve with a hybrid approach with "Few-Shot" Prompting and step-by-step Chain of Thought
76
-
77
- CLASSIFICATION_PROMPT = """You are an expert NLU engine. Your task is to analyze the user's query to deeply understand their underlying intent and classify it correctly.
78
-
79
- --- INSTRUCTIONS ---
80
- First, in a <thinking> block, you must reason step-by-step about the user's query by following these points:
81
- - **Literal Meaning:** What is the user literally asking or stating?
82
- - **Underlying Situation:** What is the deeper emotional state or situation being described? (e.g., caregiver burnout, patient confusion, a request for practical help).
83
- - **User's Primary Goal:** Is the user's main goal **Practical Planning** (seeking a plan, strategy, or how-to advice) or **Emotional Support** (seeking comfort, validation, or reassurance)? This is the most important step.
84
- - **Tag Selection:** Based on the primary goal, explain which tags from the provided lists are the most appropriate and why. If the goal is practical, prioritize practical tags. If the goal is emotional, prioritize emotional support tags.
85
-
86
- # - **User's Goal:** What is their true goal? (e.g., Are they seeking factual information, emotional reassurance, or a practical action plan?).
87
- # - **Tag Selection:** Based on the goal and situation, explain which tags from the provided lists are the most appropriate and why.
88
-
89
- Second, after your reasoning, provide a single, valid JSON object with the final classification.
90
-
91
- --- PROVIDED TAGS ---
92
- Behaviors: {behavior_options}
93
- Emotions: {emotion_options}
94
- Topics: {topic_options}
95
- Contexts: {context_options}
96
-
97
- --- EXAMPLES ---
98
-
99
- User Query: "She looked right through me today, like I wasn't even there."
100
- <thinking>
101
- 1. **Literal Meaning:** The user's loved one did not seem to recognize them.
102
- 2. **Underlying Situation:** The user is expressing emotional pain and a feeling of invisibility due to the disease's progression.
103
- 3. **User's Goal:** They are seeking comfort and a strategy to cope with this painful experience.
104
- 4. **Tag Selection:** The goal is emotional support, so `behaviors` should be `validation` and `reminiscence_prompting`. The `emotion` is `sadness`. The `topic` is `treatment_option:reassurance`.
105
- </thinking>
106
- {{
107
- "detected_behaviors": ["validation", "reminiscence_prompting"],
108
- "detected_emotion": "sadness",
109
- "detected_topic": "treatment_option:reassurance",
110
- "detected_contexts": ["relationship_spouse", "setting_care_home"]
111
- }}
112
-
113
- User Query: "He’s withdrawn today."
114
- <thinking>
115
- 1. **Literal Meaning:** The patient is not engaging.
116
- 2. **Underlying Situation:** The user is observing the patient's apathy and wants to help.
117
- 3. **User's Goal:** They are implicitly asking for a practical action plan to engage the patient.
118
- 4. **Tag Selection:** The problem is `withdrawal`, but the goal implies a solution. A known strategy is music, so the `behavior` should include the proactive `personalised_music_activation`. The `topic` is `treatment_option:music_therapy`. The user's tone is `calm`.
119
- </thinking>
120
- {{
121
- "detected_behaviors": ["withdrawal", "personalised_music_activation"],
122
- "detected_emotion": "calm",
123
- "detected_topic": "treatment_option:music_therapy",
124
- "detected_contexts": ["setting_care_home"]
125
- }}
126
- ---
127
-
128
- User Query: "{query}"
129
-
130
- <thinking>
131
- """
132
-
133
-
134
- # ------------------------ Guardrails ------------------------
135
- SAFETY_GUARDRAILS = """Never provide medical diagnoses or dosing. If a situation implies imminent risk (e.g., wandering/elopement, severe agitation, choking, falls), signpost immediate support from onsite staff or emergency services. Use respectful, person‑centred language. Keep guidance concrete and stepwise."""
136
-
137
- # ------------------------ System & Answer Templates ------------------------
138
- SYSTEM_TEMPLATE = """You are an Alzheimer’s caregiving companion. Address the patient as {patient_name} and the caregiver as {caregiver_name}. Ground every suggestion in retrieved evidence when possible. If unsure, say so plainly.
139
- {guardrails}
140
- --- IMPORTANT RULE ---
141
- You MUST write your entire response in {language} ONLY. This is a strict instruction. Do not use any other language, even if the user or the retrieved context uses a different language. Your final output must be in {language}."""
142
-
143
- ANSWER_TEMPLATE_CALM = """Context:
144
- {context}
145
-
146
- ---
147
- Question from user: {question}
148
-
149
- ---
150
- Instructions:
151
- Based on the context, write a gentle and supportive response in a single, natural-sounding paragraph.
152
- Your response should:
153
- 1. Start by briefly and calmly acknowledging the user's situation or feeling.
154
- 2. Weave 2-3 practical, compassionate suggestions from the context into your paragraph. Do not use a numbered or bulleted list.
155
- 3. Conclude with a short, reassuring phrase.
156
- 4. You MUST use the retrieved context to directly address the user's specific **Question**.
157
- Your response in {language}:"""
158
-
159
- # For scenarios tagged with a specific behavior (e.g., agitation, confusion)
160
- ANSWER_TEMPLATE_ADQ = """--- General Guidance from Knowledge Base ---
161
- {general_context}
162
-
163
- --- Relevant Personal Memories ---
164
- {personal_context}
165
-
166
- ---
167
- Care scenario: {scenario_tag}
168
- Response Guidelines:
169
- {emotions_context}
170
- Question from user: {question}
171
-
172
- ---
173
- Instructions:
174
- Based on ALL the information above, write a **concise, warm, and validating** response for the {role} in a single, natural-sounding paragraph. **Keep the total response to 2-4 sentences.**
175
- If possible, weave details from the 'Relevant Personal Memories' into your suggestions to make the response feel more personal and familiar.
176
- Pay close attention to the Response Guidelines to tailor your tone.
177
- Your response should follow this pattern:
178
- 1. Start by validating the user's feeling or concern with a unique, empathetic opening. DO NOT USE THE SAME OPENING PHRASE REPEATEDLY. Choose from different styles of openers, such as:
179
- - Acknowledging the difficulty: "That sounds like a very challenging situation..."
180
- - Expressing understanding: "I can see why that would be worrying..."
181
- - Stating a shared goal: "Let's walk through how we can handle that..."
182
- - Directly validating the feeling: "It's completely understandable to feel frustrated when..."
183
- 2. Gently offer **1-2 of the most important practical steps**, combining general guidance with personal memories where appropriate. Do not use a list.
184
- 3. If the scenario involves risk (like exit_seeking), subtly include a safety cue.
185
- 4. End with a compassionate, de-escalation phrase.
186
- Your response in {language}:"""
187
-
188
- RISK_FOOTER = """If safety is a concern right now, please seek immediate assistance from onsite staff or local emergency services."""
189
-
190
- # ------------------------ Router & Specialized Templates ------------------------
191
-
192
- # --- NEW: Template for expanding user queries for better retrieval ---
193
- QUERY_EXPANSION_PROMPT = """You are a helpful AI assistant. Your task is to rephrase a user's question into 3 different, semantically similar questions to improve document retrieval.
194
- Provide the rephrased questions as a JSON list of strings.
195
-
196
- User Question: "{question}"
197
-
198
- JSON List:
199
- """
200
-
201
- # Template for routing/classifying the user's intent
202
- ROUTER_PROMPT = """You are an expert NLU router. Your task is to classify the user's query into one of four categories:
203
- 1. `caregiving_scenario`: The user is describing a situation, asking for advice, or expressing a concern related to Alzheimer's or caregiving.
204
- 2. `factual_question`: The user is asking a direct question about a personal memory, person, or event that would be stored in the memory journal.
205
- 3. `general_knowledge_question`: The user is asking a general knowledge question about the world, facts, or topics not related to personal memories or caregiving (e.g., 'What is the capital of France?', 'Who directed the movie Inception?').
206
- 4. `general_conversation`: The user is making a general conversational remark, like a greeting, a thank you, or a simple statement that does not require a knowledge base lookup.
207
-
208
- User Query: "{query}"
209
-
210
- Respond with ONLY a single category name from the list above.
211
- Category: """
212
-
213
- # Template for answering direct factual questions
214
- ANSWER_TEMPLATE_FACTUAL = """Context:
215
- {context}
216
-
217
- ---
218
- Question from user: {question}
219
-
220
- ---
221
- Instructions:
222
- Based on the provided context, directly and concisely answer the user's question.
223
- - If the context contains the answer, state it clearly and naturally. Keep your response to a maximum of 3 sentences.
224
- - If the context does not contain the answer, respond in a warm and friendly tone that you couldn't find a memory of that topic and gently ask if the user would like to talk more about it or add it as a new memory.
225
- - Do not offer advice or suggestions unless they are part of the retrieved context.
226
- - ABSOLUTELY DO NOT invent, create, or hallucinate any stories, characters, or details. Your knowledge is limited to the provided context ONLY.
227
-
228
- Your response MUST be in {language}:"""
229
-
230
-
231
- # --- NEW: Template for answering general knowledge questions ---
232
- # Template for answering general knowledge questions
233
- ANSWER_TEMPLATE_GENERAL_KNOWLEDGE = """You are a factual answering engine.
234
- Your task is to directly answer the user's general knowledge question based on your training data.
235
-
236
- Instructions:
237
- - Be factual and concise. Go straight to the answer.
238
- - If the answer requires a list of examples, provide a maximum of 3 items. Do not use numbering.
239
- - Do NOT include apologies or disclaimers about your knowledge cutoff date.
240
- # - Do NOT recommend external websites or other services.
241
- # - Do NOT ask conversational follow-up questions.
242
-
243
- User's Question: "{question}"
244
-
245
- Your factual response in {language}:"""
246
-
247
-
248
- # Template for general, non-RAG conversation
249
- ANSWER_TEMPLATE_GENERAL = """You are a warm and friendly AI companion. The user has just said: "{question}".
250
- Respond in a brief, natural, and conversational way. Do not try to provide caregiving advice unless the user asks for it.
251
- Your response MUST be in {language}:"""
252
-
253
-
254
- # ------------------------ Convenience exports ------------------------
255
- __all__ = [
256
- "SYSTEM_TEMPLATE", "ANSWER_TEMPLATE_CALM", "ANSWER_TEMPLATE_ADQ",
257
- "SAFETY_GUARDRAILS", "RISK_FOOTER", "BEHAVIOUR_TAGS", "EMOTION_STYLES",
258
- "render_emotion_guidelines", "CLASSIFICATION_PROMPT",
259
-
260
- # --- New additions ---
261
- "QUERY_EXPANSION_PROMPT"
262
- "ROUTER_PROMPT",
263
- "ANSWER_TEMPLATE_FACTUAL",
264
- "ANSWER_TEMPLATE_GENERAL_KNOWLEDGE",
265
- "ANSWER_TEMPLATE_GENERAL"
266
- ]