File size: 2,417 Bytes
ce077f3 4a3dc90 ed5cfb3 4a3dc90 ce077f3 4a3dc90 ed5cfb3 4a3dc90 ed5cfb3 4a3dc90 64309e6 ed5cfb3 4a3dc90 64309e6 ed5cfb3 4a3dc90 ce077f3 ed5cfb3 | 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 62 63 64 65 | 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() |