Build an AI Chatbot with Python

Build a terminal AI chatbot in Python that connects to Google's Gemini API.

Introduction

30 Second Summary

AI chatbots like ChatGPT have become part of daily life. You use them to brainstorm ideas, answer questions, and even write emails. But how do they actually work under the hood?

In this project, you will build your own AI chatbot from scratch using Python and Google's Gemini API. You'll write code that sends your messages to an AI model and displays its responses right in your terminal.

What You'll Build

A terminal-based AI chatbot powered by Google's Gemini model that holds multi-turn conversations and remembers what you said earlier in the chat.

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

  • A working Python script (chatbot.py) that connects to Google's Gemini AI and responds to your messages.
  • A solid understanding of Python fundamentals (variables, functions, loops, conditionals) learned by building something real.
  • A chatbot that maintains conversation history, so the AI remembers context from earlier in your chat.
  • Secret Mission: Give your chatbot a custom personality using system instructions.

Are there any prerequisites?

None. This project includes full setup instructions for every tool you need, including Python and VS Code. All you need is a computer and a Google account.

Before We Start

Before We Start...

Install Python and VS Code

Before writing any code, you need two tools on your computer. Python is the programming language your chatbot runs on.

VS Code is the code editor where you'll write and run your Python code. In this step, you'll install both tools and create a project folder to keep your chatbot files organized.

In this step, get ready to:
  • Install Python 3.14 on your computer.
  • Install VS Code with the Python extension.
  • Create your ai-chatbot project folder.
Download and install Python

Python is the language your chatbot is written in. Let's check if it's already on your computer.

  • Open a terminal on your computer.
  • Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
  • Type Terminal (macOS) or Command Prompt (Windows) and press Enter to open it.
  • Check your Python version by running this command:

macOS

python3 --version

Windows

python --version

✔️ I see version 3.14 or higher

Python is ready to go. Move on to the next substep.

ⓧ I see an older version

You have Python installed, but your version is too old for this project. You need 3.14 or higher.

macOS

  • Go to python.org/downloads in your browser.
  • Click the Download Python 3.14.5 button.
  • Open the downloaded .pkg file and follow the installation prompts.
  • Close your terminal and open a new one.
  • Run python3 --version again to confirm you see 3.14.5.

Windows

  • Go to python.org/downloads in your browser.
  • Click the Download Python 3.14.5 button.
  • Run the installer. On the first screen, check the box that says Add python.exe to PATH before clicking Install Now.
  • Close your Command Prompt and open a new one.
  • Run python --version again to confirm you see 3.14.5.

Why a new terminal?

Environment changes like PATH updates only take effect in new terminal windows. Your old terminal still has the outdated settings loaded.

ⓧ Command not found

Python is not installed on your computer yet. Let's install it now.

macOS

  • Go to python.org/downloads in your browser.
  • Click the Download Python 3.14.5 button.
  • Open the downloaded .pkg file and follow the installation prompts.
  • Close your terminal and open a new one.
  • Verify the installation by running:
python3 --version

You should see Python 3.14.5 printed in the output.

Windows

  • Go to python.org/downloads in your browser.
  • Click the Download Python 3.14.5 button.
  • Run the installer. On the first screen, check the box that says Add python.exe to PATH before clicking Install Now.
  • Wait for the installation to complete, then click Close.
  • Close your Command Prompt and open a new one.
  • Verify the installation by running:
python --version

You should see Python 3.14.5 printed in the output.

Still seeing 'command not found'?

Make sure you opened a brand new terminal window after installing. If it still doesn't work, the installer may not have added Python to your PATH correctly.

On Windows, re-run the installer, select Modify, and make sure the PATH option is enabled. On macOS, try running /Library/Frameworks/Python.framework/Versions/3.14/bin/python3 --version to confirm the install exists.

help me fix Python not being recognized in my terminal

What is PATH?

PATH is a list of folders your computer checks when you type a command. Adding Python to PATH means you can run python from any terminal window without typing the full file path to the program.

Install VS Code

VS Code is a free code editor that makes writing Python much easier with features like syntax highlighting and error detection.

  • Go to code.visualstudio.com in your browser.
  • Click the large Download button. The site automatically detects your operating system.
  • Run the downloaded installer and follow the prompts to complete the installation.
  • Open VS Code.
  • Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
  • Type Visual Studio Code and press Enter to open it.

Now install the Python extension so VS Code understands Python code.

  • Open the Extensions panel by pressing Cmd+Shift+X (macOS) or Ctrl+Shift+X (Windows).
  • Type Python in the search box at the top of the panel.
  • Find the extension called Python by Microsoft. It should be the first result.
  • Click Install.

What does the Python extension do?

The Python extension gives VS Code superpowers for Python development. It adds code completion, error highlighting, and the ability to run Python files directly from the editor.

Don't see the extension?

Make sure you're searching in the Extensions panel (the icon looks like four squares on the left sidebar) and not in the file search. The Python extension by Microsoft has millions of installs and a blue verified checkmark.

help me find and install the Python extension in VS Code

Create your project folder

Every project needs its own folder to keep files organized. You'll create a folder called ai-chatbot on your Desktop.

  • Open the VS Code terminal by pressing Ctrl+` (Windows) or Cmd+` (macOS). This opens a terminal panel at the bottom of VS Code.
  • Move to your Desktop by running this command:
cd ~/Desktop
  • Create your project folder by running this command:
mkdir ai-chatbot
  • Confirm the folder was created by running:
ls

You should see ai-chatbot listed in the output.

Now open this folder in VS Code so it becomes your workspace.

  • Click File in the top menu bar.
  • Click Open Folder.
  • Navigate to your Desktop, select the ai-chatbot folder, then click Open (macOS) or Select Folder (Windows).

What does opening a folder do?

Opening a folder tells VS Code that everything inside it belongs to your project. The Explorer sidebar on the left now shows your project files, and the terminal automatically starts in this folder.

VS Code may ask if you trust the authors of the files in this folder. Click Yes, I trust the authors.

Don't see the ai-chatbot folder?

Make sure you're navigating to your Desktop in the file picker. On Windows, check under C:\Users\YourName\Desktop. On macOS, check under /Users/YourName/Desktop.

help me find my ai-chatbot folder on my computer

Your tools are installed and your project folder is ready. Next up, you'll grab a free API key that lets your chatbot talk to Google's Gemini AI.

Get Your Free Gemini API Key

Your development environment is ready with Python and VS Code. Now your chatbot needs a way to communicate with Google's Gemini AI model.

To connect to Gemini, your code needs an API key. In this step, you'll create a free key from Google AI Studio and store it securely on your computer as an environment variable.

In this step, get ready to:
  • Sign in to Google AI Studio.
  • Create and copy a Gemini API key.
  • Store the key as an environment variable on your computer.
Create a Google AI Studio account

Google AI Studio is the free web tool where you manage your Gemini API keys. You just need a Google account to get started.

  • Open your browser and go to aistudio.google.com.
  • Sign in with your Google account.
  • If prompted, accept the Terms of Service.

What is Google AI Studio?

Google AI Studio is a free platform from Google where developers can test AI models, manage API keys, and experiment with prompts. It is the control panel for accessing Gemini from your own code.

For new users, Google AI Studio automatically creates a default project after you accept the Terms of Service. This means you can jump straight into creating your API key.

Get your API key
  • In the left sidebar, click Get API key.
  • Click Create API key.
  • If prompted to choose a project, select Create key in new project. Google AI Studio will create a project for you automatically.
  • Once the key appears, click the copy icon next to it to copy it to your clipboard.

What is an API key?

An API key is a unique string of characters that identifies your application to a service. When your Python code sends a request to Gemini, it includes this key so Google knows who is making the request.

Keep your API key private. Never share it publicly or commit it to a code repository.

Your key stays visible

Unlike some other AI providers, Google AI Studio lets you view and copy your key again later from the same page. If you lose it from your clipboard, you can always return to the API keys page.

Set up your API key as an environment variable

Instead of pasting your key directly into your code, you'll store it in a Windows environment variable. Your Python code can then read the key without it ever appearing in your files.

  • Press the Windows key to open your search bar.
  • Type Environment Variables and click Edit the system environment variables from the results.
  • In the System Properties window that appears, click the Environment Variables button near the bottom.
  • Under User variables, click New.
  • In the Variable name field, type GEMINI_API_KEY.
  • In the Variable value field, paste the API key you copied from Google AI Studio.
  • Click OK on all open dialogs to save your changes.

What is an environment variable?

An environment variable is a value stored by your operating system that any program can read. It keeps sensitive information like API keys out of your code files.

When you set GEMINI_API_KEY here, Python can access it later without you ever typing the key into your script.

  • Close VS Code completely.
  • Press the Windows key, type VS Code, and press Enter to reopen it.
  • Click File in the top menu bar, then Open Folder.
  • Select your ai-chatbot folder on the Desktop, then click Select Folder.

VS Code loads environment variables when it first starts. Closing and reopening it ensures your new GEMINI_API_KEY variable is available to Python.

Python can't find your API key later?

Make sure you closed and reopened VS Code after setting the variable. VS Code only reads environment variables at startup.

Double-check that you added the variable under User variables, not System variables. Both sections are visible in the Environment Variables dialog.

Help me troubleshoot why Python can't find my GEMINI_API_KEY environment variable on Windows.

Your API key is configured and ready to go. Next up, you'll write your first Python code and start building the chatbot.

Write Your First Python Code

Your API key is stored safely as an environment variable, and VS Code is ready to use it. Now it's time to write the Python code that will power your chatbot.

In this step, you'll create your first Python file and learn two fundamental building blocks: variables (which store data) and functions (which package reusable actions).

In this step, get ready to:
  • Create chatbot.py and store your chatbot's name in a variable.
  • Write a function that asks the user for input.
  • Run your code and test the chatbot's welcome message.
Create your file and learn variables

Every Python program starts with a file. You'll create one now and use it to learn about variables and the print() function.

  • In VS Code, look at the Explorer sidebar on the left (the top icon that looks like two stacked files).
  • Hover over the AI-CHATBOT section header and click the New File... icon (a page with a plus sign).
  • Type chatbot.py and press Enter.

A blank editor tab opens for your new file.

  • Type the following code into chatbot.py:
# Store the chatbot's name in a variable
bot_name = "Gemini Chatbot"

# Print a welcome banner using f-strings
print(f"\n{'='*50}")
print(f"  Welcome to {bot_name}!")
print(f"  Type 'quit' or 'exit' to end the conversation.")
print(f"{'='*50}")

What does this code do?

bot_name = "Gemini Chatbot" creates a variable. A variable is a label that holds a value you can reuse later.

The print() lines display text in your terminal. The f before the quote marks makes it an f-string, which lets you insert variables directly inside curly braces like {bot_name}.

{'='*50} repeats the = character 50 times to create a decorative line.

  • Save chatbot.py by pressing Ctrl+S.

You won't see output yet because you haven't run the file. The next substep adds a function, then you'll run everything together.

Learn about functions

A function is a named block of code that performs a specific job. You define it once, then call it whenever you need that job done.

  • In chatbot.py, place your cursor at the very top of the file (above the # Store the chatbot's name comment).
  • Add this function definition at the top, followed by a blank line:
def get_user_input():
    """Get a message from the user."""
    user_message = input("\nYou: ")
    return user_message

What does this function do?

def get_user_input(): defines a new function called get_user_input. The def keyword tells Python you're creating a function.

input("\nYou: ") pauses the program and waits for the user to type something. Whatever they type gets stored in user_message.

return user_message sends that value back to wherever the function was called.

  • Now scroll to the very bottom of the file (below the last print line).
  • Add these lines at the bottom to call the function and display what the user typed:
message = get_user_input()
print(f"You typed: {message}")

What does calling a function look like?

message = get_user_input() runs the function you defined earlier. The value it returns (whatever the user typed) gets stored in a new variable called message.

This pattern of "define once, call many times" is how professional code stays organized.

  • Save chatbot.py by pressing Ctrl+S.

Your file now has a function at the top, the welcome message in the middle, and the function call at the bottom.

✔️ Awesome, I've got everything!

Great. Double check you've saved your file, then move on to run it.

ⓧ I'd like to double check the full code

Here is the complete chatbot.py file at this point:

def get_user_input():
    """Get a message from the user."""
    user_message = input("\nYou: ")
    return user_message

bot_name = "Gemini Chatbot"
print(f"\n{'='*50}")
print(f"  Welcome to {bot_name}!")
print(f"  Type 'quit' or 'exit' to end the conversation.")
print(f"{'='*50}")

message = get_user_input()
print(f"You typed: {message}")
Run your code

Time to see your code in action. You'll use the VS Code terminal to run the file.

  • Open the VS Code terminal by pressing Ctrl+` (the backtick key, usually above Tab).
  • Run your chatbot by entering this command:
python chatbot.py

You should see your welcome banner printed with a row of = signs, your bot name, and a prompt that says You: waiting for you to type.

  • Type any message (like hello) and press Enter.

You should see You typed: hello printed back to you. This confirms your variable, f-strings, and function all work correctly.

Seeing an error instead?

  • If you see IndentationError, check that the lines inside your function are indented with exactly 4 spaces. Python uses indentation to know which lines belong inside a function.
  • If you see SyntaxError, look for missing parentheses, quotes, or colons. Every print( needs a matching ), and every opening quote needs a closing quote.
  • If the terminal says python is not recognized, close and reopen VS Code so it picks up the PATH change from your Python installation.

Still stuck? Help me debug my chatbot.py code.

Your first Python code is alive. Next up, you'll connect this code to the Gemini API so your chatbot can actually think.

Connect to the Gemini API

Your chatbot can greet users and accept their input. It just can't do anything intelligent with that input yet.

In this step, you'll connect your code to Google's Gemini AI using their official Python SDK. Once connected, your chatbot will be able to send messages to the AI and receive real responses.

In this step, get ready to:
  • Install the Google GenAI Python SDK.
  • Connect to the Gemini API using a client object.
  • Send your first message to the AI and print its response.
Install the Google GenAI SDK

The Google GenAI SDK is a Python library that handles all the complexity of communicating with Gemini's servers. Instead of manually building web requests, you just call simple Python methods.

  • Install the official Google GenAI Python library by running this command in your VS Code terminal:
pip install google-genai

What does this command do?

`pip` is Python's package manager. It downloads the `google-genai` library and all its dependencies from the internet and installs them into your Python environment.

  • You should see output ending with a line that says Successfully installed followed by package names. This confirms the library is ready to use.

Seeing an error during install?

  • If you see pip is not recognized, close and reopen VS Code so it picks up your Python PATH. Then try the command again.
  • If you see a permissions error, try running pip install --user google-genai instead.
  • Make sure your VS Code terminal is open inside the ai-chatbot folder.

Why isn't pip installing the package?

Write the API connection code

With the library installed, you need two things to connect to Gemini: an import statement that loads the library, and a client object that manages the connection. The client automatically reads the GEMINI_API_KEY environment variable you set up earlier.

  • In chatbot.py, add this import line at the very top of the file (above everything else):
from google import genai
  • Now find the closing line of your get_user_input() function:
    return user_message
  • Add this line below it, leaving a blank line between the function and this new code:
client = genai.Client()

What does this code do?

`from google import genai` loads the GenAI library so you can use its features in your code.

`genai.Client()` creates a client object that handles communication with Gemini's servers. It automatically looks for your GEMINI_API_KEY environment variable to authenticate your requests.

You won't see a change yet. The next substep uses this client to actually talk to Gemini.

Send your first message to Gemini

Your client is connected. Now you'll replace the test code at the bottom of your file with a real API call that sends a message to Gemini and prints its response.

  • In chatbot.py, scroll to the bottom and find these two lines:
message = get_user_input()
print(f"You typed: {message}")
  • Delete both lines and replace them with the following code:
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Hello! What can you do?"
)
print(response.text)

What does this code do?

  • `client.models.generate_content()` sends a request to the Gemini AI model and waits for a response.
  • `model="gemini-2.5-flash"` tells the API which AI model to use. Flash is fast and available on the free tier.
  • `contents="Hello! What can you do?"` is the message you're sending to the AI.
  • `response.text` extracts the text portion of Gemini's response so you can print it.
  • Save chatbot.py.
  • Run your chatbot by entering this command in the terminal:
python chatbot.py
  • You should see your welcome message printed, followed by a paragraph of text from Gemini describing what it can do.

Not seeing a response from Gemini?

  • If you see an error about API key, make sure you closed and reopened VS Code after setting the GEMINI_API_KEY environment variable.
  • If you see a ModuleNotFoundError, the google-genai package did not install correctly. Run pip install google-genai again.
  • If you see a network or timeout error, check your internet connection and try running the script again.

Help me debug my Gemini API connection.

✔️ Awesome, I've got everything!

Great. Double check you've saved your file before moving on.

ⓧ I'd like to double check the full code

Here's what your complete chatbot.py should look like at this point:

from google import genai


def get_user_input():
    """Get a message from the user."""
    user_message = input("\nYou: ")
    return user_message


client = genai.Client()

bot_name = "Gemini Chatbot"
print(f"\n{'='*50}")
print(f"  Welcome to {bot_name}!")
print(f"  Type 'quit' or 'exit' to end the conversation.")
print(f"{'='*50}")

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Hello! What can you do?"
)
print(response.text)

Your chatbot is officially talking to an AI model. Next up, you'll build a chat loop so you can have a real back-and-forth conversation with Gemini.

Build the Chat Loop

Your chatbot can talk to Gemini, but right now it only sends one hardcoded message and exits. A real chatbot needs to keep the conversation going until you decide to stop.

In this step, you will replace the single-message code with an interactive loop. The loop will keep asking for your input, send each message to Gemini, and display the AI's response.

In this step, get ready to:
  • Replace the single-message code with a multi-turn chat session.
  • Build a while loop that keeps the conversation going until you type quit or exit.
  • Format responses with You: and Gemini: prefixes for readability.
Create a multi-turn chat session

Right now, your code uses client.models.generate_content() to send a single message. This method has no memory. Each call is independent, so the AI cannot remember what you said before.

The Gemini SDK provides a chat object that maintains conversation history automatically. Every message you send through it gets added to a running transcript, so the AI can reference earlier parts of your conversation.

  • In chatbot.py, find this line:
client = genai.Client()
  • Add this new line directly below it:
chat = client.chats.create(model="gemini-2.5-flash")

What does this line do?

client.chats.create() creates a stateful chat session tied to the gemini-2.5-flash model. Unlike generate_content(), this object keeps track of every message exchanged.

When you send a new message through the chat object, it automatically includes the full conversation history so Gemini can respond with context.

  • Now scroll to the bottom of your file and find these lines:
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Hello! What can you do?"
)
print(response.text)
  • Delete all five of those lines. You will replace them with a chat loop in the next substep.
Build a while loop for continuous conversation

A while True: loop runs forever until something inside it calls break. This is the standard pattern for interactive programs that wait for user input.

  • At the bottom of chatbot.py (below the welcome message prints), add the following while loop:
while True:
    # Get user input
    user_message = get_user_input()

    # Check if user wants to quit
    if user_message.lower() in ["quit", "exit"]:
        print("\nGoodbye! Thanks for chatting.")
        break

    # Skip empty messages
    if not user_message.strip():
        print("Please type a message.")
        continue

    # Send message to Gemini and print formatted response
    response = chat.send_message(user_message)
    print(f"\nGemini: {response.text}")

What does this code do?

  • while True: starts an infinite loop that keeps the chatbot running.
  • get_user_input() calls the function you wrote earlier, which displays the You: prompt and waits for input.
  • user_message.lower() in ["quit", "exit"] checks if the user wants to stop. The .lower() means typing QUIT or Exit also works.
  • break exits the loop entirely, ending the program.
  • continue skips the rest of the current loop iteration and goes back to asking for input.
  • chat.send_message() sends your message through the chat session and returns the AI's response.
  • Save chatbot.py.

Seeing an indentation error?

Python uses indentation (spaces) to define what code belongs inside a loop or condition. Make sure all lines inside while True: are indented by exactly 4 spaces.

If you see IndentationError: expected an indented block, check that the line after while True: is indented. Help me fix my indentation error in chatbot.py

Test the formatted output

Your chatbot now uses f-strings to display messages with clear prefixes. The You: prefix comes from get_user_input(), and Gemini: prefixes the AI's response. The \n characters add blank lines between exchanges for readability.

  • Run your chatbot by entering this command in the VS Code terminal:
python chatbot.py
  • Type a message (like Hello!) and press Enter.
  • You should see Gemini: followed by the AI's response on a new line.
  • Send a few more messages to see the conversation flow.
  • Type quit and press Enter to exit. You should see Goodbye! Thanks for chatting. and the program ends.

What should I see?

Your terminal output should look something like this:

==================================================
  Welcome to Gemini Chatbot!
  Type 'quit' or 'exit' to end the conversation.
==================================================

You: Hello!

Gemini: Hello! How can I help you today?

You: What is Python?

Gemini: Python is a popular programming language...

You: quit

Goodbye! Thanks for chatting.

The AI's actual responses will vary, but the formatting with prefixes and blank lines should match this structure.

Chatbot not responding or crashing?

  • If you see an error about the API key, make sure you closed and reopened VS Code after setting the GEMINI_API_KEY environment variable in Step 2.
  • If the chatbot hangs and never responds, check your internet connection. The Gemini API requires an active connection to process messages.
  • If you accidentally get stuck in the loop, press Ctrl+C to force-stop the program.

My chatbot is crashing or not responding to messages

✔️ Awesome, I've got everything!

Great. Double check you have saved chatbot.py and that your chatbot responded to at least one message.

ⓧ I'd like to double check the full code

Here is the complete chatbot.py at this point:

from google import genai


def get_user_input():
    """Get a message from the user."""
    user_message = input("\nYou: ")
    return user_message


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

bot_name = "Gemini Chatbot"
print(f"\n{'='*50}")
print(f"  Welcome to {bot_name}!")
print(f"  Type 'quit' or 'exit' to end the conversation.")
print(f"{'='*50}")

while True:
    user_message = get_user_input()

    if user_message.lower() in ["quit", "exit"]:
        print("\nGoodbye! Thanks for chatting.")
        break

    if not user_message.strip():
        print("Please type a message.")
        continue

    response = chat.send_message(user_message)
    print(f"\nGemini: {response.text}")

Your chatbot now holds real conversations. Next up, you will add error handling so it does not crash if something goes wrong, and organize the code like a professional Python developer.

Add Error Handling and Polish

Your chatbot can hold a full conversation, but there is one problem. If your internet drops or the API has an issue, the whole program crashes.

In this step, you will add error handling so your chatbot recovers gracefully from problems. You will also reorganize your code into a proper structure that professional Python developers use.

In this step, get ready to:
  • Wrap your API call in error handling so crashes become friendly messages.
  • Organize your code into a main function like professional Python scripts.
  • Test a multi-turn conversation to confirm your chatbot remembers context.
Handle errors gracefully

Right now, if the Gemini API returns an error (maybe your internet is down, or you have exceeded your rate limit), Python crashes and shows a scary red traceback. A try/except block catches errors and lets you respond with a friendly message instead of crashing.

  • In chatbot.py, scroll down to the bottom of your while True: loop.
  • Find these two lines at the end of the loop:
    response = chat.send_message(user_message)
    print(f"\nGemini: {response.text}")
  • Replace those two lines with this try/except block, so they now look like this:
    try:
        response = chat.send_message(user_message)
        print(f"\nGemini: {response.text}")
    except Exception as e:
        print(f"\nError: Something went wrong - {e}")
        print("Please try again.")

What does try/except do?

Python runs the code inside try: normally. If anything goes wrong, instead of crashing, Python jumps to the except block and runs that code instead.

The as e part captures the error details in a variable called e, so you can print it out and see what went wrong.

Organize with a main function

Professional Python scripts wrap their logic inside a def main(): function and use an if __name__ == "__main__": guard at the bottom. This pattern makes your code reusable and tells Python where to start running.

  • Select all the code below your get_user_input() function (everything from client = genai.Client() down to the end of the file) and delete it.
  • Replace it with this code, which wraps everything inside a main() function:
def main():
    """Run the AI chatbot."""
    # Create the Gemini client (reads GEMINI_API_KEY automatically)
    client = genai.Client()

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

    # Print welcome message
    bot_name = "Gemini Chatbot"
    print(f"\n{'='*50}")
    print(f"  Welcome to {bot_name}!")
    print(f"  Type 'quit' or 'exit' to end the conversation.")
    print(f"{'='*50}")

    # Main chat loop
    while True:
        # Get user input
        user_message = get_user_input()

        # Check if user wants to quit
        if user_message.lower() in ["quit", "exit"]:
            print("\nGoodbye! Thanks for chatting.")
            break

        # Skip empty messages
        if not user_message.strip():
            print("Please type a message.")
            continue

        # Send message to Gemini and get response
        try:
            response = chat.send_message(user_message)
            print(f"\nGemini: {response.text}")
        except Exception as e:
            print(f"\nError: Something went wrong - {e}")
            print("Please try again.")


if __name__ == "__main__":
    main()

What does if __name__ == "__main__" do?

This line checks whether the file is being run directly (like when you type python chatbot.py) or imported by another file. If run directly, it calls main() to start the chatbot.

Without this guard, your chatbot would start running any time another script tried to import a function from this file. It is a best practice you will see in almost every professional Python project.

  • Save chatbot.py.

Seeing an IndentationError?

Python is very strict about indentation. Every line inside def main(): must be indented by exactly 4 spaces. Lines inside the while True: loop need 8 spaces (4 for being inside main(), plus 4 for being inside the loop).

If you copied the code and the indentation looks off, try selecting all the code inside main() and pressing Tab or Shift+Tab to adjust.

Help me fix an IndentationError in my chatbot.py file

✔️ Awesome, I've got everything!

Great. Double check you have saved your file before moving on.

ⓧ I'd like to double check the full code

Here is the complete chatbot.py file. Make sure yours matches exactly:

from google import genai


def get_user_input():
    """Get a message from the user."""
    user_message = input("\nYou: ")
    return user_message


def main():
    """Run the AI chatbot."""
    # Create the Gemini client (reads GEMINI_API_KEY automatically)
    client = genai.Client()

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

    # Print welcome message
    bot_name = "Gemini Chatbot"
    print(f"\n{'='*50}")
    print(f"  Welcome to {bot_name}!")
    print(f"  Type 'quit' or 'exit' to end the conversation.")
    print(f"{'='*50}")

    # Main chat loop
    while True:
        # Get user input
        user_message = get_user_input()

        # Check if user wants to quit
        if user_message.lower() in ["quit", "exit"]:
            print("\nGoodbye! Thanks for chatting.")
            break

        # Skip empty messages
        if not user_message.strip():
            print("Please type a message.")
            continue

        # Send message to Gemini and get response
        try:
            response = chat.send_message(user_message)
            print(f"\nGemini: {response.text}")
        except Exception as e:
            print(f"\nError: Something went wrong - {e}")
            print("Please try again.")


if __name__ == "__main__":
    main()
Test your complete chatbot

Time to take your finished chatbot for a spin. You will have a multi-turn conversation and verify that the AI remembers what you told it earlier.

  • Run your chatbot by running this command in your VS Code terminal:
python chatbot.py
  • You should see the welcome banner with the = border and the prompt You: waiting for your input.
  • Type your name (for example, "My name is Alex") and press Enter.
  • Wait for Gemini to respond, then type "What's my name?" and press Enter.
  • Gemini should remember and repeat your name back to you. This proves the chat session is maintaining conversation history.
  • Type quit to end the conversation when you are done testing.

Chatbot not starting or crashing?

If you see an error about GEMINI_API_KEY, make sure you restarted VS Code after setting the environment variable in the previous step.

If you see a SyntaxError or IndentationError, compare your file against the full code in the double-check tab above. Pay close attention to indentation levels.

Help me debug my chatbot.py that is not running correctly

Your chatbot is complete. You have built a working AI chatbot from scratch using Python that connects to a real AI model, holds multi-turn conversations, and handles errors gracefully. Next up, you will take on a Secret Mission to give your chatbot a custom personality.

Secret mission

Give Your Chatbot a Personality

Your chatbot works, but it talks like a generic AI assistant. What if it could respond like a pirate, a scientist, or a poet? In this secret mission, you'll use system instructions to give your chatbot a custom personality that changes how it responds to every message.

Clean Up Your Resources

Clean Up Your Resources

This project runs entirely on your local machine and uses the free tier of the Gemini API. There are no ongoing costs, so nothing will charge you if you walk away.

Decide whether to keep your resources running, pause them to come back later, or delete them entirely.

Resources you used:

  • ai-chatbot project folder on your Desktop.
  • GEMINI_API_KEY environment variable (Windows user variables).
  • Gemini API key in Google AI Studio.
  • google-genai Python package.
  • Python 3.14 and VS Code (installed applications).

Keep everything running

No action needed. Choose this if you plan to keep building with Python and the Gemini API.

  • Your ai-chatbot folder stays on your Desktop, ready for you to open and run anytime.
  • Your GEMINI_API_KEY environment variable stays set, so future Python scripts can use the Gemini API immediately.
  • Python and VS Code remain installed and useful for any future coding projects.

Pause - I'll come back to this later

Close everything to free up memory. Your files and configuration stay in place for when you return.

  • Close VS Code.
  • Close any open Command Prompt or terminal windows.
  • Your project folder and environment variable will still be there when you come back.

Delete - I don't want to use this again

Remove all project resources completely. Follow each step below to clean up everything.

  • Delete the ai-chatbot project folder by opening File Explorer, navigating to your Desktop, right-clicking the ai-chatbot folder, and selecting Delete.
  • Remove the GEMINI_API_KEY environment variable. Open Windows Settings, search for Environment Variables, click Edit the system environment variables, then click the Environment Variables button. Under User variables, select GEMINI_API_KEY and click Delete. Click OK to confirm.
  • Delete your Gemini API key. Go to aistudio.google.com/api-keys, find the API key you created, click the Actions icon (three dots) next to it, and select Delete API key. Confirm the deletion in the modal.
  • Uninstall the google-genai package. Open Command Prompt and run:
pip uninstall google-genai
  • Type y when prompted to confirm the uninstall.
  • Uninstall Python. Open Windows Settings, go to Apps, then Installed apps. Search for Python 3.14, click the three-dot menu, and select Uninstall.
  • Uninstall VS Code. In the same Installed apps list, search for Visual Studio Code, click the three-dot menu, and select Uninstall.

Nice Work!

Nice Work!

You just built a working AI chatbot from scratch using Python and Google's Gemini API. You wrote real code that connects to a cutting-edge AI model and holds multi-turn conversations in your terminal.

You've learned how to:

  • Write a complete Python script from scratch using variables, f-strings, functions, while loops, conditionals, and error handling.
  • Connect to Google's Gemini API and send prompts to a live AI model using the google-genai SDK.
  • Build a multi-turn chatbot that maintains conversation history across messages automatically.
  • Secret Mission: Gave your chatbot a custom personality using system instructions and let users choose from multiple characters with an if/elif/else chain.

Ready to quiz yourself?