Phoenix21 commited on
Commit
521000a
·
verified ·
1 Parent(s): 6d02a71

try to handle this for the no more insomia bugs (#2)

Browse files

- try to handle this for the no more insomia bugs (1e87777285bcf2f55c2666d9584b0d8bbec109ff)

Files changed (1) hide show
  1. chain_problems.py +133 -39
chain_problems.py CHANGED
@@ -1,7 +1,7 @@
1
  # chain_problems.py
2
  import json
3
  import logging
4
- from typing import Dict
5
  from langchain import PromptTemplate, LLMChain
6
  from models import chat_model
7
 
@@ -17,35 +17,12 @@ problem_prompt_template = PromptTemplate(
17
  "From these inputs, determine a 'problem severity percentage' for the user in the following areas: "
18
  "stress_management, low_therapy, balanced_weight, restless_night, lack_of_motivation, gut_health, anxiety, burnout.\n\n"
19
  "Consider how these severity percentages will later be used to recommend suitable wellness packages such as:\n\n"
20
- "1. Fitness Mobility:\n"
21
- "Our Fitness Mobility Package is designed to help you move better, feel stronger, and embrace an active lifestyle. This comprehensive program focuses on improving your flexibility, strength, and joint mobility through tailored exercises, mindful movement, and practical guidance.\n"
22
- "With a mix of yoga-inspired stretches, mobility drills, and functional exercises, this package aims to enhance your body's natural range of motion, reduce stiffness, and support injury prevention. Whether you're a beginner or a fitness enthusiast, our program is adaptable to all levels and lifestyles.\n\n"
23
- "2. Balance Weight:\n"
24
- "Achieve a healthier, more balanced weight with our Balance Weight Package—a holistic approach to weight management that prioritizes your overall well-being. This program combines personalized nutrition guidance, effective workout routines, and mindful lifestyle practices to help you reach and maintain your ideal weight sustainably.\n"
25
- "With expert tips on portion control, meal planning, and calorie balance, along with strategies to boost your metabolism and build strength, this package is perfect for anyone looking to shed extra weight or build healthy habits.\n\n"
26
- "3. No More Insomnia:\n"
27
- "Say goodbye to restless nights with our No More Insomnia Package—designed to help you enjoy deep, rejuvenating sleep every night. This comprehensive program focuses on restoring your natural sleep cycle through proven techniques like guided relaxation, breathing exercises, and mindfulness practices.\n"
28
- "Explore the benefits of calming nighttime routines, sleep-friendly nutrition, and stress management tools, all tailored to help you fall asleep faster and wake up feeling refreshed. Whether you're battling occasional sleeplessness or chronic insomnia, this package empowers you to reclaim your rest naturally and effectively.\n\n"
29
- "4. Chronic Care:\n"
30
- "Manage chronic conditions with ease and confidence through our Chronic Care Package, thoughtfully designed to support your long-term health and well-being. This package provides a holistic approach to managing conditions like diabetes, hypertension, arthritis, and more by combining expert wellness guidance with practical, sustainable strategies.\n"
31
- "Discover personalized nutrition plans, stress-relief techniques, gentle mobility exercises, and mindfulness practices tailored to your needs. Our focus is on empowering you to lead a healthier, more active life while minimizing discomfort and promoting overall vitality.\n\n"
32
- "5. Mental Wellness:\n"
33
- "Prioritize your peace of mind with our Mental Wellness Package, crafted to help you navigate stress, anxiety, and emotional challenges while fostering a calm and balanced life. This package integrates ancient practices with modern techniques, offering a well-rounded approach to mental well-being.\n"
34
- "Explore guided meditation, breathing exercises, and mindfulness techniques designed to reduce stress and enhance focus. Pair these with personalized self-care routines, Ayurvedic insights, and strategies for improving sleep quality to rejuvenate your mind and body.\n"
35
- "Take the first step toward emotional resilience and inner harmony—because your mental health matters.\n\n"
36
- "6. Focus Flow:\n"
37
- "Unlock your productivity potential with the Focus Flow Package, designed to sharpen your concentration, boost creativity, and help you achieve a state of effortless focus. Whether you're tackling work, studies, or creative pursuits, this package provides tools to elevate your mental clarity and efficiency.\n"
38
- "Delve into focus-enhancing meditation techniques, mindful breathing exercises, and brain-boosting nutritional guidance. With insights from yoga and Ayurveda, you'll learn how to create an environment and routine that supports sustained attention and peak performance.\n"
39
- "Step into the flow and get more done—without the overwhelm!\n\n"
40
- "Consider the following connections between the questions and these themes:\n"
41
- "- stress_management is influenced by responses such as stress_level, stress_management, mood, mindfulness_frequency, and similar stress-related questions.\n"
42
- "- low_therapy relates to aspects of the user's mindset, wellness_goals, personal_growth_reflection, and similar therapeutic indicators.\n"
43
- "- balanced_weight depends on exercise, eating_habits, dietary_restrictions, activity_tracking, and other fitness/nutrition details.\n"
44
- "- restless_night is linked to answers about sleep duration, bedtime_routine, uninterrupted_sleep, and other sleep quality indicators.\n"
45
- "- lack_of_motivation correlates with mood, energy_rating, personal_growth_reflection, break_frequency, and similar motivation-related queries.\n"
46
- "- gut_health is connected to eating_habits, dietary_restrictions, health_issues, and other digestive or nutritional feedback.\n"
47
- "- anxiety is associated with responses about mood, stress_level, mindset, and related emotional well-being questions.\n"
48
- "- burnout may be reflected in high stress_level, low energy_rating, lack_of_motivation, and related fatigue or overwhelm indicators.\n\n"
49
  "Return your answer in JSON format with keys: stress_management, low_therapy, balanced_weight, restless_night, "
50
  "lack_of_motivation, gut_health, anxiety, burnout.\n"
51
  "Ensure severity percentages are numbers from 0 to 100.\n\n"
@@ -55,17 +32,113 @@ problem_prompt_template = PromptTemplate(
55
 
56
  problem_chain = LLMChain(llm=chat_model, prompt=problem_prompt_template)
57
 
58
- def analyze_problems_with_chain(responses: Dict[str, str], internal_report: str) -> Dict[str, float]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  responses_str = "\n".join(f"{q}: {a}" for q, a in responses.items())
60
  raw_text = problem_chain.run(responses=responses_str, internal_report=internal_report)
 
 
61
  try:
62
- # Extract JSON from the LLM output
63
  start_idx = raw_text.find('{')
64
  end_idx = raw_text.rfind('}') + 1
65
  json_str = raw_text[start_idx:end_idx]
66
  problems = json.loads(json_str)
67
-
68
- # Ensure all eight keys are present with default values
69
  for key in [
70
  "stress_management",
71
  "low_therapy",
@@ -77,12 +150,14 @@ def analyze_problems_with_chain(responses: Dict[str, str], internal_report: str)
77
  "burnout"
78
  ]:
79
  problems.setdefault(key, 0.0)
80
-
81
- return {k: float(v) for k, v in problems.items()}
 
 
82
  except Exception as e:
83
  logger.error(f"Error parsing problem percentages from LLM: {e}")
84
- # Return default values for all eight themes in case of an error
85
- return {
86
  "stress_management": 0.0,
87
  "low_therapy": 0.0,
88
  "balanced_weight": 0.0,
@@ -91,4 +166,23 @@ def analyze_problems_with_chain(responses: Dict[str, str], internal_report: str)
91
  "gut_health": 0.0,
92
  "anxiety": 0.0,
93
  "burnout": 0.0
94
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # chain_problems.py
2
  import json
3
  import logging
4
+ from typing import Dict, Optional
5
  from langchain import PromptTemplate, LLMChain
6
  from models import chat_model
7
 
 
17
  "From these inputs, determine a 'problem severity percentage' for the user in the following areas: "
18
  "stress_management, low_therapy, balanced_weight, restless_night, lack_of_motivation, gut_health, anxiety, burnout.\n\n"
19
  "Consider how these severity percentages will later be used to recommend suitable wellness packages such as:\n\n"
20
+ "1. Fitness Mobility\n"
21
+ "2. Balance Weight\n"
22
+ "3. No More Insomnia\n"
23
+ "4. Chronic Care\n"
24
+ "5. Mental Wellness\n"
25
+ "6. Focus Flow\n\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  "Return your answer in JSON format with keys: stress_management, low_therapy, balanced_weight, restless_night, "
27
  "lack_of_motivation, gut_health, anxiety, burnout.\n"
28
  "Ensure severity percentages are numbers from 0 to 100.\n\n"
 
32
 
33
  problem_chain = LLMChain(llm=chat_model, prompt=problem_prompt_template)
34
 
35
+
36
+ def recommend_wellness_packages(
37
+ problems: Dict[str, float],
38
+ sleep_hours: Optional[float] = None
39
+ ) -> Dict[str, str]:
40
+ """
41
+ Given the severity dictionary and the user's reported sleep hours,
42
+ recommend one or more wellness packages.
43
+
44
+ Returns:
45
+ A dictionary with:
46
+ - 'recommended_packages': comma-separated string of package names
47
+ - 'recommendation_details': textual explanation of why these were chosen
48
+ """
49
+ # Threshold for considering an issue "significant"
50
+ THRESHOLD = 50.0
51
+
52
+ recommended = []
53
+ rationale = []
54
+
55
+ # 1. Stress / Mood => "Mental Wellness", "Focus Flow"
56
+ if (
57
+ problems["stress_management"] >= THRESHOLD
58
+ or problems["anxiety"] >= THRESHOLD
59
+ or problems["burnout"] >= THRESHOLD
60
+ or problems["low_therapy"] >= THRESHOLD
61
+ or problems["lack_of_motivation"] >= THRESHOLD
62
+ ):
63
+ recommended.append("Mental Wellness")
64
+ rationale.append(
65
+ "Mental Wellness Package suggested due to elevated stress, anxiety, "
66
+ "or motivation-related concerns."
67
+ )
68
+
69
+ if problems["lack_of_motivation"] >= THRESHOLD or problems["stress_management"] >= THRESHOLD:
70
+ recommended.append("Focus Flow")
71
+ rationale.append(
72
+ "Focus Flow Package recommended to improve concentration and reduce mental fatigue."
73
+ )
74
+
75
+ # 2. Balanced Weight / Gut Health => "Balance Weight"
76
+ if problems["balanced_weight"] >= THRESHOLD or problems["gut_health"] >= THRESHOLD:
77
+ recommended.append("Balance Weight")
78
+ rationale.append(
79
+ "Balance Weight Package suggested due to weight management or gut health concerns."
80
+ )
81
+
82
+ # 3. Restless nights => "No More Insomnia"
83
+ # **FIX**: Only recommend if user sleeps < 4 hours (to avoid recommending it for 10+ hours).
84
+ if sleep_hours is not None and sleep_hours < 4:
85
+ # If the user is sleeping less than 4 hours, we consider insomnia a big issue.
86
+ recommended.append("No More Insomnia")
87
+ rationale.append(
88
+ "No More Insomnia Package recommended because the user reported sleeping less than 4 hours."
89
+ )
90
+
91
+ # 4. High burnout => "Chronic Care"
92
+ if problems["burnout"] >= THRESHOLD:
93
+ recommended.append("Chronic Care")
94
+ rationale.append(
95
+ "Chronic Care Package recommended to help manage long-term stress and burnout."
96
+ )
97
+
98
+ # 5. If user has borderline or higher weight/stress => "Fitness Mobility"
99
+ if (
100
+ problems["balanced_weight"] >= (THRESHOLD * 0.7)
101
+ or problems["stress_management"] >= (THRESHOLD * 0.7)
102
+ ):
103
+ recommended.append("Fitness Mobility")
104
+ rationale.append(
105
+ "Fitness Mobility Package may support better physical conditioning and relieve stress."
106
+ )
107
+
108
+ # Ensure uniqueness if appended multiple times
109
+ unique_packages = list(dict.fromkeys(recommended))
110
+
111
+ # Build a clear explanation
112
+ recommendation_details = "\n".join(rationale) if rationale else "No particular issues detected."
113
+
114
+ return {
115
+ "recommended_packages": ", ".join(unique_packages),
116
+ "recommendation_details": recommendation_details
117
+ }
118
+
119
+
120
+ def analyze_problems_with_chain(responses: Dict[str, str], internal_report: str) -> Dict[str, object]:
121
+ """
122
+ Analyzes user responses and internal report to extract problem severity
123
+ and then recommends relevant wellness packages.
124
+
125
+ Returns:
126
+ A dictionary with:
127
+ - keys for each problem severity (stress_management, low_therapy, etc.)
128
+ - 'recommended_packages': comma-separated package names
129
+ - 'recommendation_details': textual explanation
130
+ """
131
  responses_str = "\n".join(f"{q}: {a}" for q, a in responses.items())
132
  raw_text = problem_chain.run(responses=responses_str, internal_report=internal_report)
133
+
134
+ # Try to parse problem severities from LLM output
135
  try:
 
136
  start_idx = raw_text.find('{')
137
  end_idx = raw_text.rfind('}') + 1
138
  json_str = raw_text[start_idx:end_idx]
139
  problems = json.loads(json_str)
140
+
141
+ # Ensure all eight keys exist
142
  for key in [
143
  "stress_management",
144
  "low_therapy",
 
150
  "burnout"
151
  ]:
152
  problems.setdefault(key, 0.0)
153
+
154
+ # Convert values to float
155
+ problems = {k: float(v) for k, v in problems.items()}
156
+
157
  except Exception as e:
158
  logger.error(f"Error parsing problem percentages from LLM: {e}")
159
+ # Default to zero severities
160
+ problems = {
161
  "stress_management": 0.0,
162
  "low_therapy": 0.0,
163
  "balanced_weight": 0.0,
 
166
  "gut_health": 0.0,
167
  "anxiety": 0.0,
168
  "burnout": 0.0
169
+ }
170
+
171
+ # --- EXTRACT USER SLEEP HOURS ---
172
+ # We assume the user answer is in responses["sleep_duration"] or similar key.
173
+ # If your data uses a different key for the hours of sleep, adjust accordingly.
174
+ sleep_hours = None
175
+ if "sleep_duration" in responses:
176
+ try:
177
+ sleep_hours = float(responses["sleep_duration"])
178
+ except ValueError:
179
+ sleep_hours = None
180
+
181
+ # Now get the recommendations based on problem severities + sleep_hours
182
+ recommendations = recommend_wellness_packages(problems, sleep_hours=sleep_hours)
183
+
184
+ # Merge and return
185
+ return {
186
+ **problems,
187
+ **recommendations
188
+ }