File size: 2,146 Bytes
c38504e e49526f d3b1a4f e49526f c38504e d3b1a4f e49526f c38504e e49526f c38504e a910699 c38504e e49526f c38504e e49526f c38504e e49526f a2b4df5 c38504e a910699 a2b4df5 c38504e e49526f c38504e e49526f c38504e a910699 e49526f c38504e e49526f c38504e 577e353 c38504e e49526f c38504e e49526f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# 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()
|