invincible-jha commited on
Commit
6f0fdff
Β·
1 Parent(s): d6fdb88

Add CrewAI orchestrator for agent coordination

Browse files
Files changed (2) hide show
  1. agents/orchestrator.py +184 -117
  2. interface/app.py +39 -52
agents/orchestrator.py CHANGED
@@ -1,128 +1,195 @@
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()
 
1
+ from typing import Dict, List
2
+ from crewai import Crew, Process, Task
3
+ from agents.conversation_agent import ConversationAgent
4
+ from agents.assessment_agent import AssessmentAgent
5
+ from agents.mindfulness_agent import MindfulnessAgent
6
+ from agents.crisis_agent import CrisisAgent
7
+ import logging
8
+ from utils.log_manager import LogManager
9
 
10
  class WellnessOrchestrator:
11
+ """Orchestrates the coordination between different agents"""
12
 
13
+ def __init__(self, model_config: Dict):
14
+ self.model_config = model_config
15
+ self.log_manager = LogManager()
16
+ self.logger = self.log_manager.get_agent_logger("orchestrator")
 
17
 
18
+ # Initialize agents
19
+ self.initialize_agents()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ # Initialize CrewAI
22
+ self.initialize_crew()
23
 
24
+ def initialize_agents(self):
25
+ """Initialize all agents with their specific roles and tools"""
26
+ self.logger.info("Initializing agents")
27
 
28
+ try:
29
+ # Conversation Agent
30
+ self.conversation_agent = ConversationAgent(
31
+ name="Therapeutic Conversation Agent",
32
+ role="Lead conversation therapist",
33
+ goal="Guide therapeutic conversations and provide emotional support",
34
+ backstory="Expert in therapeutic dialogue and emotional support",
35
+ tools=["chat", "emotion_detection"],
36
+ model_config=self.model_config
37
+ )
38
+
39
+ # Assessment Agent
40
+ self.assessment_agent = AssessmentAgent(
41
+ name="Mental Health Assessment Agent",
42
+ role="Mental health evaluator",
43
+ goal="Conduct mental health assessments and track progress",
44
+ backstory="Specialist in mental health evaluation and monitoring",
45
+ tools=["assessment_tools", "progress_tracking"],
46
+ model_config=self.model_config
47
+ )
48
+
49
+ # Mindfulness Agent
50
+ self.mindfulness_agent = MindfulnessAgent(
51
+ name="Mindfulness Guide Agent",
52
+ role="Mindfulness and meditation instructor",
53
+ goal="Guide mindfulness exercises and meditation sessions",
54
+ backstory="Expert in mindfulness techniques and meditation",
55
+ tools=["meditation_guide", "breathing_exercises"],
56
+ model_config=self.model_config
57
+ )
58
+
59
+ # Crisis Agent
60
+ self.crisis_agent = CrisisAgent(
61
+ name="Crisis Intervention Agent",
62
+ role="Emergency response specialist",
63
+ goal="Provide immediate support in crisis situations",
64
+ backstory="Trained in crisis intervention and emergency response",
65
+ tools=["crisis_protocol", "emergency_resources"],
66
+ model_config=self.model_config
67
+ )
68
+
69
+ self.logger.info("All agents initialized successfully")
70
+
71
+ except Exception as e:
72
+ self.logger.error(f"Error initializing agents: {str(e)}")
73
+ raise
74
+
75
+ def initialize_crew(self):
76
+ """Initialize CrewAI with agents and tasks"""
77
+ self.logger.info("Initializing CrewAI")
78
 
79
+ try:
80
+ # Create the crew
81
+ self.crew = Crew(
82
+ agents=[
83
+ self.conversation_agent,
84
+ self.assessment_agent,
85
+ self.mindfulness_agent,
86
+ self.crisis_agent
87
+ ],
88
+ tasks=[], # Tasks will be added dynamically
89
+ process=Process.sequential # Can be changed to parallel if needed
90
+ )
91
+
92
+ self.logger.info("CrewAI initialized successfully")
93
+
94
+ except Exception as e:
95
+ self.logger.error(f"Error initializing CrewAI: {str(e)}")
96
+ raise
97
+
98
+ def create_task(self, task_type: str, description: str, agent) -> Task:
99
+ """Create a task for an agent"""
100
+ return Task(
101
+ description=description,
102
+ agent=agent,
103
+ expected_output="Detailed response with next steps"
104
+ )
105
 
106
+ def process_message(self, message: str, context: Dict = None) -> Dict:
107
+ """Process user message through appropriate agents"""
108
+ self.logger.info("Processing message through agents")
 
109
 
110
+ try:
111
+ # Clear previous tasks
112
+ self.crew.tasks = []
113
+
114
+ # Initial assessment by conversation agent
115
+ initial_task = self.create_task(
116
+ "initial_assessment",
117
+ f"Analyze this message and determine required support: {message}",
118
+ self.conversation_agent
119
+ )
120
+ self.crew.tasks.append(initial_task)
121
+
122
+ # Analyze for crisis indicators
123
+ crisis_check = self.create_task(
124
+ "crisis_check",
125
+ f"Check for crisis indicators in: {message}",
126
+ self.crisis_agent
127
+ )
128
+ self.crew.tasks.append(crisis_check)
129
+
130
+ # Execute the crew tasks
131
+ result = self.crew.kickoff()
132
+
133
+ # Process results and determine next steps
134
+ if "crisis" in result.lower():
135
+ # Add crisis intervention task
136
+ crisis_task = self.create_task(
137
+ "crisis_intervention",
138
+ f"Provide crisis intervention for: {message}",
139
+ self.crisis_agent
140
+ )
141
+ self.crew.tasks = [crisis_task]
142
+ response = self.crew.kickoff()
143
+
144
+ elif "assessment" in result.lower():
145
+ # Add assessment task
146
+ assessment_task = self.create_task(
147
+ "mental_health_assessment",
148
+ f"Conduct mental health assessment based on: {message}",
149
+ self.assessment_agent
150
+ )
151
+ self.crew.tasks = [assessment_task]
152
+ response = self.crew.kickoff()
153
+
154
+ elif "mindfulness" in result.lower():
155
+ # Add mindfulness task
156
+ mindfulness_task = self.create_task(
157
+ "mindfulness_session",
158
+ f"Guide mindfulness exercise based on: {message}",
159
+ self.mindfulness_agent
160
+ )
161
+ self.crew.tasks = [mindfulness_task]
162
+ response = self.crew.kickoff()
163
+
164
+ else:
165
+ # Continue therapeutic conversation
166
+ conversation_task = self.create_task(
167
+ "therapeutic_conversation",
168
+ f"Continue therapeutic conversation: {message}",
169
+ self.conversation_agent
170
+ )
171
+ self.crew.tasks = [conversation_task]
172
+ response = self.crew.kickoff()
173
+
174
+ return {
175
+ "message": response,
176
+ "agent_type": self.crew.tasks[-1].agent.name,
177
+ "task_type": self.crew.tasks[-1].task_type
178
+ }
179
+
180
+ except Exception as e:
181
+ self.logger.error(f"Error processing message: {str(e)}")
182
+ return {
183
+ "message": "I apologize, but I encountered an error. Please try again.",
184
+ "agent_type": "error",
185
+ "task_type": "error_handling"
186
+ }
187
+
188
+ def get_agent_status(self) -> Dict:
189
+ """Get status of all agents"""
190
  return {
191
+ "conversation": self.conversation_agent.get_status(),
192
+ "assessment": self.assessment_agent.get_status(),
193
+ "mindfulness": self.mindfulness_agent.get_status(),
194
+ "crisis": self.crisis_agent.get_status()
195
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
interface/app.py CHANGED
@@ -5,10 +5,7 @@ import logging
5
  from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
6
  from utils.log_manager import LogManager
7
  from utils.analytics_logger import AnalyticsLogger
8
- from agents.conversation_agent import ConversationAgent
9
- from agents.assessment_agent import AssessmentAgent
10
- from agents.mindfulness_agent import MindfulnessAgent
11
- from agents.crisis_agent import CrisisAgent
12
 
13
  # Force CPU-only mode
14
  torch.cuda.is_available = lambda: False
@@ -29,8 +26,8 @@ class WellnessInterface:
29
  # Initialize models
30
  self.initialize_models()
31
 
32
- # Initialize agents
33
- self.initialize_agents()
34
 
35
  # Initialize interface
36
  self.setup_interface()
@@ -61,28 +58,16 @@ class WellnessInterface:
61
  self.logger.error(f"Error initializing models: {str(e)}")
62
  raise
63
 
64
- def initialize_agents(self):
65
- """Initialize AI agents"""
66
- self.logger.info("Initializing AI agents")
67
  try:
68
- # Initialize all agents
69
- self.conversation_agent = ConversationAgent(
70
  model_config=self.config["MODEL_CONFIGS"]
71
  )
72
- self.assessment_agent = AssessmentAgent(
73
- model_config=self.config["MODEL_CONFIGS"]
74
- )
75
- self.mindfulness_agent = MindfulnessAgent(
76
- model_config=self.config["MODEL_CONFIGS"]
77
- )
78
- self.crisis_agent = CrisisAgent(
79
- model_config=self.config["MODEL_CONFIGS"]
80
- )
81
-
82
- self.logger.info("AI agents initialized successfully")
83
-
84
  except Exception as e:
85
- self.logger.error(f"Error initializing agents: {str(e)}")
86
  raise
87
 
88
  def setup_interface(self):
@@ -232,27 +217,30 @@ class WellnessInterface:
232
  }}
233
  )
234
 
235
- # Analyze emotion if text is present
236
- emotion = None
237
- if text:
238
- emotion_result = self.emotion_model(text)
239
- emotion = emotion_result[0] if emotion_result else None
240
- self.logger.info(f"Detected emotion: {emotion}")
 
241
 
242
- # Route to appropriate agent based on content and emotion
243
- if emotion and emotion.get("label") in ["anxiety", "fear", "panic"]:
244
- response = self.crisis_agent.process_message(text)
245
- elif "meditate" in text.lower() or "mindfulness" in text.lower():
246
- response = self.mindfulness_agent.process_message(text)
247
- elif "assess" in text.lower() or "check" in text.lower():
248
- response = self.assessment_agent.process_message(text)
249
- else:
250
- response = self.conversation_agent.process_message(text)
251
 
252
  # Add to chat history using message format
253
  history = history or []
254
  history.append({"role": "user", "content": text if text else "Sent media"})
255
- history.append({"role": "assistant", "content": response["message"]})
 
 
 
 
 
 
 
256
 
257
  return history, "" # Return empty string to clear text input
258
 
@@ -274,20 +262,19 @@ class WellnessInterface:
274
  """Provide emergency help information"""
275
  self.logger.info("Emergency help requested")
276
 
 
 
 
 
 
 
277
  return [{
278
  "role": "assistant",
279
- "content": """🚨 EMERGENCY RESOURCES 🚨
280
-
281
- If you're experiencing a mental health emergency:
282
-
283
- πŸ“ž Emergency Services: 911 (US)
284
- πŸ†˜ National Crisis Hotline: 988
285
- πŸ’­ Crisis Text Line: Text HOME to 741741
286
-
287
- These services are available 24/7 and are staffed by trained professionals.
288
- Your life matters, and help is available immediately.
289
-
290
- Please don't hesitate to reach out - caring people are ready to help."""
291
  }]
292
 
293
  def launch(self, **kwargs):
 
5
  from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
6
  from utils.log_manager import LogManager
7
  from utils.analytics_logger import AnalyticsLogger
8
+ from agents.orchestrator import WellnessOrchestrator
 
 
 
9
 
10
  # Force CPU-only mode
11
  torch.cuda.is_available = lambda: False
 
26
  # Initialize models
27
  self.initialize_models()
28
 
29
+ # Initialize orchestrator
30
+ self.initialize_orchestrator()
31
 
32
  # Initialize interface
33
  self.setup_interface()
 
58
  self.logger.error(f"Error initializing models: {str(e)}")
59
  raise
60
 
61
+ def initialize_orchestrator(self):
62
+ """Initialize CrewAI orchestrator"""
63
+ self.logger.info("Initializing CrewAI orchestrator")
64
  try:
65
+ self.orchestrator = WellnessOrchestrator(
 
66
  model_config=self.config["MODEL_CONFIGS"]
67
  )
68
+ self.logger.info("Orchestrator initialized successfully")
 
 
 
 
 
 
 
 
 
 
 
69
  except Exception as e:
70
+ self.logger.error(f"Error initializing orchestrator: {str(e)}")
71
  raise
72
 
73
  def setup_interface(self):
 
217
  }}
218
  )
219
 
220
+ # Process through orchestrator
221
+ context = {
222
+ "history": history,
223
+ "emotion": self.emotion_model(text)[0] if text else None,
224
+ "has_audio": bool(audio),
225
+ "has_image": bool(image)
226
+ }
227
 
228
+ response = self.orchestrator.process_message(
229
+ message=text if text else "Sent media",
230
+ context=context
231
+ )
 
 
 
 
 
232
 
233
  # Add to chat history using message format
234
  history = history or []
235
  history.append({"role": "user", "content": text if text else "Sent media"})
236
+ history.append({
237
+ "role": "assistant",
238
+ "content": response["message"],
239
+ "metadata": {
240
+ "agent": response["agent_type"],
241
+ "task": response["task_type"]
242
+ }
243
+ })
244
 
245
  return history, "" # Return empty string to clear text input
246
 
 
262
  """Provide emergency help information"""
263
  self.logger.info("Emergency help requested")
264
 
265
+ # Use crisis agent through orchestrator
266
+ response = self.orchestrator.process_message(
267
+ message="EMERGENCY_HELP_REQUESTED",
268
+ context={"is_emergency": True}
269
+ )
270
+
271
  return [{
272
  "role": "assistant",
273
+ "content": response["message"],
274
+ "metadata": {
275
+ "agent": response["agent_type"],
276
+ "task": response["task_type"]
277
+ }
 
 
 
 
 
 
 
278
  }]
279
 
280
  def launch(self, **kwargs):