Multi-Turn AI Chatbot with Gemini

Build a terminal chatbot with Python and Google Gemini that streams responses.

Introduction

30 Second Summary

Every time you ask ChatGPT or Google's Gemini a question, you're sending text to an AI model over an API and getting a response back. That same technology is available to you as a developer, and it's surprisingly simple to use.

In this project, you will build a terminal-based AI chatbot powered by Google's Gemini API. You'll give it a custom personality, hold multi-turn conversations where it remembers what you said earlier, and watch responses stream in word-by-word.

What You'll Build

A Python chatbot that connects to Google's Gemini API, holds intelligent conversations with memory, and streams responses in real-time directly in your terminal.

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

  • A working Python script (chatbot.py) that sends prompts to the Gemini API and receives AI-generated responses.
  • A custom AI personality defined through system prompts that shapes how the bot talks and behaves.
  • A multi-turn conversation loop with real-time streaming responses that appear word-by-word in the terminal.
  • Secret Mission: Add multiple personality modes the user can switch between mid-conversation.

Are there any prerequisites?

You should have basic Python knowledge (variables, functions, loops, and dictionaries). You'll also need a Google account to get your free API key. No credit card is required.

Set Up Your Environment

Before your chatbot can talk to anyone, it needs a connection to Google's Gemini AI.

In this step, you will grab a free API key from Google, configure your terminal to use it, and install the Python package that lets your code communicate with Gemini.

In this step, get ready to:
  • Get a free Gemini API key from Google AI Studio.
  • Set the API key as an environment variable in PowerShell.
  • Install and verify the Google Gen AI SDK.
Get your free Gemini API key

An API key is a unique string that identifies your application when it talks to Gemini. Google provides these for free through Google AI Studio.

  • Open your browser and navigate to aistudio.google.com.
  • Sign in with your Google account.
  • Click Get API Key in the left sidebar.
  • Click Create API key.
  • Copy the key that appears and save it somewhere safe (you will need it in the next substep).

Why is this free?

Google's Gemini API offers a free tier with no credit card required. You get up to 1,000 requests per day, which is more than enough for this project.

Keep your API key private

Your API key is like a password. Never share it publicly, commit it to Git, or paste it into code that others can see.

You will store it in an environment variable to keep it out of your source files.

Set your API key as an environment variable

Instead of pasting your key directly into your code, you will store it in an environment variable. Your Python script can read it from there without ever exposing the raw value.

  • Press the Windows key to open your search bar.
  • Type PowerShell and press Enter to open it.
  • Set the environment variable for this session by running this command:
$env:GEMINI_API_KEY = "your-api-key-here"
  • Replace your-api-key-here with the API key you copied from Google AI Studio.

What does this command do?

The $env: prefix tells PowerShell to create an environment variable. The Google Gen AI SDK automatically looks for a variable named GEMINI_API_KEY when it connects to the API, so your code never needs to contain the key itself.

This variable lasts only for your current PowerShell session. If you close the window, you will need to run the command again next time.

Make it permanent

To avoid re-entering the key every session, add it to your system environment variables. Search for Environment Variables in the Windows start menu, click Edit the system environment variables, then add a new User variable named GEMINI_API_KEY with your key as the value.

Install the Google Gen AI SDK

The google-genai package is the official Python SDK for talking to Google's Gemini models. It handles authentication, request formatting, and response parsing for you.

  • Install the package by running this command in PowerShell:
pip install google-genai

Seeing 'pip' is not recognized?

This means Python is not added to your system PATH. Reinstall Python and make sure to check the Add Python to PATH box during installation.

Help me fix my pip installation.

  • Verify the installation worked by running:
python -c "from google import genai; print('SDK ready!')"

✔️ I see SDK ready!

The SDK is installed and working. You are ready to start building your chatbot.

ⓧ I see an error

Here are common fixes depending on the error you see:

  • If you see ModuleNotFoundError: the pip install may not have completed. Run pip install google-genai again and check for error messages in the output.
  • If you see a version error: the google-genai package requires Python 3.10 or higher. Check your version with python --version and upgrade if needed.

Still stuck?

Help me troubleshoot my SDK installation.

Your environment is ready. Next up, you will write your first few lines of Python to call the Gemini API and see it respond.

Make Your First API Call

Your environment is ready with the SDK installed and your API key stored safely. Now it's time to write some Python that actually talks to Gemini.

Every AI-powered app starts the same way: send text to a model, get text back. In this step, you'll build that foundational loop and then upgrade it with streaming so responses appear in real-time.

In this step, get ready to:
  • Send your first prompt to Gemini and receive a response.
  • Upgrade to streaming so responses appear word-by-word in the terminal.
Create your project folder and chatbot file

Before writing code, you need a dedicated folder to keep your chatbot project organized.

  • Move to your Desktop by running this command:
cd ~/Desktop
  • Create your project folder and move into it by running these commands:
mkdir gemini-chatbot
cd gemini-chatbot
  • Confirm the folder exists by running:
ls

You should see the gemini-chatbot folder listed in the output (it will be empty for now).

  • Open the gemini-chatbot folder in your code editor.
  • Create a new file called chatbot.py inside this folder.

This is the only file your chatbot needs. All of your code will live here.

Send your first prompt to Gemini

The Gemini API follows a simple request/response pattern. You send text (a prompt) to a model, and the model returns generated text.

  • In chatbot.py, add the following code to create a Gemini client and send a single prompt:
import os
import sys
from google import genai
from google.genai import types

# Initialize the Gemini client
client = genai.Client()

# Send a single prompt to Gemini
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Hello! What can you help me with?"
)

print(response.text)

What does this code do?

This script sets up the connection to Gemini and sends one message.

  • client = genai.Client() creates a client that automatically reads your GEMINI_API_KEY environment variable. No need to pass the key explicitly.
  • client.models.generate_content() sends your prompt to the gemini-2.5-flash model and waits for the full response.
  • response.text contains the AI-generated reply as a single string.
  • Save chatbot.py.
  • Run the script in your terminal by running this command:
python chatbot.py

You should see a friendly response from Gemini printed in your terminal. The exact wording will vary each time since the AI generates new text for every request.

What just happened?

Your script sent the text "Hello! What can you help me with?" to Google's servers. Gemini processed it and returned a complete response all at once.

Notice the slight pause before anything appears. The API waits until the entire response is generated before sending it back. Streaming fixes this.

Not seeing a response?

  • Make sure your GEMINI_API_KEY environment variable is set in the same terminal session where you're running the script. Run echo $env:GEMINI_API_KEY in PowerShell to check.
  • If you see a "module not found" error, confirm you installed google-genai with pip install google-genai.
  • If you see a rate limit or quota error, wait a few seconds and try again.

Help me debug my first Gemini API call in Python

Add streaming for real-time responses

Streaming lets you display text as it's generated instead of waiting for the complete response. This creates the "typing" effect you see in tools like ChatGPT.

  • In chatbot.py, find this code:
# Send a single prompt to Gemini
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Hello! What can you help me with?"
)

print(response.text)
  • Replace it with this streaming version:
# Basic streaming API call
response = client.models.generate_content_stream(
    model="gemini-2.5-flash",
    contents="Hello! What can you help me with?"
)

for chunk in response:
    print(chunk.text, end="", flush=True)
print()

What changed?

  • generate_content_stream() returns chunks of text as they're generated, instead of waiting for the full response.
  • The for chunk in response loop processes each piece as it arrives.
  • end="" prevents Python from adding a newline after each chunk, so the text flows together naturally.
  • flush=True forces each chunk to display immediately instead of waiting in a buffer.
  • The final print() adds a newline after the full response finishes.
  • Save chatbot.py and run it again:
python chatbot.py

This time, you should see text appearing word-by-word in your terminal instead of all at once.

Text still appearing all at once?

  • Check that you changed generate_content to generate_content_stream (with _stream at the end).
  • Confirm you have flush=True in your print statement. Without it, Python buffers output.
  • If the response is very short, streaming may appear instantaneous. Try a longer prompt like "Explain how the internet works" to see the effect clearly.

Help me get streaming working with the Gemini API

✔️ Awesome, I've got everything!

Great. Make sure you've saved chatbot.py before moving on.

ⓧ I'd like to double check the full code

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

import os
import sys
from google import genai
from google.genai import types

# Initialize the Gemini client
client = genai.Client()

# Basic streaming API call
response = client.models.generate_content_stream(
    model="gemini-2.5-flash",
    contents="Hello! What can you help me with?"
)

for chunk in response:
    print(chunk.text, end="", flush=True)
print()

You've made your first successful AI API call and upgraded it with streaming. Next up, you'll give your chatbot a personality using system prompts.

Add a Custom Personality with System Prompts

Right now, your chatbot responds like a generic AI assistant. It has no personality, no guardrails, and no specific role.

System prompts let you define who the AI is before the conversation even starts. Think of it like giving an actor a character sheet. Every response the model generates will follow the personality and rules you set in the system prompt.

In this step, get ready to:
  • Define a custom personality using a system prompt.
  • Pass the system prompt to the Gemini API and test it.
Define your chatbot's personality

A system instruction is a block of text that the model reads before processing any user message. It shapes tone, length, expertise, and behavior for the entire conversation.

  • In chatbot.py, find the line that says # Basic streaming API call.
  • Replace that comment and the response = ... block below it (but NOT the for chunk loop) with the following code:
# Define the chatbot personality
SYSTEM_PROMPT = """You are a friendly and enthusiastic coding tutor named Sparky. 
You explain technical concepts in simple terms using analogies and examples. 
You keep responses concise (2-3 paragraphs max) and always encourage the learner. 
When you don't know something, you say so honestly."""

config = types.GenerateContentConfig(
    system_instruction=SYSTEM_PROMPT
)

response = client.models.generate_content_stream(
    model="gemini-2.5-flash",
    contents="Hello! What can you help me with?",
    config=config
)

What does this code do?

SYSTEM_PROMPT is a multi-line string that defines your chatbot's personality. It tells the model to act as "Sparky," a friendly coding tutor who uses simple language and keeps things concise.

types.GenerateContentConfig(system_instruction=SYSTEM_PROMPT) wraps that personality into a configuration object. Passing config=config to the API call tells Gemini to follow those instructions for every response it generates.

  • Save chatbot.py.

Seeing a syntax error?

Make sure the triple quotes """ open and close your SYSTEM_PROMPT string. Missing a set of triple quotes is the most common cause of unexpected syntax errors here.

Also check that config=config appears inside the generate_content_stream() parentheses, with a comma after the contents line above it.

Help me fix a syntax error in my Gemini system prompt configuration.

Test the personality

Your chatbot now has a personality baked in. Every response Gemini generates will follow Sparky's rules: simple language, analogies, encouragement, and honesty.

  • Run your chatbot by entering this command in the terminal:
python chatbot.py

You should see a response that sounds like a friendly tutor introducing themselves. Instead of a generic AI reply, Sparky should use casual language, offer encouragement, and keep things brief.

What is a system prompt doing behind the scenes?

The model reads your system instruction before it reads the user's message. It treats the system prompt as higher-priority context that shapes every response.

Try changing the contents string to ask a technical question like "What is a variable in Python?" and run the script again. Notice how Sparky explains it with analogies and keeps it short.

Response doesn't sound different?

Double check that config=config is actually being passed to generate_content_stream(). Without it, the model never sees your system instruction.

Help me figure out why my system prompt isn't changing Gemini's responses.

✔️ 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 at this point:

import os
import sys
from google import genai
from google.genai import types

# Initialize the Gemini client
client = genai.Client()

# Define the chatbot personality
SYSTEM_PROMPT = """You are a friendly and enthusiastic coding tutor named Sparky. 
You explain technical concepts in simple terms using analogies and examples. 
You keep responses concise (2-3 paragraphs max) and always encourage the learner. 
When you don't know something, you say so honestly."""

config = types.GenerateContentConfig(
    system_instruction=SYSTEM_PROMPT
)

response = client.models.generate_content_stream(
    model="gemini-2.5-flash",
    contents="Hello! What can you help me with?",
    config=config
)

for chunk in response:
    print(chunk.text, end="", flush=True)
print()

Your chatbot now has its own personality. Next up, you will add multi-turn conversation memory so Sparky can remember what you said earlier in the chat.

Build Multi-Turn Conversation Memory

Your chatbot has a personality and streams responses in real time. Sparky sounds great. But right now, the script handles one message and exits.

Real conversations flow back and forth. The Gemini SDK provides a chat session object that automatically tracks everything you and the AI have said. In this step, you'll build a persistent conversation loop that lets Sparky remember earlier context.

In this step, get ready to:
  • Create a reusable chat session function that wraps the system prompt and model config.
  • Build a conversation loop with streaming responses.
  • Add a graceful exit command and test multi-turn memory.
Replace the single-prompt pattern with a chat session

The current script sends one message and exits. The client.chats.create() method returns a stateful Chat object that tracks the full conversation history automatically. Each message you send includes all previous messages behind the scenes.

  • In chatbot.py, find and delete everything from the config = types.GenerateContentConfig( line all the way down to the final print() at the bottom of the file.
  • Here is the code to delete:
config = types.GenerateContentConfig(
    system_instruction=SYSTEM_PROMPT
)

response = client.models.generate_content_stream(
    model="gemini-2.5-flash",
    contents="Hello! What can you help me with?",
    config=config
)

for chunk in response:
    print(chunk.text, end="", flush=True)
print()
  • In its place, add the create_chat() function by pasting this code below the SYSTEM_PROMPT variable:
def create_chat():
    """Create a new chat session with the system prompt."""
    config = types.GenerateContentConfig(
        system_instruction=SYSTEM_PROMPT
    )
    chat = client.chats.create(
        model="gemini-2.5-flash",
        config=config
    )
    return chat

What does this code do?

This function wraps the config and chat creation into a reusable unit.

  • types.GenerateContentConfig(system_instruction=SYSTEM_PROMPT) attaches Sparky's personality to every message in the session.
  • client.chats.create() returns a Chat object that tracks conversation history. You no longer need to manage message arrays yourself.
  • The model parameter tells the SDK which Gemini model to use for this chat.
  • Save chatbot.py.
  • You won't see a change yet. The next chunk adds the conversation loop that uses this function.

Seeing a syntax error?

Make sure you deleted all of the old standalone code. If any lines from the previous response = client.models.generate_content_stream(...) block remain, Python will throw an indentation or name error.

Help me fix a syntax error in my chatbot.py after deleting the old code

Add the conversation loop with streaming

A chatbot needs two more pieces: a helper to print streamed chunks, and a main loop that keeps asking for input until the user quits.

  • Add the stream_response() function below create_chat():
def stream_response(response):
    """Print streaming response chunks as they arrive."""
    for chunk in response:
        print(chunk.text, end="", flush=True)
    print()  # New line after response completes

What does this code do?

This is the same streaming logic from earlier, wrapped in a reusable function. It iterates over response chunks and prints each one immediately with flush=True. The final print() adds a newline once the full response is done.

  • Now add the main() function and entry point below stream_response():
def main():
    """Main chatbot loop."""
    chat = create_chat()

    while True:
        try:
            user_input = input("You: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nGoodbye!")
            break

        if not user_input:
            continue

        if user_input.lower() in ("quit", "exit"):
            print("\nSparky: It was great chatting with you! Keep coding! 🚀")
            break

        print("Sparky: ", end="", flush=True)
        response = chat.send_message_stream(user_input)
        stream_response(response)
        print()

if __name__ == "__main__":
    main()

What does this code do?

  • chat = create_chat() starts a fresh chat session with Sparky's personality loaded.
  • while True creates an infinite loop that keeps the conversation going until the user explicitly exits.
  • input("You: ") prompts for user input. The try/except handles Ctrl+C gracefully instead of crashing.
  • if user_input.lower() in ("quit", "exit") checks for the exit commands and prints a farewell message.
  • chat.send_message_stream(user_input) sends the user's message to Gemini with the full conversation history included automatically.
  • if __name__ == "__main__": main() ensures the chatbot only runs when you execute the script directly.
  • Save chatbot.py.

Seeing an indentation error?

Make sure stream_response() and main() are at the same indentation level as create_chat(). All three functions should start at column 0 (no leading spaces).

Help me fix an indentation error in my chatbot.py

✔️ Awesome, I've got everything!

Great. Double check you've saved chatbot.py before moving on.

ⓧ I'd like to double check the full code

import os
import sys
from google import genai
from google.genai import types

# Initialize the Gemini client
client = genai.Client()

# Define the chatbot personality
SYSTEM_PROMPT = """You are a friendly and enthusiastic coding tutor named Sparky. 
You explain technical concepts in simple terms using analogies and examples. 
You keep responses concise (2-3 paragraphs max) and always encourage the learner. 
When you don't know something, you say so honestly."""

def create_chat():
    """Create a new chat session with the system prompt."""
    config = types.GenerateContentConfig(
        system_instruction=SYSTEM_PROMPT
    )
    chat = client.chats.create(
        model="gemini-2.5-flash",
        config=config
    )
    return chat

def stream_response(response):
    """Print streaming response chunks as they arrive."""
    for chunk in response:
        print(chunk.text, end="", flush=True)
    print()  # New line after response completes

def main():
    """Main chatbot loop."""
    chat = create_chat()

    while True:
        try:
            user_input = input("You: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nGoodbye!")
            break

        if not user_input:
            continue

        if user_input.lower() in ("quit", "exit"):
            print("\nSparky: It was great chatting with you! Keep coding! 🚀")
            break

        print("Sparky: ", end="", flush=True)
        response = chat.send_message_stream(user_input)
        stream_response(response)
        print()

if __name__ == "__main__":
    main()
Test that the bot remembers your conversation

The whole point of a chat session is memory. Each message you send includes the full history, so Sparky can reference things you said earlier.

  • Run the chatbot by entering this command in your terminal:
python chatbot.py
  • Try a multi-turn conversation to test memory. For example:
  • First message: My name is Alex and I'm learning Python.
  • Second message: What's my name?
  • Sparky should remember your name and reference it in the response.
  • Type quit to end the conversation gracefully.

You should see Sparky's farewell message and the program exits cleanly.

Bot not remembering earlier messages?

Make sure you're using chat.send_message_stream() inside the loop, not client.models.generate_content_stream(). The chat method carries history automatically. The models method treats each call as a fresh request with no memory.

Help me figure out why my chatbot doesn't remember earlier messages

Your chatbot now holds real conversations with full memory. Next up, you'll polish the experience with a welcome message, error handling, and a conversation history display.

Polish Your Chatbot

Your chatbot already holds multi-turn conversations and streams responses in real-time. Right now, though, it starts silently and crashes if the API has a hiccup.

In this step, you'll add the finishing touches that make a chatbot feel polished. A welcome message, graceful error handling, and a conversation summary at the end.

In this step, get ready to:
  • Add a welcome message that introduces the bot's personality.
  • Handle API errors gracefully so the chatbot never crashes unexpectedly.
  • Display the full conversation history when the session ends.
Add a welcome message banner

When someone launches your chatbot, the first thing they see should tell them who they're talking to and how to leave. A clear welcome banner sets expectations immediately.

  • In chatbot.py, find the main() function. Locate this line:
    chat = create_chat()
  • Add the following welcome banner above that line, right after the docstring:
    print("=" * 50)
    print("Hi! I'm Sparky, your friendly coding tutor!")
    print("Ask me anything about programming.")
    print("Type 'quit' or 'exit' to end the conversation.")
    print("=" * 50)
    print()

What does this code do?

This prints a bordered welcome message the moment the chatbot starts. It introduces Sparky by name, tells the user what to ask about, and shows them how to exit.

The "=" * 50 creates a visual separator line of 50 equals signs. This makes the banner stand out from the rest of the terminal output.

  • Save chatbot.py.
  • Run your chatbot by running:
python chatbot.py
  • You should see the welcome banner with Sparky's greeting and instructions before the input prompt appears.

Don't see the welcome banner?

Make sure the print statements are inside the main() function and placed before chat = create_chat(). If they're outside the function, they won't run when the script starts.

Help me fix my welcome banner

Add error handling for API failures

Network connections can drop. APIs can rate-limit you. Without error handling, any of these issues would crash your chatbot and end the conversation abruptly.

  • In chatbot.py, find these lines inside the while True loop:
        print("Sparky: ", end="", flush=True)
        response = chat.send_message_stream(user_input)
        stream_response(response)
        print()
  • Replace those four lines with this try/except block:
        try:
            print("Sparky: ", end="", flush=True)
            response = chat.send_message_stream(user_input)
            stream_response(response)
            print()
        except Exception as e:
            print(f"\nOops! Something went wrong: {e}")
            print("Let's try again.\n")

What does this code do?

The try/except block catches any error that happens during the API call. Instead of crashing, the chatbot prints a friendly message and lets the user try again.

This covers network timeouts, rate limit errors, and any unexpected API responses. The conversation stays alive even when something goes wrong.

  • Save chatbot.py.
  • Run the chatbot again and have a short conversation. If the API responds normally, your error handling is in place and ready to catch any future failures.

Seeing a syntax error?

Check your indentation carefully. The try: line should be at the same level as the old print("Sparky: "...) line was. The code inside try and except needs one extra level of indentation.

Help me fix my error handling code

Display conversation history at the end of the session

When a conversation ends, it's useful to see a summary of everything that was discussed. The chat.get_history() method returns every message exchanged during the session.

  • In chatbot.py, scroll to the bottom of the main() function. Find the closing line of the while True loop (after both break statements).
  • Add the following code after the while loop, at the same indentation level as the loop itself:
    # Display conversation history
    print("\n" + "=" * 50)
    print("Conversation History:")
    print("=" * 50)
    for message in chat.get_history():
        role = "You" if message.role == "user" else "Sparky"
        text = message.parts[0].text
        preview = text[:100] + "..." if len(text) > 100 else text
        print(f"  {role}: {preview}")

What does this code do?

After the conversation loop ends, this code loops through every message in the chat history. Each message has a .role (either "user" or "model") and a .parts[0].text containing the actual message content.

Long responses get truncated to the first 100 characters with "..." appended. This keeps the summary readable without flooding the terminal.

  • Save chatbot.py.
  • Run the chatbot, ask 2-3 questions, then type quit to exit.
python chatbot.py
  • After exiting, you should see a "Conversation History" section listing each exchange with a truncated preview of each message.

Not seeing the conversation history?

Make sure the history code is outside the while True loop but still inside the main() function. It should be indented with 4 spaces (one level), not 8 spaces (inside the loop).

Also confirm you exited with quit or exit rather than closing the terminal window. The history only prints if the loop exits normally through a break.

Help me debug my conversation history display

✔️ 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 the complete chatbot.py at this point:

import os
import sys
from google import genai
from google.genai import types

# Initialize the Gemini client
client = genai.Client()

# Define the chatbot personality
SYSTEM_PROMPT = """You are a friendly and enthusiastic coding tutor named Sparky. 
You explain technical concepts in simple terms using analogies and examples. 
You keep responses concise (2-3 paragraphs max) and always encourage the learner. 
When you don't know something, you say so honestly."""

def create_chat():
    """Create a new chat session with the system prompt."""
    config = types.GenerateContentConfig(
        system_instruction=SYSTEM_PROMPT
    )
    chat = client.chats.create(
        model="gemini-2.5-flash",
        config=config
    )
    return chat

def stream_response(response):
    """Print streaming response chunks as they arrive."""
    for chunk in response:
        print(chunk.text, end="", flush=True)
    print()  # New line after response completes

def main():
    """Main chatbot loop."""
    print("=" * 50)
    print("Hi! I'm Sparky, your friendly coding tutor!")
    print("Ask me anything about programming.")
    print("Type 'quit' or 'exit' to end the conversation.")
    print("=" * 50)
    print()

    chat = create_chat()

    while True:
        try:
            user_input = input("You: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nGoodbye!")
            break

        if not user_input:
            continue

        if user_input.lower() in ("quit", "exit"):
            print("\nSparky: It was great chatting with you! Keep coding! \U0001f680")
            break

        try:
            print("Sparky: ", end="", flush=True)
            response = chat.send_message_stream(user_input)
            stream_response(response)
            print()
        except Exception as e:
            print(f"\nOops! Something went wrong: {e}")
            print("Let's try again.\n")

    # Display conversation history
    print("\n" + "=" * 50)
    print("Conversation History:")
    print("=" * 50)
    for message in chat.get_history():
        role = "You" if message.role == "user" else "Sparky"
        text = message.parts[0].text
        preview = text[:100] + "..." if len(text) > 100 else text
        print(f"  {role}: {preview}")

if __name__ == "__main__":
    main()

Secret mission

Multiple Personality Modes

Your chatbot has one personality right now. What if users could switch between completely different AI characters mid-conversation? Add a /switch command that lets users pick from multiple personalities on the fly.

Clean Up Your Resources

Clean Up Your Resources

This project runs entirely on your local machine and uses Google Gemini's free tier, so there are no ongoing costs. Decide whether to keep your resources available, pause them to come back later, or delete them entirely.

Resources you used:

  • chatbot.py file on your Desktop.
  • google-genai Python package.
  • GEMINI_API_KEY environment variable.
  • Gemini API key in Google AI Studio.

Keep everything running

No action needed. Choose this if you plan to keep building on your chatbot or experimenting with the Gemini API.

  • Your chatbot.py file stays on your Desktop, ready to run anytime.
  • Your GEMINI_API_KEY environment variable remains available in your current PowerShell session.
  • The google-genai package stays installed in your Python environment.
  • Your API key remains active in Google AI Studio.

Pause - I'll come back to this later

Clear the environment variable from your current session so the API key is not exposed. Your files and packages stay in place for when you return.

  • Remove the environment variable from your current PowerShell session by running:
Remove-Item Env:GEMINI_API_KEY
  • If you added GEMINI_API_KEY to your system environment variables for persistence, you can leave it in place. It does not cost anything and poses minimal risk on your personal machine.
  • Your chatbot.py file and the google-genai package remain installed for next time.

Delete - I don't want to use this again

Remove all project resources and start fresh. Follow each step below to fully clean up.

  • Delete your project file by running this in PowerShell:
Remove-Item ~\Desktop\chatbot.py
  • Uninstall the google-genai package by running:
pip uninstall google-genai -y
  • Remove the environment variable from your current session by running:
Remove-Item Env:GEMINI_API_KEY
  • If you added GEMINI_API_KEY as a persistent system environment variable, remove it through System Properties > Environment Variables. Find GEMINI_API_KEY in the user variables list and click Delete.
  • Delete your Gemini API key from Google Cloud. Open the Google Cloud API Credentials page at https://console.cloud.google.com/apis/credentials.
  • Find your API key in the list and click the Actions icon (three dots).
  • Select Delete API key.
  • In the Delete credential modal, click Delete to confirm.

Nice Work!

Nice Work!

You just built a fully functional AI chatbot from scratch using Python and Google's Gemini API.

What you learned:

  • Connected to Google's Gemini API using the official Python SDK and shaped AI behavior with system prompts.
  • Built multi-turn conversations with automatic memory management so the bot remembers context across messages.
  • Implemented streaming responses for real-time word-by-word display and added error handling for a production-quality experience.
  • Added switchable personality modes for a dynamic chat experience.

Ready to quiz yourself?