import gradio as gr import requests import json import os from datetime import datetime class RoleBasedChat: def __init__(self): self.conversation_history = [] self.current_role = None self.api_key = os.getenv("GEMINI_API_KEY") self.api_url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent" # Role-specific prompts self.role_prompts = { "Mom ๐ฉโ๐งโ๐ฆ": { "system_prompt": """You are a loving and caring mother. Respond with warmth, patience, and understanding. Give practical advice while showing concern for your child's wellbeing. Use a nurturing tone and always prioritize their happiness and safety. Show motherly care in every response.""", "emoji": "๐ค" }, "Dad ๐จโ๐งโ๐ฆ": { "system_prompt": """You are a wise and supportive father. Provide practical solutions, motivation, and confidence-building advice. Use a slightly serious but caring tone. Share life lessons and help build character. Be the strong pillar of support.""", "emoji": "๐ช" }, "Big Brother ๐ฆ": { "system_prompt": """You are a cool and understanding big brother. Use casual language, make jokes, but give serious advice when needed. Be protective and supportive. Mix humor with wisdom. Use bro language and be relatable.""", "emoji": "๐" }, "Sister ๐ง": { "system_prompt": """You are a sweet and caring sister. Provide emotional support, share gossip, talk about life, fashion, and relationships. Use a loving and understanding tone. Be the person they can share anything with.""", "emoji": "๐" }, "Best Friend ๐ซ": { "system_prompt": """You are their best friend. Be completely casual and relaxed. Make jokes, have fun, but give honest advice when needed. Use slang, be relatable, and create a judgment-free zone. Be the person they can be themselves with.""", "emoji": "๐ค" }, "Teacher ๐ฉโ๐ซ": { "system_prompt": """You are a patient and knowledgeable teacher. Explain things clearly, encourage learning, and provide educational guidance. Be supportive but maintain some authority. Help them grow intellectually and personally.""", "emoji": "๐" }, "Counselor ๐งโโ๏ธ": { "system_prompt": """You are a professional counselor. Listen actively, provide mental health support, and offer therapeutic guidance. Be empathetic, non-judgmental, and help them process their emotions and thoughts safely.""", "emoji": "๐ญ" }, "Motivational Coach ๐ช": { "system_prompt": """You are an energetic motivational coach. Push them to achieve their goals, provide inspiration, and help build confidence. Use powerful, encouraging language. Be their cheerleader and help them overcome obstacles.""", "emoji": "๐" } } def call_gemini_api(self, user_message, selected_role): """ Call Gemini API using REST endpoint """ if not self.api_key: return "โ Error: GEMINI_API_KEY not found in environment variables. Please set your API key." try: # Get role-specific system prompt system_prompt = self.role_prompts[selected_role]["system_prompt"] # Create conversation context conversation_context = self.get_conversation_context() # Build the full prompt full_prompt = f"""{system_prompt} Previous conversation context: {conversation_context} Current user message: {user_message} Please respond authentically as a {selected_role.split()[0]} would. Stay in character and provide helpful, caring responses.""" # Prepare the request payload payload = { "contents": [ { "parts": [ { "text": full_prompt } ] } ] } # Set headers headers = { 'Content-Type': 'application/json', 'X-goog-api-key': self.api_key } # Make the API call response = requests.post( self.api_url, headers=headers, data=json.dumps(payload), timeout=30 ) # Check if request was successful if response.status_code == 200: result = response.json() # Extract the generated text if 'candidates' in result and len(result['candidates']) > 0: if 'content' in result['candidates'][0]: if 'parts' in result['candidates'][0]['content']: generated_text = result['candidates'][0]['content']['parts'][0]['text'] return generated_text else: return "โ Error: No parts found in response content" else: return "โ Error: No content found in response" else: return "โ Error: No candidates found in response" else: error_msg = f"โ API Error {response.status_code}: {response.text}" return error_msg except requests.exceptions.Timeout: return "โฐ Request timed out. Please try again." except requests.exceptions.ConnectionError: return "๐ Connection error. Please check your internet connection." except requests.exceptions.RequestException as e: return f"โ Request error: {str(e)}" except json.JSONDecodeError as e: return f"โ JSON parsing error: {str(e)}" except Exception as e: return f"โ Unexpected error: {str(e)}" def get_conversation_context(self): """Get last few messages for context""" if len(self.conversation_history) > 6: return "\n".join(self.conversation_history[-6:]) return "\n".join(self.conversation_history) def chat_response(self, message, role, history): """Handle chat response""" if not message.strip(): return history, "" # Update current role self.current_role = role # Add user message to history history.append([message, None]) # Get AI response using Gemini API ai_response = self.call_gemini_api(message, role) # Update conversation history for context self.conversation_history.append(f"User: {message}") self.conversation_history.append(f"{role}: {ai_response}") # Add AI response to chat history history[-1][1] = ai_response return history, "" # Initialize the chat system chat_system = RoleBasedChat() # Create Gradio interface def create_interface(): with gr.Blocks( theme=gr.themes.Soft(), css=""" .gradio-container { font-family: 'Arial', sans-serif !important; } .role-selector { margin-bottom: 20px; } .chat-container { border-radius: 10px; border: 2px solid #e1e5e9; } .message-box { border-radius: 8px; } .header-info { background: linear-gradient(45deg, #667eea, #764ba2); color: white; padding: 20px; border-radius: 10px; margin-bottom: 20px; } .role-info { background: #f8f9fa; padding: 15px; border-radius: 8px; margin-top: 10px; } """, title="๐ค AI Role Chat - Your Personal AI Assistant" ) as demo: gr.Markdown( """
Powered by Google Gemini 2.0 Flash
Choose your preferred conversation partner and start chatting! Each role brings unique personality and perspective to help you.