🤖 Gemini Chatbot
Unit 7 · Generative AI · Advanced Learners
Build a Gemini API Chatbot
Step-by-Step Guide
Complete Python code · API setup · Prompt engineering · Multi-turn conversation · CBSE Class 12 AI Subject Code 843
Unit 7 · Gen AI
Python
Gemini API
Advanced Learners
Free API Key
What is the Gemini API?
Understanding before building
Gemini
Google's most powerful Large Language Model (LLM) — trained on billions of text examples to understand and generate human-like responses
API Key
A secret code that gives your Python program permission to talk to Google's Gemini AI. Free for students at aistudio.google.com
Chatbot
A program that has conversations with users. Your chatbot will use Gemini to generate intelligent, context-aware replies
Multi-turn Chat
The chatbot remembers previous messages in a conversation — just like WhatsApp — so it understands context across multiple questions
Phase 1 — Setup (Do This First)
Get your free API key and install the library
S1
5 min
Get Your Free Gemini API Key
Step 1: Open Chrome → go to aistudio.google.com
Step 2: Sign in with your Google account (Gmail)
Step 3: Click "Get API key" → click "Create API key"
Step 4: Select "Create API key in new project"
Step 5: Your API key appears — it looks like: AIzaSyBxxxxxxxxxxxxxxxxxxxxxxxx
Step 6: Click Copy → paste it in Notepad and save — you will need this
Step 2: Sign in with your Google account (Gmail)
Step 3: Click "Get API key" → click "Create API key"
Step 4: Select "Create API key in new project"
Step 5: Your API key appears — it looks like: AIzaSyBxxxxxxxxxxxxxxxxxxxxxxxx
Step 6: Click Copy → paste it in Notepad and save — you will need this
⚠️ Keep it secret! Never share your API key publicly or post it on social media. If someone else uses your key, your account may get blocked.
S2
3 min
Install the Gemini Python Library
Open Command Prompt (Windows: press Windows key → type cmd → Enter) and type:
pip install google-generativeai
Wait for installation to complete. You should see "Successfully installed google-generativeai"
✅ If you are using Google Colab (recommended for students), type this in the first cell instead:
!pip install google-generativeai
!pip install google-generativeai
S3
2 min
Open Google Colab (Recommended Platform)
Step 1: Go to colab.research.google.com
Step 2: Click "+ New notebook"
Step 3: You will see empty code cells — you will type programs here
Step 4: To run a cell → press Shift+Enter
Step 2: Click "+ New notebook"
Step 3: You will see empty code cells — you will type programs here
Step 4: To run a cell → press Shift+Enter
✅ Google Colab is free, runs in browser, needs no installation, and saves your work automatically to Google Drive.
Phase 2 — Program 1: Basic Gemini Response
Send one question to Gemini and get an answer
P1
Type this program in Colab — Cell 1
# Program 1 — Send a question to Gemini and get a reply # Unit 7: Generative AI | CBSE Class 12 AI | Sub Code 843 import google.generativeai as genai # Step 1: Add your API key here genai.configure(api_key="PASTE_YOUR_API_KEY_HERE") # Step 2: Choose the Gemini model model = genai.GenerativeModel("gemini-1.5-flash") # Step 3: Send a question response = model.generate_content("What is Artificial Intelligence?") # Step 4: Print the answer print(response.text)
Replace PASTE_YOUR_API_KEY_HERE with your actual API key → Press Shift+Enter to run
Artificial Intelligence (AI) is the simulation of human
intelligence processes by machines, especially computer
systems. These processes include learning (acquiring
information and rules for using it), reasoning (using rules
to reach approximate or definite conclusions), and
self-correction...
✅ If you see a response like above — your API is working correctly!
Phase 3 — Program 2: Multi-Turn Chatbot
Build a chatbot that remembers the conversation
P2
Complete Chatbot Program — Paste in Colab Cell 2
# Program 2 — Complete Multi-Turn Chatbot using Gemini API # Unit 7: Generative AI | CBSE Class 12 AI | Sub Code 843 import google.generativeai as genai # ── Configure API ── genai.configure(api_key="PASTE_YOUR_API_KEY_HERE") # ── Choose Model ── model = genai.GenerativeModel("gemini-1.5-flash") # ── Start Chat Session (remembers conversation history) ── chat = model.start_chat(history=[]) # ── Welcome Message ── print("=" * 50) print(" 🤖 AI Logic School Chatbot") print(" Powered by Google Gemini AI") print(" Type 'quit' or 'bye' to exit") print("=" * 50) print() # ── Conversation Loop ── while True: # Get user input user_input = input("You: ").strip() # Check if user wants to exit if user_input.lower() in ['quit', 'bye', 'exit', 'goodbye']: print("Bot: Thank you for chatting! Goodbye! 👋") break # Skip empty input if not user_input: print("Bot: Please type something!") continue # Send message to Gemini and get response try: response = chat.send_message(user_input) print(f"Bot: {response.text}") print() except Exception as e: print(f"Error: {e}") print("Please try again.") print()
==================================================
🤖 AI Logic School Chatbot
Powered by Google Gemini AI
Type 'quit' or 'bye' to exit
==================================================
You: What is machine learning?
Bot: Machine learning is a subset of artificial intelligence
where computers learn from data without being explicitly
programmed. Instead of following fixed rules, ML systems
identify patterns in data and improve their performance
over time...
You: Give me 3 examples
Bot: Here are 3 examples of machine learning in daily life:
1. Email spam filters (Gmail learns what is spam)
2. Netflix recommendations (learns your preferences)
3. Google Translate (learns from millions of translations)
You: bye
Bot: Thank you for chatting! Goodbye! 👋
Phase 4 — Program 3: CBSE AI Subject Tutor Bot
Advanced — give the bot a specific role and personality
P3
Specialised Tutor Chatbot — System Instructions
# Program 3 — CBSE AI Subject Tutor Chatbot with System Role # Unit 7: Generative AI | CBSE Class 12 | Sub Code 843 import google.generativeai as genai genai.configure(api_key="PASTE_YOUR_API_KEY_HERE") # ── Give Gemini a specific role using system instruction ── system_instruction = """ You are an expert CBSE AI subject tutor for Class 12 students. Your role is to: - Answer questions about CBSE AI curriculum (Subject Code 843) - Explain concepts from all 8 units clearly and simply - Give examples relevant to Indian students - Help with Python programs, Orange tool, Neural Networks - Explain topics like Data Science, Generative AI, Data Storytelling - Always end your answer with one exam tip or important point to remember - Keep answers concise but complete — suitable for board exam preparation """ model = genai.GenerativeModel( model_name="gemini-1.5-flash", system_instruction=system_instruction ) chat = model.start_chat(history=[]) print("=" * 55) print(" 📚 CBSE AI Tutor Bot — Class 12 Subject Code 843") print(" Ask me anything about the AI curriculum!") print(" Type 'quit' to exit") print("=" * 55) print() question_count = 0 while True: user_input = input("Student: ").strip() if user_input.lower() in ['quit', 'bye', 'exit']: print(f"Tutor: Good luck with your studies! You asked {question_count} questions. Keep it up! 🌟") break if not user_input: continue try: question_count += 1 response = chat.send_message(user_input) print(f"\nTutor: {response.text}\n") except Exception as e: print(f"Error: {e}\n")
Student: What is backpropagation?
Tutor: Backpropagation is the process by which a neural
network learns from its mistakes. Here's how it works:
1. Forward pass: Input data flows through the network
to produce a prediction
2. Calculate error: Compare prediction with actual answer
using a loss function
3. Backward pass: Error signals travel backwards through
the network, adjusting each weight proportionally
📌 Exam Tip: Remember — backpropagation uses gradient
descent to minimise the loss function. The formula involves
partial derivatives. For board exams, understand the concept
not the math.
💡 What system_instruction does: It sets the personality and role of the chatbot. The model will always behave like a CBSE tutor — no matter what question is asked. This is called "role prompting" — an important Prompt Engineering technique.
Prompt Engineering — 6 Techniques to Know
How to get better answers from Gemini — important for board exams
Technique 1
Zero-Shot Prompting
"Explain what a neural network is."
✅ Simple direct question — no examples given
Technique 2
Role Prompting
"Act as a CBSE AI teacher. Explain neural networks to a Class 12 student."
✅ Assigns a role — gives tailored, specific answers
Technique 3
Few-Shot Prompting
"Translate: Hello = Namaste, Goodbye = Alvida, Thank you = ?"
✅ Gives examples to show the pattern expected
Technique 4
Chain of Thought
"Explain photosynthesis step by step. Think through each stage carefully."
✅ Asks model to think step by step — better for complex topics
Technique 5
Format Specification
"List 5 applications of AI in healthcare. Format as a numbered list with one sentence each."
✅ Specifies the exact output format needed
Technique 6
Audience Specification
"Explain machine learning for a 16-year-old student who has never studied programming."
✅ Tells the model who the audience is — simpler language
Practical File — What to Include for Unit 7
Screenshots and code required for your practical file
| Item | What to include | How to capture |
|---|---|---|
| P1 — Basic Response | Code + output showing Gemini answering a question | Screenshot of Colab with code and output |
| P2 — Chatbot | Code + 3–4 exchanges of conversation shown | Screenshot of complete conversation |
| P3 — Tutor Bot | Code + system instruction + sample conversation | Screenshot showing role-based response |
| Prompt Engineering | Demonstrate 3 techniques with before/after comparison | Two screenshots — basic vs engineered prompt |
| Canva AI | Screenshot of AI-generated image from text prompt | Screenshot from canva.com |
| Animaker | Screenshot of AI video creation steps | Screenshot from animaker.com |
📌 Important: For the practical file, take a screenshot of your code AND the output together in one screen. Press Windows + Shift + S to take a screenshot on Windows. Paste screenshots in your practical file with proper labels.
Common Errors and How to Fix Them
E1
Error: "Invalid API key"
Cause: API key was not copied correctly — extra space or missing characters
Fix: Go back to aistudio.google.com → copy the key again carefully → paste it fresh
Fix: Go back to aistudio.google.com → copy the key again carefully → paste it fresh
E2
Error: "ModuleNotFoundError: No module named 'google'"
Cause: Library not installed
Fix: Run !pip install google-generativeai in the first Colab cell → then run your program cell
Fix: Run !pip install google-generativeai in the first Colab cell → then run your program cell
E3
Error: "Quota exceeded"
Cause: You sent too many requests in a short time (free tier limit)
Fix: Wait 1–2 minutes → try again. The free tier allows 15 requests per minute.
Fix: Wait 1–2 minutes → try again. The free tier allows 15 requests per minute.
E4
Chatbot not remembering previous messages
Cause: Using generate_content() instead of chat.send_message()
Fix: Use model.start_chat(history=[]) and then chat.send_message() for multi-turn conversations
Fix: Use model.start_chat(history=[]) and then chat.send_message() for multi-turn conversations
⭐ Important for Board Exams — Unit 7 Key Points
LLM Definition
Large Language Model — AI trained on massive text data to understand and generate human-like text
Gen AI vs Discriminative
Generative AI creates new content. Discriminative AI classifies existing data.
Examples of Gen AI
ChatGPT, Gemini, DALL-E (images), Sora (video), GitHub Copilot (code)
Ethical Issues
Deepfakes, copyright violation, misinformation, bias, privacy concerns
Comments
Post a Comment