| # We are importing three things we need: | |
| # 1. gradio - to make a simple website interface | |
| # 2. requests - to talk to Gemini API on the internet | |
| # 3. os - to get our secret API key safely | |
| import gradio as gr | |
| import requests | |
| import os | |
| # We get our secret Gemini API key from the environment. | |
| # This is like unlocking the door so we can talk to the Gemini robot. | |
| GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") | |
| # This function sends your question (prompt) to Gemini and gets an answer back | |
| def query_gemini(prompt): | |
| # This is the website link (URL) where we send our question | |
| url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={GEMINI_API_KEY}" | |
| # We tell the Gemini robot that we are sending text in JSON format | |
| headers = { | |
| "Content-Type": "application/json" | |
| } | |
| # We put our prompt (question) inside a special box (dictionary) | |
| data = { | |
| "contents": [ | |
| { | |
| "parts": [ | |
| {"text": prompt} # This is the question the user types | |
| ] | |
| } | |
| ] | |
| } | |
| # We send the data to Gemini using a POST request | |
| response = requests.post(url, headers=headers, json=data) | |
| # Now we try to get the answer from Gemini’s reply | |
| try: | |
| # Gemini replies with some candidates, and we take the first answer | |
| return response.json()['candidates'][0]['content']['parts'][0]['text'] | |
| except Exception as e: | |
| # If something goes wrong, we show an error | |
| return f"Error: {e}\nFull Response: {response.text}" | |
| # Here we build the user interface using Gradio | |
| iface = gr.Interface( | |
| fn=query_gemini, # This is the function we call when the user asks something | |
| inputs=gr.Textbox(lines=4, placeholder="Ask something..."), # Textbox for input | |
| outputs=gr.Markdown(), # ← this enables formatted output | |
| title="Gemini 2.0 Flash with Gradio", # Title of the web app | |
| description="Powered by Google's Gemini 2.0 Flash API" # A short description | |
| ) | |
| # This line says: "Run the app" if you run this file directly | |
| if __name__ == "__main__": | |
| iface.launch() | |