Spaces:
No application file
No application file
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from google import genai
|
| 4 |
+
|
| 5 |
+
# --- Load Gemini API key from Hugging Face secret ---
|
| 6 |
+
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 7 |
+
if not GEMINI_API_KEY:
|
| 8 |
+
raise ValueError("❌ GEMINI_API_KEY not found in environment. Add it in Hugging Face Secrets.")
|
| 9 |
+
|
| 10 |
+
# --- Configure Gemini client ---
|
| 11 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 12 |
+
client = genai.Client()
|
| 13 |
+
|
| 14 |
+
# Create a persistent chat session
|
| 15 |
+
chat = client.chats.create(model="gemini-2.5-flash")
|
| 16 |
+
|
| 17 |
+
# --- Define chatbot function ---
|
| 18 |
+
def chat_with_gemini(user_input, history):
|
| 19 |
+
try:
|
| 20 |
+
response = chat.send_message(user_input)
|
| 21 |
+
history.append((user_input, response.text))
|
| 22 |
+
return history, history
|
| 23 |
+
except Exception as e:
|
| 24 |
+
return history + [(user_input, f"⚠️ Error: {str(e)}")], history
|
| 25 |
+
|
| 26 |
+
# --- Gradio UI ---
|
| 27 |
+
with gr.Blocks(title="Gemini 2.5 Flash Chatbot") as demo:
|
| 28 |
+
gr.Markdown("# 🤖 Gemini 2.5 Flash Chatbot\nAsk me anything!")
|
| 29 |
+
chatbot = gr.Chatbot()
|
| 30 |
+
message = gr.Textbox(placeholder="Type your message and press Enter")
|
| 31 |
+
clear = gr.Button("Clear Chat")
|
| 32 |
+
state = gr.State([])
|
| 33 |
+
|
| 34 |
+
message.submit(chat_with_gemini, inputs=[message, state], outputs=[chatbot, state])
|
| 35 |
+
clear.click(lambda: ([], []), None, [chatbot, state])
|
| 36 |
+
|
| 37 |
+
# --- Launch app ---
|
| 38 |
+
if __name__ == "__main__":
|
| 39 |
+
demo.launch()
|