mentalwellness / agents /crisis_agent.py
invincible-jha
Update interface for Gradio 5.8.0
76166e3
raw
history blame
10.2 kB
from typing import Dict, List
from .base_agent import BaseWellnessAgent
import json
from pathlib import Path
class CrisisAgent(BaseWellnessAgent):
"""Agent specialized in crisis intervention and emergency response"""
def __init__(self, model_config: Dict, verbose: bool = False):
super().__init__(
name="Crisis Intervention Agent",
role="Crisis Support Specialist",
goal="Provide immediate support and intervention in crisis situations",
backstory="""I am an AI agent specialized in crisis intervention.
I am trained to recognize and respond to emergency situations,
provide immediate support, and connect users with appropriate resources.""",
tools=["emotion_detection", "conversation"],
model_config=model_config,
verbose=verbose
)
self.protocols = self._load_protocols()
self.current_intervention = None
self.emergency_contacts = self._load_emergency_contacts()
def _load_protocols(self) -> Dict:
"""Load crisis intervention protocols"""
protocols_path = Path(__file__).parent.parent / "knowledge_base" / "guidelines" / "crisis_protocols.json"
try:
with open(protocols_path) as f:
return json.load(f)
except FileNotFoundError:
return {
"suicide_risk": {
"severity_levels": {
"low": {
"indicators": [
"Passing thoughts of death",
"No specific plan",
"Some protective factors"
],
"response": "Provide support and resources"
},
"medium": {
"indicators": [
"Frequent thoughts of death",
"Vague plans",
"Some risk factors present"
],
"response": "Immediate counseling referral"
},
"high": {
"indicators": [
"Specific suicide plan",
"Access to means",
"Multiple risk factors"
],
"response": "Emergency services contact"
}
},
"immediate_actions": [
"Express concern and care",
"Assess immediate safety",
"Connect with emergency services if needed"
]
},
"panic_attack": {
"symptoms": [
"Rapid heartbeat",
"Difficulty breathing",
"Feeling of doom"
],
"interventions": [
"Grounding techniques",
"Breathing exercises",
"Reassurance and support"
]
}
}
def _load_emergency_contacts(self) -> Dict:
"""Load emergency contact information"""
return {
"emergency_services": "911",
"crisis_hotline": "988",
"text_line": "741741",
"poison_control": "1-800-222-1222"
}
def process_message(self, message: str) -> Dict:
"""Process crisis-related message and provide appropriate response"""
# Analyze message for crisis indicators
risk_assessment = self._assess_risk(message)
# Update intervention state
self._update_intervention_state(risk_assessment)
# Generate appropriate response based on risk level
response = self._generate_crisis_response(risk_assessment)
# Record interaction
self.add_to_history({
"message": message,
"risk_assessment": risk_assessment,
"response": response
})
return self.format_response(response)
def _assess_risk(self, message: str) -> Dict:
"""Assess risk level from message content"""
# Analyze emotion
emotion = self.analyze_emotion(message)
# Check for critical keywords
risk_level = self._determine_risk_level(message.lower())
return {
"risk_level": risk_level,
"emotion": emotion,
"timestamp": self._get_timestamp()
}
def _determine_risk_level(self, message: str) -> str:
"""Determine risk level based on message content"""
high_risk_keywords = [
"kill myself", "end my life", "suicide plan",
"want to die", "no reason to live"
]
medium_risk_keywords = [
"want to disappear", "everyone better off",
"cant take it", "hopeless"
]
if any(keyword in message for keyword in high_risk_keywords):
return "high"
elif any(keyword in message for keyword in medium_risk_keywords):
return "medium"
return "low"
def _update_intervention_state(self, risk_assessment: Dict):
"""Update or create intervention state"""
if not self.current_intervention:
self.current_intervention = {
"start_time": self._get_timestamp(),
"risk_assessments": [],
"escalation_level": "initial"
}
self.current_intervention["risk_assessments"].append(risk_assessment)
self._update_escalation_level(risk_assessment["risk_level"])
def _update_escalation_level(self, risk_level: str):
"""Update intervention escalation level"""
if risk_level == "high":
self.current_intervention["escalation_level"] = "emergency"
elif risk_level == "medium" and self.current_intervention["escalation_level"] == "initial":
self.current_intervention["escalation_level"] = "elevated"
def _generate_crisis_response(self, risk_assessment: Dict) -> str:
"""Generate appropriate crisis response"""
risk_level = risk_assessment["risk_level"]
escalation_level = self.current_intervention["escalation_level"]
if risk_level == "high" or escalation_level == "emergency":
return self._generate_emergency_response()
elif risk_level == "medium" or escalation_level == "elevated":
return self._generate_elevated_response()
else:
return self._generate_supportive_response()
def _generate_emergency_response(self) -> str:
"""Generate response for emergency situations"""
return f"""I'm very concerned about your safety right now. This is an emergency situation that requires immediate attention.
EMERGENCY CONTACTS:
- Emergency Services: {self.emergency_contacts['emergency_services']}
- Crisis Hotline: {self.emergency_contacts['crisis_hotline']}
- Crisis Text Line: Text HOME to {self.emergency_contacts['text_line']}
Please:
1. Call emergency services immediately
2. Stay on the line with me
3. If possible, contact a trusted person to be with you
Your life has value and people care about you. Help is available 24/7."""
def _generate_elevated_response(self) -> str:
"""Generate response for elevated risk situations"""
return f"""I hear how much pain you're in, and I want to help ensure your safety.
Please consider:
1. Calling the Crisis Hotline: {self.emergency_contacts['crisis_hotline']}
2. Texting HOME to {self.emergency_contacts['text_line']}
3. Reaching out to a trusted friend, family member, or counselor
Would you be willing to talk about what's troubling you? I'm here to listen without judgment."""
def _generate_supportive_response(self) -> str:
"""Generate supportive response for lower risk situations"""
return """I can hear that you're going through a difficult time. Your feelings are valid, and you're not alone.
Let's talk about what's happening. I'm here to:
1. Listen and understand
2. Help you explore your feelings
3. Discuss coping strategies
4. Connect you with resources
What would be most helpful for you right now?"""
def end_intervention(self) -> Dict:
"""End current crisis intervention"""
if not self.current_intervention:
return self.format_response(
"No active crisis intervention to end."
)
# Generate intervention summary
summary = self._generate_intervention_summary()
# Add final summary to history
self.add_to_history({
"intervention_summary": summary,
"end_time": self._get_timestamp()
})
# Reset current intervention
self.current_intervention = None
return self.format_response(summary)
def _generate_intervention_summary(self) -> str:
"""Generate summary of crisis intervention"""
assessments = self.current_intervention["risk_assessments"]
max_risk = max(a["risk_level"] for a in assessments)
return f"""Crisis Intervention Summary
Duration: {self._calculate_duration(
self.current_intervention["start_time"],
self._get_timestamp()
) // 60} minutes
Maximum Risk Level: {max_risk}
Escalation Level: {self.current_intervention["escalation_level"]}
Follow-up Recommendations:
1. Continue monitoring emotional state
2. Maintain contact with support system
3. Follow up with mental health professional
4. Keep crisis resources readily available
Remember: Support is always available at {self.emergency_contacts['crisis_hotline']}"""