Building a Simple Gemini Chatbot in Python
Recently I experimented with Google’s Generative AI (Gemini) to make a lightweight chatbot in Python. Below I’ll walk you through the basic script and highlight how it works.
How to Get Your Gemini API Key
To use the Gemini (Google Generative AI) API in Python, you first need to create an API key. Follow these steps:
- Go to the Google AI Studio API Key page.
- Click on “Create API key”.
- Select a project (or create a new one).
- Copy the generated API key and keep it safe.
- Use it in your Python script like this:
genai.configure(api_key="YOUR_API_KEY_HERE")
⚠️ Important: Never share your API key publicly (GitHub, blog, forums).
Store it in environment variables or a
.env
file for security.
The Python Script
import google.generativeai as genai
# Configure the API key securely
#get api key on:https://aistudio.google.com/app/apikey
genai.configure(api_key="YOUR_API_KEY_HERE")
# Load the Gemini model (flash version for faster responses)
#you can add your own models also
model = genai.GenerativeModel("gemini-1.5-flash")
print("Hello Sir\n How Can I help You\n Type\t'off'\tTo End this Session") # welcome message
while True:
q = input("Enter your Query : ")
if q.lower() == "off":
print("Session ended.")
break
try:
response = model.generate_content(f"{q}")
print("Gemini:", response.text)
except:
print("Error:")
How It Works
- genai.configure: connects your API key to Gemini.
- GenerativeModel("gemini-1.5-flash"): loads a lightweight model for faster replies.
- while loop: keeps asking for user queries until you type
off
. - response.text: prints the AI’s reply.
This small project is a fun way to start experimenting with Google’s Generative AI in Python. Just remember: protect your API keys before deploying anything to production or sharing code online.