import os import gradio as gr import google.generativeai as genai # ============================ # KONFIGURASI GEMINI # ============================ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") if not GEMINI_API_KEY: raise ValueError("API Key tidak ditemukan. Tambahkan GEMINI_API_KEY di Settings → Variables.") genai.configure(api_key=GEMINI_API_KEY) model = genai.GenerativeModel("gemini-2.5-pro") # ============================ # FUNGSI CHATBOT # ============================ def chat_with_gemini(message, history): # Konversi history ke format Gemini convo = model.start_chat(history=[]) for msg in history: if msg["role"] == "user": convo.history.append({"role": "user", "parts": [msg["content"]]}) elif msg["role"] == "assistant": convo.history.append({"role": "model", "parts": [msg["content"]]}) # Kirim pesan baru convo.send_message(message) return convo.last.text def respond(user_message, history): # Tambahkan pesan user history.append({"role": "user", "content": user_message}) # Dapatkan balasan bot bot_reply = chat_with_gemini(user_message, history) # Tambahkan balasan bot ke history history.append({"role": "assistant", "content": bot_reply}) return history, "" # ============================ # UI GRADIO # ============================ with gr.Blocks(title="Beta AI - Gemini 2.5 Pro") as demo: gr.Markdown("## 🤖 Beta AI - Chatbot Pintar dengan Gemini 2.5 Pro") chatbot = gr.Chatbot(type="messages", label="Beta AI", height=500) msg = gr.Textbox(label="Ketik pesan Anda...", placeholder="Tulis pesan di sini...") submit = gr.Button("Kirim", variant="primary") clear = gr.Button("Hapus Chat") submit.click(respond, [msg, chatbot], [chatbot, msg]) msg.submit(respond, [msg, chatbot], [chatbot, msg]) clear.click(lambda: [], None, chatbot, queue=False) demo.launch()