|
import os |
|
import gradio as gr |
|
from langchain.chat_models import ChatOpenAI |
|
from langchain.chains import LLMChain |
|
from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, SystemMessagePromptTemplate |
|
import tempfile |
|
from gtts import gTTS |
|
|
|
|
|
os.environ["OPENAI_API_KEY"] = os.environ.get("OPENAI_API_KEY") |
|
|
|
|
|
def load_mental_health_resources(): |
|
with open("mental-health-crisis-strategies.md", "r") as file: |
|
content = file.read() |
|
|
|
sections = content.split('\n\n') |
|
structured_content = { |
|
"Crisis Overview": sections[1], |
|
"Principles and Characteristics": sections[2], |
|
"Process of Crisis Intervention": sections[3], |
|
"6-Step Model": sections[4], |
|
"Assessment in Crisis Intervention": sections[5], |
|
"ABC's of Assessment": sections[6], |
|
"Strategies of Crisis Intervention": sections[7], |
|
"Conditions for Client Growth": sections[8], |
|
"Suicide Assessment": sections[9], |
|
"Creating a Safety Plan": sections[10], |
|
"Culturally Sensitive Approaches": sections[11:14], |
|
"Enhancing Crisis Intervention": sections[14], |
|
"Wrap-Up": sections[15] |
|
} |
|
|
|
return structured_content |
|
|
|
mental_health_resources = load_mental_health_resources() |
|
|
|
|
|
system_template = """ |
|
You are an empathetic and supportive mental health chatbot specialized in crisis intervention. Your goal is to understand the user's situation and provide appropriate support based on established crisis intervention strategies. Use the following guidelines and resources to inform your responses: |
|
|
|
Mental Health Crisis Intervention Strategies: |
|
{mental_health_info} |
|
|
|
When responding to users: |
|
1. Assess the severity of the situation using the ABC's of Assessment (Affective state, Behavioural functioning, Cognitive state). |
|
2. Use the 6-Step Model of Crisis Intervention as a guide for your interaction: 1) Define the problem, 2) Ensure client safety, 3) Provide support, 4) Examine alternatives, 5) Make plans, 6) Obtain commitment. |
|
3. Incorporate relevant strategies from the Strategies of Crisis Intervention section, adapting them into conversational language. |
|
4. Be mindful of cultural sensitivities as outlined in the Culturally Sensitive Approaches section. |
|
5. If suicide risk is detected, use guidelines from the Suicide Assessment and Creating a Safety Plan sections. |
|
6. Always prioritize client safety and encourage professional help when needed. |
|
|
|
Customize your approach based on the severity of the crisis: |
|
- Low Severity: Focus on coping strategies and emotional support. |
|
- Medium Severity: Emphasize problem-solving and resource connection. |
|
- High Severity: Prioritize safety planning and immediate professional intervention. |
|
|
|
Follow these guidelines in your interactions: |
|
1. For the first 2-3 exchanges, focus on understanding the user's situation by asking open-ended questions. |
|
2. After initial exchanges, transition to providing support and gentle suggestions based on what you've learned. |
|
3. Always be empathetic and acknowledge the user's feelings. |
|
4. Offer coping strategies or advice that are relevant to the user's specific situation, drawing from the provided resources. |
|
5. Periodically check in on the user's emotional state to gauge any changes in distress levels. |
|
6. Be flexible - if the user introduces a new topic or concern, be ready to explore that. |
|
7. If you suspect the user is in immediate danger, strongly encourage them to seek professional help or emergency services. |
|
8. Regularly provide information about professional resources or hotlines, ensuring users are aware of additional support options. |
|
|
|
Remember to keep the tone warm, supportive, and non-judgmental throughout. |
|
|
|
Chat History: |
|
{chat_history} |
|
|
|
Current conversation stage: {stage} |
|
(Stages: initial_assessment, problem_definition, safety_check, support_provision, alternative_exploration, plan_making, commitment_obtaining, follow_up) |
|
|
|
Severity level: {severity} |
|
(Levels: low, medium, high) |
|
""" |
|
|
|
human_template = "{user_input}" |
|
|
|
system_message_prompt = SystemMessagePromptTemplate.from_template(system_template) |
|
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template) |
|
|
|
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) |
|
|
|
|
|
def setup_chatbot_chain(): |
|
llm = ChatOpenAI(temperature=0.7, model_name="gpt-4-turbo") |
|
return LLMChain(llm=llm, prompt=chat_prompt) |
|
|
|
chatbot_chain = setup_chatbot_chain() |
|
|
|
def respond(message, history, stage, severity): |
|
chat_history = "\n".join([f"Human: {h[0]}\nAI: {h[1]}" for h in history]) |
|
|
|
response = chatbot_chain.run( |
|
user_input=message, |
|
mental_health_info=mental_health_resources, |
|
chat_history=chat_history, |
|
stage=stage, |
|
severity=severity |
|
) |
|
|
|
|
|
new_stage = "support_provision" if stage == "initial_assessment" else "follow_up" |
|
new_severity = severity |
|
|
|
return response, new_stage, new_severity |
|
|
|
def text_to_speech(text): |
|
tts = gTTS(text=text, lang='en') |
|
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as fp: |
|
tts.save(fp.name) |
|
return fp.name |
|
|
|
css = """ |
|
.chatbot-header { |
|
display: flex; |
|
align-items: center; |
|
justify-content: center; |
|
margin-bottom: 20px; |
|
} |
|
.chatbot-title { |
|
font-size: 24px; |
|
margin: 0; |
|
padding: 0; |
|
} |
|
.heart-logo { |
|
font-size: 28px; |
|
margin-right: 10px; |
|
} |
|
""" |
|
|
|
with gr.Blocks(css=css) as demo: |
|
gr.HTML( |
|
""" |
|
<div class="chatbot-header"> |
|
<span class="heart-logo">❤️</span> |
|
<h1 class="chatbot-title">Mental Health Crisis Support Chatbot</h1> |
|
</div> |
|
""" |
|
) |
|
gr.Markdown("I'm here to listen and provide support during difficult times. How are you feeling today?") |
|
|
|
chatbot = gr.Chatbot() |
|
msg = gr.Textbox() |
|
submit_button = gr.Button("Submit") |
|
clear = gr.Button("Clear") |
|
state = gr.State("initial_assessment") |
|
severity = gr.State("low") |
|
audio_output = gr.Audio(label="Response Audio", autoplay=True) |
|
|
|
def user(user_message, history, stage, severity): |
|
return "", history + [[user_message, None]], stage, severity |
|
|
|
def bot(history, stage, severity): |
|
bot_message, new_stage, new_severity = respond(history[-1][0], history[:-1], stage, severity) |
|
history[-1][1] = bot_message |
|
|
|
audio_file = text_to_speech(bot_message) |
|
|
|
return history, new_stage, new_severity, audio_file |
|
|
|
msg.submit(user, [msg, chatbot, state, severity], [msg, chatbot, state, severity], queue=False).then( |
|
bot, [chatbot, state, severity], [chatbot, state, severity, audio_output] |
|
) |
|
submit_button.click(user, [msg, chatbot, state, severity], [msg, chatbot, state, severity], queue=False).then( |
|
bot, [chatbot, state, severity], [chatbot, state, severity, audio_output] |
|
) |
|
clear.click(lambda: ([], "initial_assessment", "low", None), None, [chatbot, state, severity, audio_output], queue=False) |
|
|
|
gr.Examples( |
|
examples=[ |
|
"I'm feeling overwhelmed and don't know what to do", |
|
"I'm having thoughts of hurting myself", |
|
"I'm worried about a friend who seems depressed", |
|
"I'm struggling to cope with a recent loss" |
|
], |
|
inputs=msg |
|
) |
|
|
|
gr.Markdown( |
|
""" |
|
**Disclaimer:** This chatbot is for informational purposes only and is not a substitute for professional medical advice, |
|
diagnosis, or treatment. If you're experiencing a mental health emergency, please call your local emergency services or |
|
a mental health crisis hotline immediately. |
|
""" |
|
) |
|
|
|
if __name__ == "__main__": |
|
demo.launch() |