I Built My Own AI Chatbot in 15 Lines of Python (Using Gemini API)

Build Your Own AI Chatbot in 15 Lines of Python (Using Google Gemini API)



Real Developers Build. They Don’t Just Prompt.

Using ChatGPT on a website is fine for consumers. But you are a developer. Real developers don't just use tools. They build them.

When you use an API, you stop being a passenger. You start driving. You gain the power to:

  • Integrate AI into your own apps.

  • Automate your workflows.

  • Control the data.

We are building a fully functional AI chatbot using Google's Gemini API. It fits in 15 lines. Let’s go.


The Setup (Prerequisites)

We need two things. A key and a library.

1. Get Your Free API Key Think of this as your digital ID card.

  • Go to Google AI Studio.

  • Sign in with Google.

  • Click Get API key.

  • Copy it. Keep it safe. Never share it.

2. Install the Library Open your terminal. Run this command:

pip install google-generativeai

Now you are ready to code.


The Code

Create a file named chatbot.py. Copy this code. Paste your API key where it says YOUR_API_KEY.

Python
import google.generativeai as genai

# 1. Configure the API
genai.configure(api_key="YOUR_API_KEY")

# 2. Initialize the Model (with memory)
model = genai.GenerativeModel("gemini-pro")
chat = model.start_chat(history=[])

print("Bot: I'm ready! Type 'exit' to stop.")

# 3. The Infinite Loop
while True:
    user_input = input("You: ")
    
    if user_input.lower() == "exit":
        break
    
    response = chat.send_message(user_input)
    print(f"Bot: {response.text}")

Run it in your terminal: python chatbot.py


The Breakdown

Let’s understand what we just built. No textbook fluff.

The Import import google.generativeai This brings in the heavy machinery. You aren't writing the math. You are importing Google's brain.

The Configuration genai.configure(api_key=...) This is the handshake. It tells Google's server: "It's me. I have permission to be here."

The Chat Session chat = model.start_chat(history=[]) This is crucial. Most AI requests are "stateless" (they forget you instantly). By starting a chat, the bot remembers your previous messages. It creates a real conversation, not just a Q&A machine.

The While Loop while True: This is the heartbeat. Without this loop, the script runs once and dies. The loop keeps the program alive, constantly waiting for your next input.


Challenge: Level Up

You have a working bot. But when you type "exit", it just stops abruptly.

Your Mission: Modify the code so the bot is polite. Make it print "Goodbye! Happy coding." before the program ends.

Hint: Look at the if statement inside the loop.


Welcome to the builder side. The Dev Mind 💻

Comments

Popular Posts