From 431bb6fc487d62b494bd86e3deac6e6787d1caad Mon Sep 17 00:00:00 2001 From: Madhu Date: Wed, 19 Feb 2025 21:28:02 +0530 Subject: [PATCH 1/9] NEW PROJ: autogen agent with magneticOne --- ai_agent_tutorials/ai_magenticag2_agent/main.py | 16 ++++++++++++++++ .../ai_magenticag2_agent/requirements.txt | 3 +++ ai_agent_tutorials/ai_magenticag2_agent/test.py | 0 3 files changed, 19 insertions(+) create mode 100644 ai_agent_tutorials/ai_magenticag2_agent/main.py create mode 100644 ai_agent_tutorials/ai_magenticag2_agent/requirements.txt create mode 100644 ai_agent_tutorials/ai_magenticag2_agent/test.py diff --git a/ai_agent_tutorials/ai_magenticag2_agent/main.py b/ai_agent_tutorials/ai_magenticag2_agent/main.py new file mode 100644 index 0000000..e477d4b --- /dev/null +++ b/ai_agent_tutorials/ai_magenticag2_agent/main.py @@ -0,0 +1,16 @@ +import asyncio +from autogen_ext.models.openai import OpenAIChatCompletionClient +from autogen_ext.teams.magentic_one import MagenticOne +from autogen_agentchat.ui import Console + + +async def example_usage(): + client = OpenAIChatCompletionClient(model="gpt-4o", api_key="") + m1 = MagenticOne(client=client) + task = "Write a Python script to fetch data from an API." + result = await Console(m1.run_stream(task=task)) + print(result) + + +if __name__ == "__main__": + asyncio.run(example_usage()) \ No newline at end of file diff --git a/ai_agent_tutorials/ai_magenticag2_agent/requirements.txt b/ai_agent_tutorials/ai_magenticag2_agent/requirements.txt new file mode 100644 index 0000000..1d07d36 --- /dev/null +++ b/ai_agent_tutorials/ai_magenticag2_agent/requirements.txt @@ -0,0 +1,3 @@ +autogen-agentchat +autogen-ext +playwright install --with-deps chromium \ No newline at end of file diff --git a/ai_agent_tutorials/ai_magenticag2_agent/test.py b/ai_agent_tutorials/ai_magenticag2_agent/test.py new file mode 100644 index 0000000..e69de29 From 1062536f4ac5bb1ea0b365c705a577e069cf4a2a Mon Sep 17 00:00:00 2001 From: Madhu Date: Thu, 20 Feb 2025 05:43:39 +0530 Subject: [PATCH 2/9] climate aqi script with swarms ag2 --- .../ai_magenticag2_agent/main.py | 272 +++++++++++++++++- .../ai_magenticag2_agent/requirements.txt | 7 +- .../ai_magenticag2_agent/test.py | 0 3 files changed, 267 insertions(+), 12 deletions(-) delete mode 100644 ai_agent_tutorials/ai_magenticag2_agent/test.py diff --git a/ai_agent_tutorials/ai_magenticag2_agent/main.py b/ai_agent_tutorials/ai_magenticag2_agent/main.py index e477d4b..923727b 100644 --- a/ai_agent_tutorials/ai_magenticag2_agent/main.py +++ b/ai_agent_tutorials/ai_magenticag2_agent/main.py @@ -1,16 +1,266 @@ import asyncio -from autogen_ext.models.openai import OpenAIChatCompletionClient -from autogen_ext.teams.magentic_one import MagenticOne -from autogen_agentchat.ui import Console +import streamlit as st +from autogen import ( + SwarmAgent, + SwarmResult, + initiate_swarm_chat, + OpenAIWrapper, + AFTER_WORK, + UPDATE_SYSTEM_MESSAGE +) +import agentops +import os +from contextlib import contextmanager +# Add this at the top of the file, before any other code +os.environ["AUTOGEN_USE_DOCKER"] = "0" -async def example_usage(): - client = OpenAIChatCompletionClient(model="gpt-4o", api_key="") - m1 = MagenticOne(client=client) - task = "Write a Python script to fetch data from an API." - result = await Console(m1.run_stream(task=task)) - print(result) +# Initialize session state +if 'output' not in st.session_state: + st.session_state.output = { + 'climate': '', + 'urban': '', + 'economic': '', + 'community': '' + } +# Sidebar for API key input +st.sidebar.title("OpenAI API Key") +api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password") -if __name__ == "__main__": - asyncio.run(example_usage()) \ No newline at end of file +st.sidebar.title("AgentOps API Key") +agentops_key = st.sidebar.text_input("Enter your AgentOps API Key", type="password", value="4e725ba8-b57e-49b5-809a-4eeef18d92ed") + +# Main app UI +st.title("🌍 Climate Impact Response Planner") + +# Add agent information below title +st.info(""" +**Meet Your Climate Planning Team:** + +🌡️ **Climate Analysis Agent** - Analyzes climate data and risk projections +🏙️ **Urban Planning Agent** - Develops infrastructure and zoning strategies +💰 **Economic Impact Agent** - Assesses financial implications +👥 **Community Engagement Agent** - Plans public involvement and behavior change +""") + +# User input +st.subheader("City Information") +city_name = st.text_input("Enter City Name", "") +city_description = st.text_area("Brief description of the city (population, geography, main industries, etc.)", "") + +@contextmanager +def agentops_session(api_key: str, tags: list): + """Context manager for AgentOps sessions""" + try: + # Initialize new session + agentops.init( + api_key=api_key, + tags=tags, + instrument_llm_calls=True, + auto_start_session=True + ) + yield + finally: + # Always ensure session is ended + try: + agentops.end_session("Success") + except Exception as e: + print(f"Failed to end AgentOps session: {e}") + +# Button to start the agent collaboration +if st.button("Generate Climate Response Plan"): + if not api_key: + st.error("Please enter your OpenAI API key.") + else: + with st.spinner('🤖 AI Agents are collaborating on your climate response plan...'): + with agentops_session(api_key=agentops_key, tags=["aqi_agent"]): + try: + task = f""" + Create a comprehensive climate impact response plan for: + City: {city_name} + Description: {city_description} + + Consider all aspects of climate adaptation including environmental, infrastructural, economic, and social factors. + """ + + # Then modify the agent configurations + llm_config = { + "config_list": [{"model": "gpt-4o", "api_key": api_key}] + } + + # Context management for agent communication + context_variables = { + "climate": None, + "urban": None, + "economic": None, + "community": None, + } + + # Update functions for each agent + def update_climate_overview(climate_summary: str, context_variables: dict) -> SwarmResult: + """Keep the summary as short as possible.""" + context_variables["climate"] = climate_summary + st.sidebar.success('Climate Analysis: ' + climate_summary) + return SwarmResult(agent="urban_agent", context_variables=context_variables) + + def update_urban_overview(urban_summary: str, context_variables: dict) -> SwarmResult: + """Keep the summary as short as possible.""" + context_variables["urban"] = urban_summary + st.sidebar.success('Urban Planning: ' + urban_summary) + return SwarmResult(agent="economic_agent", context_variables=context_variables) + + def update_economic_overview(economic_summary: str, context_variables: dict) -> SwarmResult: + """Keep the summary as short as possible.""" + context_variables["economic"] = economic_summary + st.sidebar.success('Economic Impact: ' + economic_summary) + return SwarmResult(agent="community_agent", context_variables=context_variables) + + def update_community_overview(community_summary: str, context_variables: dict) -> SwarmResult: + """Keep the summary as short as possible.""" + context_variables["community"] = community_summary + st.sidebar.success('Community Engagement: ' + community_summary) + return SwarmResult(agent="climate_agent", context_variables=context_variables) + + system_messages = { + "climate_agent": """ + You are an expert climate scientist and risk analyst. Your task is to: + 1. Analyze historical climate data and future projections for the specified city + 2. Identify key climate risks (flooding, heat waves, storms, etc.) + 3. Assess vulnerability of different city areas and systems + 4. Prioritize climate threats based on likelihood and impact + 5. Recommend key areas for climate resilience focus + 6. Provide specific climate scenarios the city should prepare for + """, + + "urban_agent": """ + You are an experienced urban planner specializing in climate adaptation. Your task is to: + 1. Design infrastructure modifications for climate resilience + 2. Develop zoning recommendations for risk reduction + 3. Plan green infrastructure and nature-based solutions + 4. Identify critical infrastructure vulnerabilities + 5. Create phased implementation strategies + 6. Consider both immediate and long-term adaptation needs + """, + + "economic_agent": """ + You are a climate economics and finance specialist. Your task is to: + 1. Calculate potential economic impacts of climate risks + 2. Identify funding sources for adaptation projects + 3. Analyze cost-benefit ratios of proposed solutions + 4. Assess impacts on local industries and businesses + 5. Develop economic incentives for climate adaptation + 6. Create budget allocation recommendations + """, + + "community_agent": """ + You are a community engagement and behavior change expert. Your task is to: + 1. Design public communication strategies + 2. Plan community involvement in adaptation efforts + 3. Develop education and awareness programs + 4. Create behavior change initiatives + 5. Plan vulnerable population support systems + 6. Design feedback and monitoring systems + """ + } + + def update_system_message_func(agent: SwarmAgent, messages) -> str: + """""" + system_prompt = system_messages[agent.name] + + current_gen = agent.name.split("_")[0] + if agent._context_variables.get(current_gen) is None: + system_prompt += f"Call the update function provided to first provide a 2-3 sentence summary of your ideas on {current_gen.upper()} based on the context provided." + agent.llm_config['tool_choice'] = {"type": "function", "function": {"name": f"update_{current_gen}_overview"}} + agent.client = OpenAIWrapper(**agent.llm_config) + else: + # remove the tools to avoid the agent from using it and reduce cost + agent.llm_config["tools"] = None + agent.llm_config['tool_choice'] = None + agent.client = OpenAIWrapper(**agent.llm_config) + # the agent has given a summary, now it should generate a detailed response + system_prompt += f"\n\nYour task\nYou task is write the {current_gen} part of the report. Do not include any other parts. Do not use XML tags.\nStart your reponse with: '## {current_gen.capitalize()} Design'." + + # Remove all messages except the first one with less cost + k = list(agent._oai_messages.keys())[-1] + agent._oai_messages[k] = agent._oai_messages[k][:1] + + system_prompt += f"\n\n\nBelow are some context for you to refer to:" + # Add context variables to the prompt + for k, v in agent._context_variables.items(): + if v is not None: + system_prompt += f"\n{k.capitalize()} Summary:\n{v}" + + return system_prompt + + state_update = UPDATE_SYSTEM_MESSAGE(update_system_message_func) + + # Define agents with proper code execution config + climate_agent = SwarmAgent( + "climate_agent", + llm_config=llm_config, + functions=update_climate_overview, + update_agent_state_before_reply=[state_update] + ) + + urban_agent = SwarmAgent( + "urban_agent", + llm_config=llm_config, + functions=update_urban_overview, + update_agent_state_before_reply=[state_update] + ) + + economic_agent = SwarmAgent( + "economic_agent", + llm_config=llm_config, + functions=update_economic_overview, + update_agent_state_before_reply=[state_update] + ) + + community_agent = SwarmAgent( + name="community_agent", + llm_config=llm_config, + functions=update_community_overview, + update_agent_state_before_reply=[state_update] + ) + + climate_agent.register_hand_off(AFTER_WORK(urban_agent)) + urban_agent.register_hand_off(AFTER_WORK(economic_agent)) + economic_agent.register_hand_off(AFTER_WORK(community_agent)) + community_agent.register_hand_off(AFTER_WORK(climate_agent)) + + result, _, _ = initiate_swarm_chat( + initial_agent=climate_agent, + agents=[climate_agent, urban_agent, economic_agent, community_agent], + user_agent=None, + messages=task, + max_rounds=13, + ) + + # Update session state with the individual responses + st.session_state.output = { + 'climate': result.chat_history[-4]['content'], + 'urban': result.chat_history[-3]['content'], + 'economic': result.chat_history[-2]['content'], + 'community': result.chat_history[-1]['content'] + } + + # Display success message after completion + st.success('✨ Climate response plan generated successfully!') + + # Display the individual outputs in expanders + with st.expander("Climate Analysis"): + st.markdown(st.session_state.output['climate']) + + with st.expander("Urban Planning"): + st.markdown(st.session_state.output['urban']) + + with st.expander("Economic Impact"): + st.markdown(st.session_state.output['economic']) + + with st.expander("Community Engagement"): + st.markdown(st.session_state.output['community']) + + except Exception as e: + st.error(f"An error occurred: {str(e)}") + raise # Re-raise to trigger session end with error diff --git a/ai_agent_tutorials/ai_magenticag2_agent/requirements.txt b/ai_agent_tutorials/ai_magenticag2_agent/requirements.txt index 1d07d36..451a368 100644 --- a/ai_agent_tutorials/ai_magenticag2_agent/requirements.txt +++ b/ai_agent_tutorials/ai_magenticag2_agent/requirements.txt @@ -1,3 +1,8 @@ autogen-agentchat autogen-ext -playwright install --with-deps chromium \ No newline at end of file +playwright install --with-deps chromium + +pyautogen +agentops + +streamlit diff --git a/ai_agent_tutorials/ai_magenticag2_agent/test.py b/ai_agent_tutorials/ai_magenticag2_agent/test.py deleted file mode 100644 index e69de29..0000000 From e07ab78a3502344088365eca57b173dfd10e1bf2 Mon Sep 17 00:00:00 2001 From: Madhu Date: Thu, 20 Feb 2025 06:25:09 +0530 Subject: [PATCH 3/9] changed it to mental health crisis agent --- .../ai_magenticag2_agent/main.py | 281 ++++++++++-------- 1 file changed, 165 insertions(+), 116 deletions(-) diff --git a/ai_agent_tutorials/ai_magenticag2_agent/main.py b/ai_agent_tutorials/ai_magenticag2_agent/main.py index 923727b..ef765ef 100644 --- a/ai_agent_tutorials/ai_magenticag2_agent/main.py +++ b/ai_agent_tutorials/ai_magenticag2_agent/main.py @@ -18,10 +18,10 @@ os.environ["AUTOGEN_USE_DOCKER"] = "0" # Initialize session state if 'output' not in st.session_state: st.session_state.output = { - 'climate': '', - 'urban': '', - 'economic': '', - 'community': '' + 'psychology': '', + 'resources': '', + 'action': '', + 'followup': '' } # Sidebar for API key input @@ -32,28 +32,63 @@ st.sidebar.title("AgentOps API Key") agentops_key = st.sidebar.text_input("Enter your AgentOps API Key", type="password", value="4e725ba8-b57e-49b5-809a-4eeef18d92ed") # Main app UI -st.title("🌍 Climate Impact Response Planner") +st.title("🧠 Mental Health Crisis Navigator") # Add agent information below title st.info(""" -**Meet Your Climate Planning Team:** +**Meet Your Mental Health Support Team:** -🌡️ **Climate Analysis Agent** - Analyzes climate data and risk projections -🏙️ **Urban Planning Agent** - Develops infrastructure and zoning strategies -💰 **Economic Impact Agent** - Assesses financial implications -👥 **Community Engagement Agent** - Plans public involvement and behavior change +🧠 **Psychology Agent** - Analyzes emotional state and psychological needs +📋 **Resource Agent** - Identifies relevant support services and professionals +🎯 **Action Agent** - Creates immediate step-by-step action plans +🔄 **Follow-up Agent** - Designs ongoing support and prevention strategies """) -# User input -st.subheader("City Information") -city_name = st.text_input("Enter City Name", "") -city_description = st.text_area("Brief description of the city (population, geography, main industries, etc.)", "") +# User inputs +st.subheader("Personal Information") +col1, col2 = st.columns(2) + +with col1: + mental_state = st.text_area("How have you been feeling recently?", + placeholder="Describe your emotional state, thoughts, or concerns...") + sleep_pattern = st.select_slider( + "Sleep Pattern (hours per night)", + options=[f"{i}" for i in range(0, 13)], + value="7" + ) + +with col2: + stress_level = st.slider("Current Stress Level (1-10)", 1, 10, 5) + support_system = st.multiselect( + "Current Support System", + ["Family", "Friends", "Therapist", "Support Groups", "None"] + ) + +# Additional context +recent_changes = st.text_area( + "Any significant life changes or events recently?", + placeholder="Job changes, relationships, losses, etc..." +) + +current_symptoms = st.multiselect( + "Current Symptoms", + ["Anxiety", "Depression", "Insomnia", "Fatigue", "Loss of Interest", + "Difficulty Concentrating", "Changes in Appetite", "Social Withdrawal", + "Mood Swings", "Physical Discomfort"] +) + +# Emergency notice +st.warning(""" +⚠️ **Important**: If you're having thoughts of self-harm or experiencing a severe crisis, +please immediately contact emergency services or crisis hotlines: +- National Crisis Hotline: 988 +- Emergency: 911 +""") @contextmanager def agentops_session(api_key: str, tags: list): """Context manager for AgentOps sessions""" try: - # Initialize new session agentops.init( api_key=api_key, tags=tags, @@ -62,28 +97,84 @@ def agentops_session(api_key: str, tags: list): ) yield finally: - # Always ensure session is ended try: agentops.end_session("Success") except Exception as e: print(f"Failed to end AgentOps session: {e}") # Button to start the agent collaboration -if st.button("Generate Climate Response Plan"): +if st.button("Get Support Plan"): if not api_key: st.error("Please enter your OpenAI API key.") else: - with st.spinner('🤖 AI Agents are collaborating on your climate response plan...'): - with agentops_session(api_key=agentops_key, tags=["aqi_agent"]): + with st.spinner('🤖 AI Agents are analyzing your situation...'): + with agentops_session(api_key=agentops_key, tags=["mental_health_navigator"]): try: task = f""" - Create a comprehensive climate impact response plan for: - City: {city_name} - Description: {city_description} + Create a comprehensive mental health support plan based on: - Consider all aspects of climate adaptation including environmental, infrastructural, economic, and social factors. + Emotional State: {mental_state} + Sleep: {sleep_pattern} hours per night + Stress Level: {stress_level}/10 + Support System: {', '.join(support_system) if support_system else 'None reported'} + Recent Changes: {recent_changes} + Current Symptoms: {', '.join(current_symptoms) if current_symptoms else 'None reported'} """ + system_messages = { + "psychology_agent": """ + You are an experienced mental health professional speaking directly to the user. Your task is to: + 1. Analyze their emotional state and psychological symptoms with empathy + 2. Help them understand potential mental health concerns + 3. Assess their risk levels and urgency + 4. Suggest therapeutic approaches that would work for them + 5. Help them understand how their life changes and stressors are affecting them + 6. Provide supportive psychological insights + + Always use "you" and "your" when addressing the user. Maintain a warm, supportive, and non-judgmental tone. + Example: "Based on what you've shared about your sleep patterns..." instead of "The individual's sleep patterns..." + """, + + "resource_agent": """ + You are a mental health resource coordinator speaking directly to the user. Your task is to: + 1. Connect you with appropriate mental health services + 2. Suggest support groups or communities that would benefit you + 3. Recommend professional care options for your situation + 4. Provide crisis resources when needed + 5. Consider what resources would be most accessible for you + 6. Share specific contact information for your local resources + + Always address the user directly using "you" and "your". Focus on practical, accessible resources. + Example: "Given your current situation, these resources might help..." instead of "The following resources are recommended..." + """, + + "action_agent": """ + You are a crisis intervention specialist speaking directly to the user. Your task is to: + 1. Help you develop immediate coping strategies + 2. Work with you to create a daily wellness routine + 3. Teach you stress management techniques + 4. Guide you in improving your sleep habits + 5. Help you make healthy lifestyle adjustments + 6. Create an emergency response plan with you if needed + + Use "you" and "your" when providing guidance. Give clear, actionable steps. + Example: "Here are steps you can take right now..." instead of "The following steps are recommended..." + """, + + "followup_agent": """ + You are a mental health recovery planner speaking directly to the user. Your task is to: + 1. Help you develop long-term support strategies + 2. Create a progress monitoring plan that works for you + 3. Work with you on relapse prevention strategies + 4. Plan how to engage your support system + 5. Guide you through lifestyle modifications + 6. Set up maintenance and check-in schedules with you + + Always use "you" and "your" in your recommendations. Focus on sustainable, long-term solutions. + Example: "To maintain your progress, you might want to..." instead of "The following maintenance plan is suggested..." + """ + } + # Then modify the agent configurations llm_config = { "config_list": [{"model": "gpt-4o", "api_key": api_key}] @@ -91,78 +182,36 @@ if st.button("Generate Climate Response Plan"): # Context management for agent communication context_variables = { - "climate": None, - "urban": None, - "economic": None, - "community": None, + "psychology": None, + "resources": None, + "action": None, + "followup": None, } # Update functions for each agent - def update_climate_overview(climate_summary: str, context_variables: dict) -> SwarmResult: + def update_psychology_overview(psychology_summary: str, context_variables: dict) -> SwarmResult: """Keep the summary as short as possible.""" - context_variables["climate"] = climate_summary - st.sidebar.success('Climate Analysis: ' + climate_summary) - return SwarmResult(agent="urban_agent", context_variables=context_variables) + context_variables["psychology"] = psychology_summary + st.sidebar.success('Psychology Analysis: ' + psychology_summary) + return SwarmResult(agent="resource_agent", context_variables=context_variables) - def update_urban_overview(urban_summary: str, context_variables: dict) -> SwarmResult: + def update_resource_overview(resource_summary: str, context_variables: dict) -> SwarmResult: """Keep the summary as short as possible.""" - context_variables["urban"] = urban_summary - st.sidebar.success('Urban Planning: ' + urban_summary) - return SwarmResult(agent="economic_agent", context_variables=context_variables) + context_variables["resources"] = resource_summary + st.sidebar.success('Resource Identification: ' + resource_summary) + return SwarmResult(agent="action_agent", context_variables=context_variables) - def update_economic_overview(economic_summary: str, context_variables: dict) -> SwarmResult: + def update_action_overview(action_summary: str, context_variables: dict) -> SwarmResult: """Keep the summary as short as possible.""" - context_variables["economic"] = economic_summary - st.sidebar.success('Economic Impact: ' + economic_summary) - return SwarmResult(agent="community_agent", context_variables=context_variables) + context_variables["action"] = action_summary + st.sidebar.success('Action Plan: ' + action_summary) + return SwarmResult(agent="followup_agent", context_variables=context_variables) - def update_community_overview(community_summary: str, context_variables: dict) -> SwarmResult: + def update_followup_overview(followup_summary: str, context_variables: dict) -> SwarmResult: """Keep the summary as short as possible.""" - context_variables["community"] = community_summary - st.sidebar.success('Community Engagement: ' + community_summary) - return SwarmResult(agent="climate_agent", context_variables=context_variables) - - system_messages = { - "climate_agent": """ - You are an expert climate scientist and risk analyst. Your task is to: - 1. Analyze historical climate data and future projections for the specified city - 2. Identify key climate risks (flooding, heat waves, storms, etc.) - 3. Assess vulnerability of different city areas and systems - 4. Prioritize climate threats based on likelihood and impact - 5. Recommend key areas for climate resilience focus - 6. Provide specific climate scenarios the city should prepare for - """, - - "urban_agent": """ - You are an experienced urban planner specializing in climate adaptation. Your task is to: - 1. Design infrastructure modifications for climate resilience - 2. Develop zoning recommendations for risk reduction - 3. Plan green infrastructure and nature-based solutions - 4. Identify critical infrastructure vulnerabilities - 5. Create phased implementation strategies - 6. Consider both immediate and long-term adaptation needs - """, - - "economic_agent": """ - You are a climate economics and finance specialist. Your task is to: - 1. Calculate potential economic impacts of climate risks - 2. Identify funding sources for adaptation projects - 3. Analyze cost-benefit ratios of proposed solutions - 4. Assess impacts on local industries and businesses - 5. Develop economic incentives for climate adaptation - 6. Create budget allocation recommendations - """, - - "community_agent": """ - You are a community engagement and behavior change expert. Your task is to: - 1. Design public communication strategies - 2. Plan community involvement in adaptation efforts - 3. Develop education and awareness programs - 4. Create behavior change initiatives - 5. Plan vulnerable population support systems - 6. Design feedback and monitoring systems - """ - } + context_variables["followup"] = followup_summary + st.sidebar.success('Follow-up Strategy: ' + followup_summary) + return SwarmResult(agent="psychology_agent", context_variables=context_variables) def update_system_message_func(agent: SwarmAgent, messages) -> str: """""" @@ -196,42 +245,42 @@ if st.button("Generate Climate Response Plan"): state_update = UPDATE_SYSTEM_MESSAGE(update_system_message_func) # Define agents with proper code execution config - climate_agent = SwarmAgent( - "climate_agent", + psychology_agent = SwarmAgent( + "psychology_agent", llm_config=llm_config, - functions=update_climate_overview, + functions=update_psychology_overview, update_agent_state_before_reply=[state_update] ) - urban_agent = SwarmAgent( - "urban_agent", + resource_agent = SwarmAgent( + "resource_agent", llm_config=llm_config, - functions=update_urban_overview, + functions=update_resource_overview, update_agent_state_before_reply=[state_update] ) - economic_agent = SwarmAgent( - "economic_agent", + action_agent = SwarmAgent( + "action_agent", llm_config=llm_config, - functions=update_economic_overview, + functions=update_action_overview, update_agent_state_before_reply=[state_update] ) - community_agent = SwarmAgent( - name="community_agent", + followup_agent = SwarmAgent( + name="followup_agent", llm_config=llm_config, - functions=update_community_overview, + functions=update_followup_overview, update_agent_state_before_reply=[state_update] ) - climate_agent.register_hand_off(AFTER_WORK(urban_agent)) - urban_agent.register_hand_off(AFTER_WORK(economic_agent)) - economic_agent.register_hand_off(AFTER_WORK(community_agent)) - community_agent.register_hand_off(AFTER_WORK(climate_agent)) + psychology_agent.register_hand_off(AFTER_WORK(resource_agent)) + resource_agent.register_hand_off(AFTER_WORK(action_agent)) + action_agent.register_hand_off(AFTER_WORK(followup_agent)) + followup_agent.register_hand_off(AFTER_WORK(psychology_agent)) result, _, _ = initiate_swarm_chat( - initial_agent=climate_agent, - agents=[climate_agent, urban_agent, economic_agent, community_agent], + initial_agent=psychology_agent, + agents=[psychology_agent, resource_agent, action_agent, followup_agent], user_agent=None, messages=task, max_rounds=13, @@ -239,27 +288,27 @@ if st.button("Generate Climate Response Plan"): # Update session state with the individual responses st.session_state.output = { - 'climate': result.chat_history[-4]['content'], - 'urban': result.chat_history[-3]['content'], - 'economic': result.chat_history[-2]['content'], - 'community': result.chat_history[-1]['content'] + 'psychology': result.chat_history[-4]['content'], + 'resources': result.chat_history[-3]['content'], + 'action': result.chat_history[-2]['content'], + 'followup': result.chat_history[-1]['content'] } # Display success message after completion - st.success('✨ Climate response plan generated successfully!') + st.success('✨ Mental health support plan generated successfully!') # Display the individual outputs in expanders - with st.expander("Climate Analysis"): - st.markdown(st.session_state.output['climate']) + with st.expander("Psychology Analysis"): + st.markdown(st.session_state.output['psychology']) - with st.expander("Urban Planning"): - st.markdown(st.session_state.output['urban']) + with st.expander("Resource Identification"): + st.markdown(st.session_state.output['resources']) - with st.expander("Economic Impact"): - st.markdown(st.session_state.output['economic']) + with st.expander("Action Plan"): + st.markdown(st.session_state.output['action']) - with st.expander("Community Engagement"): - st.markdown(st.session_state.output['community']) + with st.expander("Follow-up Strategy"): + st.markdown(st.session_state.output['followup']) except Exception as e: st.error(f"An error occurred: {str(e)}") From aa7c21b067214a11762ac3ebe65c80bcd789208a Mon Sep 17 00:00:00 2001 From: Madhu Date: Thu, 20 Feb 2025 07:07:04 +0530 Subject: [PATCH 4/9] changed it to mental health crisis agent2 --- .../ai_mental_health_crisis_agent/README.md | 0 .../ai_mental_health_crisis_agent.py | 260 ++++++++++++++++++ .../requirements.txt | 8 + 3 files changed, 268 insertions(+) create mode 100644 ai_agent_tutorials/ai_mental_health_crisis_agent/README.md create mode 100644 ai_agent_tutorials/ai_mental_health_crisis_agent/ai_mental_health_crisis_agent.py create mode 100644 ai_agent_tutorials/ai_mental_health_crisis_agent/requirements.txt diff --git a/ai_agent_tutorials/ai_mental_health_crisis_agent/README.md b/ai_agent_tutorials/ai_mental_health_crisis_agent/README.md new file mode 100644 index 0000000..e69de29 diff --git a/ai_agent_tutorials/ai_mental_health_crisis_agent/ai_mental_health_crisis_agent.py b/ai_agent_tutorials/ai_mental_health_crisis_agent/ai_mental_health_crisis_agent.py new file mode 100644 index 0000000..5ce13d0 --- /dev/null +++ b/ai_agent_tutorials/ai_mental_health_crisis_agent/ai_mental_health_crisis_agent.py @@ -0,0 +1,260 @@ +import asyncio +import streamlit as st +from autogen import ( + SwarmAgent, + SwarmResult, + initiate_swarm_chat, + OpenAIWrapper, + AFTER_WORK, + UPDATE_SYSTEM_MESSAGE +) +import os + +# Add this at the top of the file, before any other code +os.environ["AUTOGEN_USE_DOCKER"] = "0" + +# Initialize session state with 3 key components +if 'output' not in st.session_state: + st.session_state.output = { + 'assessment': '', # Combined psychology/analysis + 'action': '', # Immediate actions and resources + 'followup': '' # Long-term planning + } + +# Sidebar for API key input +st.sidebar.title("OpenAI API Key") +api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password") + +# Main app UI +st.title("🧠 Mental Health Crisis Navigator") + +# Update UI description +st.info(""" +**Meet Your Mental Health Support Team:** + +🧠 **Assessment Agent** - Analyzes your situation and emotional needs +🎯 **Action Agent** - Creates immediate action plan and connects you with resources +🔄 **Follow-up Agent** - Designs your long-term support strategy +""") + +# User inputs +st.subheader("Personal Information") +col1, col2 = st.columns(2) + +with col1: + mental_state = st.text_area("How have you been feeling recently?", + placeholder="Describe your emotional state, thoughts, or concerns...") + sleep_pattern = st.select_slider( + "Sleep Pattern (hours per night)", + options=[f"{i}" for i in range(0, 13)], + value="7" + ) + +with col2: + stress_level = st.slider("Current Stress Level (1-10)", 1, 10, 5) + support_system = st.multiselect( + "Current Support System", + ["Family", "Friends", "Therapist", "Support Groups", "None"] + ) + +# Additional context +recent_changes = st.text_area( + "Any significant life changes or events recently?", + placeholder="Job changes, relationships, losses, etc..." +) + +current_symptoms = st.multiselect( + "Current Symptoms", + ["Anxiety", "Depression", "Insomnia", "Fatigue", "Loss of Interest", + "Difficulty Concentrating", "Changes in Appetite", "Social Withdrawal", + "Mood Swings", "Physical Discomfort"] +) + +# Emergency notice +st.warning(""" +⚠️ **Important**: If you're having thoughts of self-harm or experiencing a severe crisis, +please immediately contact emergency services or crisis hotlines: +- National Crisis Hotline: 988 +- Emergency: 911 +""") + +# Button to start the agent collaboration +if st.button("Get Support Plan"): + if not api_key: + st.error("Please enter your OpenAI API key.") + else: + with st.spinner('🤖 AI Agents are analyzing your situation...'): + try: + task = f""" + Create a comprehensive mental health support plan based on: + + Emotional State: {mental_state} + Sleep: {sleep_pattern} hours per night + Stress Level: {stress_level}/10 + Support System: {', '.join(support_system) if support_system else 'None reported'} + Recent Changes: {recent_changes} + Current Symptoms: {', '.join(current_symptoms) if current_symptoms else 'None reported'} + """ + + # Update system messages for 3 agents + system_messages = { + "assessment_agent": """ + You are an experienced mental health professional speaking directly to the user. Your task is to: + 1. Create a safe space by acknowledging their courage in seeking support + 2. Analyze their emotional state with clinical precision and genuine empathy + 3. Ask targeted follow-up questions to understand their full situation + 4. Identify patterns in their thoughts, behaviors, and relationships + 5. Assess risk levels with validated screening approaches + 6. Help them understand their current mental health in accessible language + 7. Validate their experiences without minimizing or catastrophizing + + Always use "you" and "your" when addressing the user. Blend clinical expertise with genuine warmth and never rush to conclusions. + """, + + "action_agent": """ + You are a crisis intervention and resource specialist speaking directly to the user. Your task is to: + 1. Provide immediate evidence-based coping strategies tailored to their specific situation + 2. Prioritize interventions based on urgency and effectiveness + 3. Connect them with appropriate mental health services while acknowledging barriers (cost, access, stigma) + 4. Create a concrete daily wellness plan with specific times and activities + 5. Suggest specific support communities with details on how to join + 6. Balance crisis resources with empowerment techniques + 7. Teach simple self-regulation techniques they can use immediately + + Focus on practical, achievable steps that respect their current capacity and energy levels. Provide options ranging from minimal effort to more involved actions. + """, + + "followup_agent": """ + You are a mental health recovery planner speaking directly to the user. Your task is to: + 1. Design a personalized long-term support strategy with milestone markers + 2. Create a progress monitoring system that matches their preferences and habits + 3. Develop specific relapse prevention strategies based on their unique triggers + 4. Establish a support network mapping exercise to identify existing resources + 5. Build a graduated self-care routine that evolves with their recovery + 6. Plan for setbacks with self-compassion techniques + 7. Set up a maintenance schedule with clear check-in mechanisms + + Focus on building sustainable habits that integrate with their lifestyle and values. Emphasize progress over perfection and teach skills for self-directed care. + """ + } + + # Then modify the agent configurations + llm_config = { + "config_list": [{"model": "gpt-4o", "api_key": api_key}] + } + + # Context management for agent communication + context_variables = { + "assessment": None, + "action": None, + "followup": None, + } + + # Update functions for each agent + def update_assessment_overview(assessment_summary: str, context_variables: dict) -> SwarmResult: + """Keep the summary as short as possible.""" + context_variables["assessment"] = assessment_summary + st.sidebar.success('Assessment: ' + assessment_summary) + return SwarmResult(agent="action_agent", context_variables=context_variables) + + def update_action_overview(action_summary: str, context_variables: dict) -> SwarmResult: + """Keep the summary as short as possible.""" + context_variables["action"] = action_summary + st.sidebar.success('Action Plan: ' + action_summary) + return SwarmResult(agent="followup_agent", context_variables=context_variables) + + def update_followup_overview(followup_summary: str, context_variables: dict) -> SwarmResult: + """Keep the summary as short as possible.""" + context_variables["followup"] = followup_summary + st.sidebar.success('Follow-up Strategy: ' + followup_summary) + return SwarmResult(agent="assessment_agent", context_variables=context_variables) + + def update_system_message_func(agent: SwarmAgent, messages) -> str: + """""" + system_prompt = system_messages[agent.name] + + current_gen = agent.name.split("_")[0] + if agent._context_variables.get(current_gen) is None: + system_prompt += f"Call the update function provided to first provide a 2-3 sentence summary of your ideas on {current_gen.upper()} based on the context provided." + agent.llm_config['tool_choice'] = {"type": "function", "function": {"name": f"update_{current_gen}_overview"}} + agent.client = OpenAIWrapper(**agent.llm_config) + else: + # remove the tools to avoid the agent from using it and reduce cost + agent.llm_config["tools"] = None + agent.llm_config['tool_choice'] = None + agent.client = OpenAIWrapper(**agent.llm_config) + # the agent has given a summary, now it should generate a detailed response + system_prompt += f"\n\nYour task\nYou task is write the {current_gen} part of the report. Do not include any other parts. Do not use XML tags.\nStart your reponse with: '## {current_gen.capitalize()} Design'." + + # Remove all messages except the first one with less cost + k = list(agent._oai_messages.keys())[-1] + agent._oai_messages[k] = agent._oai_messages[k][:1] + + system_prompt += f"\n\n\nBelow are some context for you to refer to:" + # Add context variables to the prompt + for k, v in agent._context_variables.items(): + if v is not None: + system_prompt += f"\n{k.capitalize()} Summary:\n{v}" + + return system_prompt + + state_update = UPDATE_SYSTEM_MESSAGE(update_system_message_func) + + # Initialize agents + assessment_agent = SwarmAgent( + "assessment_agent", + llm_config=llm_config, + functions=update_assessment_overview, + update_agent_state_before_reply=[state_update] + ) + + action_agent = SwarmAgent( + "action_agent", + llm_config=llm_config, + functions=update_action_overview, + update_agent_state_before_reply=[state_update] + ) + + followup_agent = SwarmAgent( + "followup_agent", + llm_config=llm_config, + functions=update_followup_overview, + update_agent_state_before_reply=[state_update] + ) + + # Update handoffs + 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)) + + # Update result handling + result, _, _ = initiate_swarm_chat( + initial_agent=assessment_agent, + agents=[assessment_agent, action_agent, followup_agent], + user_agent=None, + messages=task, + max_rounds=13, + ) + + # Update session state with responses + st.session_state.output = { + 'assessment': result.chat_history[-3]['content'], + 'action': result.chat_history[-2]['content'], + 'followup': result.chat_history[-1]['content'] + } + + # Display outputs + with st.expander("Situation Assessment"): + st.markdown(st.session_state.output['assessment']) + + with st.expander("Action Plan & Resources"): + st.markdown(st.session_state.output['action']) + + with st.expander("Long-term Support Strategy"): + st.markdown(st.session_state.output['followup']) + + # Display success message after completion + st.success('✨ Mental health support plan generated successfully!') + + except Exception as e: + st.error(f"An error occurred: {str(e)}") diff --git a/ai_agent_tutorials/ai_mental_health_crisis_agent/requirements.txt b/ai_agent_tutorials/ai_mental_health_crisis_agent/requirements.txt new file mode 100644 index 0000000..451a368 --- /dev/null +++ b/ai_agent_tutorials/ai_mental_health_crisis_agent/requirements.txt @@ -0,0 +1,8 @@ +autogen-agentchat +autogen-ext +playwright install --with-deps chromium + +pyautogen +agentops + +streamlit From bf819af5a3a06567f7993c83b3c11219a3a49929 Mon Sep 17 00:00:00 2001 From: Madhu Date: Thu, 20 Feb 2025 07:34:04 +0530 Subject: [PATCH 5/9] readme + req --- .../ai_magenticag2_agent/main.py | 315 ------------------ .../ai_magenticag2_agent/requirements.txt | 8 - 2 files changed, 323 deletions(-) delete mode 100644 ai_agent_tutorials/ai_magenticag2_agent/main.py delete mode 100644 ai_agent_tutorials/ai_magenticag2_agent/requirements.txt diff --git a/ai_agent_tutorials/ai_magenticag2_agent/main.py b/ai_agent_tutorials/ai_magenticag2_agent/main.py deleted file mode 100644 index ef765ef..0000000 --- a/ai_agent_tutorials/ai_magenticag2_agent/main.py +++ /dev/null @@ -1,315 +0,0 @@ -import asyncio -import streamlit as st -from autogen import ( - SwarmAgent, - SwarmResult, - initiate_swarm_chat, - OpenAIWrapper, - AFTER_WORK, - UPDATE_SYSTEM_MESSAGE -) -import agentops -import os -from contextlib import contextmanager - -# Add this at the top of the file, before any other code -os.environ["AUTOGEN_USE_DOCKER"] = "0" - -# Initialize session state -if 'output' not in st.session_state: - st.session_state.output = { - 'psychology': '', - 'resources': '', - 'action': '', - 'followup': '' - } - -# Sidebar for API key input -st.sidebar.title("OpenAI API Key") -api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password") - -st.sidebar.title("AgentOps API Key") -agentops_key = st.sidebar.text_input("Enter your AgentOps API Key", type="password", value="4e725ba8-b57e-49b5-809a-4eeef18d92ed") - -# Main app UI -st.title("🧠 Mental Health Crisis Navigator") - -# Add agent information below title -st.info(""" -**Meet Your Mental Health Support Team:** - -🧠 **Psychology Agent** - Analyzes emotional state and psychological needs -📋 **Resource Agent** - Identifies relevant support services and professionals -🎯 **Action Agent** - Creates immediate step-by-step action plans -🔄 **Follow-up Agent** - Designs ongoing support and prevention strategies -""") - -# User inputs -st.subheader("Personal Information") -col1, col2 = st.columns(2) - -with col1: - mental_state = st.text_area("How have you been feeling recently?", - placeholder="Describe your emotional state, thoughts, or concerns...") - sleep_pattern = st.select_slider( - "Sleep Pattern (hours per night)", - options=[f"{i}" for i in range(0, 13)], - value="7" - ) - -with col2: - stress_level = st.slider("Current Stress Level (1-10)", 1, 10, 5) - support_system = st.multiselect( - "Current Support System", - ["Family", "Friends", "Therapist", "Support Groups", "None"] - ) - -# Additional context -recent_changes = st.text_area( - "Any significant life changes or events recently?", - placeholder="Job changes, relationships, losses, etc..." -) - -current_symptoms = st.multiselect( - "Current Symptoms", - ["Anxiety", "Depression", "Insomnia", "Fatigue", "Loss of Interest", - "Difficulty Concentrating", "Changes in Appetite", "Social Withdrawal", - "Mood Swings", "Physical Discomfort"] -) - -# Emergency notice -st.warning(""" -⚠️ **Important**: If you're having thoughts of self-harm or experiencing a severe crisis, -please immediately contact emergency services or crisis hotlines: -- National Crisis Hotline: 988 -- Emergency: 911 -""") - -@contextmanager -def agentops_session(api_key: str, tags: list): - """Context manager for AgentOps sessions""" - try: - agentops.init( - api_key=api_key, - tags=tags, - instrument_llm_calls=True, - auto_start_session=True - ) - yield - finally: - try: - agentops.end_session("Success") - except Exception as e: - print(f"Failed to end AgentOps session: {e}") - -# Button to start the agent collaboration -if st.button("Get Support Plan"): - if not api_key: - st.error("Please enter your OpenAI API key.") - else: - with st.spinner('🤖 AI Agents are analyzing your situation...'): - with agentops_session(api_key=agentops_key, tags=["mental_health_navigator"]): - try: - task = f""" - Create a comprehensive mental health support plan based on: - - Emotional State: {mental_state} - Sleep: {sleep_pattern} hours per night - Stress Level: {stress_level}/10 - Support System: {', '.join(support_system) if support_system else 'None reported'} - Recent Changes: {recent_changes} - Current Symptoms: {', '.join(current_symptoms) if current_symptoms else 'None reported'} - """ - - system_messages = { - "psychology_agent": """ - You are an experienced mental health professional speaking directly to the user. Your task is to: - 1. Analyze their emotional state and psychological symptoms with empathy - 2. Help them understand potential mental health concerns - 3. Assess their risk levels and urgency - 4. Suggest therapeutic approaches that would work for them - 5. Help them understand how their life changes and stressors are affecting them - 6. Provide supportive psychological insights - - Always use "you" and "your" when addressing the user. Maintain a warm, supportive, and non-judgmental tone. - Example: "Based on what you've shared about your sleep patterns..." instead of "The individual's sleep patterns..." - """, - - "resource_agent": """ - You are a mental health resource coordinator speaking directly to the user. Your task is to: - 1. Connect you with appropriate mental health services - 2. Suggest support groups or communities that would benefit you - 3. Recommend professional care options for your situation - 4. Provide crisis resources when needed - 5. Consider what resources would be most accessible for you - 6. Share specific contact information for your local resources - - Always address the user directly using "you" and "your". Focus on practical, accessible resources. - Example: "Given your current situation, these resources might help..." instead of "The following resources are recommended..." - """, - - "action_agent": """ - You are a crisis intervention specialist speaking directly to the user. Your task is to: - 1. Help you develop immediate coping strategies - 2. Work with you to create a daily wellness routine - 3. Teach you stress management techniques - 4. Guide you in improving your sleep habits - 5. Help you make healthy lifestyle adjustments - 6. Create an emergency response plan with you if needed - - Use "you" and "your" when providing guidance. Give clear, actionable steps. - Example: "Here are steps you can take right now..." instead of "The following steps are recommended..." - """, - - "followup_agent": """ - You are a mental health recovery planner speaking directly to the user. Your task is to: - 1. Help you develop long-term support strategies - 2. Create a progress monitoring plan that works for you - 3. Work with you on relapse prevention strategies - 4. Plan how to engage your support system - 5. Guide you through lifestyle modifications - 6. Set up maintenance and check-in schedules with you - - Always use "you" and "your" in your recommendations. Focus on sustainable, long-term solutions. - Example: "To maintain your progress, you might want to..." instead of "The following maintenance plan is suggested..." - """ - } - - # Then modify the agent configurations - llm_config = { - "config_list": [{"model": "gpt-4o", "api_key": api_key}] - } - - # Context management for agent communication - context_variables = { - "psychology": None, - "resources": None, - "action": None, - "followup": None, - } - - # Update functions for each agent - def update_psychology_overview(psychology_summary: str, context_variables: dict) -> SwarmResult: - """Keep the summary as short as possible.""" - context_variables["psychology"] = psychology_summary - st.sidebar.success('Psychology Analysis: ' + psychology_summary) - return SwarmResult(agent="resource_agent", context_variables=context_variables) - - def update_resource_overview(resource_summary: str, context_variables: dict) -> SwarmResult: - """Keep the summary as short as possible.""" - context_variables["resources"] = resource_summary - st.sidebar.success('Resource Identification: ' + resource_summary) - return SwarmResult(agent="action_agent", context_variables=context_variables) - - def update_action_overview(action_summary: str, context_variables: dict) -> SwarmResult: - """Keep the summary as short as possible.""" - context_variables["action"] = action_summary - st.sidebar.success('Action Plan: ' + action_summary) - return SwarmResult(agent="followup_agent", context_variables=context_variables) - - def update_followup_overview(followup_summary: str, context_variables: dict) -> SwarmResult: - """Keep the summary as short as possible.""" - context_variables["followup"] = followup_summary - st.sidebar.success('Follow-up Strategy: ' + followup_summary) - return SwarmResult(agent="psychology_agent", context_variables=context_variables) - - def update_system_message_func(agent: SwarmAgent, messages) -> str: - """""" - system_prompt = system_messages[agent.name] - - current_gen = agent.name.split("_")[0] - if agent._context_variables.get(current_gen) is None: - system_prompt += f"Call the update function provided to first provide a 2-3 sentence summary of your ideas on {current_gen.upper()} based on the context provided." - agent.llm_config['tool_choice'] = {"type": "function", "function": {"name": f"update_{current_gen}_overview"}} - agent.client = OpenAIWrapper(**agent.llm_config) - else: - # remove the tools to avoid the agent from using it and reduce cost - agent.llm_config["tools"] = None - agent.llm_config['tool_choice'] = None - agent.client = OpenAIWrapper(**agent.llm_config) - # the agent has given a summary, now it should generate a detailed response - system_prompt += f"\n\nYour task\nYou task is write the {current_gen} part of the report. Do not include any other parts. Do not use XML tags.\nStart your reponse with: '## {current_gen.capitalize()} Design'." - - # Remove all messages except the first one with less cost - k = list(agent._oai_messages.keys())[-1] - agent._oai_messages[k] = agent._oai_messages[k][:1] - - system_prompt += f"\n\n\nBelow are some context for you to refer to:" - # Add context variables to the prompt - for k, v in agent._context_variables.items(): - if v is not None: - system_prompt += f"\n{k.capitalize()} Summary:\n{v}" - - return system_prompt - - state_update = UPDATE_SYSTEM_MESSAGE(update_system_message_func) - - # Define agents with proper code execution config - psychology_agent = SwarmAgent( - "psychology_agent", - llm_config=llm_config, - functions=update_psychology_overview, - update_agent_state_before_reply=[state_update] - ) - - resource_agent = SwarmAgent( - "resource_agent", - llm_config=llm_config, - functions=update_resource_overview, - update_agent_state_before_reply=[state_update] - ) - - action_agent = SwarmAgent( - "action_agent", - llm_config=llm_config, - functions=update_action_overview, - update_agent_state_before_reply=[state_update] - ) - - followup_agent = SwarmAgent( - name="followup_agent", - llm_config=llm_config, - functions=update_followup_overview, - update_agent_state_before_reply=[state_update] - ) - - psychology_agent.register_hand_off(AFTER_WORK(resource_agent)) - resource_agent.register_hand_off(AFTER_WORK(action_agent)) - action_agent.register_hand_off(AFTER_WORK(followup_agent)) - followup_agent.register_hand_off(AFTER_WORK(psychology_agent)) - - result, _, _ = initiate_swarm_chat( - initial_agent=psychology_agent, - agents=[psychology_agent, resource_agent, action_agent, followup_agent], - user_agent=None, - messages=task, - max_rounds=13, - ) - - # Update session state with the individual responses - st.session_state.output = { - 'psychology': result.chat_history[-4]['content'], - 'resources': result.chat_history[-3]['content'], - 'action': result.chat_history[-2]['content'], - 'followup': result.chat_history[-1]['content'] - } - - # Display success message after completion - st.success('✨ Mental health support plan generated successfully!') - - # Display the individual outputs in expanders - with st.expander("Psychology Analysis"): - st.markdown(st.session_state.output['psychology']) - - with st.expander("Resource Identification"): - st.markdown(st.session_state.output['resources']) - - with st.expander("Action Plan"): - st.markdown(st.session_state.output['action']) - - with st.expander("Follow-up Strategy"): - st.markdown(st.session_state.output['followup']) - - except Exception as e: - st.error(f"An error occurred: {str(e)}") - raise # Re-raise to trigger session end with error diff --git a/ai_agent_tutorials/ai_magenticag2_agent/requirements.txt b/ai_agent_tutorials/ai_magenticag2_agent/requirements.txt deleted file mode 100644 index 451a368..0000000 --- a/ai_agent_tutorials/ai_magenticag2_agent/requirements.txt +++ /dev/null @@ -1,8 +0,0 @@ -autogen-agentchat -autogen-ext -playwright install --with-deps chromium - -pyautogen -agentops - -streamlit From 979d99ef43692fbce9779b0059156a0ab87a63e6 Mon Sep 17 00:00:00 2001 From: Madhu Date: Thu, 20 Feb 2025 07:36:13 +0530 Subject: [PATCH 6/9] final inclusions --- .../ai_mental_health_crisis_agent/README.md | 73 +++++++++++++++++++ .../ai_mental_health_crisis_agent.py | 18 +++-- .../requirements.txt | 6 +- 3 files changed, 85 insertions(+), 12 deletions(-) diff --git a/ai_agent_tutorials/ai_mental_health_crisis_agent/README.md b/ai_agent_tutorials/ai_mental_health_crisis_agent/README.md index e69de29..755f299 100644 --- a/ai_agent_tutorials/ai_mental_health_crisis_agent/README.md +++ b/ai_agent_tutorials/ai_mental_health_crisis_agent/README.md @@ -0,0 +1,73 @@ +# AI Mental Health Crisis Navigator 🧠 + +The AI Mental Health Crisis Navigator is a supportive mental health assessment and guidance system powered by [AG2](https://github.com/ag2ai/ag2?tab=readme-ov-file)(formerly AutoGen)'s AI Agent framework. This app 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. This is built on AG2's new swarm feature run through initiate_swarm_chat() method. + +## Features + +- **Specialized Mental Health Support Team** + - 🧠 **Assessment Agent**: Analyzes emotional state and psychological needs with clinical precision and empathy + - 🎯 **Action Agent**: Creates immediate action plans and connects users with appropriate resources + - 🔄 **Follow-up Agent**: Designs long-term support strategies and prevention plans + +- **Comprehensive Mental Health Support**: + - Detailed psychological assessment + - Immediate coping strategies + - Resource recommendations + - Long-term support planning + - Crisis prevention strategies + - Progress monitoring systems + +- **Customizable Input Parameters**: + - Current emotional state + - Sleep patterns + - Stress levels + - Support system information + - Recent life changes + - Current symptoms + +- **Interactive Results**: + - Real-time assessment summaries + - Detailed recommendations in expandable sections + - Clear action steps and resources + - Long-term support strategies + +## How to Run + +Follow these steps to set up and run the application: + +1. **Clone the Repository**: + ```bash + git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git + cd ai_agent_tutorials/ai_mental_health_crisis_agent + ``` + +2. **Install Dependencies**: + ```bash + pip install -r requirements.txt + ``` + +3. **Create Environment File**: + Create a `.env` file in the project directory: + ```bash + echo "AUTOGEN_USE_DOCKER=0" > .env + ``` + This disables Docker requirement for code execution in AutoGen. + +4. **Set Up OpenAI API Key**: + - Obtain an OpenAI API key from [OpenAI's platform](https://platform.openai.com) + - You'll input this key in the app's sidebar when running + +5. **Run the Streamlit App**: + ```bash + streamlit run ai_mental_health_crisis_agent.py + ``` + + +## ⚠️ Important Notice + +This 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 + diff --git a/ai_agent_tutorials/ai_mental_health_crisis_agent/ai_mental_health_crisis_agent.py b/ai_agent_tutorials/ai_mental_health_crisis_agent/ai_mental_health_crisis_agent.py index 5ce13d0..d586722 100644 --- a/ai_agent_tutorials/ai_mental_health_crisis_agent/ai_mental_health_crisis_agent.py +++ b/ai_agent_tutorials/ai_mental_health_crisis_agent/ai_mental_health_crisis_agent.py @@ -25,6 +25,17 @@ if 'output' not in st.session_state: st.sidebar.title("OpenAI API Key") api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password") +# Add privacy notice in sidebar +st.sidebar.warning(""" +## ⚠️ Important Notice + +This 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 +""") + # Main app UI st.title("🧠 Mental Health Crisis Navigator") @@ -70,13 +81,6 @@ current_symptoms = st.multiselect( "Mood Swings", "Physical Discomfort"] ) -# Emergency notice -st.warning(""" -⚠️ **Important**: If you're having thoughts of self-harm or experiencing a severe crisis, -please immediately contact emergency services or crisis hotlines: -- National Crisis Hotline: 988 -- Emergency: 911 -""") # Button to start the agent collaboration if st.button("Get Support Plan"): diff --git a/ai_agent_tutorials/ai_mental_health_crisis_agent/requirements.txt b/ai_agent_tutorials/ai_mental_health_crisis_agent/requirements.txt index 451a368..da4c21a 100644 --- a/ai_agent_tutorials/ai_mental_health_crisis_agent/requirements.txt +++ b/ai_agent_tutorials/ai_mental_health_crisis_agent/requirements.txt @@ -1,8 +1,4 @@ autogen-agentchat autogen-ext -playwright install --with-deps chromium - pyautogen -agentops - -streamlit +streamlit \ No newline at end of file From d0f33b3edc5328b5166880948df88d0c6baab59d Mon Sep 17 00:00:00 2001 From: Madhu Date: Thu, 20 Feb 2025 07:39:23 +0530 Subject: [PATCH 7/9] removed unnecessary imports and code --- .../ai_mental_health_crisis_agent.py | 41 +++---------------- 1 file changed, 5 insertions(+), 36 deletions(-) diff --git a/ai_agent_tutorials/ai_mental_health_crisis_agent/ai_mental_health_crisis_agent.py b/ai_agent_tutorials/ai_mental_health_crisis_agent/ai_mental_health_crisis_agent.py index d586722..54d95ec 100644 --- a/ai_agent_tutorials/ai_mental_health_crisis_agent/ai_mental_health_crisis_agent.py +++ b/ai_agent_tutorials/ai_mental_health_crisis_agent/ai_mental_health_crisis_agent.py @@ -1,4 +1,3 @@ -import asyncio import streamlit as st from autogen import ( SwarmAgent, @@ -10,22 +9,18 @@ from autogen import ( ) import os -# Add this at the top of the file, before any other code os.environ["AUTOGEN_USE_DOCKER"] = "0" -# Initialize session state with 3 key components if 'output' not in st.session_state: st.session_state.output = { - 'assessment': '', # Combined psychology/analysis - 'action': '', # Immediate actions and resources - 'followup': '' # Long-term planning + 'assessment': '', + 'action': '', + 'followup': '' } -# Sidebar for API key input st.sidebar.title("OpenAI API Key") api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password") -# Add privacy notice in sidebar st.sidebar.warning(""" ## ⚠️ Important Notice @@ -36,10 +31,8 @@ This application is a supportive tool and does not replace professional mental h - Seek immediate professional help """) -# Main app UI st.title("🧠 Mental Health Crisis Navigator") -# Update UI description st.info(""" **Meet Your Mental Health Support Team:** @@ -48,7 +41,6 @@ st.info(""" 🔄 **Follow-up Agent** - Designs your long-term support strategy """) -# User inputs st.subheader("Personal Information") col1, col2 = st.columns(2) @@ -68,7 +60,6 @@ with col2: ["Family", "Friends", "Therapist", "Support Groups", "None"] ) -# Additional context recent_changes = st.text_area( "Any significant life changes or events recently?", placeholder="Job changes, relationships, losses, etc..." @@ -81,8 +72,6 @@ current_symptoms = st.multiselect( "Mood Swings", "Physical Discomfort"] ) - -# Button to start the agent collaboration if st.button("Get Support Plan"): if not api_key: st.error("Please enter your OpenAI API key.") @@ -100,7 +89,6 @@ if st.button("Get Support Plan"): Current Symptoms: {', '.join(current_symptoms) if current_symptoms else 'None reported'} """ - # Update system messages for 3 agents system_messages = { "assessment_agent": """ You are an experienced mental health professional speaking directly to the user. Your task is to: @@ -142,69 +130,55 @@ if st.button("Get Support Plan"): """ } - # Then modify the agent configurations llm_config = { "config_list": [{"model": "gpt-4o", "api_key": api_key}] } - # Context management for agent communication context_variables = { "assessment": None, "action": None, "followup": None, } - # Update functions for each agent def update_assessment_overview(assessment_summary: str, context_variables: dict) -> SwarmResult: - """Keep the summary as short as possible.""" context_variables["assessment"] = assessment_summary st.sidebar.success('Assessment: ' + assessment_summary) return SwarmResult(agent="action_agent", context_variables=context_variables) def update_action_overview(action_summary: str, context_variables: dict) -> SwarmResult: - """Keep the summary as short as possible.""" context_variables["action"] = action_summary st.sidebar.success('Action Plan: ' + action_summary) return SwarmResult(agent="followup_agent", context_variables=context_variables) def update_followup_overview(followup_summary: str, context_variables: dict) -> SwarmResult: - """Keep the summary as short as possible.""" context_variables["followup"] = followup_summary st.sidebar.success('Follow-up Strategy: ' + followup_summary) return SwarmResult(agent="assessment_agent", context_variables=context_variables) def update_system_message_func(agent: SwarmAgent, messages) -> str: - """""" system_prompt = system_messages[agent.name] - current_gen = agent.name.split("_")[0] + if agent._context_variables.get(current_gen) is None: system_prompt += f"Call the update function provided to first provide a 2-3 sentence summary of your ideas on {current_gen.upper()} based on the context provided." agent.llm_config['tool_choice'] = {"type": "function", "function": {"name": f"update_{current_gen}_overview"}} - agent.client = OpenAIWrapper(**agent.llm_config) else: - # remove the tools to avoid the agent from using it and reduce cost agent.llm_config["tools"] = None agent.llm_config['tool_choice'] = None - agent.client = OpenAIWrapper(**agent.llm_config) - # the agent has given a summary, now it should generate a detailed response system_prompt += f"\n\nYour task\nYou task is write the {current_gen} part of the report. Do not include any other parts. Do not use XML tags.\nStart your reponse with: '## {current_gen.capitalize()} Design'." - - # Remove all messages except the first one with less cost k = list(agent._oai_messages.keys())[-1] agent._oai_messages[k] = agent._oai_messages[k][:1] system_prompt += f"\n\n\nBelow are some context for you to refer to:" - # Add context variables to the prompt 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 state_update = UPDATE_SYSTEM_MESSAGE(update_system_message_func) - # Initialize agents assessment_agent = SwarmAgent( "assessment_agent", llm_config=llm_config, @@ -226,12 +200,10 @@ if st.button("Get Support Plan"): update_agent_state_before_reply=[state_update] ) - # Update handoffs 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)) - # Update result handling result, _, _ = initiate_swarm_chat( initial_agent=assessment_agent, agents=[assessment_agent, action_agent, followup_agent], @@ -240,14 +212,12 @@ if st.button("Get Support Plan"): max_rounds=13, ) - # Update session state with responses st.session_state.output = { 'assessment': result.chat_history[-3]['content'], 'action': result.chat_history[-2]['content'], 'followup': result.chat_history[-1]['content'] } - # Display outputs with st.expander("Situation Assessment"): st.markdown(st.session_state.output['assessment']) @@ -257,7 +227,6 @@ if st.button("Get Support Plan"): with st.expander("Long-term Support Strategy"): st.markdown(st.session_state.output['followup']) - # Display success message after completion st.success('✨ Mental health support plan generated successfully!') except Exception as e: From fc33d3a0dd28c4dfb8c2ec9dd611411af6b4c9f5 Mon Sep 17 00:00:00 2001 From: Madhu Date: Thu, 27 Feb 2025 04:20:49 +0530 Subject: [PATCH 8/9] changed the file name in readme too --- .../ai_mental_wellbeing_agent/README.md | 73 ++++++ .../ai_mental_wellbeing_agent.py | 226 ++++++++++++++++++ .../requirements.txt | 4 + 3 files changed, 303 insertions(+) create mode 100644 ai_agent_tutorials/ai_mental_wellbeing_agent/README.md create mode 100644 ai_agent_tutorials/ai_mental_wellbeing_agent/ai_mental_wellbeing_agent.py create mode 100644 ai_agent_tutorials/ai_mental_wellbeing_agent/requirements.txt diff --git a/ai_agent_tutorials/ai_mental_wellbeing_agent/README.md b/ai_agent_tutorials/ai_mental_wellbeing_agent/README.md new file mode 100644 index 0000000..a70b0bc --- /dev/null +++ b/ai_agent_tutorials/ai_mental_wellbeing_agent/README.md @@ -0,0 +1,73 @@ +# AI Mental Wellbeing Agent Team 🧠 + +The AI Mental Wellbeing Agent Team is a supportive mental health assessment and guidance system powered by [AG2](https://github.com/ag2ai/ag2?tab=readme-ov-file)(formerly AutoGen)'s AI Agent framework. This app 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. This is built on AG2's new swarm feature run through initiate_swarm_chat() method. + +## Features + +- **Specialized Mental Wellbeing Support Team** + - 🧠 **Assessment Agent**: Analyzes emotional state and psychological needs with clinical precision and empathy + - 🎯 **Action Agent**: Creates immediate action plans and connects users with appropriate resources + - 🔄 **Follow-up Agent**: Designs long-term support strategies and prevention plans + +- **Comprehensive Mental Wellbeing Support**: + - Detailed psychological assessment + - Immediate coping strategies + - Resource recommendations + - Long-term support planning + - Crisis prevention strategies + - Progress monitoring systems + +- **Customizable Input Parameters**: + - Current emotional state + - Sleep patterns + - Stress levels + - Support system information + - Recent life changes + - Current symptoms + +- **Interactive Results**: + - Real-time assessment summaries + - Detailed recommendations in expandable sections + - Clear action steps and resources + - Long-term support strategies + +## How to Run + +Follow these steps to set up and run the application: + +1. **Clone the Repository**: + ```bash + git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git + cd ai_agent_tutorials/ai_mental_wellbeing_agent + ``` + +2. **Install Dependencies**: + ```bash + pip install -r requirements.txt + ``` + +3. **Create Environment File**: + Create a `.env` file in the project directory: + ```bash + echo "AUTOGEN_USE_DOCKER=0" > .env + ``` + This disables Docker requirement for code execution in AutoGen. + +4. **Set Up OpenAI API Key**: + - Obtain an OpenAI API key from [OpenAI's platform](https://platform.openai.com) + - You'll input this key in the app's sidebar when running + +5. **Run the Streamlit App**: + ```bash + streamlit run ai_mental_wellbeing_agent.py + ``` + + +## ⚠️ Important Notice + +This 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 + diff --git a/ai_agent_tutorials/ai_mental_wellbeing_agent/ai_mental_wellbeing_agent.py b/ai_agent_tutorials/ai_mental_wellbeing_agent/ai_mental_wellbeing_agent.py new file mode 100644 index 0000000..2210743 --- /dev/null +++ b/ai_agent_tutorials/ai_mental_wellbeing_agent/ai_mental_wellbeing_agent.py @@ -0,0 +1,226 @@ +import streamlit as st +from autogen import (SwarmAgent, SwarmResult, initiate_swarm_chat, OpenAIWrapper,AFTER_WORK,UPDATE_SYSTEM_MESSAGE) +import os + +os.environ["AUTOGEN_USE_DOCKER"] = "0" + +if 'output' not in st.session_state: + st.session_state.output = { + 'assessment': '', + 'action': '', + 'followup': '' + } + +st.sidebar.title("OpenAI API Key") +api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password") + +st.sidebar.warning(""" +## ⚠️ Important Notice + +This 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 +""") + +st.title("🧠 Mental Wellbeing Agent") + +st.info(""" +**Meet Your Mental Wellbeing Agent Team:** + +🧠 **Assessment Agent** - Analyzes your situation and emotional needs +🎯 **Action Agent** - Creates immediate action plan and connects you with resources +🔄 **Follow-up Agent** - Designs your long-term support strategy +""") + +st.subheader("Personal Information") +col1, col2 = st.columns(2) + +with col1: + mental_state = st.text_area("How have you been feeling recently?", + placeholder="Describe your emotional state, thoughts, or concerns...") + sleep_pattern = st.select_slider( + "Sleep Pattern (hours per night)", + options=[f"{i}" for i in range(0, 13)], + value="7" + ) + +with col2: + stress_level = st.slider("Current Stress Level (1-10)", 1, 10, 5) + support_system = st.multiselect( + "Current Support System", + ["Family", "Friends", "Therapist", "Support Groups", "None"] + ) + +recent_changes = st.text_area( + "Any significant life changes or events recently?", + placeholder="Job changes, relationships, losses, etc..." +) + +current_symptoms = st.multiselect( + "Current Symptoms", + ["Anxiety", "Depression", "Insomnia", "Fatigue", "Loss of Interest", + "Difficulty Concentrating", "Changes in Appetite", "Social Withdrawal", + "Mood Swings", "Physical Discomfort"] +) + +if st.button("Get Support Plan"): + if not api_key: + st.error("Please enter your OpenAI API key.") + else: + with st.spinner('🤖 AI Agents are analyzing your situation...'): + try: + task = f""" + Create a comprehensive mental health support plan based on: + + Emotional State: {mental_state} + Sleep: {sleep_pattern} hours per night + Stress Level: {stress_level}/10 + Support System: {', '.join(support_system) if support_system else 'None reported'} + Recent Changes: {recent_changes} + Current Symptoms: {', '.join(current_symptoms) if current_symptoms else 'None reported'} + """ + + system_messages = { + "assessment_agent": """ + You are an experienced mental health professional speaking directly to the user. Your task is to: + 1. Create a safe space by acknowledging their courage in seeking support + 2. Analyze their emotional state with clinical precision and genuine empathy + 3. Ask targeted follow-up questions to understand their full situation + 4. Identify patterns in their thoughts, behaviors, and relationships + 5. Assess risk levels with validated screening approaches + 6. Help them understand their current mental health in accessible language + 7. Validate their experiences without minimizing or catastrophizing + + Always use "you" and "your" when addressing the user. Blend clinical expertise with genuine warmth and never rush to conclusions. + """, + + "action_agent": """ + You are a crisis intervention and resource specialist speaking directly to the user. Your task is to: + 1. Provide immediate evidence-based coping strategies tailored to their specific situation + 2. Prioritize interventions based on urgency and effectiveness + 3. Connect them with appropriate mental health services while acknowledging barriers (cost, access, stigma) + 4. Create a concrete daily wellness plan with specific times and activities + 5. Suggest specific support communities with details on how to join + 6. Balance crisis resources with empowerment techniques + 7. Teach simple self-regulation techniques they can use immediately + + Focus on practical, achievable steps that respect their current capacity and energy levels. Provide options ranging from minimal effort to more involved actions. + """, + + "followup_agent": """ + You are a mental health recovery planner speaking directly to the user. Your task is to: + 1. Design a personalized long-term support strategy with milestone markers + 2. Create a progress monitoring system that matches their preferences and habits + 3. Develop specific relapse prevention strategies based on their unique triggers + 4. Establish a support network mapping exercise to identify existing resources + 5. Build a graduated self-care routine that evolves with their recovery + 6. Plan for setbacks with self-compassion techniques + 7. Set up a maintenance schedule with clear check-in mechanisms + + Focus on building sustainable habits that integrate with their lifestyle and values. Emphasize progress over perfection and teach skills for self-directed care. + """ + } + + llm_config = { + "config_list": [{"model": "gpt-4o", "api_key": api_key}] + } + + context_variables = { + "assessment": None, + "action": None, + "followup": None, + } + + def update_assessment_overview(assessment_summary: str, context_variables: dict) -> SwarmResult: + context_variables["assessment"] = assessment_summary + st.sidebar.success('Assessment: ' + assessment_summary) + return SwarmResult(agent="action_agent", context_variables=context_variables) + + def update_action_overview(action_summary: str, context_variables: dict) -> SwarmResult: + context_variables["action"] = action_summary + st.sidebar.success('Action Plan: ' + action_summary) + return SwarmResult(agent="followup_agent", context_variables=context_variables) + + def update_followup_overview(followup_summary: str, context_variables: dict) -> SwarmResult: + context_variables["followup"] = followup_summary + st.sidebar.success('Follow-up Strategy: ' + followup_summary) + return SwarmResult(agent="assessment_agent", context_variables=context_variables) + + def update_system_message_func(agent: SwarmAgent, messages) -> str: + system_prompt = system_messages[agent.name] + current_gen = agent.name.split("_")[0] + + if agent._context_variables.get(current_gen) is None: + system_prompt += f"Call the update function provided to first provide a 2-3 sentence summary of your ideas on {current_gen.upper()} based on the context provided." + agent.llm_config['tool_choice'] = {"type": "function", "function": {"name": f"update_{current_gen}_overview"}} + else: + agent.llm_config["tools"] = None + agent.llm_config['tool_choice'] = None + system_prompt += f"\n\nYour task\nYou task is write the {current_gen} part of the report. Do not include any other parts. Do not use XML tags.\nStart your reponse with: '## {current_gen.capitalize()} Design'." + k = list(agent._oai_messages.keys())[-1] + agent._oai_messages[k] = agent._oai_messages[k][:1] + + system_prompt += f"\n\n\nBelow are some context for you to refer to:" + 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 + + state_update = UPDATE_SYSTEM_MESSAGE(update_system_message_func) + + assessment_agent = SwarmAgent( + "assessment_agent", + llm_config=llm_config, + functions=update_assessment_overview, + update_agent_state_before_reply=[state_update] + ) + + action_agent = SwarmAgent( + "action_agent", + llm_config=llm_config, + functions=update_action_overview, + update_agent_state_before_reply=[state_update] + ) + + followup_agent = SwarmAgent( + "followup_agent", + llm_config=llm_config, + functions=update_followup_overview, + update_agent_state_before_reply=[state_update] + ) + + 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)) + + result, _, _ = initiate_swarm_chat( + initial_agent=assessment_agent, + agents=[assessment_agent, action_agent, followup_agent], + user_agent=None, + messages=task, + max_rounds=13, + ) + + st.session_state.output = { + 'assessment': result.chat_history[-3]['content'], + 'action': result.chat_history[-2]['content'], + 'followup': result.chat_history[-1]['content'] + } + + with st.expander("Situation Assessment"): + st.markdown(st.session_state.output['assessment']) + + with st.expander("Action Plan & Resources"): + st.markdown(st.session_state.output['action']) + + with st.expander("Long-term Support Strategy"): + st.markdown(st.session_state.output['followup']) + + st.success('✨ Mental health support plan generated successfully!') + + except Exception as e: + st.error(f"An error occurred: {str(e)}") diff --git a/ai_agent_tutorials/ai_mental_wellbeing_agent/requirements.txt b/ai_agent_tutorials/ai_mental_wellbeing_agent/requirements.txt new file mode 100644 index 0000000..da4c21a --- /dev/null +++ b/ai_agent_tutorials/ai_mental_wellbeing_agent/requirements.txt @@ -0,0 +1,4 @@ +autogen-agentchat +autogen-ext +pyautogen +streamlit \ No newline at end of file From 9780cf759854af89cdbb25f19fcf388b638ddc65 Mon Sep 17 00:00:00 2001 From: Madhu Date: Thu, 27 Feb 2025 04:23:08 +0530 Subject: [PATCH 9/9] deleted them --- .../ai_mental_health_crisis_agent/README.md | 73 ------ .../ai_mental_health_crisis_agent.py | 233 ------------------ .../requirements.txt | 4 - 3 files changed, 310 deletions(-) delete mode 100644 ai_agent_tutorials/ai_mental_health_crisis_agent/README.md delete mode 100644 ai_agent_tutorials/ai_mental_health_crisis_agent/ai_mental_health_crisis_agent.py delete mode 100644 ai_agent_tutorials/ai_mental_health_crisis_agent/requirements.txt diff --git a/ai_agent_tutorials/ai_mental_health_crisis_agent/README.md b/ai_agent_tutorials/ai_mental_health_crisis_agent/README.md deleted file mode 100644 index 755f299..0000000 --- a/ai_agent_tutorials/ai_mental_health_crisis_agent/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# AI Mental Health Crisis Navigator 🧠 - -The AI Mental Health Crisis Navigator is a supportive mental health assessment and guidance system powered by [AG2](https://github.com/ag2ai/ag2?tab=readme-ov-file)(formerly AutoGen)'s AI Agent framework. This app 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. This is built on AG2's new swarm feature run through initiate_swarm_chat() method. - -## Features - -- **Specialized Mental Health Support Team** - - 🧠 **Assessment Agent**: Analyzes emotional state and psychological needs with clinical precision and empathy - - 🎯 **Action Agent**: Creates immediate action plans and connects users with appropriate resources - - 🔄 **Follow-up Agent**: Designs long-term support strategies and prevention plans - -- **Comprehensive Mental Health Support**: - - Detailed psychological assessment - - Immediate coping strategies - - Resource recommendations - - Long-term support planning - - Crisis prevention strategies - - Progress monitoring systems - -- **Customizable Input Parameters**: - - Current emotional state - - Sleep patterns - - Stress levels - - Support system information - - Recent life changes - - Current symptoms - -- **Interactive Results**: - - Real-time assessment summaries - - Detailed recommendations in expandable sections - - Clear action steps and resources - - Long-term support strategies - -## How to Run - -Follow these steps to set up and run the application: - -1. **Clone the Repository**: - ```bash - git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git - cd ai_agent_tutorials/ai_mental_health_crisis_agent - ``` - -2. **Install Dependencies**: - ```bash - pip install -r requirements.txt - ``` - -3. **Create Environment File**: - Create a `.env` file in the project directory: - ```bash - echo "AUTOGEN_USE_DOCKER=0" > .env - ``` - This disables Docker requirement for code execution in AutoGen. - -4. **Set Up OpenAI API Key**: - - Obtain an OpenAI API key from [OpenAI's platform](https://platform.openai.com) - - You'll input this key in the app's sidebar when running - -5. **Run the Streamlit App**: - ```bash - streamlit run ai_mental_health_crisis_agent.py - ``` - - -## ⚠️ Important Notice - -This 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 - diff --git a/ai_agent_tutorials/ai_mental_health_crisis_agent/ai_mental_health_crisis_agent.py b/ai_agent_tutorials/ai_mental_health_crisis_agent/ai_mental_health_crisis_agent.py deleted file mode 100644 index 54d95ec..0000000 --- a/ai_agent_tutorials/ai_mental_health_crisis_agent/ai_mental_health_crisis_agent.py +++ /dev/null @@ -1,233 +0,0 @@ -import streamlit as st -from autogen import ( - SwarmAgent, - SwarmResult, - initiate_swarm_chat, - OpenAIWrapper, - AFTER_WORK, - UPDATE_SYSTEM_MESSAGE -) -import os - -os.environ["AUTOGEN_USE_DOCKER"] = "0" - -if 'output' not in st.session_state: - st.session_state.output = { - 'assessment': '', - 'action': '', - 'followup': '' - } - -st.sidebar.title("OpenAI API Key") -api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password") - -st.sidebar.warning(""" -## ⚠️ Important Notice - -This 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 -""") - -st.title("🧠 Mental Health Crisis Navigator") - -st.info(""" -**Meet Your Mental Health Support Team:** - -🧠 **Assessment Agent** - Analyzes your situation and emotional needs -🎯 **Action Agent** - Creates immediate action plan and connects you with resources -🔄 **Follow-up Agent** - Designs your long-term support strategy -""") - -st.subheader("Personal Information") -col1, col2 = st.columns(2) - -with col1: - mental_state = st.text_area("How have you been feeling recently?", - placeholder="Describe your emotional state, thoughts, or concerns...") - sleep_pattern = st.select_slider( - "Sleep Pattern (hours per night)", - options=[f"{i}" for i in range(0, 13)], - value="7" - ) - -with col2: - stress_level = st.slider("Current Stress Level (1-10)", 1, 10, 5) - support_system = st.multiselect( - "Current Support System", - ["Family", "Friends", "Therapist", "Support Groups", "None"] - ) - -recent_changes = st.text_area( - "Any significant life changes or events recently?", - placeholder="Job changes, relationships, losses, etc..." -) - -current_symptoms = st.multiselect( - "Current Symptoms", - ["Anxiety", "Depression", "Insomnia", "Fatigue", "Loss of Interest", - "Difficulty Concentrating", "Changes in Appetite", "Social Withdrawal", - "Mood Swings", "Physical Discomfort"] -) - -if st.button("Get Support Plan"): - if not api_key: - st.error("Please enter your OpenAI API key.") - else: - with st.spinner('🤖 AI Agents are analyzing your situation...'): - try: - task = f""" - Create a comprehensive mental health support plan based on: - - Emotional State: {mental_state} - Sleep: {sleep_pattern} hours per night - Stress Level: {stress_level}/10 - Support System: {', '.join(support_system) if support_system else 'None reported'} - Recent Changes: {recent_changes} - Current Symptoms: {', '.join(current_symptoms) if current_symptoms else 'None reported'} - """ - - system_messages = { - "assessment_agent": """ - You are an experienced mental health professional speaking directly to the user. Your task is to: - 1. Create a safe space by acknowledging their courage in seeking support - 2. Analyze their emotional state with clinical precision and genuine empathy - 3. Ask targeted follow-up questions to understand their full situation - 4. Identify patterns in their thoughts, behaviors, and relationships - 5. Assess risk levels with validated screening approaches - 6. Help them understand their current mental health in accessible language - 7. Validate their experiences without minimizing or catastrophizing - - Always use "you" and "your" when addressing the user. Blend clinical expertise with genuine warmth and never rush to conclusions. - """, - - "action_agent": """ - You are a crisis intervention and resource specialist speaking directly to the user. Your task is to: - 1. Provide immediate evidence-based coping strategies tailored to their specific situation - 2. Prioritize interventions based on urgency and effectiveness - 3. Connect them with appropriate mental health services while acknowledging barriers (cost, access, stigma) - 4. Create a concrete daily wellness plan with specific times and activities - 5. Suggest specific support communities with details on how to join - 6. Balance crisis resources with empowerment techniques - 7. Teach simple self-regulation techniques they can use immediately - - Focus on practical, achievable steps that respect their current capacity and energy levels. Provide options ranging from minimal effort to more involved actions. - """, - - "followup_agent": """ - You are a mental health recovery planner speaking directly to the user. Your task is to: - 1. Design a personalized long-term support strategy with milestone markers - 2. Create a progress monitoring system that matches their preferences and habits - 3. Develop specific relapse prevention strategies based on their unique triggers - 4. Establish a support network mapping exercise to identify existing resources - 5. Build a graduated self-care routine that evolves with their recovery - 6. Plan for setbacks with self-compassion techniques - 7. Set up a maintenance schedule with clear check-in mechanisms - - Focus on building sustainable habits that integrate with their lifestyle and values. Emphasize progress over perfection and teach skills for self-directed care. - """ - } - - llm_config = { - "config_list": [{"model": "gpt-4o", "api_key": api_key}] - } - - context_variables = { - "assessment": None, - "action": None, - "followup": None, - } - - def update_assessment_overview(assessment_summary: str, context_variables: dict) -> SwarmResult: - context_variables["assessment"] = assessment_summary - st.sidebar.success('Assessment: ' + assessment_summary) - return SwarmResult(agent="action_agent", context_variables=context_variables) - - def update_action_overview(action_summary: str, context_variables: dict) -> SwarmResult: - context_variables["action"] = action_summary - st.sidebar.success('Action Plan: ' + action_summary) - return SwarmResult(agent="followup_agent", context_variables=context_variables) - - def update_followup_overview(followup_summary: str, context_variables: dict) -> SwarmResult: - context_variables["followup"] = followup_summary - st.sidebar.success('Follow-up Strategy: ' + followup_summary) - return SwarmResult(agent="assessment_agent", context_variables=context_variables) - - def update_system_message_func(agent: SwarmAgent, messages) -> str: - system_prompt = system_messages[agent.name] - current_gen = agent.name.split("_")[0] - - if agent._context_variables.get(current_gen) is None: - system_prompt += f"Call the update function provided to first provide a 2-3 sentence summary of your ideas on {current_gen.upper()} based on the context provided." - agent.llm_config['tool_choice'] = {"type": "function", "function": {"name": f"update_{current_gen}_overview"}} - else: - agent.llm_config["tools"] = None - agent.llm_config['tool_choice'] = None - system_prompt += f"\n\nYour task\nYou task is write the {current_gen} part of the report. Do not include any other parts. Do not use XML tags.\nStart your reponse with: '## {current_gen.capitalize()} Design'." - k = list(agent._oai_messages.keys())[-1] - agent._oai_messages[k] = agent._oai_messages[k][:1] - - system_prompt += f"\n\n\nBelow are some context for you to refer to:" - 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 - - state_update = UPDATE_SYSTEM_MESSAGE(update_system_message_func) - - assessment_agent = SwarmAgent( - "assessment_agent", - llm_config=llm_config, - functions=update_assessment_overview, - update_agent_state_before_reply=[state_update] - ) - - action_agent = SwarmAgent( - "action_agent", - llm_config=llm_config, - functions=update_action_overview, - update_agent_state_before_reply=[state_update] - ) - - followup_agent = SwarmAgent( - "followup_agent", - llm_config=llm_config, - functions=update_followup_overview, - update_agent_state_before_reply=[state_update] - ) - - 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)) - - result, _, _ = initiate_swarm_chat( - initial_agent=assessment_agent, - agents=[assessment_agent, action_agent, followup_agent], - user_agent=None, - messages=task, - max_rounds=13, - ) - - st.session_state.output = { - 'assessment': result.chat_history[-3]['content'], - 'action': result.chat_history[-2]['content'], - 'followup': result.chat_history[-1]['content'] - } - - with st.expander("Situation Assessment"): - st.markdown(st.session_state.output['assessment']) - - with st.expander("Action Plan & Resources"): - st.markdown(st.session_state.output['action']) - - with st.expander("Long-term Support Strategy"): - st.markdown(st.session_state.output['followup']) - - st.success('✨ Mental health support plan generated successfully!') - - except Exception as e: - st.error(f"An error occurred: {str(e)}") diff --git a/ai_agent_tutorials/ai_mental_health_crisis_agent/requirements.txt b/ai_agent_tutorials/ai_mental_health_crisis_agent/requirements.txt deleted file mode 100644 index da4c21a..0000000 --- a/ai_agent_tutorials/ai_mental_health_crisis_agent/requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -autogen-agentchat -autogen-ext -pyautogen -streamlit \ No newline at end of file