Spaces:
Sleeping
Sleeping
File size: 2,750 Bytes
d8c4e2c 1bb900a d8c4e2c 1bb900a 89d1f2e 5224379 f17f7ed 3e49695 1bb900a 3e49695 1bb900a 4764087 1bb900a f17f7ed 3e49695 1bb900a 536669c 3e49695 536669c 3e49695 1bb900a ca8e9d0 1bb900a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | import os
import streamlit as st
import google.generativeai as genai
# Access the API key as an environment variable from Hugging Face secrets.
# Then, configure the official Gemini client with the API key.
api_key = os.getenv("MentalHealth")
genai.configure(api_key=api_key)
if "messages" not in st.session_state:
# Initialize the session state for the chat history
st.session_state.messages = []
# Gemini models have different roles, so we use 'user' and 'model'.
# A system message is not directly supported, so we will handle the persona
# in the prompt or in the response generation logic.
for message in st.session_state.messages:
# Display existing messages from the session state
with st.chat_message(message["role"]):
st.markdown(message["parts"][0])
if prompt := st.chat_input("Type your thoughts here..."):
# Append the user's message to the chat history and display it
user_message = {"role": "user", "parts": [prompt]}
st.session_state.messages.append(user_message)
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
with st.spinner("Thinking..."):
# Prepare the list of messages for the Gemini model.
# We add a preamble to maintain the therapist persona.
chat_history_for_gemini = [
{"role": "user", "parts": ["You are a supportive therapist AI. All your responses should be in this persona."]},
{"role": "model", "parts": ["Understood. I will respond as a supportive therapist."]}
] + st.session_state.messages
# Initialize the model and generate a response
model = genai.GenerativeModel('gemini-1.5-flash-latest')
try:
# Use the new API syntax to create a completion.
# The model automatically handles the chat history.
response = model.generate_content(chat_history_for_gemini, stream=True)
full_reply_content = ""
# Stream the response to the screen for a better user experience.
for chunk in response:
# Check if the chunk has text before adding it to the reply.
if chunk.text:
full_reply_content += chunk.text
st.markdown(full_reply_content)
except Exception as e:
full_reply_content = f"An error occurred: {e}"
st.markdown(full_reply_content)
# Append the assistant's full response to the session state
assistant_message = {"role": "model", "parts": [full_reply_content]}
st.session_state.messages.append(assistant_message) |