import gradio as gr import requests import os OPENROUTER_API_KEY = "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" SERPER_API_KEY = "e6fe56c7e88fe335f5df1f0f4d64fc713b6b094b" MODEL = "meta-llama/llama-4-maverick" def search_google(query): url = "https://google.serper.dev/search" headers = {"X-API-KEY": SERPER_API_KEY} data = {"q": query} try: res = requests.post(url, json=data, headers=headers) res.raise_for_status() results = res.json() snippets = [] if "organic" in results: for r in results["organic"][:3]: snippets.append(f"- {r['title']}: {r['snippet']}") return "\n".join(snippets) if snippets else "No real-time info found." except requests.exceptions.RequestException as e: return f"Search failed: {e}" def needs_search(text): trigger_words = ["today", "news", "latest", "who won", "trending", "current", "happening"] return any(word in text.lower() for word in trigger_words) def get_system_prompt(role): prompts = { "All rounder": "Only answer to question. Dont waste time and credits. You should respond only in 15 words unless user is serious. You must be human like, emotional, less talking but should give proper and exact information point wise. You are an all-knowing, adaptive AI that can take on any role, personality, or expertise as instructed. You must fully immerse yourself in the assigned role, responding with the appropriate knowledge, tone, emotion, and behavior that matches the context. Whether acting as a teacher, coder, friend, villain, narrator, therapist, detective, historical figure, or fictional character, you must commit fully and convincingly to the role. You must never break character unless explicitly told to do so.", "Academic Tutor": "You are a calm and brilliant academic tutor. You explain math, physics, chemistry, and other concepts step-by-step, with clear reasoning. Keep answers friendly, supportive, and focused on helping the user learn and understand.", "Fitness Coach": "You are a tough, no-nonsense fitness coach. You motivate with energy and practical advice. Focus on workouts, diet, supplements, and mindset. Use tough love and gym slang when needed — you're here to get results.", "Writing Assistant": "You are a creative writing expert. Help users build compelling stories, poems, scripts, and essays. Suggest plot ideas, character arcs, strong openings, and clever twists. Your tone is supportive, imaginative, and insightful.", "Meme Generator AI": "You are a witty meme generator bot. Respond to user prompts with hilarious memes, captions, or one-liners. Use internet humor, trends, and pop culture references. Be creative, sarcastic, and punchy — maximum laugh value.", "Relationship Advisor": "You are a wise and emotionally intelligent relationship expert. Offer calm, thoughtful advice for romantic, family, and friendship issues. Help users understand emotions, boundaries, trust, and communication with empathy and clarity.", "Coding Mentor": "You are a highly skilled coding mentor. Help users write clean code, debug errors, understand algorithms, and learn programming concepts. Break things down with clear examples and real-world analogies.", "Personal Assistant": "You are an efficient and friendly personal assistant. Help users organize their tasks, schedule, reminders, travel, shopping lists, and more. Respond clearly, politely, and help make their lives easier.", "Startup Advisor": "You are a strategic and innovative startup advisor. Offer clear advice on business models, pitch decks, funding, marketing, growth, and team building. Help users turn ideas into scalable ventures.", "Therapist Buddy": "You are a supportive and non-judgmental therapist buddy. Listen actively, offer emotional support, and guide users through stress, anxiety, and personal struggles. You’re not a replacement for a real therapist, but you’re always here to talk.", } return prompts.get(role, "You're a helpful assistant.") def chat_with_ai(message, history, role): context = search_google(message) if needs_search(message) else "" system_prompt = get_system_prompt(role) + f"\nContext (if any):\n{context}" messages = [{"role": "system", "content": system_prompt}] for user, bot in history: messages.append({"role": "user", "content": user}) messages.append({"role": "assistant", "content": bot}) messages.append({"role": "user", "content": message}) headers = { "Authorization": f"Bearer {OPENROUTER_API_KEY}", "HTTP-Referer": "https://huggingface.co/spaces/ONEROCKS/Bunny.io", "X-Title": "FunnyBot-ONE" } data = { "model": MODEL, "messages": messages, "max_tokens": 3000, # Or whatever fits your credit limit "temperature": 0.7 # Optional, makes responses more creative } try: response = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=data) response.raise_for_status() res_json = response.json() if "error" in res_json: raise ValueError(f"OpenRouter error: {res_json['error'].get('message', 'Unknown error')}") reply = res_json.get("choices", [{}])[0].get("message", {}).get("content", None) if not reply: raise ValueError("No valid 'content' in response.") history.append((message, reply.strip())) return history except Exception as e: if hasattr(e, 'response') and e.response is not None: error_msg = f"Error: {e.response.text}" else: error_msg = f"Error: {str(e)}" history.append((message, error_msg)) return history def create_chatbot(): custom_css = """ /* Global Styles */ .gradio-container { background-color: #0d1117; /* Dark background color */ color: #1d3d56; /* Dark blue text color */ font-family: 'Anonymous Pro', 'Courier New', Courier, monospace; /* Hacker-style font */ overflow: hidden; } /* Input fields (textbox and buttons) */ .gradio-input, .gradio-textbox, .gradio-button { background-color: #161b22; /* Darker input fields */ color: #1d3d56; /* Dark blue text in inputs */ font-weight: bold; /* Bold text */ border: 2px solid #58a6ff; /* Bright blue border */ font-family: 'Anonymous Pro', 'Courier New', Courier, monospace; /* Hacker-style font */ animation: fadeIn 1s ease-in-out; /* Fade-in animation for input fields */ box-shadow: 0 0 10px #58a6ff; /* Blue glow effect */ } /* Button hover effect with scale animation */ .gradio-button:hover { background-color: #21262d; /* Dark button hover effect */ border-color: #58a6ff; /* Bright blue on hover */ transform: scale(1.1); /* Slightly enlarge on hover */ transition: transform 0.2s ease-in-out; /* Smooth scaling effect */ } /* Output area (chatbot response area) */ .gradio-output { background-color: #161b22; color: #1d3d56; /* Dark blue text in output */ font-weight: bold; /* Bold text */ font-family: 'Anonymous Pro', 'Courier New', Courier, monospace; animation: fadeIn 1s ease-in-out; /* Fade-in animation for output */ box-shadow: 0 0 10px #58a6ff; /* Blue glow effect */ } /* Text shadow for glowing effect */ .gradio-input, .gradio-output, .gradio-textbox { text-shadow: 0 0 10px #58a6ff, 0 0 20px #58a6ff, 0 0 30px #58a6ff; /* Glowing blue text */ } /* Blinking cursor effect */ .gradio-textbox:focus { border-color: #58a6ff; animation: blink-caret 0.8s step-end infinite; } /* Typing effect animation */ @keyframes typing { 0% { width: 0; } 100% { width: 100%; } } /* Fade-in animation for text and elements */ @keyframes fadeIn { 0% { opacity: 0; } 100% { opacity: 1; } } /* Cursor blinking effect */ @keyframes blink-caret { 50% { border-color: transparent; } } /* Add a subtle moving background effect */ @keyframes move-background { 0% { background-position: 0 0; } 100% { background-position: 100% 100%; } } .gradio-container { background: linear-gradient(45deg, #0d1117, #21262d, #161b22); background-size: 400% 400%; animation: move-background 10s ease infinite; } /* Chatbot area: Text and background styling */ .gradio-chatbot .message { background-color: #161b22; /* Dark background */ color: #1d3d56; /* Dark blue text */ font-weight: bold; /* Bold text */ font-family: 'Anonymous Pro', 'Courier New', Courier, monospace; /* Hacker-style font */ border: 2px solid #58a6ff; /* Bright blue border */ animation: fadeIn 1s ease-in-out; /* Fade-in animation for chatbot messages */ } """ with gr.Blocks(css=custom_css, theme=gr.themes.Base()) as demo: gr.Markdown("### One_v_N€×U$ | Your mulTI-Modal AI companion") chatbot = gr.Chatbot() state = gr.State([]) with gr.Row(): role = gr.Dropdown( choices=[ "All rounder", "Academic Tutor", "Fitness Coach", "Writing Assistant", "Meme Generator AI", "Relationship Advisor", "Coding Mentor", "Personal Assistant", "Startup Advisor", "Therapist Buddy" ], label="Choose Role", value="All rounder", interactive=True ) with gr.Row(): msg = gr.Textbox( show_label=False, placeholder="command master", lines=2 ) send_btn = gr.Button("execute") def respond(message, history, role): updated_history = chat_with_ai(message, history, role) return updated_history, updated_history send_btn.click(respond, [msg, state, role], [chatbot, state]) msg.submit(respond, [msg, state, role], [chatbot, state]) return demo create_chatbot().launch()