Dev's school has a WhatsApp group where students post questions about homework. One evening he thought: "What if I could build a simple bot that automatically answers basic science questions?" His older cousin, a software developer, said: "Easy โ use the Gemini API. You don't need to train any AI. You call Google's AI through an API, and it does all the work."
In 40 minutes, Dev had a Python script running in Colab that could answer any science question by calling the Gemini API. He learned something powerful: you don't need to build AI to use AI. APIs let you connect to the world's most powerful models with 5 lines of code. Today you'll build the same.
An API (Application Programming Interface) is a way for one program to talk to another program over the internet. It's like a waiter in a restaurant: you (your code) place an order โ the waiter (API) takes it to the kitchen (the server) โ returns with your food (the response).
- REST API: The most common type. Uses standard HTTP verbs โ GET (fetch data), POST (send data), PUT (update), DELETE. The Gemini API is a REST API.
- JSON: JavaScript Object Notation โ the format APIs use to send structured data. Looks like a Python dictionary.
- API Key: A secret password that proves you are who you say you are. Never share it or post it publicly.
When you call an API, the response comes back as JSON. Here's what a Gemini API response looks like:
{
"candidates": [
{
"content": {
"parts": [
{
"text": "Photosynthesis is the process by which plants use sunlight, water and carbon dioxide to produce glucose and oxygen."
}
],
"role": "model"
},
"finishReason": "STOP"
}
],
"usageMetadata": {
"promptTokenCount": 12,
"candidatesTokenCount": 28
}
}To extract just the answer text from Python: response['candidates'][0]['content']['parts'][0]['text']
API_KEY = os.environ.get("GEMINI_KEY")
# Science Q&A Tool using Google Gemini API
# Run this in Google Colab
# 1. Get your free API key at: https://aistudio.google.com/app/apikey
# 2. In Colab: click the ๐ icon (Secrets), add GEMINI_KEY = your_key
import google.generativeai as genai
import os
# โโ Step 1: Configure API key from environment โโ
# In Colab Secrets: name=GEMINI_KEY, value=your_actual_key
from google.colab import userdata
API_KEY = userdata.get('GEMINI_KEY')
genai.configure(api_key=API_KEY)
# โโ Step 2: Choose a model โโ
model = genai.GenerativeModel('gemini-1.5-flash') # fast, free tier
# โโ Step 3: Create a system prompt โโ
SYSTEM_PROMPT = """You are a helpful science tutor for Class 9 students in India.
Answer questions clearly and concisely in simple English.
Use real Indian examples where possible.
Maximum 4 sentences per answer."""
def ask_science_question(question):
"""Send a science question to Gemini and return the answer."""
try:
full_prompt = f"{SYSTEM_PROMPT}\n\nStudent question: {question}"
response = model.generate_content(full_prompt)
return response.text
except Exception as e:
return f"Error: {e}. Check your API key and internet connection."
# โโ Step 4: Interactive Q&A loop โโ
print("๐ฌ Science Q&A Tutor (powered by Gemini AI)")
print("Type 'quit' to exit\n")
questions = [
"What is photosynthesis and why is it important?",
"Explain Newton's second law with a cricket ball example.",
"How does a vaccine work in simple terms?"
]
for q in questions:
print(f"Q: {q}")
answer = ask_science_question(q)
print(f"A: {answer}")
print("-" * 60)
# โโ Step 5: Interactive mode โโ
print("\nYour turn! Ask your own question:")
while True:
user_q = input("Question (or 'quit'): ").strip()
if user_q.lower() == 'quit':
print("Goodbye!")
break
if len(user_q) < 5:
print("Please ask a proper question.")
continue
print(f"Gemini: {ask_science_question(user_q)}\n")import time
def ask_with_retry(question, max_retries=3):
"""Call the API with basic retry logic for rate limit errors."""
for attempt in range(max_retries):
try:
full_prompt = f"{SYSTEM_PROMPT}\n\nQuestion: {question}"
response = model.generate_content(full_prompt)
return response.text
except Exception as e:
error_str = str(e)
if '429' in error_str:
wait_time = 2 ** attempt # exponential backoff: 1s, 2s, 4s
print(f"Rate limited. Waiting {wait_time}s before retry...")
time.sleep(wait_time)
elif '403' in error_str:
return "API key error โ check your key in Colab Secrets."
elif '400' in error_str:
return "Bad request โ your question may contain blocked content."
else:
return f"Unexpected error: {error_str}"
return "Max retries reached. Try again in a minute."
# Test it
print(ask_with_retry("How do earthquakes happen? Explain for a Class 9 student."))