Easy Steps to Create Your First AI Chatbot with Google Gemini and Python

Can we make our personal chatbot that can work like Gemini, ChatGPT and others chatbot.

Are you interested in harnessing the power of artificial intelligence to generate content or build interactive applications? In this blog post, we’ll guide you through creating a simple yet powerful AI chatbot using Python and Google’s Gemini API. Whether you’re a beginner or an experienced developer, you’ll learn how to set up the API, take user input, and generate intelligent responses—all in just a few lines of code. Let’s dive in and explore how easy it is to integrate advanced AI capabilities into your Python projects!

There are two ways to make a chatbot

  1. By making your own JSON file

  2. By using the Api

By making your own JSON file :

The most basic type of chatbot you can build with a JSON file is a rule-based chatbot. This means the chatbot's responses are predetermined based on specific keywords or phrases in the user's input. There's no advanced AI or natural language understanding (NLU) involved, just pattern matching.

Example:

{
  "intents": [
    {
      "tag": "greeting",
      "patterns": [
        "Hi",
        "Hello",
        "Hey",
        "Good morning",
        "Good afternoon",
        "Good evening"
      ],
      "responses": [
        "Hello!",
        "Hi there!",
        "Greetings!",
        "How can I help you today?"
      ]
    },
    {
      "tag": "goodbye",
      "patterns": [
        "Bye",
        "Goodbye",
        "See you later",
        "Farewell",
        "I'm leaving"
      ],
      "responses": [
        "Goodbye!",
        "See you soon!",
        "Have a great day!",
        "Bye for now!"
      ]
    },
    {
      "tag": "name_inquiry",
      "patterns": [
        "What's your name?",
        "Who are you?",
        "Can I know your name?"
      ],
      "responses": [
        "I am a chatbot.",
        "You can call me Bot.",
        "I don't have a name, I'm just a program."
      ]
    },
    {
      "tag": "weather_inquiry",
      "patterns": [
        "What's the weather like?",
        "Is it raining?",
        "Tell me about the weather."
      ],
      "responses": [
        "I'm sorry, I cannot provide real-time weather information.",
        "I don't have access to live weather data."
      ]
    },
    {
      "tag": "thanks",
      "patterns": [
        "Thanks",
        "Thank you",
        "That's helpful"
      ],
      "responses": [
        "You're welcome!",
        "No problem!",
        "Glad to help!"
      ]
    }
  ]
}

If you want to make a chatbot using your own JSON, I would like to suggest one GitHub repo

By using the Api :

This is the simplest way to create a personal chatbot. You need to get an API from many platforms likes

Google AI Studio, OpenAI, Mistral AI, Hugging Face, Dialogflow, Rasa, Botpress etc.

For making my chatbot i will use Google AI Studio API you can use any one from above list.

Using Python 3.9+, install the google-genai package using the following pip command:

pip install -q -U google-genai

Make your first request

Make a new file named chatbot.py.

Use this simple code.

from google import genai

client = genai.Client(api_key="YOUR_API_KEY")

response = client.models.generate_content(
    model="gemini-2.0-flash", contents="Explain how AI works in a few words"
)
print(response.text)

Run this script, and you'll see your chatbot generate an intelligent explanation of AI!

Making Your Chatbot Conversational

To transform this into a truly interactive chatbot, you'll need to enable continuous conversation. This involves a simple while loop that repeatedly takes user input, sends it to the Gemini API, and prints the response.

import google.generativeai as genai
import pyttsx3 # For text-to-speech output
import speech_recognition as sr # For speech-to-text input

# --- API Key Configuration (replace with your actual key or environment variable) ---
genai.configure(api_key="YOUR_API_KEY") # Consider using os.getenv("GEMINI_API_KEY")

# Initialize the Gemini model
model = genai.GenerativeModel('gemini-pro')
chat = model.start_chat(history=[]) # Start a chat session to maintain conversation history

# Initialize Text-to-Speech engine
engine = pyttsx3.init()
engine.setProperty('rate', 150) # Speed of speech (words per minute)

# Initialize Speech Recognizer
r = sr.Recognizer()

def speak(text):
    """Converts text to speech."""
    engine.say(text)
    engine.runAndWait()

def listen():
    """Listens for user's voice input and converts it to text."""
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 1 # seconds of non-speaking before a phrase is considered complete
        audio = r.listen(source)
        try:
            print("Recognizing...")
            query = r.recognize_google(audio, language='en-in') # Use Google's speech recognition
            print(f"You said: {query}\n")
            return query
        except Exception as e:
            print(f"Sorry, I didn't catch that. Please say it again. Error: {e}")
            return "None"

print("Hello! I am your personal AI assistant. How can I help you today?")
speak("Hello! I am your personal AI assistant. How can I help you today?")

while True:
    user_input = listen().lower() # Listen for voice input and convert to lowercase

    if user_input == "none": # If speech recognition failed
        continue
    elif "exit" in user_input or "quit" in user_input or "goodbye" in user_input:
        speak("Goodbye! Have a great day.")
        print("Goodbye! Have a great day.")
        break
    else:
        try:
            # Send the user's input to the Gemini model and get a response
            response = chat.send_message(user_input)
            ai_response = response.text
            print(f"AI: {ai_response}\n")
            speak(ai_response)
        except Exception as e:
            print(f"An error occurred: {e}")
            speak("I'm sorry, I encountered an error. Please try again.")

Key Enhancements in the Conversational Code:

  • pyttsx3 and speech_recognition: These modules are crucial for making your chatbot truly interactive.

    • pyttsx3 (Text-to-Speech) allows your chatbot to "speak" its responses.

    • speech_recognition (Speech-to-Text) enables your chatbot to understand spoken commands from your microphone.

  • genai.configure(api_key="YOUR_API_KEY"): The correct way to set your API key for the google-generativeai library.

  • model.start_chat(history=[]): This initiates a chat session, allowing the Gemini model to maintain context across multiple turns of conversation, making interactions more fluid and coherent.

  • Error Handling: Basic try-except blocks are added to handle potential issues with speech recognition or API calls gracefully.

  • Exit Commands: Users can easily end the conversation.

  • Clearer Prompts: More user-friendly messages for listening and responding.

1
Subscribe to my newsletter

Read articles from Raj Vardhan Thakur directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Raj Vardhan Thakur
Raj Vardhan Thakur