Skip to main content

Overview

The AI Mental Wellbeing Agent Team is a supportive mental health assessment and guidance system powered by AG2 (formerly AutoGen)‘s AI Agent framework. This application provides personalized mental health support through the coordination of specialized AI agents, each focusing on different aspects of mental health care based on user inputs such as emotional state, stress levels, sleep patterns, and current symptoms. Built using AG2’s swarm feature with the initiate_swarm_chat() method.
Important NoticeThis application is a supportive tool and does not replace professional mental health care. If you’re experiencing thoughts of self-harm or severe crisis:
  • Call National Crisis Hotline: 988
  • Call Emergency Services: 911
  • Seek immediate professional help

Architecture

Swarm Orchestration Pattern

The Mental Wellbeing Team uses AG2’s swarm pattern for coordinated therapeutic support:

Agent Roles

Assessment Agent

Role: Psychological assessment specialistApproach:
  • Clinical precision with empathy
  • Safe space creation
  • Pattern identification
  • Risk assessment
  • Validation without minimizing

Action Agent

Role: Crisis intervention and resourcesApproach:
  • Immediate coping strategies
  • Intervention prioritization
  • Resource connections
  • Daily wellness plans
  • Empowerment techniques

Follow-up Agent

Role: Long-term recovery planningApproach:
  • Sustainable strategies
  • Progress monitoring
  • Relapse prevention
  • Maintenance schedules
  • Self-compassion focus

Implementation

from autogen import (
    SwarmAgent,
    SwarmResult,
    initiate_swarm_chat,
    OpenAIWrapper,
    AFTER_WORK,
    UPDATE_SYSTEM_MESSAGE
)
import os

# Disable Docker requirement
os.environ["AUTOGEN_USE_DOCKER"] = "0"

# LLM Configuration
llm_config = {
    "config_list": [{
        "model": "gpt-4o",
        "api_key": api_key
    }]
}

# Context variables for agent coordination
context_variables = {
    "assessment": None,
    "action": None,
    "followup": None,
}

# Assessment Agent
assessment_agent = SwarmAgent(
    "assessment_agent",
    llm_config=llm_config,
    functions=update_assessment_overview,
    update_agent_state_before_reply=[state_update]
)

# Action Agent
action_agent = SwarmAgent(
    "action_agent",
    llm_config=llm_config,
    functions=update_action_overview,
    update_agent_state_before_reply=[state_update]
)

# Follow-up Agent
followup_agent = SwarmAgent(
    "followup_agent",
    llm_config=llm_config,
    functions=update_followup_overview,
    update_agent_state_before_reply=[state_update]
)

# Register handoffs (circular flow)
assessment_agent.register_hand_off(AFTER_WORK(action_agent))
action_agent.register_hand_off(AFTER_WORK(followup_agent))
followup_agent.register_hand_off(AFTER_WORK(assessment_agent))

Agent Coordination Flow

1

Assessment Phase

Assessment Agent analyzes the user’s situation:
  • Reviews emotional state and symptoms
  • Identifies patterns and risk factors
  • Validates experiences with empathy
  • Provides 2-3 sentence summary
Hands off to Action Agent with context
2

Action Phase

Action Agent creates immediate support:
  • Develops evidence-based coping strategies
  • Connects with appropriate resources
  • Creates daily wellness plan
  • Suggests support communities
  • Provides 2-3 sentence summary
Hands off to Follow-up Agent with context
3

Follow-up Phase

Follow-up Agent designs long-term strategy:
  • Creates personalized support plan
  • Establishes progress monitoring
  • Develops relapse prevention strategies
  • Builds sustainable self-care routine
  • Provides 2-3 sentence summary
Completes cycle with full context
4

Detailed Generation

Each agent generates comprehensive report:
  • Assessment: Full psychological analysis
  • Action: Detailed coping strategies and resources
  • Follow-up: Complete long-term recovery plan

Key Features

Clinical Precision:
  • Emotional state analysis
  • Pattern identification in thoughts and behaviors
  • Risk assessment using validated approaches
  • Relationship dynamics evaluation
Empathetic Approach:
  • Creates safe space for sharing
  • Acknowledges courage in seeking help
  • Validates experiences without judgment
  • Uses accessible, non-clinical language
Evidence-Based Strategies:
  • Tailored coping techniques
  • Self-regulation exercises
  • Crisis management approaches
  • Grounding and mindfulness practices
Practical Resources:
  • Mental health services connections
  • Support community recommendations
  • Concrete daily wellness plans
  • Specific times and activities
  • Options for varying energy levels
Personalized Strategy:
  • Milestone markers for progress
  • Monitoring systems matched to preferences
  • Relapse prevention based on triggers
  • Support network mapping
Sustainable Habits:
  • Graduated self-care routines
  • Integration with lifestyle and values
  • Progress over perfection emphasis
  • Self-compassion techniques
  • Regular check-in mechanisms
User-Friendly Presentation:
  • Real-time summaries in sidebar
  • Detailed expandable sections
  • Clear action steps
  • Organized by support phase
  • Easy to save and reference

Input Parameters

# Free-form emotional description
mental_state = st.text_area(
    "How have you been feeling recently?",
    placeholder="Describe your emotional state, "
               "thoughts, or concerns..."
)

# Captures:
# - Current feelings and moods
# - Recurring thoughts
# - Concerns and worries
# - Recent experiences
# - Changes in emotional state

Installation

1

Clone Repository

git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git
cd advanced_ai_agents/multi_agent_apps/ai_mental_wellbeing_agent
2

Install Dependencies

pip install -r requirements.txt
Required packages:
  • autogen-agentchat
  • autogen-ext
  • pyautogen
  • streamlit
3

Create Environment File

echo "AUTOGEN_USE_DOCKER=0" > .env
This disables Docker requirement for code execution
4

Set OpenAI API Key

You’ll input your OpenAI API key in the Streamlit sidebarGet your key from platform.openai.com
5

Run Application

streamlit run ai_mental_wellbeing_agent.py

Usage Example

User Input:
  • Emotional State: “Feeling overwhelmed, anxious about work, trouble sleeping”
  • Sleep: 4-5 hours per night
  • Stress Level: 8/10
  • Support System: Family, Friends
  • Recent Changes: “New job, moved to new city”
  • Symptoms: Anxiety, Insomnia, Difficulty Concentrating
Assessment Agent Output:Thank you for having the courage to reach out. What you’re experiencing is a very real response to significant life transitions. Moving to a new city and starting a new job are both major stressors, and when combined, they can feel overwhelming.What I’m Noticing:
  • Your body is showing clear signs of stress (poor sleep, difficulty concentrating)
  • Anxiety levels are significantly elevated (8/10)
  • You have important support systems (family, friends) which is a strength
  • Sleep deprivation is likely amplifying other symptoms
Risk Assessment: Moderate stress response to life transitions. No immediate crisis indicators, but intervention needed to prevent escalation.Action Agent Output:Let’s create an immediate action plan that’s realistic for your current energy level:Tonight (Minimal Effort):
  1. Set phone alarm for same bedtime (10:30 PM)
  2. Dim lights 1 hour before bed
  3. Try 4-7-8 breathing: Breathe in for 4, hold for 7, out for 8 (4 times)
This Week (Moderate Effort):
  1. Schedule one 20-minute walk daily (morning preferred)
  2. Text one friend/family member each day
  3. Keep a “worry dump” journal before bed
Resources:
  • BetterHelp or Talkspace: Online therapy ($60-90/week)
  • Headspace app: Guided meditation free trial
  • City-specific meetups: Search “[Your City] newcomers group”
Crisis Resources:
  • National Crisis Hotline: 988 (24/7, free)
  • Crisis Text Line: Text HOME to 741741
Follow-up Agent Output:Let’s build a sustainable recovery plan:Week 1-2: Foundation
  • Primary goal: Sleep regulation
  • Track: Sleep hours, anxiety level (1-10 scale)
  • Milestone: 6+ hours sleep for 3 consecutive nights
Week 3-4: Building Routine
  • Add: Weekly social activity
  • Continue: Sleep hygiene, daily walks
  • Milestone: Stress level below 6/10
Week 5-8: Connection
  • Join: One local interest group
  • Establish: Weekly friend check-in
  • Milestone: Feeling “somewhat settled” in new city
Relapse Prevention: Your triggers appear to be: uncertainty, social isolation, work pressureWhen you notice these, immediately:
  1. Use 4-7-8 breathing (3 rounds)
  2. Text your support system
  3. Take a 10-minute walk
Monthly Check-ins:
  • 1st of month: Review sleep tracker
  • 15th of month: Assess stress level
  • End of month: Celebrate one accomplishment

Technical Architecture

Two-Phase Execution

def update_system_message_func(agent: SwarmAgent, messages) -> str:
    system_prompt = system_messages[agent.name]
    current_gen = agent.name.split("_")[0]
    
    # Phase 1: Generate summary
    if agent._context_variables.get(current_gen) is None:
        system_prompt += f"""Call the update function to provide 
                            a 2-3 sentence summary of your {current_gen} 
                            based on the context."""
        agent.llm_config['tool_choice'] = {
            "type": "function",
            "function": {"name": f"update_{current_gen}_overview"}
        }
    # Phase 2: Generate detailed response
    else:
        agent.llm_config["tools"] = None
        agent.llm_config['tool_choice'] = None
        system_prompt += f"""Write the {current_gen} part of the report.
                            Start with: '## {current_gen.capitalize()} Design'"""
        # Clear message history for efficiency
        k = list(agent._oai_messages.keys())[-1]
        agent._oai_messages[k] = agent._oai_messages[k][:1]
    
    # Add context from other agents
    system_prompt += "\n\nContext from other agents:"
    for k, v in agent._context_variables.items():
        if v is not None:
            system_prompt += f"\n{k.capitalize()} Summary:\n{v}"
    
    agent.client = OpenAIWrapper(**agent.llm_config)
    return system_prompt

Context Accumulation

# Action Agent sees Assessment Agent's summary
context_variables = {
    "assessment": "User experiencing moderate stress from life transitions...",
    "action": None,  # Not yet generated
    "followup": None
}

# Follow-up Agent sees both previous summaries
context_variables = {
    "assessment": "User experiencing moderate stress...",
    "action": "Immediate sleep hygiene and breathing exercises...",
    "followup": None  # Not yet generated
}

Best Practices

Honest Input

  • Be truthful about your feelings
  • Share relevant context
  • Don’t minimize symptoms
  • Include physical symptoms
  • Mention support system honestly

Action Follow-Through

  • Start with smallest actions
  • Build gradually
  • Track progress
  • Celebrate small wins
  • Be patient with setbacks

Professional Help

  • Consider therapy if symptoms persist
  • Use crisis resources when needed
  • Don’t rely solely on AI support
  • Verify advice with professionals
  • Seek immediate help for crisis

Privacy Awareness

  • Review OpenAI data policies
  • Don’t share identifying details
  • Use general descriptions
  • Clear session data after use
  • Consider privacy implications
When to Seek Immediate Help:Contact emergency services or crisis hotlines immediately if you experience:
  • Thoughts of self-harm or suicide
  • Plans to harm yourself or others
  • Severe panic attacks
  • Complete inability to function
  • Psychotic symptoms
  • Substance abuse crisis
Crisis Resources:
  • National Crisis Hotline: 988
  • Crisis Text Line: Text HOME to 741741
  • Emergency Services: 911

Advanced Features

Adaptive Response Depth

# Agent adjusts detail based on severity
if stress_level >= 8 or "crisis" in symptoms:
    # More detailed immediate actions
    # Prioritize crisis resources
    # Shorter-term focus
else:
    # Balanced approach
    # Mix of immediate and long-term
    # Broader strategies

Personalized Strategies

# Tailored to user context
if "None" in support_system:
    # Focus on building connections
    # Online resources prioritized
if sleep_hours < 5:
    # Sleep hygiene emphasized
    # Energy-conscious strategies
if recent_changes:
    # Transition-focused support
    # Adjustment strategies

Performance Considerations

  • Summary phase: ~30-40s per agent
  • Detailed phase: ~60-90s per agent
  • Total: ~6-8 minutes for complete plan
  • Model: GPT-4o (higher quality for sensitive content)

Ethical Considerations

This tool provides supportive guidance but:
  • Cannot diagnose mental health conditions
  • Cannot provide clinical treatment
  • Cannot replace licensed professionals
  • Cannot handle emergency situations
  • Should complement, not replace, professional care
  • Conversations processed by OpenAI
  • Review OpenAI’s data policies
  • No local storage of sensitive data
  • Session state cleared on refresh
  • Consider anonymizing personal details
  • AI cannot assess suicide risk reliably
  • Always provides crisis hotline info
  • Encourages professional help
  • Clear about limitations
  • Emphasizes immediate help when needed
  • Trained on diverse data
  • May not capture cultural nuances
  • Mental health stigma varies by culture
  • Consider cultural context
  • Seek culturally competent professionals

Game Design Team

Another swarm orchestration example

Health & Fitness Agent

Related wellness application

Deep Research Agent

Research on mental health topics

Build docs developers (and LLMs) love