Build an AI Study Buddy with Gemini

Build a Python CLI tool that uses the Gemini API to explain CS concepts.

Introduction

30 Second Summary

You know that feeling when you're stuck on a CS concept at 11pm and wish you could just ask someone to explain it clearly? What if you could build your own AI tutor that's always available and always patient?

In this project, you will build a command-line AI Study Buddy in Python that connects to Google's Gemini AI model. You'll type any CS question and get a tailored explanation with code examples and check questions.

What You'll Build

You run your script, type "explain recursion", and within seconds a clear, beginner-friendly explanation appears in your terminal complete with a code example and a question to test your understanding.

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

  • A working CLI study tool where you type any CS question and get a clear explanation with code examples written for your level.
  • A multi-turn conversation where the AI remembers your previous questions and builds on them when you ask follow-ups.
  • Full control over the AI's behavior through system instructions you wrote yourself, making it a purpose-built study tool instead of a generic chatbot.
  • Secret Mission: error handling and a save command that exports your entire study session to a text file.

Are there any prerequisites?

You should be comfortable with Python basics (variables, loops, conditions) and have VS Code and Python already installed on your machine. You also need a Google account (free) to get your API key.

Before We Start

Before We Start...

Before we dive in, let's lock in what you're about to build and why it matters. Understanding the goal up front helps you connect each step to the bigger picture of AI engineering.

Install the SDK and Get Your API Key

To build an AI-powered tool, your Python code needs a way to talk to an AI model over the internet.

In this step, you will install the Python package that connects to Google's Gemini API, and get the API key that authenticates your requests. This is the same client-key pattern used in every AI engineering job.

In this step, get ready to:
  • Install the google-genai Python package with pip.
  • Obtain an API key from Google AI Studio.
  • Verify your setup is ready for AI development.
Install the Google GenAI SDK

The google-genai package is Google's official Python library for the Gemini API. It gives your code the functions needed to send requests to the AI model and read responses back.

  • In VS Code, open the integrated terminal by pressing Ctrl+` (backtick key, top-left of your keyboard).
  • Install the Google GenAI SDK by running this command:
pip install google-genai

What does this command do?

pip is Python's package manager. It downloads the google-genai library from the internet and makes it available for your Python scripts to import.

You should see download progress and a success message ending with something like "Successfully installed google-genai".

Seeing a permission error or 'pip not found'?

  • If you see "command not found", try pip3 install google-genai instead. Some systems use pip3 for Python 3.
  • If you see a permissions error on macOS/Linux, try pip install --user google-genai to install for your user only.

Still stuck? Help me troubleshoot my pip install

Get your API key from Google AI Studio

An API key is a unique string that identifies your requests to the Gemini API. Without it, Google has no way to know who is sending the request.

  • Open your web browser and go to aistudio.google.com.
  • Sign in with your Google account.
  • If this is your first time, accept the Terms of Service when prompted.
  • Click Get API Key in the left sidebar to open the API Keys page.
  • Click the Create API key button.
  • Copy your new API key and paste it somewhere safe (a notes app or text file on your computer).

Why do I need to save this key?

You will paste this key into your Python code in the next step. Treat it like a password. Do not share it publicly or commit it to GitHub.

The Gemini API free tier gives you 1,500 requests per day at no cost and does not require a credit card.

Can't create an API key?

  • Make sure you are signed in with a personal Google account, not a work or school account (organizations sometimes restrict API key creation).
  • If you see a permission error, try using an incognito browser window and signing in again.

Need more help? Help me get my Gemini API key

Verify your setup

You have the SDK installed and an API key saved. Now confirm everything is wired up correctly.

  • Confirm your Python version by running this command:
python --version

You should see Python 3.10 or higher printed (for example, Python 3.12.4).

Seeing a version below 3.10 or 'command not found'?

  • On macOS, try python3 --version instead. If that shows 3.10+, use python3 everywhere this project says python.
  • If your version is below 3.10, you will need to install a newer version of Python from python.org before continuing.

Need help upgrading? Help me install the right Python version

  • Before you run the next command, what do you think will happen? Will it print a message or throw an error?
  • Verify the SDK is importable by running:
python -c "from google import genai; print('SDK ready!')"

You should see SDK ready! printed in your terminal. This confirms Python can find and load the google-genai library.

Seeing 'ModuleNotFoundError'?

  • This means pip installed the package for a different Python version than the one you are running. Try pip3 install google-genai followed by python3 -c "from google import genai; print('SDK ready!')".
  • Make sure you are running the command in the same terminal where you ran pip install.

Still stuck? Help me fix my SDK import error

Your tools are ready. Next up, you will write your first lines of code and make a real request to the Gemini AI model.

Make Your First AI API Call

You have the SDK installed and your API key ready. Now it's time to put them to work and talk to a real AI model.

Before building anything complex, you need to confirm you can send a request to the AI and get a response back. This one call teaches the entire pattern every AI API follows: create a client, send input, read output.

In this step, get ready to:
  • Create study_buddy.py with a minimal API call.
  • Run the script and see Gemini respond with an explanation.
Create your project folder

You need a dedicated place on your computer for this project's files. Your Desktop is a good spot because you can find it easily.

  • In VS Code, open the integrated terminal by pressing Ctrl+` (macOS) or Ctrl+` (Windows).
  • Move to your Desktop by running this command:
cd ~/Desktop
  • Create your project folder and move into it by running these commands:
mkdir study-buddy
cd study-buddy
  • Confirm the folder exists by running:
ls

The folder is empty for now. You are about to create your first file in it.

  • Open this folder in VS Code by clicking File in the top menu bar.
  • Click Open Folder.
  • Navigate to your Desktop, select the study-buddy folder, and click Open.

Why open the folder in VS Code?

Opening a folder (instead of a single file) tells VS Code to treat that folder as your project workspace. Your terminal will automatically start inside it, and new files you create will be saved there.

Write the code that calls Gemini

Every AI API call follows the same three-step structure: create a client, send a request, read the response. You are about to write all three in just 10 lines of Python.

  • Create a new file by pressing Cmd+N (macOS) or Ctrl+N (Windows).
  • Save the file immediately with Cmd+S (macOS) or Ctrl+S (Windows), and name it study_buddy.py.
  • Paste the following code into study_buddy.py:
# Import the Google GenAI library
from google import genai

# Replace this with the API key you copied from Google AI Studio
API_KEY = "your-api-key-here"

# Create a client that handles communication with the Gemini API
client = genai.Client(api_key=API_KEY)

# Make a single API call asking Gemini to explain recursion
interaction = client.interactions.create(
    model="gemini-2.5-flash",
    input="Explain recursion",
)

# Print the AI's response text
print(interaction.output_text)

What does this code do?

  • from google import genai loads the SDK you installed in the previous step.
  • genai.Client(api_key=API_KEY) creates a client object. This is your connection to Google's servers. Every request goes through it.
  • client.interactions.create() sends your question to the gemini-2.5-flash model. The input parameter is the text you want the AI to respond to.
  • interaction.output_text extracts the AI's text response from the interaction object.
  • Replace your-api-key-here with the actual API key you copied from Google AI Studio in the previous step. Keep the quotes around it.
  • Save the file with Cmd+S (macOS) or Ctrl+S (Windows).

Before you run this, what do you think will happen? Will you see a short answer or a long explanation?

  • Open the terminal in VS Code by pressing Ctrl+` and run your script:
python study_buddy.py

You should see an AI-generated explanation of recursion printed in your terminal. It may take a few seconds for the response to arrive.

What just happened?

Your Python script sent a request over the internet to Google's Gemini model. The model processed your input, generated a response, and sent it back. Your script printed that response. That is the complete AI API pattern: client, request, response.

Seeing an error instead of an explanation?

  • If you see Invalid API key or a 400/403 error, double-check that you pasted your full API key between the quotes on the API_KEY line. Make sure there are no extra spaces or missing characters.
  • If you see ModuleNotFoundError: No module named 'google', the SDK is not installed in the Python that ran the script. Try running pip install google-genai again, then re-run the script.
  • If you get a timeout or connection error, check that you have an active internet connection. The script needs to reach Google's servers.

Still stuck? Help me debug my first Gemini API call

✔️ Awesome, I've got everything!

Great. Double-check you have saved study_buddy.py and that the output appeared in your terminal.

ⓧ I'd like to double check the full code

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

from google import genai

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

interaction = client.interactions.create(
    model="gemini-2.5-flash",
    input="Explain recursion",
)
print(interaction.output_text)

You just made your first AI API call. That single pattern (client, request, response) is the foundation of every AI-powered application. Next up, you will turn this into an interactive study tool where you can ask any question and get instant explanations.

Build the Interactive Study Buddy

Your first API call proved that Python can talk to Gemini and get a response back. The problem is that a hardcoded question makes for a pretty useless tool.

In this step, you will turn that one-shot script into a real interactive study buddy. You will add a system instruction that controls how the AI behaves, and wrap everything in a loop so you can keep asking questions.

In this step, get ready to:
  • Add a system instruction that makes the AI act as a study buddy.
  • Build an interactive loop so you can ask any question.
  • Discover a critical limitation in how the AI handles conversations.
Add a system instruction

A system instruction is a message you send to the AI before the user's question. It tells the model how to behave, what tone to use, and what format to follow. Without one, the AI gives generic answers. With one, it becomes a purpose-built tool.

  • In VS Code, open study_buddy.py.
  • Find these lines at the bottom of your file:
interaction = client.interactions.create(
    model="gemini-2.5-flash",
    input="Explain recursion",
)
print(interaction.output_text)
  • Select all of these lines and delete them.
  • In their place, add the following system instruction:
# Define how the AI should behave as a study buddy
SYSTEM_INSTRUCTION = """You are a friendly study buddy for a second-year computer science student.
When explaining concepts:
- Use simple language and analogies
- Give a short example in code when relevant
- End with a quick check question to test understanding
Keep responses concise (under 200 words)."""

What does this code do?

This multiline string is a set of instructions the AI will follow every time it responds. It tells Gemini to explain things simply, give code examples, ask check questions, and keep answers short.

You are doing prompt engineering. The system instruction shapes the AI's personality and output format without the user needing to repeat these rules every time they ask a question.

Create the interactive loop

Right now your script does nothing after deleting those lines. You need a function that runs an infinite loop, accepting user input and sending it to the AI each time.

  • Below your SYSTEM_INSTRUCTION variable, add the following main() function:
def main():
    print("=== AI Study Buddy ===")
    print("Ask me anything about CS! Type 'quit' to exit.\n")

    # Keep asking questions until the user types 'quit'
    while True:
        user_input = input("You: ")
        if user_input.lower() == "quit":
            print("Happy studying! Goodbye.")
            break

        # Send the question to Gemini with our system instruction
        interaction = client.interactions.create(
            model="gemini-2.5-flash",
            system_instruction=SYSTEM_INSTRUCTION,
            input=user_input,
        )
        print(f"\nStudy Buddy: {interaction.output_text}\n")


if __name__ == "__main__":
    main()

What does this code do?

  • while True: creates an infinite loop that keeps the conversation going until the user decides to stop.
  • input("You: ") pauses and waits for the user to type a question.
  • The system_instruction=SYSTEM_INSTRUCTION parameter passes your study buddy rules to Gemini with every request.
  • if __name__ == "__main__": is a Python pattern that runs main() only when you execute this file directly.
  • Save study_buddy.py.
  • Run your script in the terminal:
python study_buddy.py
  • You should see the welcome message === AI Study Buddy === and a You: prompt waiting for your input.
  • Type what is a linked list? and press Enter.

You should see a study-buddy-style response with a simple explanation, a code example, and a check question at the end.

Not seeing a response?

  • Check that you deleted the old hardcoded lines completely. Your file should have no leftover input="Explain recursion" anywhere.
  • Make sure your API key is still set correctly on line 3. The string should match the key you copied from Google AI Studio.
  • Confirm you saved the file before running it.

Help me debug my study buddy script

Discover the memory problem

Your study buddy answers questions. But a real study session involves follow-up questions. Let's test whether the AI can handle that.

Before you ask your next question, think about this: you just asked about linked lists. What do you think will happen if you now ask "what about arrays?" Will the AI compare arrays to linked lists, or will it have no idea what you were just talking about?

  • At the You: prompt, type what about arrays? and press Enter.

The AI gives a standalone explanation of arrays. It does NOT reference your previous question about linked lists. It has no idea what you asked 10 seconds ago.

Why does this happen?

Each call to client.interactions.create() is completely independent. The AI receives your new question with zero context about what came before. It is like calling a stranger on the phone every time you want to ask a follow-up.

This is the memory problem. Fixing it is what separates a toy script from a real conversational tool.

  • Type quit to exit the script.

✔️ Awesome, I've got everything!

Great. Double check you have saved your file.

ⓧ I'd like to double check the full code

Your study_buddy.py should have these sections in order. Scroll up and confirm each one is present:

  • The from google import genai import at the top.
  • The API_KEY variable and client = genai.Client(api_key=API_KEY) line.
  • The SYSTEM_INSTRUCTION multiline string with study buddy rules.
  • The def main(): function containing the while True loop, input(), quit check, API call with system_instruction, and print statement.
  • The if __name__ == "__main__": guard at the very bottom calling main().

You now have a working interactive study buddy that answers CS questions with clear explanations. But it forgets everything between messages. Next up, you will give it a memory so follow-up questions actually work.

Add Conversation Memory

In the last step, you discovered a critical gap: every message you send is treated as a brand new conversation. Ask about recursion, then ask "can you show me another example?" and the AI has no idea what you were talking about.

The Gemini Interactions API solves this with a parameter called previous_interaction_id. When you pass the ID of your last interaction, Gemini can see everything that came before. Each request chains to the previous one, building a connected conversation.

In this step, get ready to:
  • Add a previous_id variable to track conversation state.
  • Pass the interaction chain to each new API call.
  • Verify that follow-up questions correctly reference prior context.
Chain your interactions together

Three small additions to your existing code create the memory chain. You initialize a tracker, pass it to the API, and update it after each response.

  • In study_buddy.py, find the section inside your main() function that starts at while True: and includes your API call. It currently looks like this:
    while True:
        user_input = input("You: ")
        if user_input.lower() == "quit":
            print("Happy studying! Goodbye.")
            break

        interaction = client.interactions.create(
            model="gemini-2.5-flash",
            system_instruction=SYSTEM_INSTRUCTION,
            input=user_input,
        )
        print(f"\nStudy Buddy: {interaction.output_text}\n")
  • Replace that entire section with this updated version that adds conversation memory:
    # Track the previous interaction for memory
    previous_id = None

    while True:
        user_input = input("You: ")
        if user_input.lower() == "quit":
            print("Happy studying! Goodbye.")
            break

        interaction = client.interactions.create(
            model="gemini-2.5-flash",
            system_instruction=SYSTEM_INSTRUCTION,
            input=user_input,
            # Chain to previous interaction for context
            previous_interaction_id=previous_id,
        )
        print(f"\nStudy Buddy: {interaction.output_text}\n")
        # Save this interaction's ID for the next request
        previous_id = interaction.id

What do these three additions do?

  • previous_id = None starts the chain. The first message has no predecessor, so it begins as None.
  • previous_interaction_id=previous_id tells Gemini which interaction came before this one. The API uses this to load the full conversation history server-side.
  • previous_id = interaction.id saves the current interaction's ID so the NEXT request can chain to it. This keeps the chain growing with every exchange.
  • Save study_buddy.py.
Test conversation memory

Before you ran the script, follow-up questions failed because each call was independent. Now the chain should connect them.

Before you run this, predict: if you ask "explain what a for loop is" and then ask "now show me a while loop version of that", will the AI understand what "that" refers to?

  • Run your script by entering this command in the terminal:
python study_buddy.py
  • Type explain what a for loop is and press Enter.
  • After the response, type now show me a while loop version of that and press Enter.

The AI now correctly references your previous question about for loops and builds on it. It knows what "that" means because the interaction chain gives it full context of your conversation.

  • Type quit to exit the script.

AI still not remembering context?

  • Check that previous_id = None is placed ABOVE the while True: line, not inside the loop. If it resets to None every iteration, memory breaks.
  • Confirm that previous_id = interaction.id is AFTER the print statement but still inside the while True: loop.
  • Make sure you spelled previous_interaction_id exactly. A typo in the parameter name means the API silently ignores it.

Why isn't my AI Study Buddy remembering previous questions?

✔️ Awesome, I've got everything!

Great. Double check you've saved study_buddy.py.

ⓧ I'd like to double check the full code

Here is the complete study_buddy.py file at this point. Make sure yours matches:

from google import genai

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

SYSTEM_INSTRUCTION = """You are a friendly study buddy for a second-year computer science student.
When explaining concepts:
- Use simple language and analogies
- Give a short example in code when relevant
- End with a quick check question to test understanding
Keep responses concise (under 200 words)."""


def main():
    print("=== AI Study Buddy ===")
    print("Ask me anything about CS! Type 'quit' to exit.\n")
    previous_id = None

    while True:
        user_input = input("You: ")
        if user_input.lower() == "quit":
            print("Happy studying! Goodbye.")
            break

        interaction = client.interactions.create(
            model="gemini-2.5-flash",
            system_instruction=SYSTEM_INSTRUCTION,
            input=user_input,
            previous_interaction_id=previous_id,
        )
        print(f"\nStudy Buddy: {interaction.output_text}\n")
        previous_id = interaction.id


if __name__ == "__main__":
    main()

Your Study Buddy now remembers everything you discuss in a session. You can build understanding across multiple questions, ask for follow-ups, and have a real learning conversation. Next up, you'll take on the Secret Mission to add error handling and session export.

Secret mission

Add Error Handling and Session Export

Your study buddy works, but what happens when the internet drops mid-session? Or when you have a great explanation you want to revisit later? In this mission, you'll make your tool production-ready by adding graceful error handling and a save command that exports your conversation to a file.

Clean Up Your Resources

Clean Up Your Resources

Decide whether to keep your resources running, pause them to come back later, or delete them entirely. This project runs entirely locally with a free API key, so there are no ongoing costs.

Resources you used:

  • Google AI Studio API key (free tier, no charges).
  • Local project files (study_buddy.py, study_session.txt).
  • google-genai Python package.

Keep everything running

No action needed. Choose this if you plan to keep using your AI Study Buddy or want to build on it further.

  • Your API key stays active on the free tier (1,500 requests per day). No charges will apply.
  • Your study_buddy.py script is ready to run anytime with python study_buddy.py.
  • The google-genai package remains installed and available for future projects.

Pause - I'll come back to this later

There are no running processes to shut down. Your script only runs when you explicitly start it.

  • Close VS Code if you want to free up memory.
  • Your API key and installed packages will still be ready when you come back.
  • No costs accrue while the script is not running.

Delete - I don't want to use this again

Remove all project resources and revoke your API key.

  • Revoke your API key: go to aistudio.google.com, sign in, and navigate to your API keys page. Find the key you created for this project and delete it.
  • Delete your local project files. On macOS/Linux, run:
rm study_buddy.py study_session.txt

On Windows, run:

del study_buddy.py, study_session.txt
  • Uninstall the google-genai package by running:
pip uninstall google-genai

Confirm the uninstall when prompted by typing y.

Nice Work!

Nice Work!

You just built a fully functional AI-powered study tool using Python and the Gemini API. This is the exact integration pattern that production AI applications use every day.

You've learned how to:

  • Install packages with pip, obtain an API key, and authenticate requests to Google's Gemini model.
  • Build an interactive CLI tool that calls the Gemini API programmatically using the client, request, response pattern.
  • Write a system instruction to control AI behavior and implement conversation memory using interaction chaining.
  • Secret Mission: Add error handling and a /save command that exports your study session to a file for production-quality polish.

Ready to quiz yourself?