removed unnecessary imports and code

This commit is contained in:
Madhu 2025-02-20 07:39:23 +05:30
parent 979d99ef43
commit d0f33b3edc

View file

@ -1,4 +1,3 @@
import asyncio
import streamlit as st import streamlit as st
from autogen import ( from autogen import (
SwarmAgent, SwarmAgent,
@ -10,22 +9,18 @@ from autogen import (
) )
import os import os
# Add this at the top of the file, before any other code
os.environ["AUTOGEN_USE_DOCKER"] = "0" os.environ["AUTOGEN_USE_DOCKER"] = "0"
# Initialize session state with 3 key components
if 'output' not in st.session_state: if 'output' not in st.session_state:
st.session_state.output = { st.session_state.output = {
'assessment': '', # Combined psychology/analysis 'assessment': '',
'action': '', # Immediate actions and resources 'action': '',
'followup': '' # Long-term planning 'followup': ''
} }
# Sidebar for API key input
st.sidebar.title("OpenAI API Key") st.sidebar.title("OpenAI API Key")
api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password") api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password")
# Add privacy notice in sidebar
st.sidebar.warning(""" st.sidebar.warning("""
## ⚠️ Important Notice ## ⚠️ Important Notice
@ -36,10 +31,8 @@ This application is a supportive tool and does not replace professional mental h
- Seek immediate professional help - Seek immediate professional help
""") """)
# Main app UI
st.title("🧠 Mental Health Crisis Navigator") st.title("🧠 Mental Health Crisis Navigator")
# Update UI description
st.info(""" st.info("""
**Meet Your Mental Health Support Team:** **Meet Your Mental Health Support Team:**
@ -48,7 +41,6 @@ st.info("""
🔄 **Follow-up Agent** - Designs your long-term support strategy 🔄 **Follow-up Agent** - Designs your long-term support strategy
""") """)
# User inputs
st.subheader("Personal Information") st.subheader("Personal Information")
col1, col2 = st.columns(2) col1, col2 = st.columns(2)
@ -68,7 +60,6 @@ with col2:
["Family", "Friends", "Therapist", "Support Groups", "None"] ["Family", "Friends", "Therapist", "Support Groups", "None"]
) )
# Additional context
recent_changes = st.text_area( recent_changes = st.text_area(
"Any significant life changes or events recently?", "Any significant life changes or events recently?",
placeholder="Job changes, relationships, losses, etc..." placeholder="Job changes, relationships, losses, etc..."
@ -81,8 +72,6 @@ current_symptoms = st.multiselect(
"Mood Swings", "Physical Discomfort"] "Mood Swings", "Physical Discomfort"]
) )
# Button to start the agent collaboration
if st.button("Get Support Plan"): if st.button("Get Support Plan"):
if not api_key: if not api_key:
st.error("Please enter your OpenAI 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'} Current Symptoms: {', '.join(current_symptoms) if current_symptoms else 'None reported'}
""" """
# Update system messages for 3 agents
system_messages = { system_messages = {
"assessment_agent": """ "assessment_agent": """
You are an experienced mental health professional speaking directly to the user. Your task is to: 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 = { llm_config = {
"config_list": [{"model": "gpt-4o", "api_key": api_key}] "config_list": [{"model": "gpt-4o", "api_key": api_key}]
} }
# Context management for agent communication
context_variables = { context_variables = {
"assessment": None, "assessment": None,
"action": None, "action": None,
"followup": None, "followup": None,
} }
# Update functions for each agent
def update_assessment_overview(assessment_summary: str, context_variables: dict) -> SwarmResult: def update_assessment_overview(assessment_summary: str, context_variables: dict) -> SwarmResult:
"""Keep the summary as short as possible."""
context_variables["assessment"] = assessment_summary context_variables["assessment"] = assessment_summary
st.sidebar.success('Assessment: ' + assessment_summary) st.sidebar.success('Assessment: ' + assessment_summary)
return SwarmResult(agent="action_agent", context_variables=context_variables) return SwarmResult(agent="action_agent", context_variables=context_variables)
def update_action_overview(action_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["action"] = action_summary context_variables["action"] = action_summary
st.sidebar.success('Action Plan: ' + action_summary) st.sidebar.success('Action Plan: ' + action_summary)
return SwarmResult(agent="followup_agent", context_variables=context_variables) return SwarmResult(agent="followup_agent", context_variables=context_variables)
def update_followup_overview(followup_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["followup"] = followup_summary context_variables["followup"] = followup_summary
st.sidebar.success('Follow-up Strategy: ' + followup_summary) st.sidebar.success('Follow-up Strategy: ' + followup_summary)
return SwarmResult(agent="assessment_agent", context_variables=context_variables) return SwarmResult(agent="assessment_agent", context_variables=context_variables)
def update_system_message_func(agent: SwarmAgent, messages) -> str: def update_system_message_func(agent: SwarmAgent, messages) -> str:
""""""
system_prompt = system_messages[agent.name] system_prompt = system_messages[agent.name]
current_gen = agent.name.split("_")[0] current_gen = agent.name.split("_")[0]
if agent._context_variables.get(current_gen) is None: 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." 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.llm_config['tool_choice'] = {"type": "function", "function": {"name": f"update_{current_gen}_overview"}}
agent.client = OpenAIWrapper(**agent.llm_config)
else: else:
# remove the tools to avoid the agent from using it and reduce cost
agent.llm_config["tools"] = None agent.llm_config["tools"] = None
agent.llm_config['tool_choice'] = 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'." 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] k = list(agent._oai_messages.keys())[-1]
agent._oai_messages[k] = agent._oai_messages[k][:1] agent._oai_messages[k] = agent._oai_messages[k][:1]
system_prompt += f"\n\n\nBelow are some context for you to refer to:" 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(): for k, v in agent._context_variables.items():
if v is not None: if v is not None:
system_prompt += f"\n{k.capitalize()} Summary:\n{v}" system_prompt += f"\n{k.capitalize()} Summary:\n{v}"
agent.client = OpenAIWrapper(**agent.llm_config)
return system_prompt return system_prompt
state_update = UPDATE_SYSTEM_MESSAGE(update_system_message_func) state_update = UPDATE_SYSTEM_MESSAGE(update_system_message_func)
# Initialize agents
assessment_agent = SwarmAgent( assessment_agent = SwarmAgent(
"assessment_agent", "assessment_agent",
llm_config=llm_config, llm_config=llm_config,
@ -226,12 +200,10 @@ if st.button("Get Support Plan"):
update_agent_state_before_reply=[state_update] update_agent_state_before_reply=[state_update]
) )
# Update handoffs
assessment_agent.register_hand_off(AFTER_WORK(action_agent)) assessment_agent.register_hand_off(AFTER_WORK(action_agent))
action_agent.register_hand_off(AFTER_WORK(followup_agent)) action_agent.register_hand_off(AFTER_WORK(followup_agent))
followup_agent.register_hand_off(AFTER_WORK(assessment_agent)) followup_agent.register_hand_off(AFTER_WORK(assessment_agent))
# Update result handling
result, _, _ = initiate_swarm_chat( result, _, _ = initiate_swarm_chat(
initial_agent=assessment_agent, initial_agent=assessment_agent,
agents=[assessment_agent, action_agent, followup_agent], agents=[assessment_agent, action_agent, followup_agent],
@ -240,14 +212,12 @@ if st.button("Get Support Plan"):
max_rounds=13, max_rounds=13,
) )
# Update session state with responses
st.session_state.output = { st.session_state.output = {
'assessment': result.chat_history[-3]['content'], 'assessment': result.chat_history[-3]['content'],
'action': result.chat_history[-2]['content'], 'action': result.chat_history[-2]['content'],
'followup': result.chat_history[-1]['content'] 'followup': result.chat_history[-1]['content']
} }
# Display outputs
with st.expander("Situation Assessment"): with st.expander("Situation Assessment"):
st.markdown(st.session_state.output['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"): with st.expander("Long-term Support Strategy"):
st.markdown(st.session_state.output['followup']) st.markdown(st.session_state.output['followup'])
# Display success message after completion
st.success('✨ Mental health support plan generated successfully!') st.success('✨ Mental health support plan generated successfully!')
except Exception as e: except Exception as e: