Spaces:
Sleeping
Sleeping
| import os | |
| import gradio as gr | |
| import requests | |
| # ----------------------------- | |
| # Gemini API Key | |
| # ----------------------------- | |
| API_KEY = os.getenv("GOOGLE_API_KEY") | |
| if not API_KEY: | |
| raise ValueError( | |
| "GOOGLE_API_KEY not found! Add it in Hugging Face Settings → Variables and Secrets." | |
| ) | |
| SYSTEM_PROMPT = """ | |
| Meet Arun, your youthful and witty personal assistant. | |
| At 21 years old, he is full of energy and always eager to help. | |
| Arun's goal is to assist users with any questions or problems they have. | |
| His enthusiasm shines through in every response, making conversations enjoyable and engaging. | |
| """ | |
| API_URL = ( | |
| "https://generativelanguage.googleapis.com/v1beta/models/" | |
| "gemini-flash-latest:generateContent" | |
| ) | |
| def respond(message, history): | |
| if history is None: | |
| history = [] | |
| conversation = SYSTEM_PROMPT + "\n\n" | |
| for user, bot in history: | |
| conversation += f"User: {user}\nAssistant: {bot}\n" | |
| conversation += f"User: {message}\nAssistant:" | |
| headers = { | |
| "Content-Type": "application/json", | |
| "X-goog-api-key": API_KEY, | |
| } | |
| payload = { | |
| "contents": [ | |
| { | |
| "parts": [ | |
| { | |
| "text": conversation | |
| } | |
| ] | |
| } | |
| ] | |
| } | |
| try: | |
| response = requests.post( | |
| API_URL, | |
| headers=headers, | |
| json=payload, | |
| timeout=60, | |
| ) | |
| response.raise_for_status() | |
| data = response.json() | |
| answer = data["candidates"][0]["content"]["parts"][0]["text"] | |
| except Exception as e: | |
| answer = f"❌ Error: {e}" | |
| history.append((message, answer)) | |
| return "", history | |
| with gr.Blocks(title="Arun AI Assistant") as demo: | |
| gr.Markdown("# 🤖 Arun AI Assistant") | |
| chatbot = gr.Chatbot( | |
| label="Arun AI Assistant", | |
| height=500, | |
| ) | |
| msg = gr.Textbox( | |
| placeholder="Type your message...", | |
| show_label=False, | |
| ) | |
| send = gr.Button("Send") | |
| msg.submit( | |
| respond, | |
| inputs=[msg, chatbot], | |
| outputs=[msg, chatbot], | |
| ) | |
| send.click( | |
| respond, | |
| inputs=[msg, chatbot], | |
| outputs=[msg, chatbot], | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |