Build an AI Chatbot with Python

Call a real LLM API with Python to build a multi-turn AI chatbot.

Introduction

30 Second Summary

Every time you ask ChatGPT a question or get a suggestion from an AI assistant, there is code behind the scenes making that conversation happen. The skill of writing that code is now the most in-demand ability in tech.

In this project, you will build a working AI chatbot in Python that connects to Google's Gemini model, holds multi-turn conversations, and has a custom personality you define.

What You'll Build

A terminal-based AI chatbot powered by Google's Gemini model that maintains conversation memory and responds with a custom personality.

By the end of this project, you'll have:

  • A Python script that calls a real LLM API to generate AI responses.
  • An interactive chatbot that remembers context across multiple messages.
  • A custom AI personality (a coding tutor named "PyBot") shaped by a system prompt.
  • Secret Mission: Add error handling and retry logic to make your chatbot production-ready.

Do I need programming experience?

Nope. This project teaches you Python from scratch as you build. You only need a Google account (Gmail) to get a free API key.

Set Up Python and Your Project

Every AI chatbot starts with two things: a programming language to write instructions in, and a connection to an AI model. Python is the most popular language for AI engineering because of its simple syntax and powerful libraries.

In this step, you will install Python, create a project folder, and install the software library that lets Python talk to Google's AI.

In this step, get ready to:
  • Install Python 3.14 on your computer.
  • Create a project folder with a virtual environment.
  • Install the google-genai SDK for connecting to Google's AI.
Install Python on Windows

Python is the programming language you will write your chatbot in. The Python Install Manager is the recommended way to get Python on Windows.

  • Press the Windows key to open your search bar.
  • Type PowerShell and press Enter to open it.
  • Install the Python Install Manager by running this command:
winget install 9NQ7512CXL7T

What does this command do?

This uses Windows Package Manager (winget) to install the Python Install Manager.

The Python Install Manager handles downloading and setting up Python for you. It makes the python command available in any terminal window.

  • Close PowerShell completely.
  • Reopen PowerShell by pressing the Windows key, typing PowerShell, and pressing Enter.
  • Check that Python installed correctly by running:
python --version

You should see a version number printed. Check which result matches yours:

✔️ I see Python 3.14

Python is installed and ready to go. Move on to the next substep below.

ⓧ The Microsoft Store opens instead

Windows has a built-in shortcut that redirects the python command to the Microsoft Store. You need to disable it so your newly installed Python takes priority.

  • Press the Windows key and type Manage app execution aliases.
  • Press Enter to open the settings page.
  • Find the entries for python.exe and python3.exe labelled App Installer.
  • Toggle both switches to Off.
  • Close and reopen PowerShell, then run python --version again.

You should now see Python 3.14.x printed.

ⓧ I see an error or nothing happens

The install may still be completing in the background.

  • Wait 30 seconds, then close and reopen PowerShell.
  • Run python --version again.
  • If it still fails, try running winget install 9NQ7512CXL7T one more time, then close and reopen PowerShell.

If you continue to see errors, help me troubleshoot Python installation on Windows.

Create your project folder and install the SDK

Now you will create a dedicated folder for your chatbot project and install the library that connects Python to Google's Gemini AI.

  • Move to your Desktop by running this command:
cd ~/Desktop
  • Create your project folder and move into it by running these commands:
mkdir ai-chatbot
cd ai-chatbot
  • Create a virtual environment and activate it by running these commands:
python -m venv .venv
.venv\Scripts\activate

What is a virtual environment?

A virtual environment is like a sealed box for your project's tools. Any libraries you install go inside this box instead of cluttering your whole computer.

When the virtual environment is active, you will see (.venv) at the beginning of your terminal prompt. This confirms you are working inside the box.

  • Confirm you see (.venv) at the start of your terminal line.
  • Install the Google Gemini SDK by running:
pip install google-genai
  • Verify the package installed correctly by running:
pip show google-genai

You should see package information printed, including the name, version, and summary of the library.

Seeing an error during pip install?

Make sure (.venv) appears at the start of your terminal prompt. If it does not, the virtual environment is not active. Run .venv\Scripts\activate again and retry the install.

If you see a network error, check your internet connection and try running the pip install google-genai command again. Help me troubleshoot pip install errors.

Open the project in VS Code
  • Open your project in VS Code by running:
code .

VS Code opens with your ai-chatbot folder loaded in the sidebar.

What if VS Code asks about a Python interpreter?

If a notification asks you to select a Python interpreter, choose the one inside .venv. This tells VS Code to use your project's virtual environment for running code.

Your development environment is ready. Next up, you will get a free API key that unlocks access to Google's Gemini AI.

Get Your Free Gemini API Key

Your Python environment is ready with the google-genai SDK installed. Now you need one more ingredient before you can talk to an AI: an API key.

An API key is like a library card that lets your Python code connect to Google's Gemini model. You will get one for free from Google AI Studio and verify it works.

In this step, get ready to:
  • Get a free API key from Google AI Studio.
  • Verify the key works by making your first API call.
Create an API key in Google AI Studio
  • Open your browser and go to https://aistudio.google.com.
  • Sign in with your Google account (any Gmail account works).
  • Accept the Terms of Service if prompted.

For new users, Google AI Studio automatically creates a default project and API key after you accept the Terms of Service. You should see your key on the screen.

What if I don't see a key?

If no key appears automatically, you can create one manually.

  • Select API Key in the left side menu.
  • Click Create Key in the top right corner.
  • Select or create a project when prompted, then click Create.

Seeing a permission error?

Some users see a permission error when creating a key on an existing Google Cloud project. Try creating a brand new project that is not associated with an organization. If the issue persists, wait a few minutes and try again.

Help me fix a permission error when creating my Gemini API key

  • Copy your API key. It starts with AI followed by a long string of characters.
  • Paste it somewhere safe (a text file or note) so you can use it in a moment.

What is an API key?

An API key is a unique string that identifies your requests to a service. Think of it like a library card. The library (Google) checks your card to know who is borrowing books (making API calls).

The Gemini API free tier provides free input and output tokens. No billing or credit card is required. On the free tier, your prompts may be used to improve Google products.

Verify the key works

Before building your chatbot, confirm the key actually connects to Gemini. You will run a quick one-liner that sends a message and prints the AI's response.

  • Switch back to your terminal in VS Code (your virtual environment should still be active with (.venv) showing in the prompt).
  • Run this command, replacing PASTE_YOUR_KEY_HERE with the API key you just copied:
python -c "from google import genai; client = genai.Client(api_key='PASTE_YOUR_KEY_HERE'); print(client.models.generate_content(model='gemini-2.5-flash', contents='Say hello').text)"

What does this command do?

This runs a tiny Python script directly from the terminal without creating a file. It imports the google-genai library, creates a client with your API key, asks Gemini to say hello, and prints the response.

If you see any text printed (a greeting from the AI), your key is working correctly.

  • You should see a greeting from the AI printed in your terminal. The exact wording varies each time you run it.

Not seeing a response?

Make sure you replaced PASTE_YOUR_KEY_HERE with your actual API key (the string starting with AI). Keep the surrounding single quotes intact.

Check that your virtual environment is still active. You should see (.venv) at the start of your terminal prompt. If not, reactivate it by running .venv\Scripts\activate again.

Help me troubleshoot my Gemini API key verification

Your API key is verified and ready to use. Next up, you will create your first Python script that asks Gemini a real question and prints the answer.

Ask AI Your First Question

You have a working API key and a Python environment ready to go. Now it's time to actually talk to an AI model.

In this step, you'll write a Python script that sends a question to Google's Gemini model and prints the AI's response right in your terminal.

In this step, get ready to:
  • Create a Python script that calls the Gemini API.
  • Run the script and read the AI's response in your terminal.
Create your first Python script

This script will import the Google GenAI SDK, connect to the Gemini API with your key, send a question, and print the answer.

  • In VS Code, create a new file called first_question.py inside your ai-chatbot folder.
  • Copy the following code into first_question.py:
# Import the Google GenAI SDK
from google import genai

# Create a client using your API key
client = genai.Client(api_key="your-api-key-here")

# Send a question to Gemini and store the response
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="What are the top 3 programming languages for AI engineering in 2026?",
)

# Print the AI's answer
print(response.text)
  • Replace "your-api-key-here" with your actual API key from Google AI Studio (keep the quotes around it).

What does this code do?

  • from google import genai loads the SDK you installed earlier with pip.
  • genai.Client(api_key=...) creates a connection to Google's servers using your key.
  • client.models.generate_content() sends your question to the gemini-2.5-flash model and waits for a response.
  • response.text contains the AI's answer as a string, which you print to the terminal.
  • Save first_question.py.

Seeing red squiggly lines in VS Code?

If VS Code shows import errors under from google import genai, it may not be using the Python interpreter from your virtual environment.

  • Press Cmd+Shift+P (macOS) or Ctrl+Shift+P (Windows) to open the command palette.
  • Type Python: Select Interpreter and choose the interpreter inside .venv.

help me fix import errors in VS Code for google-genai

✔️ Awesome, I've got everything!

Great. Make sure you've saved the file before moving on.

ⓧ I'd like to double check the full code

from google import genai

client = genai.Client(api_key="your-api-key-here")

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="What are the top 3 programming languages for AI engineering in 2026?",
)

print(response.text)
Run your script
  • Run your script by entering this command in the terminal (make sure your virtual environment is still active):
python first_question.py

You should see a multi-paragraph response from the AI discussing top programming languages for AI engineering.

  • Try changing the question in contents= to anything you want, save the file, and run the command again to see a different response.

What just happened?

Your script sent a request over the internet to Google's servers. The Gemini model processed your question, generated a response, and sent it back to your terminal.

This is the exact same pattern used in production AI applications. The only difference is that real apps wrap this call in a user interface instead of printing to a terminal.

Not seeing a response?

  • If you see ModuleNotFoundError: No module named 'google', your virtual environment is not active. Run .venv\Scripts\activate (Windows) and try again.
  • If you see an authentication or API key error, double check that you pasted your full key between the quotes with no extra spaces.
  • If the command hangs for more than 30 seconds, check your internet connection.

help me debug my first_question.py script

You just made your first LLM API call. Next up, you'll turn this one-shot script into a chatbot that holds a full conversation and remembers what you said.

Build a Multi-Turn Chatbot

In the previous step, you asked Gemini a single question and got a single answer. That script had no memory. If you ran it again, the AI would have no idea what you asked before.

Now you will build something more powerful. A chatbot that keeps the conversation going and remembers what you said earlier.

In this step, get ready to:
  • Create an interactive chatbot script that loops until you type "quit".
  • Test that the chatbot remembers information from earlier in the conversation.
Create the chatbot script

Your first_question.py script uses client.models.generate_content() which is a one-shot call. It sends a question, gets an answer, and forgets everything. A real chatbot needs to track the full conversation so each reply builds on what came before.

  • In VS Code, create a new file called chatbot.py inside your ai-chatbot folder.
  • Type the following code into chatbot.py:
from google import genai

# Connect to the Gemini API
client = genai.Client(api_key="your-api-key-here")

# Create a chat session that remembers conversation history
chat = client.chats.create(model="gemini-2.5-flash")

print("AI Chatbot Ready! Type 'quit' to exit.\n")

# Keep the conversation going until the user types 'quit'
while True:
    user_input = input("You: ")
    if user_input.lower() == "quit":
        print("Goodbye!")
        break
    response = chat.send_message(user_input)
    print(f"AI: {response.text}\n")
  • Replace "your-api-key-here" with the actual API key you used in first_question.py.

What does this code do?

  • client.chats.create() creates a stateful chat session. Unlike generate_content(), this session automatically tracks every message you send and every reply the AI gives.
  • while True: creates an infinite loop. The chatbot keeps asking for input until the user types quit.
  • chat.send_message(user_input) sends your message to Gemini along with the full conversation history. The AI sees everything said so far, not just the latest message.
  • response.text contains the AI's reply as a string, which gets printed with the AI: label.
  • Save chatbot.py.

Seeing a syntax error?

  • Check that the f in f"AI: {response.text}\n" is directly before the opening quote with no space.
  • Make sure the while True: line ends with a colon and all lines beneath it are indented by four spaces.

Still stuck? Help me fix a syntax error in my chatbot.py file.

✔️ Awesome, I've got everything!

Great. Make sure you have saved chatbot.py before moving on.

ⓧ I'd like to double check the full code

Here is the complete chatbot.py file. Compare yours against it:

from google import genai

client = genai.Client(api_key="your-api-key-here")

chat = client.chats.create(model="gemini-2.5-flash")

print("AI Chatbot Ready! Type 'quit' to exit.\n")

while True:
    user_input = input("You: ")
    if user_input.lower() == "quit":
        print("Goodbye!")
        break
    response = chat.send_message(user_input)
    print(f"AI: {response.text}\n")
Test the conversation memory

The real power of client.chats.create() is that it maintains conversation history automatically. Each time you call chat.send_message(), the SDK sends the full conversation so far to the model.

  • Run your chatbot by entering this command in the terminal:
python chatbot.py
  • You should see AI Chatbot Ready! Type 'quit' to exit. printed in your terminal.
  • Type My name is Alex and press Enter.
  • Wait for the AI to respond, then type What is my name? and press Enter.
  • The AI should correctly recall the name you gave it.
  • Type quit to exit the chatbot.

Why does the AI remember my name?

Behind the scenes, the SDK collects every message (yours and the AI's) into a growing list. When you send a new message, the entire list is sent to the model. The AI reads the full conversation and responds in context.

Compare this to first_question.py where each call to generate_content() was completely independent. The chat session is what makes this a real conversation instead of isolated questions.

AI not remembering your name?

  • Make sure you are typing both messages in the same session without restarting the script between them.
  • If you see an error about your API key, double-check that you replaced "your-api-key-here" with your actual key.
  • If the terminal shows no output at all, your virtual environment may not be active. Run .venv\Scripts\activate and try again.

Need more help? My chatbot is not remembering earlier messages in the conversation.

Your chatbot can hold a real conversation now. Next up, you will give it a unique personality by adding a system instruction that shapes how it responds.

Give Your Chatbot a Personality

Your chatbot can hold a multi-turn conversation and remember context across messages. Right now, though, it responds as a generic AI with no defined role or personality.

In this step, you will give it a custom identity using a system instruction. A system instruction is a hidden prompt that tells the AI how to behave before the user sends their first message.

In this step, get ready to:
  • Add a system instruction that turns the chatbot into PyBot, a friendly coding tutor.
  • Test that PyBot stays in character and uses analogies across multiple questions.
Add a system instruction

A system instruction shapes every response the AI gives without the user ever seeing it. You define the AI's role, tone, and constraints before the conversation begins.

  • In VS Code, open chatbot.py and replace the entire file contents with the following code:
from google import genai
from google.genai import types

# Create a client with your API key
client = genai.Client(api_key="your-api-key-here")

# Create a chat with a system instruction that defines PyBot's personality
chat = client.chats.create(
    model="gemini-2.5-flash",
    config=types.GenerateContentConfig(
        system_instruction="You are PyBot, a friendly coding tutor. You explain programming concepts in simple terms using real-world analogies. Keep your responses concise - under 3 sentences unless the user asks for more detail."
    ),
)

# Display a welcome message from PyBot
print("PyBot: Hi! I'm PyBot, your coding tutor.")
print("Ask me anything about programming! Type 'quit' to exit.\n")

# Chat loop with PyBot branding
while True:
    user_input = input("You: ")
    if user_input.lower() == "quit":
        print("PyBot: Goodbye! Happy coding!")
        break
    response = chat.send_message(user_input)
    print(f"PyBot: {response.text}\n")
  • Replace "your-api-key-here" with your actual Gemini API key.

What does this code do?

  • from google.genai import types imports the configuration module so you can define a system instruction.
  • config=types.GenerateContentConfig(system_instruction=...) passes a hidden prompt to the model that shapes its personality for the entire chat session.
  • The system instruction tells the AI to be "PyBot", use analogies, and keep answers under 3 sentences.
  • The print() statements and f"PyBot: ..." prefix brand the chatbot so it feels like a named character.

What is a system instruction?

Think of a system instruction as a job description you hand to the AI before it starts working. The user never sees it, but it guides how the AI responds to every message.

In production AI systems, system instructions are called "system prompts" and they define the AI's boundaries, tone, and expertise. This is the foundation of prompt engineering.

  • Save chatbot.py.

Seeing a syntax error?

  • Make sure the system_instruction string is inside the GenerateContentConfig() parentheses, not outside them.
  • Check that you have a closing parenthesis for client.chats.create( after the comma following the ) that closes GenerateContentConfig(...).
  • Double-check that your API key is wrapped in quotes.

help me fix a syntax error in my chatbot.py file that uses types.GenerateContentConfig

✔️ Awesome, I've got everything!

Great. Make sure you have saved chatbot.py before moving on.

ⓧ I'd like to double check the full code

from google import genai
from google.genai import types

client = genai.Client(api_key="your-api-key-here")

chat = client.chats.create(
    model="gemini-2.5-flash",
    config=types.GenerateContentConfig(
        system_instruction="You are PyBot, a friendly coding tutor. You explain programming concepts in simple terms using real-world analogies. Keep your responses concise - under 3 sentences unless the user asks for more detail."
    ),
)

print("PyBot: Hi! I'm PyBot, your coding tutor.")
print("Ask me anything about programming! Type 'quit' to exit.\n")

while True:
    user_input = input("You: ")
    if user_input.lower() == "quit":
        print("PyBot: Goodbye! Happy coding!")
        break
    response = chat.send_message(user_input)
    print(f"PyBot: {response.text}\n")
Test the personality

Time to see PyBot in action and verify it stays in character.

  • Run your updated chatbot by entering this command in the terminal:
python chatbot.py
  • You should see the welcome message: PyBot: Hi! I'm PyBot, your coding tutor..
  • Type What is a variable? and press Enter.
  • Notice how PyBot uses a real-world analogy and keeps the answer short.
  • Type Explain more and press Enter to see it expand its explanation.
  • Type What is a for loop? and notice the consistent teaching style across different topics.
  • Type quit to exit the chatbot.

Why does the personality stick?

The system instruction is sent to the model once when the chat session is created. Every message after that is shaped by those rules automatically.

You do not need to repeat the instruction in each message. The client.chats.create() call locks in the personality for the entire session.

PyBot not using analogies or giving long responses?

  • Make sure the system_instruction string is exactly as shown, including the "under 3 sentences" constraint.
  • Try exiting with quit and running python chatbot.py again to start a fresh session.
  • AI models are non-deterministic, so responses vary slightly each time. The personality should be consistent in tone even if exact wording differs.

help me troubleshoot why my PyBot chatbot is not responding in character

You have built a fully customized AI chatbot with its own personality. In the Secret Mission, you will make PyBot production-ready by adding error handling and retry logic.

Secret mission

Add Error Handling and Retry Logic

Your chatbot works great when everything goes smoothly. But what happens when the internet drops mid-conversation, or you accidentally press Enter without typing anything? In this mission, you'll make PyBot production-ready with error handling and retry logic.

Clean Up Your Resources

Clean Up Your Resources

This project runs entirely locally with a free API key, so there are no ongoing costs. Decide whether to keep your resources for future AI projects, or delete them entirely.

Resources you used:

  • A Google AI Studio API key (free, no billing attached).
  • The ai-chatbot project folder (contains your virtual environment, scripts, and installed packages).

What about the free tier data policy?

On the Gemini API free tier, your prompts may be used to improve Google products. If you plan to send sensitive data through the API in future projects, consider upgrading to the paid tier where your data is not used for training.

Keep everything running

No action needed. Choose this if you plan to build more AI projects with Python and Gemini.

  • Your API key remains active and ready for your next project. There is no ongoing cost.
  • Your ai-chatbot folder stays on your machine with all scripts and the virtual environment intact.
  • Python remains installed and available for any future development work.

Pause - I'll come back to this later

Deactivate your virtual environment to free up your terminal session. Your files and API key remain intact for when you return.

  • In your terminal, deactivate the virtual environment by running:
deactivate
  • When you come back, reactivate by navigating to your ai-chatbot folder and running .venv\Scripts\activate.

Delete - I don't want to use this again

Remove all project resources and revoke your API key. Follow each step below.

  • Delete your API key:
  • Go to https://aistudio.google.com.
  • Select API Key in the left side menu.
  • Find your key in the list and click the trash icon to delete it.
  • Delete the project folder. First deactivate your virtual environment, then navigate to the folder that contains ai-chatbot and run the deletion command:

macOS

deactivate
cd ..
rm -rf ai-chatbot

Windows

deactivate
cd ..
rmdir /s /q ai-chatbot
  • Confirm the folder is gone by running:
ls
  • You should no longer see ai-chatbot in the output.

Nice Work!

Nice Work!

You just built a working AI chatbot from scratch using Python and the Google Gemini API. That is real AI engineering, not just theory.

Here's what you accomplished:

  • Called the Google Gemini API to generate AI responses with Python, the exact skill in the majority of AI engineer job postings.
  • Built an interactive multi-turn chatbot that maintains conversation memory across messages.
  • Customized AI behavior using system instructions to create a coding tutor personality with consistent responses.
  • Secret Mission: Made the chatbot production-ready with error handling and retry logic that gracefully handles network failures.

Ready to quiz yourself?