Spaces:
Runtime error
Runtime error
Commit
·
76166e3
0
Parent(s):
Update interface for Gradio 5.8.0
Browse files- .gitattributes +35 -0
- .gitignore +52 -0
- README.md +12 -0
- agents/assessment_agent.py +188 -0
- agents/base_agent.py +91 -0
- agents/conversation_agent.py +96 -0
- agents/crisis_agent.py +251 -0
- agents/mindfulness_agent.py +227 -0
- agents/orchestrator.py +128 -0
- app.py +21 -0
- config/config.py +47 -0
- interface/app.py +198 -0
- knowledge_base/guidelines/crisis_protocols.json +76 -0
- knowledge_base/resources/mindfulness_exercises.json +54 -0
- requirements.txt +18 -0
.gitattributes
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Python
|
2 |
+
__pycache__/
|
3 |
+
*.py[cod]
|
4 |
+
*$py.class
|
5 |
+
*.so
|
6 |
+
.Python
|
7 |
+
env/
|
8 |
+
build/
|
9 |
+
develop-eggs/
|
10 |
+
dist/
|
11 |
+
downloads/
|
12 |
+
eggs/
|
13 |
+
.eggs/
|
14 |
+
lib/
|
15 |
+
lib64/
|
16 |
+
parts/
|
17 |
+
sdist/
|
18 |
+
var/
|
19 |
+
wheels/
|
20 |
+
*.egg-info/
|
21 |
+
.installed.cfg
|
22 |
+
*.egg
|
23 |
+
|
24 |
+
# Virtual Environment
|
25 |
+
venv/
|
26 |
+
ENV/
|
27 |
+
|
28 |
+
# IDE
|
29 |
+
.idea/
|
30 |
+
.vscode/
|
31 |
+
*.swp
|
32 |
+
*.swo
|
33 |
+
|
34 |
+
# Logs
|
35 |
+
*.log
|
36 |
+
|
37 |
+
# Local configuration
|
38 |
+
.env
|
39 |
+
.env.local
|
40 |
+
|
41 |
+
# Model files
|
42 |
+
models/*.bin
|
43 |
+
models/*.pt
|
44 |
+
models/*.pth
|
45 |
+
|
46 |
+
# Temporary files
|
47 |
+
tmp/
|
48 |
+
temp/
|
49 |
+
|
50 |
+
# System files
|
51 |
+
.DS_Store
|
52 |
+
Thumbs.db
|
README.md
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: Mental Wellness Platform
|
3 |
+
emoji: 🧠
|
4 |
+
colorFrom: indigo
|
5 |
+
colorTo: purple
|
6 |
+
sdk: gradio
|
7 |
+
sdk_version: "4.4.0"
|
8 |
+
app_file: app.py
|
9 |
+
pinned: false
|
10 |
+
---
|
11 |
+
|
12 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
agents/assessment_agent.py
ADDED
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List
|
2 |
+
from .base_agent import BaseWellnessAgent
|
3 |
+
import json
|
4 |
+
from pathlib import Path
|
5 |
+
|
6 |
+
class AssessmentAgent(BaseWellnessAgent):
|
7 |
+
"""Agent specialized in mental health assessments"""
|
8 |
+
|
9 |
+
def __init__(self, model_config: Dict, verbose: bool = False):
|
10 |
+
super().__init__(
|
11 |
+
name="Mental Health Assessment Agent",
|
12 |
+
role="Mental Health Evaluator",
|
13 |
+
goal="Conduct thorough mental health assessments and provide actionable insights",
|
14 |
+
backstory="""I am an AI agent specialized in mental health assessment.
|
15 |
+
I use validated assessment tools and techniques to evaluate mental well-being
|
16 |
+
and provide personalized recommendations.""",
|
17 |
+
tools=["emotion_detection", "conversation"],
|
18 |
+
model_config=model_config,
|
19 |
+
verbose=verbose
|
20 |
+
)
|
21 |
+
self.assessment_tools = self._load_assessment_tools()
|
22 |
+
self.current_assessment = None
|
23 |
+
|
24 |
+
def _load_assessment_tools(self) -> Dict:
|
25 |
+
"""Load assessment questionnaires and scoring guides"""
|
26 |
+
tools_path = Path(__file__).parent.parent / "knowledge_base" / "assessment_tools.json"
|
27 |
+
try:
|
28 |
+
with open(tools_path) as f:
|
29 |
+
return json.load(f)
|
30 |
+
except FileNotFoundError:
|
31 |
+
return {
|
32 |
+
"phq9": {
|
33 |
+
"name": "PHQ-9 Depression Scale",
|
34 |
+
"questions": [
|
35 |
+
"Little interest or pleasure in doing things?",
|
36 |
+
"Feeling down, depressed, or hopeless?",
|
37 |
+
# Add more questions...
|
38 |
+
],
|
39 |
+
"scoring": {
|
40 |
+
"ranges": {
|
41 |
+
"0-4": "Minimal depression",
|
42 |
+
"5-9": "Mild depression",
|
43 |
+
"10-14": "Moderate depression",
|
44 |
+
"15-19": "Moderately severe depression",
|
45 |
+
"20-27": "Severe depression"
|
46 |
+
}
|
47 |
+
}
|
48 |
+
},
|
49 |
+
"gad7": {
|
50 |
+
"name": "GAD-7 Anxiety Scale",
|
51 |
+
"questions": [
|
52 |
+
"Feeling nervous, anxious, or on edge?",
|
53 |
+
"Not being able to stop or control worrying?",
|
54 |
+
# Add more questions...
|
55 |
+
],
|
56 |
+
"scoring": {
|
57 |
+
"ranges": {
|
58 |
+
"0-4": "Minimal anxiety",
|
59 |
+
"5-9": "Mild anxiety",
|
60 |
+
"10-14": "Moderate anxiety",
|
61 |
+
"15-21": "Severe anxiety"
|
62 |
+
}
|
63 |
+
}
|
64 |
+
}
|
65 |
+
}
|
66 |
+
|
67 |
+
def start_assessment(self, assessment_type: str) -> Dict:
|
68 |
+
"""Start a new assessment"""
|
69 |
+
if assessment_type not in self.assessment_tools:
|
70 |
+
raise ValueError(f"Unknown assessment type: {assessment_type}")
|
71 |
+
|
72 |
+
self.current_assessment = {
|
73 |
+
"type": assessment_type,
|
74 |
+
"tool": self.assessment_tools[assessment_type],
|
75 |
+
"responses": [],
|
76 |
+
"current_question": 0
|
77 |
+
}
|
78 |
+
|
79 |
+
return self.get_next_question()
|
80 |
+
|
81 |
+
def process_message(self, message: str) -> Dict:
|
82 |
+
"""Process user response and continue assessment"""
|
83 |
+
if not self.current_assessment:
|
84 |
+
return self.format_response(
|
85 |
+
"No active assessment. Please start an assessment first."
|
86 |
+
)
|
87 |
+
|
88 |
+
# Record response
|
89 |
+
self.current_assessment["responses"].append({
|
90 |
+
"question": self.current_assessment["current_question"],
|
91 |
+
"response": message,
|
92 |
+
"emotion": self.analyze_emotion(message)
|
93 |
+
})
|
94 |
+
|
95 |
+
# Move to next question or finish assessment
|
96 |
+
return (
|
97 |
+
self.finish_assessment()
|
98 |
+
if self._is_assessment_complete()
|
99 |
+
else self.get_next_question()
|
100 |
+
)
|
101 |
+
|
102 |
+
def get_next_question(self) -> Dict:
|
103 |
+
"""Get the next question in the assessment"""
|
104 |
+
if not self.current_assessment:
|
105 |
+
return self.format_response(
|
106 |
+
"No active assessment. Please start an assessment first."
|
107 |
+
)
|
108 |
+
|
109 |
+
tool = self.current_assessment["tool"]
|
110 |
+
question_idx = self.current_assessment["current_question"]
|
111 |
+
|
112 |
+
if question_idx >= len(tool["questions"]):
|
113 |
+
return self.finish_assessment()
|
114 |
+
|
115 |
+
question = tool["questions"][question_idx]
|
116 |
+
self.current_assessment["current_question"] += 1
|
117 |
+
|
118 |
+
return self.format_response(question)
|
119 |
+
|
120 |
+
def _is_assessment_complete(self) -> bool:
|
121 |
+
"""Check if all questions have been answered"""
|
122 |
+
if not self.current_assessment:
|
123 |
+
return False
|
124 |
+
|
125 |
+
return len(self.current_assessment["responses"]) >= len(
|
126 |
+
self.current_assessment["tool"]["questions"]
|
127 |
+
)
|
128 |
+
|
129 |
+
def finish_assessment(self) -> Dict:
|
130 |
+
"""Complete the assessment and generate report"""
|
131 |
+
if not self.current_assessment:
|
132 |
+
return self.format_response(
|
133 |
+
"No active assessment to finish."
|
134 |
+
)
|
135 |
+
|
136 |
+
# Calculate scores
|
137 |
+
scores = self._calculate_scores()
|
138 |
+
|
139 |
+
# Generate report
|
140 |
+
report = self._generate_report(scores)
|
141 |
+
|
142 |
+
# Add to history
|
143 |
+
self.add_to_history({
|
144 |
+
"assessment_type": self.current_assessment["type"],
|
145 |
+
"scores": scores,
|
146 |
+
"report": report
|
147 |
+
})
|
148 |
+
|
149 |
+
# Reset current assessment
|
150 |
+
self.current_assessment = None
|
151 |
+
|
152 |
+
return self.format_response(report)
|
153 |
+
|
154 |
+
def _calculate_scores(self) -> Dict:
|
155 |
+
"""Calculate assessment scores"""
|
156 |
+
# Implement scoring logic based on assessment type
|
157 |
+
return {
|
158 |
+
"total_score": 0, # Calculate actual score
|
159 |
+
"subscores": {},
|
160 |
+
"severity": "Unknown" # Determine from scoring ranges
|
161 |
+
}
|
162 |
+
|
163 |
+
def _generate_report(self, scores: Dict) -> str:
|
164 |
+
"""Generate detailed assessment report"""
|
165 |
+
report = f"""Assessment Report
|
166 |
+
|
167 |
+
Type: {self.current_assessment["type"].upper()}
|
168 |
+
Total Score: {scores["total_score"]}
|
169 |
+
Severity: {scores["severity"]}
|
170 |
+
|
171 |
+
Recommendations:
|
172 |
+
1. Continue monitoring your mental health
|
173 |
+
2. Consider discussing results with a mental health professional
|
174 |
+
3. Practice self-care and stress management techniques
|
175 |
+
|
176 |
+
Note: This assessment is for screening purposes only and does not constitute
|
177 |
+
a clinical diagnosis. Please consult with a qualified mental health professional
|
178 |
+
for proper evaluation and treatment."""
|
179 |
+
|
180 |
+
return report
|
181 |
+
|
182 |
+
def get_assessment_history(self) -> List[Dict]:
|
183 |
+
"""Get history of completed assessments"""
|
184 |
+
return self.get_history()
|
185 |
+
|
186 |
+
def get_available_assessments(self) -> List[str]:
|
187 |
+
"""Get list of available assessment tools"""
|
188 |
+
return list(self.assessment_tools.keys())
|
agents/base_agent.py
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List, Optional
|
2 |
+
from crewai import Agent
|
3 |
+
from pydantic import BaseModel
|
4 |
+
from transformers import pipeline
|
5 |
+
|
6 |
+
class AgentState(BaseModel):
|
7 |
+
"""State management for agents"""
|
8 |
+
context: Dict = {}
|
9 |
+
history: List[Dict] = []
|
10 |
+
current_task: Optional[str] = None
|
11 |
+
|
12 |
+
class BaseWellnessAgent(Agent):
|
13 |
+
"""Base class for all wellness platform agents"""
|
14 |
+
|
15 |
+
def __init__(
|
16 |
+
self,
|
17 |
+
name: str,
|
18 |
+
role: str,
|
19 |
+
goal: str,
|
20 |
+
backstory: str,
|
21 |
+
tools: List[str],
|
22 |
+
model_config: Dict,
|
23 |
+
verbose: bool = False
|
24 |
+
):
|
25 |
+
super().__init__(
|
26 |
+
name=name,
|
27 |
+
role=role,
|
28 |
+
goal=goal,
|
29 |
+
backstory=backstory,
|
30 |
+
verbose=verbose
|
31 |
+
)
|
32 |
+
self.tools = tools
|
33 |
+
self.model_config = model_config
|
34 |
+
self.state = AgentState()
|
35 |
+
self._initialize_models()
|
36 |
+
|
37 |
+
def _initialize_models(self):
|
38 |
+
"""Initialize required AI models for the agent"""
|
39 |
+
self.models = {}
|
40 |
+
if "emotion_detection" in self.tools:
|
41 |
+
self.models["emotion"] = pipeline(
|
42 |
+
"text-classification",
|
43 |
+
model=self.model_config["emotion_detection"]["model_id"]
|
44 |
+
)
|
45 |
+
|
46 |
+
def update_context(self, new_context: Dict):
|
47 |
+
"""Update agent's context with new information"""
|
48 |
+
self.state.context.update(new_context)
|
49 |
+
|
50 |
+
def add_to_history(self, interaction: Dict):
|
51 |
+
"""Add an interaction to agent's history"""
|
52 |
+
self.state.history.append(interaction)
|
53 |
+
|
54 |
+
def get_context(self) -> Dict:
|
55 |
+
"""Get current context"""
|
56 |
+
return self.state.context
|
57 |
+
|
58 |
+
def get_history(self) -> List[Dict]:
|
59 |
+
"""Get interaction history"""
|
60 |
+
return self.state.history
|
61 |
+
|
62 |
+
def clear_state(self):
|
63 |
+
"""Reset agent state"""
|
64 |
+
self.state = AgentState()
|
65 |
+
|
66 |
+
def analyze_emotion(self, text: str) -> Dict:
|
67 |
+
"""Analyze emotion in text if emotion detection is available"""
|
68 |
+
if "emotion" in self.models:
|
69 |
+
result = self.models["emotion"](text)
|
70 |
+
return result[0] if result else {}
|
71 |
+
return {}
|
72 |
+
|
73 |
+
def format_response(self, response: str) -> Dict:
|
74 |
+
"""Format agent response with metadata"""
|
75 |
+
return {
|
76 |
+
"content": response,
|
77 |
+
"agent_name": self.name,
|
78 |
+
"agent_role": self.role,
|
79 |
+
"timestamp": self._get_timestamp(),
|
80 |
+
"context": self.get_context(),
|
81 |
+
"emotion_analysis": self.analyze_emotion(response)
|
82 |
+
}
|
83 |
+
|
84 |
+
def _get_timestamp(self) -> str:
|
85 |
+
"""Get current timestamp"""
|
86 |
+
from datetime import datetime
|
87 |
+
return datetime.now().isoformat()
|
88 |
+
|
89 |
+
def process_message(self, message: str) -> Dict:
|
90 |
+
"""Process incoming message - to be implemented by child classes"""
|
91 |
+
raise NotImplementedError("Child classes must implement process_message")
|
agents/conversation_agent.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List
|
2 |
+
from .base_agent import BaseWellnessAgent
|
3 |
+
from transformers import pipeline
|
4 |
+
|
5 |
+
class ConversationAgent(BaseWellnessAgent):
|
6 |
+
"""Agent specialized in therapeutic conversations"""
|
7 |
+
|
8 |
+
def __init__(self, model_config: Dict, verbose: bool = False):
|
9 |
+
super().__init__(
|
10 |
+
name="Therapeutic Conversation Agent",
|
11 |
+
role="Mental Health Conversationalist",
|
12 |
+
goal="Engage in supportive therapeutic conversations while maintaining empathy and professionalism",
|
13 |
+
backstory="""I am a specialized AI agent trained in therapeutic conversation techniques.
|
14 |
+
I use evidence-based approaches to provide emotional support and guidance while maintaining
|
15 |
+
appropriate boundaries and recognizing when to escalate to crisis intervention.""",
|
16 |
+
tools=["emotion_detection", "conversation"],
|
17 |
+
model_config=model_config,
|
18 |
+
verbose=verbose
|
19 |
+
)
|
20 |
+
self._initialize_conversation_model()
|
21 |
+
|
22 |
+
def _initialize_conversation_model(self):
|
23 |
+
"""Initialize the conversation model"""
|
24 |
+
self.models["conversation"] = pipeline(
|
25 |
+
"text-generation",
|
26 |
+
model=self.model_config["conversation"]["model_id"]
|
27 |
+
)
|
28 |
+
|
29 |
+
def _generate_response(self, prompt: str) -> str:
|
30 |
+
"""Generate response using the conversation model"""
|
31 |
+
response = self.models["conversation"](
|
32 |
+
prompt,
|
33 |
+
max_length=self.model_config["conversation"]["max_length"],
|
34 |
+
temperature=self.model_config["conversation"]["temperature"]
|
35 |
+
)
|
36 |
+
return response[0]["generated_text"] if response else ""
|
37 |
+
|
38 |
+
def process_message(self, message: str) -> Dict:
|
39 |
+
"""Process user message and generate therapeutic response"""
|
40 |
+
# Analyze emotion
|
41 |
+
emotion = self.analyze_emotion(message)
|
42 |
+
|
43 |
+
# Update context with emotion
|
44 |
+
self.update_context({"last_emotion": emotion})
|
45 |
+
|
46 |
+
# Generate appropriate response based on emotion and context
|
47 |
+
prompt = self._create_prompt(message, emotion)
|
48 |
+
response = self._generate_response(prompt)
|
49 |
+
|
50 |
+
# Add to conversation history
|
51 |
+
interaction = {
|
52 |
+
"user_message": message,
|
53 |
+
"emotion": emotion,
|
54 |
+
"response": response
|
55 |
+
}
|
56 |
+
self.add_to_history(interaction)
|
57 |
+
|
58 |
+
return self.format_response(response)
|
59 |
+
|
60 |
+
def _create_prompt(self, message: str, emotion: Dict) -> str:
|
61 |
+
"""Create context-aware prompt for response generation"""
|
62 |
+
history = self.get_history()
|
63 |
+
context = self.get_context()
|
64 |
+
|
65 |
+
# Build prompt with context
|
66 |
+
prompt = f"""As a therapeutic conversation agent, respond to the following message with empathy and support.
|
67 |
+
User's message: {message}
|
68 |
+
Detected emotion: {emotion}
|
69 |
+
Conversation history: {history[-3:] if history else 'No history'}
|
70 |
+
Additional context: {context}
|
71 |
+
|
72 |
+
Response:"""
|
73 |
+
|
74 |
+
return prompt
|
75 |
+
|
76 |
+
def get_conversation_summary(self) -> Dict:
|
77 |
+
"""Generate summary of the conversation"""
|
78 |
+
history = self.get_history()
|
79 |
+
emotions = [interaction["emotion"] for interaction in history]
|
80 |
+
|
81 |
+
return {
|
82 |
+
"interaction_count": len(history),
|
83 |
+
"emotional_trajectory": emotions,
|
84 |
+
"key_topics": self._extract_key_topics(history),
|
85 |
+
"recommendations": self._generate_recommendations(history)
|
86 |
+
}
|
87 |
+
|
88 |
+
def _extract_key_topics(self, history: List[Dict]) -> List[str]:
|
89 |
+
"""Extract main topics from conversation history"""
|
90 |
+
# Implement topic extraction logic
|
91 |
+
return []
|
92 |
+
|
93 |
+
def _generate_recommendations(self, history: List[Dict]) -> List[str]:
|
94 |
+
"""Generate recommendations based on conversation"""
|
95 |
+
# Implement recommendation logic
|
96 |
+
return []
|
agents/crisis_agent.py
ADDED
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List
|
2 |
+
from .base_agent import BaseWellnessAgent
|
3 |
+
import json
|
4 |
+
from pathlib import Path
|
5 |
+
|
6 |
+
class CrisisAgent(BaseWellnessAgent):
|
7 |
+
"""Agent specialized in crisis intervention and emergency response"""
|
8 |
+
|
9 |
+
def __init__(self, model_config: Dict, verbose: bool = False):
|
10 |
+
super().__init__(
|
11 |
+
name="Crisis Intervention Agent",
|
12 |
+
role="Crisis Support Specialist",
|
13 |
+
goal="Provide immediate support and intervention in crisis situations",
|
14 |
+
backstory="""I am an AI agent specialized in crisis intervention.
|
15 |
+
I am trained to recognize and respond to emergency situations,
|
16 |
+
provide immediate support, and connect users with appropriate resources.""",
|
17 |
+
tools=["emotion_detection", "conversation"],
|
18 |
+
model_config=model_config,
|
19 |
+
verbose=verbose
|
20 |
+
)
|
21 |
+
self.protocols = self._load_protocols()
|
22 |
+
self.current_intervention = None
|
23 |
+
self.emergency_contacts = self._load_emergency_contacts()
|
24 |
+
|
25 |
+
def _load_protocols(self) -> Dict:
|
26 |
+
"""Load crisis intervention protocols"""
|
27 |
+
protocols_path = Path(__file__).parent.parent / "knowledge_base" / "guidelines" / "crisis_protocols.json"
|
28 |
+
try:
|
29 |
+
with open(protocols_path) as f:
|
30 |
+
return json.load(f)
|
31 |
+
except FileNotFoundError:
|
32 |
+
return {
|
33 |
+
"suicide_risk": {
|
34 |
+
"severity_levels": {
|
35 |
+
"low": {
|
36 |
+
"indicators": [
|
37 |
+
"Passing thoughts of death",
|
38 |
+
"No specific plan",
|
39 |
+
"Some protective factors"
|
40 |
+
],
|
41 |
+
"response": "Provide support and resources"
|
42 |
+
},
|
43 |
+
"medium": {
|
44 |
+
"indicators": [
|
45 |
+
"Frequent thoughts of death",
|
46 |
+
"Vague plans",
|
47 |
+
"Some risk factors present"
|
48 |
+
],
|
49 |
+
"response": "Immediate counseling referral"
|
50 |
+
},
|
51 |
+
"high": {
|
52 |
+
"indicators": [
|
53 |
+
"Specific suicide plan",
|
54 |
+
"Access to means",
|
55 |
+
"Multiple risk factors"
|
56 |
+
],
|
57 |
+
"response": "Emergency services contact"
|
58 |
+
}
|
59 |
+
},
|
60 |
+
"immediate_actions": [
|
61 |
+
"Express concern and care",
|
62 |
+
"Assess immediate safety",
|
63 |
+
"Connect with emergency services if needed"
|
64 |
+
]
|
65 |
+
},
|
66 |
+
"panic_attack": {
|
67 |
+
"symptoms": [
|
68 |
+
"Rapid heartbeat",
|
69 |
+
"Difficulty breathing",
|
70 |
+
"Feeling of doom"
|
71 |
+
],
|
72 |
+
"interventions": [
|
73 |
+
"Grounding techniques",
|
74 |
+
"Breathing exercises",
|
75 |
+
"Reassurance and support"
|
76 |
+
]
|
77 |
+
}
|
78 |
+
}
|
79 |
+
|
80 |
+
def _load_emergency_contacts(self) -> Dict:
|
81 |
+
"""Load emergency contact information"""
|
82 |
+
return {
|
83 |
+
"emergency_services": "911",
|
84 |
+
"crisis_hotline": "988",
|
85 |
+
"text_line": "741741",
|
86 |
+
"poison_control": "1-800-222-1222"
|
87 |
+
}
|
88 |
+
|
89 |
+
def process_message(self, message: str) -> Dict:
|
90 |
+
"""Process crisis-related message and provide appropriate response"""
|
91 |
+
# Analyze message for crisis indicators
|
92 |
+
risk_assessment = self._assess_risk(message)
|
93 |
+
|
94 |
+
# Update intervention state
|
95 |
+
self._update_intervention_state(risk_assessment)
|
96 |
+
|
97 |
+
# Generate appropriate response based on risk level
|
98 |
+
response = self._generate_crisis_response(risk_assessment)
|
99 |
+
|
100 |
+
# Record interaction
|
101 |
+
self.add_to_history({
|
102 |
+
"message": message,
|
103 |
+
"risk_assessment": risk_assessment,
|
104 |
+
"response": response
|
105 |
+
})
|
106 |
+
|
107 |
+
return self.format_response(response)
|
108 |
+
|
109 |
+
def _assess_risk(self, message: str) -> Dict:
|
110 |
+
"""Assess risk level from message content"""
|
111 |
+
# Analyze emotion
|
112 |
+
emotion = self.analyze_emotion(message)
|
113 |
+
|
114 |
+
# Check for critical keywords
|
115 |
+
risk_level = self._determine_risk_level(message.lower())
|
116 |
+
|
117 |
+
return {
|
118 |
+
"risk_level": risk_level,
|
119 |
+
"emotion": emotion,
|
120 |
+
"timestamp": self._get_timestamp()
|
121 |
+
}
|
122 |
+
|
123 |
+
def _determine_risk_level(self, message: str) -> str:
|
124 |
+
"""Determine risk level based on message content"""
|
125 |
+
high_risk_keywords = [
|
126 |
+
"kill myself", "end my life", "suicide plan",
|
127 |
+
"want to die", "no reason to live"
|
128 |
+
]
|
129 |
+
medium_risk_keywords = [
|
130 |
+
"want to disappear", "everyone better off",
|
131 |
+
"cant take it", "hopeless"
|
132 |
+
]
|
133 |
+
|
134 |
+
if any(keyword in message for keyword in high_risk_keywords):
|
135 |
+
return "high"
|
136 |
+
elif any(keyword in message for keyword in medium_risk_keywords):
|
137 |
+
return "medium"
|
138 |
+
return "low"
|
139 |
+
|
140 |
+
def _update_intervention_state(self, risk_assessment: Dict):
|
141 |
+
"""Update or create intervention state"""
|
142 |
+
if not self.current_intervention:
|
143 |
+
self.current_intervention = {
|
144 |
+
"start_time": self._get_timestamp(),
|
145 |
+
"risk_assessments": [],
|
146 |
+
"escalation_level": "initial"
|
147 |
+
}
|
148 |
+
|
149 |
+
self.current_intervention["risk_assessments"].append(risk_assessment)
|
150 |
+
self._update_escalation_level(risk_assessment["risk_level"])
|
151 |
+
|
152 |
+
def _update_escalation_level(self, risk_level: str):
|
153 |
+
"""Update intervention escalation level"""
|
154 |
+
if risk_level == "high":
|
155 |
+
self.current_intervention["escalation_level"] = "emergency"
|
156 |
+
elif risk_level == "medium" and self.current_intervention["escalation_level"] == "initial":
|
157 |
+
self.current_intervention["escalation_level"] = "elevated"
|
158 |
+
|
159 |
+
def _generate_crisis_response(self, risk_assessment: Dict) -> str:
|
160 |
+
"""Generate appropriate crisis response"""
|
161 |
+
risk_level = risk_assessment["risk_level"]
|
162 |
+
escalation_level = self.current_intervention["escalation_level"]
|
163 |
+
|
164 |
+
if risk_level == "high" or escalation_level == "emergency":
|
165 |
+
return self._generate_emergency_response()
|
166 |
+
elif risk_level == "medium" or escalation_level == "elevated":
|
167 |
+
return self._generate_elevated_response()
|
168 |
+
else:
|
169 |
+
return self._generate_supportive_response()
|
170 |
+
|
171 |
+
def _generate_emergency_response(self) -> str:
|
172 |
+
"""Generate response for emergency situations"""
|
173 |
+
return f"""I'm very concerned about your safety right now. This is an emergency situation that requires immediate attention.
|
174 |
+
|
175 |
+
EMERGENCY CONTACTS:
|
176 |
+
- Emergency Services: {self.emergency_contacts['emergency_services']}
|
177 |
+
- Crisis Hotline: {self.emergency_contacts['crisis_hotline']}
|
178 |
+
- Crisis Text Line: Text HOME to {self.emergency_contacts['text_line']}
|
179 |
+
|
180 |
+
Please:
|
181 |
+
1. Call emergency services immediately
|
182 |
+
2. Stay on the line with me
|
183 |
+
3. If possible, contact a trusted person to be with you
|
184 |
+
|
185 |
+
Your life has value and people care about you. Help is available 24/7."""
|
186 |
+
|
187 |
+
def _generate_elevated_response(self) -> str:
|
188 |
+
"""Generate response for elevated risk situations"""
|
189 |
+
return f"""I hear how much pain you're in, and I want to help ensure your safety.
|
190 |
+
|
191 |
+
Please consider:
|
192 |
+
1. Calling the Crisis Hotline: {self.emergency_contacts['crisis_hotline']}
|
193 |
+
2. Texting HOME to {self.emergency_contacts['text_line']}
|
194 |
+
3. Reaching out to a trusted friend, family member, or counselor
|
195 |
+
|
196 |
+
Would you be willing to talk about what's troubling you? I'm here to listen without judgment."""
|
197 |
+
|
198 |
+
def _generate_supportive_response(self) -> str:
|
199 |
+
"""Generate supportive response for lower risk situations"""
|
200 |
+
return """I can hear that you're going through a difficult time. Your feelings are valid, and you're not alone.
|
201 |
+
|
202 |
+
Let's talk about what's happening. I'm here to:
|
203 |
+
1. Listen and understand
|
204 |
+
2. Help you explore your feelings
|
205 |
+
3. Discuss coping strategies
|
206 |
+
4. Connect you with resources
|
207 |
+
|
208 |
+
What would be most helpful for you right now?"""
|
209 |
+
|
210 |
+
def end_intervention(self) -> Dict:
|
211 |
+
"""End current crisis intervention"""
|
212 |
+
if not self.current_intervention:
|
213 |
+
return self.format_response(
|
214 |
+
"No active crisis intervention to end."
|
215 |
+
)
|
216 |
+
|
217 |
+
# Generate intervention summary
|
218 |
+
summary = self._generate_intervention_summary()
|
219 |
+
|
220 |
+
# Add final summary to history
|
221 |
+
self.add_to_history({
|
222 |
+
"intervention_summary": summary,
|
223 |
+
"end_time": self._get_timestamp()
|
224 |
+
})
|
225 |
+
|
226 |
+
# Reset current intervention
|
227 |
+
self.current_intervention = None
|
228 |
+
|
229 |
+
return self.format_response(summary)
|
230 |
+
|
231 |
+
def _generate_intervention_summary(self) -> str:
|
232 |
+
"""Generate summary of crisis intervention"""
|
233 |
+
assessments = self.current_intervention["risk_assessments"]
|
234 |
+
max_risk = max(a["risk_level"] for a in assessments)
|
235 |
+
|
236 |
+
return f"""Crisis Intervention Summary
|
237 |
+
|
238 |
+
Duration: {self._calculate_duration(
|
239 |
+
self.current_intervention["start_time"],
|
240 |
+
self._get_timestamp()
|
241 |
+
) // 60} minutes
|
242 |
+
Maximum Risk Level: {max_risk}
|
243 |
+
Escalation Level: {self.current_intervention["escalation_level"]}
|
244 |
+
|
245 |
+
Follow-up Recommendations:
|
246 |
+
1. Continue monitoring emotional state
|
247 |
+
2. Maintain contact with support system
|
248 |
+
3. Follow up with mental health professional
|
249 |
+
4. Keep crisis resources readily available
|
250 |
+
|
251 |
+
Remember: Support is always available at {self.emergency_contacts['crisis_hotline']}"""
|
agents/mindfulness_agent.py
ADDED
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List
|
2 |
+
from .base_agent import BaseWellnessAgent
|
3 |
+
import json
|
4 |
+
from pathlib import Path
|
5 |
+
|
6 |
+
class MindfulnessAgent(BaseWellnessAgent):
|
7 |
+
"""Agent specialized in mindfulness and meditation guidance"""
|
8 |
+
|
9 |
+
def __init__(self, model_config: Dict, verbose: bool = False):
|
10 |
+
super().__init__(
|
11 |
+
name="Mindfulness & Meditation Agent",
|
12 |
+
role="Mindfulness Guide",
|
13 |
+
goal="Guide users through mindfulness exercises and meditation sessions",
|
14 |
+
backstory="""I am an AI agent specialized in mindfulness and meditation guidance.
|
15 |
+
I provide calming exercises, breathing techniques, and meditation sessions
|
16 |
+
tailored to users' needs and experience levels.""",
|
17 |
+
tools=["emotion_detection", "conversation"],
|
18 |
+
model_config=model_config,
|
19 |
+
verbose=verbose
|
20 |
+
)
|
21 |
+
self.exercises = self._load_exercises()
|
22 |
+
self.current_session = None
|
23 |
+
|
24 |
+
def _load_exercises(self) -> Dict:
|
25 |
+
"""Load mindfulness exercises and meditation scripts"""
|
26 |
+
exercises_path = Path(__file__).parent.parent / "knowledge_base" / "resources" / "mindfulness_exercises.json"
|
27 |
+
try:
|
28 |
+
with open(exercises_path) as f:
|
29 |
+
return json.load(f)
|
30 |
+
except FileNotFoundError:
|
31 |
+
return {
|
32 |
+
"breathing": {
|
33 |
+
"box_breathing": {
|
34 |
+
"name": "Box Breathing",
|
35 |
+
"description": "A simple technique to reduce stress and improve focus",
|
36 |
+
"duration": 300, # 5 minutes
|
37 |
+
"steps": [
|
38 |
+
"Inhale slowly for 4 counts",
|
39 |
+
"Hold your breath for 4 counts",
|
40 |
+
"Exhale slowly for 4 counts",
|
41 |
+
"Hold for 4 counts before the next breath"
|
42 |
+
],
|
43 |
+
"instructions": "Find a comfortable position. We'll practice box breathing for 5 minutes."
|
44 |
+
},
|
45 |
+
"deep_breathing": {
|
46 |
+
"name": "Deep Breathing",
|
47 |
+
"description": "Calming deep breathing exercise",
|
48 |
+
"duration": 300,
|
49 |
+
"steps": [
|
50 |
+
"Take a deep breath in through your nose",
|
51 |
+
"Feel your belly expand",
|
52 |
+
"Exhale slowly through your mouth",
|
53 |
+
"Feel your body relax"
|
54 |
+
],
|
55 |
+
"instructions": "Sit comfortably with your back straight. Let's begin deep breathing."
|
56 |
+
}
|
57 |
+
},
|
58 |
+
"meditation": {
|
59 |
+
"body_scan": {
|
60 |
+
"name": "Body Scan Meditation",
|
61 |
+
"description": "Progressive relaxation through body awareness",
|
62 |
+
"duration": 600, # 10 minutes
|
63 |
+
"steps": [
|
64 |
+
"Focus on your toes and feet",
|
65 |
+
"Move attention to your legs",
|
66 |
+
"Progress through torso and arms",
|
67 |
+
"End with neck and head"
|
68 |
+
],
|
69 |
+
"instructions": "Lie down comfortably. We'll guide you through a full body scan."
|
70 |
+
},
|
71 |
+
"loving_kindness": {
|
72 |
+
"name": "Loving-Kindness Meditation",
|
73 |
+
"description": "Develop compassion for self and others",
|
74 |
+
"duration": 600,
|
75 |
+
"steps": [
|
76 |
+
"Direct love to yourself",
|
77 |
+
"Extend to loved ones",
|
78 |
+
"Include neutral people",
|
79 |
+
"Embrace all beings"
|
80 |
+
],
|
81 |
+
"instructions": "Sit in a relaxed position. We'll practice sending loving-kindness."
|
82 |
+
}
|
83 |
+
}
|
84 |
+
}
|
85 |
+
|
86 |
+
def start_session(self, session_type: str, exercise_name: str = None) -> Dict:
|
87 |
+
"""Start a new mindfulness session"""
|
88 |
+
if session_type not in self.exercises:
|
89 |
+
raise ValueError(f"Unknown session type: {session_type}")
|
90 |
+
|
91 |
+
exercises = self.exercises[session_type]
|
92 |
+
if exercise_name and exercise_name not in exercises:
|
93 |
+
raise ValueError(f"Unknown exercise: {exercise_name}")
|
94 |
+
|
95 |
+
selected_exercise = exercises[exercise_name] if exercise_name else next(iter(exercises.values()))
|
96 |
+
|
97 |
+
self.current_session = {
|
98 |
+
"type": session_type,
|
99 |
+
"exercise": selected_exercise,
|
100 |
+
"start_time": self._get_timestamp(),
|
101 |
+
"current_step": 0,
|
102 |
+
"completed_steps": []
|
103 |
+
}
|
104 |
+
|
105 |
+
return self.format_response(self._create_session_intro())
|
106 |
+
|
107 |
+
def process_message(self, message: str) -> Dict:
|
108 |
+
"""Process user message during mindfulness session"""
|
109 |
+
if not self.current_session:
|
110 |
+
return self.format_response(
|
111 |
+
"No active session. Please start a mindfulness session first."
|
112 |
+
)
|
113 |
+
|
114 |
+
# Check for session control commands
|
115 |
+
if message.lower() in ["pause", "stop", "end"]:
|
116 |
+
return self.end_session()
|
117 |
+
|
118 |
+
# Progress through exercise steps
|
119 |
+
return self._progress_session()
|
120 |
+
|
121 |
+
def _progress_session(self) -> Dict:
|
122 |
+
"""Progress through the current session's steps"""
|
123 |
+
exercise = self.current_session["exercise"]
|
124 |
+
current_step = self.current_session["current_step"]
|
125 |
+
|
126 |
+
if current_step >= len(exercise["steps"]):
|
127 |
+
return self.end_session()
|
128 |
+
|
129 |
+
step = exercise["steps"][current_step]
|
130 |
+
self.current_session["completed_steps"].append({
|
131 |
+
"step": current_step,
|
132 |
+
"timestamp": self._get_timestamp()
|
133 |
+
})
|
134 |
+
|
135 |
+
self.current_session["current_step"] += 1
|
136 |
+
|
137 |
+
return self.format_response(self._create_step_guidance(step))
|
138 |
+
|
139 |
+
def _create_session_intro(self) -> str:
|
140 |
+
"""Create introduction for the session"""
|
141 |
+
exercise = self.current_session["exercise"]
|
142 |
+
return f"""Welcome to {exercise['name']}.
|
143 |
+
|
144 |
+
{exercise['description']}
|
145 |
+
|
146 |
+
Duration: {exercise['duration'] // 60} minutes
|
147 |
+
|
148 |
+
{exercise['instructions']}
|
149 |
+
|
150 |
+
When you're ready, respond with 'begin' to start."""
|
151 |
+
|
152 |
+
def _create_step_guidance(self, step: str) -> str:
|
153 |
+
"""Create guidance for the current step"""
|
154 |
+
return f"""{step}
|
155 |
+
|
156 |
+
Take your time with this step.
|
157 |
+
When you're ready to continue, send any message."""
|
158 |
+
|
159 |
+
def end_session(self) -> Dict:
|
160 |
+
"""End the current mindfulness session"""
|
161 |
+
if not self.current_session:
|
162 |
+
return self.format_response(
|
163 |
+
"No active session to end."
|
164 |
+
)
|
165 |
+
|
166 |
+
# Calculate session statistics
|
167 |
+
stats = self._calculate_session_stats()
|
168 |
+
|
169 |
+
# Generate session summary
|
170 |
+
summary = self._generate_session_summary(stats)
|
171 |
+
|
172 |
+
# Add to history
|
173 |
+
self.add_to_history({
|
174 |
+
"session_type": self.current_session["type"],
|
175 |
+
"exercise": self.current_session["exercise"]["name"],
|
176 |
+
"stats": stats,
|
177 |
+
"summary": summary
|
178 |
+
})
|
179 |
+
|
180 |
+
# Reset current session
|
181 |
+
self.current_session = None
|
182 |
+
|
183 |
+
return self.format_response(summary)
|
184 |
+
|
185 |
+
def _calculate_session_stats(self) -> Dict:
|
186 |
+
"""Calculate statistics for the completed session"""
|
187 |
+
start_time = self.current_session["start_time"]
|
188 |
+
end_time = self._get_timestamp()
|
189 |
+
completed_steps = len(self.current_session["completed_steps"])
|
190 |
+
total_steps = len(self.current_session["exercise"]["steps"])
|
191 |
+
|
192 |
+
return {
|
193 |
+
"duration": self._calculate_duration(start_time, end_time),
|
194 |
+
"completion_rate": completed_steps / total_steps,
|
195 |
+
"steps_completed": completed_steps
|
196 |
+
}
|
197 |
+
|
198 |
+
def _calculate_duration(self, start_time: str, end_time: str) -> int:
|
199 |
+
"""Calculate session duration in seconds"""
|
200 |
+
from datetime import datetime
|
201 |
+
start = datetime.fromisoformat(start_time)
|
202 |
+
end = datetime.fromisoformat(end_time)
|
203 |
+
return int((end - start).total_seconds())
|
204 |
+
|
205 |
+
def _generate_session_summary(self, stats: Dict) -> str:
|
206 |
+
"""Generate summary of the completed session"""
|
207 |
+
exercise = self.current_session["exercise"]
|
208 |
+
|
209 |
+
return f"""Session Complete: {exercise['name']}
|
210 |
+
|
211 |
+
Duration: {stats['duration'] // 60} minutes
|
212 |
+
Steps Completed: {stats['steps_completed']} of {len(exercise['steps'])}
|
213 |
+
Completion Rate: {stats['completion_rate'] * 100:.1f}%
|
214 |
+
|
215 |
+
Thank you for practicing mindfulness. Remember to:
|
216 |
+
1. Take these peaceful feelings with you
|
217 |
+
2. Practice regularly for best results
|
218 |
+
3. Be gentle with yourself
|
219 |
+
|
220 |
+
Would you like to try another exercise?"""
|
221 |
+
|
222 |
+
def get_available_exercises(self) -> Dict:
|
223 |
+
"""Get list of available exercises"""
|
224 |
+
return {
|
225 |
+
category: list(exercises.keys())
|
226 |
+
for category, exercises in self.exercises.items()
|
227 |
+
}
|
agents/orchestrator.py
ADDED
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List, Optional
|
2 |
+
from .base_agent import BaseWellnessAgent
|
3 |
+
from .conversation_agent import ConversationAgent
|
4 |
+
from .assessment_agent import AssessmentAgent
|
5 |
+
from .mindfulness_agent import MindfulnessAgent
|
6 |
+
from .crisis_agent import CrisisAgent
|
7 |
+
|
8 |
+
class WellnessOrchestrator:
|
9 |
+
"""Orchestrates multiple specialized agents for mental wellness support"""
|
10 |
+
|
11 |
+
def __init__(self, config: Dict):
|
12 |
+
self.config = config
|
13 |
+
self.agents = self._initialize_agents()
|
14 |
+
self.current_agent: Optional[BaseWellnessAgent] = None
|
15 |
+
self.session_history: List[Dict] = []
|
16 |
+
|
17 |
+
def _initialize_agents(self) -> Dict[str, BaseWellnessAgent]:
|
18 |
+
"""Initialize all specialized agents"""
|
19 |
+
return {
|
20 |
+
"conversation": ConversationAgent(
|
21 |
+
model_config=self.config["MODEL_CONFIGS"]
|
22 |
+
),
|
23 |
+
"assessment": AssessmentAgent(
|
24 |
+
model_config=self.config["MODEL_CONFIGS"]
|
25 |
+
),
|
26 |
+
"mindfulness": MindfulnessAgent(
|
27 |
+
model_config=self.config["MODEL_CONFIGS"]
|
28 |
+
),
|
29 |
+
"crisis": CrisisAgent(
|
30 |
+
model_config=self.config["MODEL_CONFIGS"]
|
31 |
+
)
|
32 |
+
}
|
33 |
+
|
34 |
+
def process_message(self, message: str, context: Optional[Dict] = None) -> Dict:
|
35 |
+
"""Process incoming message and route to appropriate agent"""
|
36 |
+
# Update context for all agents
|
37 |
+
if context:
|
38 |
+
for agent in self.agents.values():
|
39 |
+
agent.update_context(context)
|
40 |
+
|
41 |
+
# Check for crisis keywords first
|
42 |
+
if self._is_crisis_situation(message):
|
43 |
+
self.current_agent = self.agents["crisis"]
|
44 |
+
return self.current_agent.process_message(message)
|
45 |
+
|
46 |
+
# Route to appropriate agent based on message content and context
|
47 |
+
agent_key = self._determine_best_agent(message, context)
|
48 |
+
self.current_agent = self.agents[agent_key]
|
49 |
+
|
50 |
+
# Process message with selected agent
|
51 |
+
response = self.current_agent.process_message(message)
|
52 |
+
|
53 |
+
# Record interaction in session history
|
54 |
+
self._record_interaction(message, response, agent_key)
|
55 |
+
|
56 |
+
return response
|
57 |
+
|
58 |
+
def _is_crisis_situation(self, message: str) -> bool:
|
59 |
+
"""Check if message indicates a crisis situation"""
|
60 |
+
crisis_keywords = [
|
61 |
+
"suicide", "kill myself", "end it all", "self harm",
|
62 |
+
"hurt myself", "die", "death", "emergency"
|
63 |
+
]
|
64 |
+
return any(keyword in message.lower() for keyword in crisis_keywords)
|
65 |
+
|
66 |
+
def _determine_best_agent(self, message: str, context: Optional[Dict]) -> str:
|
67 |
+
"""Determine the most appropriate agent for the message"""
|
68 |
+
# Check for explicit commands or keywords
|
69 |
+
if any(cmd in message.lower() for cmd in ["assess", "evaluation", "test"]):
|
70 |
+
return "assessment"
|
71 |
+
if any(cmd in message.lower() for cmd in ["meditate", "breathe", "relax"]):
|
72 |
+
return "mindfulness"
|
73 |
+
|
74 |
+
# Default to conversation agent if no specific needs detected
|
75 |
+
return "conversation"
|
76 |
+
|
77 |
+
def _record_interaction(self, message: str, response: Dict, agent_key: str):
|
78 |
+
"""Record interaction in session history"""
|
79 |
+
self.session_history.append({
|
80 |
+
"timestamp": response.get("timestamp"),
|
81 |
+
"user_message": message,
|
82 |
+
"agent_response": response,
|
83 |
+
"agent_type": agent_key
|
84 |
+
})
|
85 |
+
|
86 |
+
def start_assessment(self, assessment_type: str) -> Dict:
|
87 |
+
"""Start a new assessment"""
|
88 |
+
self.current_agent = self.agents["assessment"]
|
89 |
+
return self.agents["assessment"].start_assessment(assessment_type)
|
90 |
+
|
91 |
+
def start_mindfulness_session(self, session_type: str) -> Dict:
|
92 |
+
"""Start a new mindfulness session"""
|
93 |
+
self.current_agent = self.agents["mindfulness"]
|
94 |
+
return self.agents["mindfulness"].start_session(session_type)
|
95 |
+
|
96 |
+
def get_session_summary(self) -> Dict:
|
97 |
+
"""Generate summary of current session"""
|
98 |
+
return {
|
99 |
+
"interaction_count": len(self.session_history),
|
100 |
+
"agent_usage": self._calculate_agent_usage(),
|
101 |
+
"key_insights": self._generate_insights(),
|
102 |
+
"recommendations": self._generate_recommendations()
|
103 |
+
}
|
104 |
+
|
105 |
+
def _calculate_agent_usage(self) -> Dict[str, int]:
|
106 |
+
"""Calculate how often each agent was used"""
|
107 |
+
usage = {}
|
108 |
+
for interaction in self.session_history:
|
109 |
+
agent_type = interaction["agent_type"]
|
110 |
+
usage[agent_type] = usage.get(agent_type, 0) + 1
|
111 |
+
return usage
|
112 |
+
|
113 |
+
def _generate_insights(self) -> List[str]:
|
114 |
+
"""Generate insights from session history"""
|
115 |
+
# Implement insight generation logic
|
116 |
+
return []
|
117 |
+
|
118 |
+
def _generate_recommendations(self) -> List[str]:
|
119 |
+
"""Generate recommendations based on session history"""
|
120 |
+
# Implement recommendation generation logic
|
121 |
+
return []
|
122 |
+
|
123 |
+
def reset_session(self):
|
124 |
+
"""Reset the current session"""
|
125 |
+
self.session_history = []
|
126 |
+
self.current_agent = None
|
127 |
+
for agent in self.agents.values():
|
128 |
+
agent.clear_state()
|
app.py
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from interface.app import WellnessInterface
|
3 |
+
from config.config import load_config
|
4 |
+
|
5 |
+
def main():
|
6 |
+
# Load configuration
|
7 |
+
config = load_config()
|
8 |
+
|
9 |
+
# Initialize interface
|
10 |
+
interface = WellnessInterface(config)
|
11 |
+
|
12 |
+
# Launch the application
|
13 |
+
interface.launch(
|
14 |
+
share=True,
|
15 |
+
enable_queue=True,
|
16 |
+
server_name="0.0.0.0",
|
17 |
+
server_port=7860
|
18 |
+
)
|
19 |
+
|
20 |
+
if __name__ == "__main__":
|
21 |
+
main()
|
config/config.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pathlib import Path
|
2 |
+
from typing import Dict
|
3 |
+
|
4 |
+
def load_config() -> Dict:
|
5 |
+
"""Load configuration settings"""
|
6 |
+
return {
|
7 |
+
"MODEL_CONFIGS": {
|
8 |
+
"conversation": {
|
9 |
+
"model_id": "TheBloke/Llama-2-7B-Chat-GGUF",
|
10 |
+
"max_length": 2048,
|
11 |
+
"temperature": 0.7,
|
12 |
+
},
|
13 |
+
"emotion_detection": {
|
14 |
+
"model_id": "bhadresh-savani/bert-base-uncased-emotion",
|
15 |
+
},
|
16 |
+
"speech_to_text": {
|
17 |
+
"model_id": "openai/whisper-base",
|
18 |
+
},
|
19 |
+
"vision": {
|
20 |
+
"model_id": "microsoft/resnet-50",
|
21 |
+
}
|
22 |
+
},
|
23 |
+
"INTERFACE_CONFIG": {
|
24 |
+
"theme": "light",
|
25 |
+
"supported_languages": ["en"],
|
26 |
+
"max_file_size_mb": 10,
|
27 |
+
"supported_file_types": [
|
28 |
+
"text/plain",
|
29 |
+
"audio/wav",
|
30 |
+
"audio/mp3",
|
31 |
+
"image/jpeg",
|
32 |
+
"image/png",
|
33 |
+
"video/mp4"
|
34 |
+
]
|
35 |
+
},
|
36 |
+
"ANALYTICS_CONFIG": {
|
37 |
+
"metrics": [
|
38 |
+
"user_engagement",
|
39 |
+
"session_duration",
|
40 |
+
"intervention_effectiveness",
|
41 |
+
"crisis_events",
|
42 |
+
"mood_trends"
|
43 |
+
],
|
44 |
+
"reporting_interval": "daily"
|
45 |
+
}
|
46 |
+
}
|
47 |
+
|
interface/app.py
ADDED
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from typing import Dict, List
|
3 |
+
import os
|
4 |
+
|
5 |
+
class WellnessInterface:
|
6 |
+
def __init__(self, config: Dict):
|
7 |
+
self.config = config
|
8 |
+
self.interface = None
|
9 |
+
self.setup_interface()
|
10 |
+
|
11 |
+
def setup_interface(self):
|
12 |
+
"""Set up the Gradio interface"""
|
13 |
+
with gr.Blocks(theme=gr.themes.Soft()) as self.interface:
|
14 |
+
gr.Markdown("# Mental Wellness Support Platform")
|
15 |
+
gr.Markdown("Welcome to your AI-powered mental wellness support system. "
|
16 |
+
"Please note that this is not a substitute for professional mental health care.")
|
17 |
+
|
18 |
+
with gr.Row():
|
19 |
+
with gr.Column(scale=3):
|
20 |
+
# Chat interface
|
21 |
+
self.chatbot = gr.Chatbot(
|
22 |
+
label="Conversation",
|
23 |
+
height=400
|
24 |
+
)
|
25 |
+
with gr.Row():
|
26 |
+
self.msg = gr.Textbox(
|
27 |
+
label="Type your message",
|
28 |
+
placeholder="Share what's on your mind...",
|
29 |
+
scale=4
|
30 |
+
)
|
31 |
+
self.send = gr.Button("Send", scale=1)
|
32 |
+
|
33 |
+
# Voice input
|
34 |
+
self.audio_input = gr.Audio(
|
35 |
+
label="Voice Input",
|
36 |
+
source="microphone",
|
37 |
+
type="filepath"
|
38 |
+
)
|
39 |
+
|
40 |
+
with gr.Column(scale=1):
|
41 |
+
# Wellness tools
|
42 |
+
with gr.Tab("Tools"):
|
43 |
+
gr.Markdown("### Wellness Tools")
|
44 |
+
self.meditation_btn = gr.Button("Start Meditation")
|
45 |
+
self.assessment_btn = gr.Button("Mental Health Check-in")
|
46 |
+
self.resources_btn = gr.Button("View Resources")
|
47 |
+
|
48 |
+
# Session analytics
|
49 |
+
with gr.Tab("Analytics"):
|
50 |
+
self.analytics_display = gr.JSON(
|
51 |
+
label="Session Analytics",
|
52 |
+
value={}
|
53 |
+
)
|
54 |
+
self.update_analytics_btn = gr.Button("Update Analytics")
|
55 |
+
|
56 |
+
# File upload for image/video
|
57 |
+
with gr.Row():
|
58 |
+
self.file_upload = gr.File(
|
59 |
+
label="Upload Image/Video",
|
60 |
+
file_types=["image", "video"]
|
61 |
+
)
|
62 |
+
|
63 |
+
# Emergency resources
|
64 |
+
with gr.Row():
|
65 |
+
gr.Markdown("""
|
66 |
+
### Emergency Resources
|
67 |
+
If you're experiencing a mental health emergency:
|
68 |
+
- Emergency Services: 911 (US)
|
69 |
+
- National Crisis Hotline: 988
|
70 |
+
- Crisis Text Line: Text HOME to 741741
|
71 |
+
""")
|
72 |
+
|
73 |
+
# Set up event handlers
|
74 |
+
self.send.click(
|
75 |
+
fn=self._handle_text_input,
|
76 |
+
inputs=[self.msg, self.chatbot],
|
77 |
+
outputs=[self.msg, self.chatbot]
|
78 |
+
)
|
79 |
+
|
80 |
+
self.audio_input.change(
|
81 |
+
fn=self._handle_voice_input,
|
82 |
+
inputs=[self.audio_input, self.chatbot],
|
83 |
+
outputs=[self.chatbot]
|
84 |
+
)
|
85 |
+
|
86 |
+
self.file_upload.change(
|
87 |
+
fn=self._handle_file_upload,
|
88 |
+
inputs=[self.file_upload, self.chatbot],
|
89 |
+
outputs=[self.chatbot]
|
90 |
+
)
|
91 |
+
|
92 |
+
self.update_analytics_btn.click(
|
93 |
+
fn=self._update_analytics,
|
94 |
+
inputs=[],
|
95 |
+
outputs=[self.analytics_display]
|
96 |
+
)
|
97 |
+
|
98 |
+
# Wellness tool handlers
|
99 |
+
self.meditation_btn.click(
|
100 |
+
fn=self._start_meditation,
|
101 |
+
inputs=[self.chatbot],
|
102 |
+
outputs=[self.chatbot]
|
103 |
+
)
|
104 |
+
|
105 |
+
self.assessment_btn.click(
|
106 |
+
fn=self._start_assessment,
|
107 |
+
inputs=[self.chatbot],
|
108 |
+
outputs=[self.chatbot]
|
109 |
+
)
|
110 |
+
|
111 |
+
self.resources_btn.click(
|
112 |
+
fn=self._show_resources,
|
113 |
+
inputs=[self.chatbot],
|
114 |
+
outputs=[self.chatbot]
|
115 |
+
)
|
116 |
+
|
117 |
+
def _handle_text_input(self, message: str, history: list) -> tuple:
|
118 |
+
"""Handle text input from user"""
|
119 |
+
if message:
|
120 |
+
# For now, just echo the message
|
121 |
+
response = f"You said: {message}"
|
122 |
+
history.append((message, response))
|
123 |
+
return "", history
|
124 |
+
return message, history
|
125 |
+
|
126 |
+
def _handle_voice_input(self, audio_path: str, history: list) -> list:
|
127 |
+
"""Handle voice input from user"""
|
128 |
+
if audio_path:
|
129 |
+
response = "Voice message received! (Voice processing coming soon)"
|
130 |
+
history.append(("🎤 Voice message", response))
|
131 |
+
return history
|
132 |
+
|
133 |
+
def _handle_file_upload(self, file: gr.File, history: list) -> list:
|
134 |
+
"""Handle file upload from user"""
|
135 |
+
if file:
|
136 |
+
response = f"Received file: {file.name} (Media processing coming soon)"
|
137 |
+
history.append((f"📎 Uploaded: {file.name}", response))
|
138 |
+
return history
|
139 |
+
|
140 |
+
def _update_analytics(self) -> Dict:
|
141 |
+
"""Update analytics display"""
|
142 |
+
return {
|
143 |
+
"sessions": 1,
|
144 |
+
"messages": len(self.chatbot.value) if self.chatbot.value else 0,
|
145 |
+
"status": "Demo Mode"
|
146 |
+
}
|
147 |
+
|
148 |
+
def _start_meditation(self, history: list) -> list:
|
149 |
+
"""Start meditation session"""
|
150 |
+
response = """Let's begin a simple breathing exercise:
|
151 |
+
1. Find a comfortable position
|
152 |
+
2. Close your eyes or maintain a soft gaze
|
153 |
+
3. We'll practice deep breathing together
|
154 |
+
|
155 |
+
Are you ready to start? (Reply 'yes' when ready)"""
|
156 |
+
history.append(("🧘 Started meditation session", response))
|
157 |
+
return history
|
158 |
+
|
159 |
+
def _start_assessment(self, history: list) -> list:
|
160 |
+
"""Start mental health assessment"""
|
161 |
+
response = """I'll help you with a quick mental health check-in.
|
162 |
+
We'll use standard screening tools to understand how you're feeling.
|
163 |
+
|
164 |
+
Would you like to:
|
165 |
+
1. Check anxiety levels (GAD-7)
|
166 |
+
2. Check mood/depression (PHQ-9)
|
167 |
+
3. General well-being assessment
|
168 |
+
|
169 |
+
Please choose a number (1-3)."""
|
170 |
+
history.append(("📋 Started assessment", response))
|
171 |
+
return history
|
172 |
+
|
173 |
+
def _show_resources(self, history: list) -> list:
|
174 |
+
"""Show mental health resources"""
|
175 |
+
response = """Here are some helpful resources:
|
176 |
+
|
177 |
+
📱 Quick Tools:
|
178 |
+
- Breathing exercises
|
179 |
+
- Grounding techniques
|
180 |
+
- Meditation guides
|
181 |
+
|
182 |
+
📚 Educational Resources:
|
183 |
+
- Understanding anxiety
|
184 |
+
- Stress management
|
185 |
+
- Building resilience
|
186 |
+
|
187 |
+
🤝 Support Services:
|
188 |
+
- Find local therapists
|
189 |
+
- Support groups
|
190 |
+
- Crisis hotlines
|
191 |
+
|
192 |
+
Which would you like to learn more about?"""
|
193 |
+
history.append(("📚 Resource guide", response))
|
194 |
+
return history
|
195 |
+
|
196 |
+
def launch(self, **kwargs):
|
197 |
+
"""Launch the Gradio interface"""
|
198 |
+
self.interface.launch(**kwargs)
|
knowledge_base/guidelines/crisis_protocols.json
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"suicide_risk": {
|
3 |
+
"severity_levels": {
|
4 |
+
"low": {
|
5 |
+
"indicators": [
|
6 |
+
"Passing thoughts of death",
|
7 |
+
"No specific plan",
|
8 |
+
"Some protective factors"
|
9 |
+
],
|
10 |
+
"response": "Provide support and resources"
|
11 |
+
},
|
12 |
+
"medium": {
|
13 |
+
"indicators": [
|
14 |
+
"Frequent thoughts of death",
|
15 |
+
"Vague plans",
|
16 |
+
"Some risk factors present"
|
17 |
+
],
|
18 |
+
"response": "Immediate counseling referral"
|
19 |
+
},
|
20 |
+
"high": {
|
21 |
+
"indicators": [
|
22 |
+
"Specific suicide plan",
|
23 |
+
"Access to means",
|
24 |
+
"Multiple risk factors"
|
25 |
+
],
|
26 |
+
"response": "Emergency services contact"
|
27 |
+
}
|
28 |
+
},
|
29 |
+
"immediate_actions": [
|
30 |
+
"Express concern and care",
|
31 |
+
"Assess immediate safety",
|
32 |
+
"Connect with emergency services if needed"
|
33 |
+
]
|
34 |
+
},
|
35 |
+
"panic_attack": {
|
36 |
+
"symptoms": [
|
37 |
+
"Rapid heartbeat",
|
38 |
+
"Difficulty breathing",
|
39 |
+
"Feeling of doom"
|
40 |
+
],
|
41 |
+
"interventions": [
|
42 |
+
"Grounding techniques",
|
43 |
+
"Breathing exercises",
|
44 |
+
"Reassurance and support"
|
45 |
+
]
|
46 |
+
},
|
47 |
+
"emergency_contacts": {
|
48 |
+
"emergency_services": "911",
|
49 |
+
"crisis_hotline": "988",
|
50 |
+
"text_line": "741741",
|
51 |
+
"poison_control": "1-800-222-1222"
|
52 |
+
},
|
53 |
+
"escalation_procedures": {
|
54 |
+
"initial": {
|
55 |
+
"actions": [
|
56 |
+
"Assess immediate risk",
|
57 |
+
"Establish rapport",
|
58 |
+
"Identify support resources"
|
59 |
+
]
|
60 |
+
},
|
61 |
+
"elevated": {
|
62 |
+
"actions": [
|
63 |
+
"Increase monitoring",
|
64 |
+
"Contact support system",
|
65 |
+
"Prepare for potential escalation"
|
66 |
+
]
|
67 |
+
},
|
68 |
+
"emergency": {
|
69 |
+
"actions": [
|
70 |
+
"Contact emergency services",
|
71 |
+
"Stay engaged with user",
|
72 |
+
"Document all interactions"
|
73 |
+
]
|
74 |
+
}
|
75 |
+
}
|
76 |
+
}
|
knowledge_base/resources/mindfulness_exercises.json
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"breathing": {
|
3 |
+
"box_breathing": {
|
4 |
+
"name": "Box Breathing",
|
5 |
+
"description": "A simple technique to reduce stress and improve focus",
|
6 |
+
"duration": 300,
|
7 |
+
"steps": [
|
8 |
+
"Inhale slowly for 4 counts",
|
9 |
+
"Hold your breath for 4 counts",
|
10 |
+
"Exhale slowly for 4 counts",
|
11 |
+
"Hold for 4 counts before the next breath"
|
12 |
+
],
|
13 |
+
"instructions": "Find a comfortable position. We'll practice box breathing for 5 minutes."
|
14 |
+
},
|
15 |
+
"deep_breathing": {
|
16 |
+
"name": "Deep Breathing",
|
17 |
+
"description": "Calming deep breathing exercise",
|
18 |
+
"duration": 300,
|
19 |
+
"steps": [
|
20 |
+
"Take a deep breath in through your nose",
|
21 |
+
"Feel your belly expand",
|
22 |
+
"Exhale slowly through your mouth",
|
23 |
+
"Feel your body relax"
|
24 |
+
],
|
25 |
+
"instructions": "Sit comfortably with your back straight. Let's begin deep breathing."
|
26 |
+
}
|
27 |
+
},
|
28 |
+
"meditation": {
|
29 |
+
"body_scan": {
|
30 |
+
"name": "Body Scan Meditation",
|
31 |
+
"description": "Progressive relaxation through body awareness",
|
32 |
+
"duration": 600,
|
33 |
+
"steps": [
|
34 |
+
"Focus on your toes and feet",
|
35 |
+
"Move attention to your legs",
|
36 |
+
"Progress through torso and arms",
|
37 |
+
"End with neck and head"
|
38 |
+
],
|
39 |
+
"instructions": "Lie down comfortably. We'll guide you through a full body scan."
|
40 |
+
},
|
41 |
+
"loving_kindness": {
|
42 |
+
"name": "Loving-Kindness Meditation",
|
43 |
+
"description": "Develop compassion for self and others",
|
44 |
+
"duration": 600,
|
45 |
+
"steps": [
|
46 |
+
"Direct love to yourself",
|
47 |
+
"Extend to loved ones",
|
48 |
+
"Include neutral people",
|
49 |
+
"Embrace all beings"
|
50 |
+
],
|
51 |
+
"instructions": "Sit in a relaxed position. We'll practice sending loving-kindness."
|
52 |
+
}
|
53 |
+
}
|
54 |
+
}
|
requirements.txt
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio>=4.4.0
|
2 |
+
transformers>=4.35.2
|
3 |
+
torch>=2.1.1
|
4 |
+
numpy>=1.24.3
|
5 |
+
pandas>=2.1.3
|
6 |
+
python-dotenv>=1.0.0
|
7 |
+
faiss-cpu>=1.7.4
|
8 |
+
langchain>=0.0.339
|
9 |
+
pydantic>=2.5.2
|
10 |
+
python-multipart>=0.0.6
|
11 |
+
soundfile>=0.12.1
|
12 |
+
librosa>=0.10.1
|
13 |
+
opencv-python>=4.8.1.78
|
14 |
+
pillow>=10.1.0
|
15 |
+
redis>=5.0.1
|
16 |
+
pytest>=7.4.3
|
17 |
+
crewai>=0.11.0
|
18 |
+
huggingface_hub>=0.26.5
|