import gradio as gr import google.generativeai as genai import os from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() # Configure Gemini API API_KEY = os.getenv("GOOGLE_API_KEY") # Ensure this is set in your Hugging Face Spaces secrets genai.configure(api_key=API_KEY) model = genai.GenerativeModel("gemini-2.0-flash") chat = model.start_chat() # Send initial instruction to the model initial_message = ( "Hey, I'm using you as a therapist to help people who are feeling sad feel better. " "I want you to improve the user's mental health and make them feel good about themselves, " "sort of like a supportive friend. Keep your responses short, concise, and make them feel like they matter. " "Do not directly guide them to a suicide prevention hotline, as it will be mentioned on my website already. " "Just be there to listen. Start the conversation by saying 'Hi, how are you doing today?'" ) chat.send_message(initial_message) # Chat function for Gradio def chat_function(message, history): # Initialize history as a list of messages if empty if not history: history = [] # Rebuild Gemini conversation history # Clear previous history to avoid duplication (Gemini maintains its own history) chat.history = [] # Reset Gemini chat history chat.send_message(initial_message) # Resend initial instruction # Send all previous messages from Gradio history to Gemini for msg in history: role = msg["role"] content = msg["content"] chat.send_message(content) # Gemini doesn't need role, just content # Send the current user message response = chat.send_message(message) # Return the user message and assistant response in the messages format return [ {"role": "user", "content": message}, {"role": "assistant", "content": response.text} ] # Create Gradio interface with gr.Blocks() as demo: gr.Markdown("# Voice: Your Supportive Chatbot") gr.Markdown("I'm here to listen and help you feel better. You matter!") chatbot = gr.ChatInterface( fn=chat_function, chatbot=gr.Chatbot(height=500, show_copy_button=True, type="messages"), title="Chat with VoiceAI", description="A supportive chatbot to lift your spirits.", submit_btn="Send" ) # Launch the app if __name__ == "__main__": demo.launch()