Spaces:
Build error

MentaHealthChat / src /app.py
fazilvk's picture
Update src/app.py
0ba9ef3 verified
Raw History Blame Contribute Delete
3.2 kB
import streamlit as st
from dotenv import load_dotenv
import os
import predibase as pb
# Load environment variables
load_dotenv()
def load_environment():
"""Load environment variables and initialize clients"""
api_key = os.getenv("PREDIBASE_API_KEY")
if not api_key:
st.error("Missing API key. Please check your .env file.")
st.stop()
client = pb.Predibase(api_token=api_key)
model_client = client.deployments.client("llama-3-1-8b-instruct")
return model_client
def get_ai_response(client, user_message, max_tokens=350):
"""Get response from the AI model"""
try:
input_prompt = f"<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\n You are a helpful mental health counselling assistant, please answer the mental health questions based on the patient's description. The assistant gives helpful, comprehensive, and appropriate answers to the user's questions. <|eot_id|><|start_header_id|>user<|end_header_id|>\n\n {user_message} <|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
result = client.generate(
prompt=input_prompt,
adapter_id="mental-health-model/1",
max_new_tokens=max_tokens,
temperature=0.3
)
return result.generated_text or "I'm sorry, I couldn't generate a response."
except Exception as e:
return f"I apologize, but there was an error: {str(e)}"
def main():
# Set up Streamlit interface
st.title("")
header = st.container()
header.title("AI Mental Health Assistant")
header.write("""<div class='fixed-header'/>""", unsafe_allow_html=True)
# Initialize session state
if 'messages' not in st.session_state:
st.session_state.messages = []
if 'client' not in st.session_state:
st.session_state.client = load_environment()
# Display previous messages
for message in st.session_state.messages:
role = message["role"]
content = message["content"]
with st.chat_message(role):
st.write(content)
# Get user input
user_input = st.chat_input("Your question:")
# Process user input
if user_input:
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": user_input})
# Display user message
with st.chat_message("user"):
st.write(user_input)
# Display AI response with loading indicator
with st.chat_message("assistant"):
# Add a placeholder for the response
message_placeholder = st.empty()
# Show loading indicator while processing
with message_placeholder:
st.write("Thinking...")
# Get AI response
response = get_ai_response(st.session_state.client, user_input)
# Replace loading indicator with actual response
message_placeholder.markdown(response)
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": response})
if __name__ == "__main__":
main()