Build BuddyAI: Your AI Friend Chatbot
Build a terminal AI chatbot with a custom personality using Google Gemini.
Introduction
30 Second Summary
Everyone needs someone to talk to. Whether you want to vent about your day, bounce ideas off someone, or just have a casual chat, AI companions are becoming a real part of how people interact with technology.
In this project, you will build BuddyAI, a terminal-based chatbot powered by Google's Gemini AI that talks to you like a real friend. You will design its personality, give it memory, and make its responses stream naturally word by word.
What You'll Build
A Python script that connects to the Gemini API and runs an interactive AI friend chatbot in your terminal with a custom personality and conversation memory.
By the end of this project, you'll have:
- A working AI chatbot with a warm, friendly personality you designed using system prompts.
- Hands-on experience with prompt engineering, the core skill of AI engineering: shaping AI behavior with natural language.
- Multi-turn conversation memory and streaming responses that appear word by word for a natural chat feel.
- Secret Mission: Add mood detection so BuddyAI notices when you seem down and responds with extra warmth and encouragement.
Are there any prerequisites?
You should be comfortable with basic Python concepts like variables, functions, loops, and input/output. No AI or API experience is needed.
Set Up Your Tools
Before you can build BuddyAI, you need three things: a working Python installation, the Google Gen AI library, and an API key that lets your code talk to Google's Gemini AI model.
This step gets your development environment ready. You will confirm your Python version, install the SDK, and grab a free API key from Google AI Studio.
In this step, get ready to:
- Confirm Python 3.10+ is installed on your machine.
- Install the google-genai package.
- Get a free Gemini API key and set it as an environment variable.
Open PyCharm and check your Python version
Your code editor PyCharm has a built-in terminal. You will use this terminal for all commands in this project.
- Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
- Type PyCharm and press Enter to open it.
- Open PyCharm's built-in terminal by pressing Option+F12 (macOS) or Alt+F12 (Windows/Linux).
Where is the terminal?
A panel opens at the bottom of PyCharm. This is a fully functional terminal where you can run any command, just like the system terminal on your computer.
Python 3.10 or higher is required for this project. The google-genai library does not support older versions.
- Check your Python version by running this command:
python3 --version
You should see output like Python 3.10.x or higher (for example, Python 3.12.4).
✔️ I see version 3.10 or higher
Your Python version is ready. Move on to the next substep below.
ⓧ I see an older version
You have Python installed, but it is an older version that will not work with google-genai.
- Go to python.org/downloads and download the latest Python installer for your operating system.
- Run the installer. On Windows, make sure to check the Add Python to PATH checkbox during installation.
- Close and reopen PyCharm's terminal after installing so it picks up the new version.
- Run python3 --version again to confirm you now see 3.10 or higher.
macOS ships an older Python
macOS often comes with an older Python version. Even after installing a new version, python3 may still point to the old one. If this happens, try running python3.12 --version (replacing 3.12 with the version you installed) to verify the new installation works.
ⓧ Command not found
Python is not installed on your machine yet.
- Go to python.org/downloads and download the latest Python installer for your operating system.
- Run the installer. On Windows, make sure to check the Add Python to PATH checkbox during installation.
- Close and reopen PyCharm's terminal after installing.
- Run python3 --version to confirm you see 3.10 or higher.
Install the Google Gen AI SDK
The google-genai package is Google's official Python library for the Gemini API. It handles connecting to the model, sending prompts, and receiving responses.
- Install the package by running this command in your PyCharm terminal:
pip install google-genai
You should see output ending with a line like Successfully installed google-genai-... along with any dependencies.
Seeing an error during install?
- If you see a permissions error, try running pip install --user google-genai instead.
- If pip is not found, try pip3 install google-genai instead.
- Make sure your terminal is using the same Python version you verified in the previous substep.
help me troubleshoot my pip install error for google-genai
Get your free API key
An API key is a unique code that identifies your application when it talks to Google's servers. The Gemini API free tier requires no credit card and gives you 1,500 requests per day.
- Open your web browser and go 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. You will only see it once, so do not close this page yet.
What is an API key?
Think of an API key like a library card. It tells Google who is making the request so it can track your usage and keep you within the free tier limits. Without it, Google would reject your requests.
Keep your key private. Never share it publicly or commit it to a code repository.
Getting a permission denied error?
- Make sure you are using a personal Google account, not a work or school account. Organization-managed accounts often block API key creation.
- Try opening the page in an incognito browser window.
- If the issue persists, wait a few minutes and try again. Google occasionally has brief provisioning delays for new accounts.
help me fix the permission denied error when creating a Gemini API key
Now you need to store the key as an environment variable so your Python script can read it without the key being hardcoded in your code.
- Back in your PyCharm terminal, set the environment variable by running this command (replace your-api-key-here with the actual key you just copied):
macOS
export GEMINI_API_KEY="your-api-key-here"
Windows
$env:GEMINI_API_KEY="your-api-key-here"
Why an environment variable?
Environment variables keep secrets out of your code files. If you ever share your code or push it to GitHub, your key stays safe because it only lives in your terminal session.
This variable lasts only as long as your current terminal session. If you close and reopen the terminal, you will need to set it again.
- Verify the variable is set correctly by running:
macOS
echo $GEMINI_API_KEY
Windows
echo $env:GEMINI_API_KEY
You should see your API key printed in the terminal. If you see a blank line, re-run the export command and make sure you included the quotes.
Your environment is ready. Next up, you will connect to Gemini and send your very first message to an AI model.
Connect to Gemini and Send Your First Message
You have your tools installed and your API key ready. Now it's time to write actual code that talks to an AI model.
In this step, you will create a Python script that connects to Google's Gemini API and sends it a message. When you run the script, Gemini will respond right in your terminal. This is the fundamental workflow of AI engineering: send a prompt, get a response.
In this step, get ready to:
- Create a Python file that connects to the Gemini API.
- Send your first message and see a response.
- Experiment with different prompts to see how the model reacts.
Create your buddy.py file
Every AI application starts with a script that connects to the model. You will create a single Python file that imports the Google Gen AI SDK, sets up a connection using your API key, and sends a test message.
- In PyCharm, right-click your project folder in the Project pane on the left.
- Select New, then Python File.
- Type buddy and press Enter. PyCharm creates buddy.py and opens it in the editor.
Now paste the following code into buddy.py:
import os
from google import genai
from google.genai import types
# Create a client using your API key from the environment variable
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
# Send a test message to the Gemini model
response = client.models.generate_content(
model="gemini-2.0-flash",
contents="Say hello and introduce yourself!"
)
print(response.text)
What does this code do?
- The first three lines import the libraries you need. os reads your environment variable, genai is the SDK itself, and types gives you configuration options you will use later.
- client = genai.Client(...) creates your connection to Google's servers. It uses the GEMINI_API_KEY environment variable you set in the previous step.
- client.models.generate_content() sends your message to the gemini-2.0-flash model and waits for a response.
- print(response.text) displays whatever the AI wrote back.
Run the script and confirm a response
- Save buddy.py by pressing Cmd+S (macOS) or Ctrl+S (Windows).
- Open the terminal inside PyCharm by clicking Terminal at the bottom of the window.
- Run the script with this command:
python3 buddy.py
You should see a friendly greeting from Gemini printed in your terminal. The exact wording will be different every time because the AI generates a unique response.
Not seeing a response?
- If you see an error about GEMINI_API_KEY being None, your environment variable is not set in this terminal session. Run export GEMINI_API_KEY="your-api-key-here" again in the same terminal, then retry.
- If you see a 403 or 429 error, wait a few minutes and try again. New API keys sometimes take a moment to activate.
- If you see a module not found error, make sure you installed the package with pip install google-genai in the same Python environment that PyCharm is using.
Still stuck? Help me debug why my buddy.py script isn't returning a response from Gemini.
✔️ Awesome, I've got everything!
Great. Make sure you have saved buddy.py. You are ready for the next substep.
ⓧ I'd like to double check the full code
import os
from google import genai
from google.genai import types
# Create a client using your API key from the environment variable
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
# Send a test message to the Gemini model
response = client.models.generate_content(
model="gemini-2.0-flash",
contents="Say hello and introduce yourself!"
)
print(response.text)
Experiment with different prompts
The text you pass to contents is your prompt. Changing it changes the AI's entire response. This is your first taste of prompt engineering.
- In buddy.py, change the contents string to something new. Try a few of these ideas:
- Save the file and run python3 buddy.py again each time you change the prompt.
- Notice how the same model produces completely different responses depending on how you word your request.
Why does prompt wording matter so much?
AI models do not read your mind. They generate text based on patterns that match your input. A vague prompt gets a vague answer. A specific prompt gets a focused answer. This is why prompt engineering is the #1 skill in AI development.
In the next step, you will use this skill to design an entire personality for your chatbot.
You just sent your first message to an AI model and got a response. Next up, you will design a custom personality so BuddyAI talks like a real friend instead of a generic assistant.
Design Your Friend's Personality
You sent your first message to Gemini and got a response back. The AI works, but it sounds like a generic assistant.
In this step, you will give BuddyAI a unique personality using system instructions. These are special prompts that tell the AI HOW to behave, not just what to answer. This is the core skill of AI engineering: programming behavior with natural language.
In this step, get ready to:
- Write a system prompt that defines BuddyAI's personality.
- Pass the system prompt to the Gemini API and test the response.
- Iterate on different personality styles through prompt engineering.
Write your system prompt
A system instruction is a special prompt that runs before every conversation. It tells the AI what role to play, what tone to use, and what rules to follow. Think of it as the AI's backstory and personality blueprint.
- In PyCharm, open buddy.py.
- Find the line that says response = client.models.generate_content(.
- Add the following SYSTEM_PROMPT variable above that line:
# Design your friend's personality
SYSTEM_PROMPT = """You are BuddyAI, a warm and supportive friend. Here's how you behave:
- You talk casually, like a real friend would (use "hey", "dude", "honestly", etc.)
- You remember what was said earlier in our conversation and reference it
- You ask follow-up questions to show you care
- You share your own "thoughts" and "experiences" to make the conversation feel two-way
- You keep responses concise (2-4 sentences usually) unless asked to elaborate
- You celebrate wins, no matter how small
- You never judge or lecture
- If someone seems stressed, you acknowledge their feelings first before offering any advice
- You use occasional emojis but don't overdo it
You are NOT a generic AI assistant. You're a friend who happens to be AI.
Never say "How can I help you?" - instead say things like "What's on your mind?" or "How's your day going?"
"""
What does this code do?
The triple-quoted string ("""...""") defines a multi-line personality description for BuddyAI.
- Each bullet point is a rule the AI will follow when generating responses.
- The last two lines explicitly forbid generic assistant behaviour, pushing the AI to sound like a real friend instead.
- This prompt runs behind the scenes before every message, so the AI always stays in character.
What is prompt engineering?
Prompt engineering is the skill of writing natural language instructions that control how an AI behaves. You are literally programming the AI's personality with words instead of code.
The better your system prompt, the more consistent and natural the AI's responses become. This is exactly what AI engineers do professionally.
- Save buddy.py.
You will not see a change yet. The next chunk connects this prompt to the API call.
Test the system instruction
Now you need to tell the Gemini API to use your system prompt. You do this by passing a GenerateContentConfig object with a system_instruction field.
- In buddy.py, find the existing generate_content call at the bottom of your file.
- Find this code:
response = client.models.generate_content(
model="gemini-2.0-flash",
contents="Say hello and introduce yourself!"
)
print(response.text)
- Replace it with the following code, which adds the config parameter and changes the message to something more conversational:
response = client.models.generate_content(
model="gemini-2.0-flash",
contents="Hey, how are you?",
config=types.GenerateContentConfig(
system_instruction=SYSTEM_PROMPT
)
)
print(response.text)
What changed here?
- config=types.GenerateContentConfig(system_instruction=SYSTEM_PROMPT) passes your personality rules to the API. The model reads these before generating its response.
- The contents changed to a casual greeting so you can see whether the AI responds like a friend or like a formal assistant.
- Save buddy.py.
- Run the script by clicking the green play button in PyCharm (or right-clicking the file and selecting Run 'buddy').
- Read the response. It should sound casual and friendly, using phrases like "hey" or asking a follow-up question about your day.
Response still sounds formal?
- Make sure SYSTEM_PROMPT is defined above the generate_content call, not below it. Python reads top to bottom.
- Check that the config= line is inside the generate_content() parentheses, not outside them.
- Verify there are no typos in system_instruction. It must be spelled exactly as shown.
Still stuck? Why is my system prompt not changing BuddyAI's response style?
Iterate on your personality prompt
The real skill of AI engineering is iteration. Your first prompt is a starting point. Now experiment with changes to see how they affect the AI's behaviour.
- Try changing the tone rules in SYSTEM_PROMPT. For example, make BuddyAI more sarcastic, more enthusiastic, or more poetic.
- Run the script again after each change and compare the responses.
- Try adding new rules, like "always reference pop culture" or "respond as if you're texting, not writing an email".
- When you are happy with the personality, revert to the original SYSTEM_PROMPT shown above (you will build on it in the next steps).
Why is this so important?
Every AI product you use (ChatGPT, Gemini, Claude) has a system prompt behind the scenes shaping its personality. When companies hire AI engineers, the ability to write and refine these prompts is one of the most in-demand skills.
You are doing that right now. Small wording changes in the system prompt can dramatically shift how the AI responds.
✔️ Awesome, I've got everything!
Great. Double check you have saved buddy.py with the original SYSTEM_PROMPT before moving on.
ⓧ I'd like to double check the full code
Here is the complete buddy.py at this point:
import os
from google import genai
from google.genai import types
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
# Design your friend's personality
SYSTEM_PROMPT = """You are BuddyAI, a warm and supportive friend. Here's how you behave:
- You talk casually, like a real friend would (use "hey", "dude", "honestly", etc.)
- You remember what was said earlier in our conversation and reference it
- You ask follow-up questions to show you care
- You share your own "thoughts" and "experiences" to make the conversation feel two-way
- You keep responses concise (2-4 sentences usually) unless asked to elaborate
- You celebrate wins, no matter how small
- You never judge or lecture
- If someone seems stressed, you acknowledge their feelings first before offering any advice
- You use occasional emojis but don't overdo it
You are NOT a generic AI assistant. You're a friend who happens to be AI.
Never say "How can I help you?" - instead say things like "What's on your mind?" or "How's your day going?"
"""
response = client.models.generate_content(
model="gemini-2.0-flash",
contents="Hey, how are you?",
config=types.GenerateContentConfig(
system_instruction=SYSTEM_PROMPT
)
)
print(response.text)
You have designed a personality for your AI friend. Next up, you will build a conversation loop so BuddyAI can remember what you said and chat back and forth like a real conversation.
Build the Conversation Loop with Memory
You've designed BuddyAI's personality using a system prompt. Right now though, your script sends one message and exits.
A real conversation goes back and forth. In this step, you'll upgrade your script into an interactive chatbot that remembers everything you say during the session.
In this step, get ready to:
- Create a chat session with built-in conversation memory.
- Build an interactive loop that lets you chat continuously.
- Add commands to view chat history and quit gracefully.
Create a chat session with memory
The Gemini API has a dedicated chat feature that automatically tracks conversation history. Every message you send and every response you receive gets stored in the session. The AI sees the full history each time it responds, so it can reference things you said earlier.
- In buddy.py, find the old test code at the bottom of your file:
response = client.models.generate_content(
model="gemini-2.0-flash",
contents="Hey, how are you?",
config=types.GenerateContentConfig(
system_instruction=SYSTEM_PROMPT
)
)
print(response.text)
- Delete all of that code (the entire response = client.models.generate_content(...) block and the print(response.text) line).
- Replace it with this main() function that creates a chat session:
def main():
"""Run the BuddyAI chatbot."""
chat = client.chats.create(
model="gemini-2.0-flash",
config=types.GenerateContentConfig(
system_instruction=SYSTEM_PROMPT
)
)
print("BuddyAI: Hey! What's on your mind today?\n")
What does this code do?
client.chats.create() opens a new chat session with Gemini. It takes your model name and the system prompt config you built earlier.
Unlike generate_content() which handles one-off messages, a chat session automatically remembers every message sent during the session. You don't need to manually track conversation history.
Build the conversation loop
With the chat session ready, you need a loop that continuously asks for input, sends it to BuddyAI, and prints the response. A quit command lets the user exit cleanly.
- Add the following code inside your main() function, directly below the print("BuddyAI: Hey!... line:
while True:
user_input = input("You: ").strip()
if not user_input:
continue
if user_input.lower() == "quit":
print("\nBuddyAI: Take care! Always here when you need to talk.\n")
break
response = chat.send_message(user_input)
print(f"BuddyAI: {response.text}\n")
- After the main() function (outside and below it, with no indentation), add this line so Python knows to run main() when you execute the script:
if __name__ == "__main__":
main()
What does this code do?
while True creates an infinite loop that keeps asking for input until the user types quit.
input("You: ").strip() displays a prompt and removes extra whitespace from whatever the user types. If the input is empty, continue skips back to the top of the loop.
chat.send_message() sends the user's text to Gemini and returns the AI's response. The chat session automatically appends both messages to its internal history.
- Save buddy.py.
- Run your chatbot by executing this command in your terminal:
python3 buddy.py
- Type a message and press Enter. You should see BuddyAI respond in its friendly personality.
- Type quit to exit the conversation.
Not getting a response?
- Make sure your GEMINI_API_KEY environment variable is still set in this terminal session. If you opened a new terminal, you need to export it again.
- Check that the while True block is indented inside main(). Python uses indentation to determine what belongs to a function.
- If you see a NameError about client, make sure you did not accidentally delete the client = genai.Client(...) line at the top of your file.
Why isn't my BuddyAI chatbot responding when I run buddy.py?
Add a history command and test memory
The chat session stores every message internally. Let's add a history command that lets you peek at the full conversation log. Then you'll test that BuddyAI actually remembers what you said.
- In buddy.py, find the quit check inside your while True loop:
if user_input.lower() == "quit":
print("\nBuddyAI: Take care! Always here when you need to talk.\n")
break
- Directly below the break statement (still inside the while True loop), add this history command block:
if user_input.lower() == "history":
print("\n--- Chat History ---")
for message in chat.get_history():
role = "You" if message.role == "user" else "BuddyAI"
print(f"{role}: {message.parts[0].text}")
print("--- End History ---\n")
continue
What does this code do?
chat.get_history() returns a list of every message in the session. Each message has a .role (either user or model) and a .parts[0].text containing the actual text.
The continue statement skips sending history as a message to the AI. Without it, BuddyAI would try to respond to the word "history" as if it were part of the conversation.
- Save buddy.py and run it again:
python3 buddy.py
- Tell BuddyAI your name (e.g. "Hey, my name is Alex").
- Chat for 2-3 more messages about anything.
- Ask "What's my name?" and confirm BuddyAI remembers it.
- Type history to see the full conversation log printed out.
- Type quit to exit.
BuddyAI doesn't remember your name?
- Make sure you're asking in the same session (without restarting the script). Memory only lasts for one run.
- Check that you're using chat.send_message() and not the old client.models.generate_content(). Only the chat method accumulates history.
Why doesn't BuddyAI remember what I said earlier in the conversation?
✔️ Awesome, I've got everything!
Great. Double check you've saved buddy.py before moving on.
ⓧ I'd like to double check the full code
import os
from google import genai
from google.genai import types
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
SYSTEM_PROMPT = """You are BuddyAI, a warm and supportive friend. Here's how you behave:
- You talk casually, like a real friend would (use "hey", "dude", "honestly", etc.)
- You remember what was said earlier in our conversation and reference it
- You ask follow-up questions to show you care
- You share your own "thoughts" and "experiences" to make the conversation feel two-way
- You keep responses concise (2-4 sentences usually) unless asked to elaborate
- You celebrate wins, no matter how small
- You never judge or lecture
- If someone seems stressed, you acknowledge their feelings first before offering any advice
- You use occasional emojis but don't overdo it
You are NOT a generic AI assistant. You're a friend who happens to be AI.
Never say "How can I help you?" - instead say things like "What's on your mind?" or "How's your day going?"
"""
def main():
"""Run the BuddyAI chatbot."""
chat = client.chats.create(
model="gemini-2.0-flash",
config=types.GenerateContentConfig(
system_instruction=SYSTEM_PROMPT
)
)
print("BuddyAI: Hey! What's on your mind today?\n")
while True:
user_input = input("You: ").strip()
if not user_input:
continue
if user_input.lower() == "quit":
print("\nBuddyAI: Take care! Always here when you need to talk.\n")
break
if user_input.lower() == "history":
print("\n--- Chat History ---")
for message in chat.get_history():
role = "You" if message.role == "user" else "BuddyAI"
print(f"{role}: {message.parts[0].text}")
print("--- End History ---\n")
continue
response = chat.send_message(user_input)
print(f"BuddyAI: {response.text}\n")
if __name__ == "__main__":
main()
Your chatbot now has a real conversation loop with memory. Next up, you'll add streaming so responses appear word-by-word, like a real person typing.
Add Streaming for Natural Responses
Your chatbot now remembers entire conversations and responds with a warm personality you designed.
There's one more thing that makes AI chat feel natural: seeing the response appear word by word, like someone typing in real time. Right now, BuddyAI waits for the full response to generate before showing anything. In this step, you'll switch to streaming so text flows in as it's created, and add a polished welcome banner.
In this step, get ready to:
- Replace the standard message call with streaming for word-by-word responses.
- Add a welcome banner showing available commands.
Stream responses word by word
When you use chat.send_message(), the API waits until the entire response is generated before returning it. Streaming sends the response in small pieces called "chunks" as they're generated. This creates the natural typing effect you see in ChatGPT or Google's Gemini chat.
- In buddy.py, scroll to the bottom of your while True loop.
- Find these two lines:
response = chat.send_message(user_input)
print(f"BuddyAI: {response.text}\n")
- Replace both lines with the following streaming code:
# Send message and stream the response word-by-word
print("BuddyAI: ", end="", flush=True)
response = chat.send_message_stream(user_input)
for chunk in response:
print(chunk.text, end="", flush=True)
print("\n")
What does this code do?
print("BuddyAI: ", end="", flush=True) prints the label without a newline, so the streamed text appears on the same line.
chat.send_message_stream(user_input) sends your message but returns an iterable of chunks instead of one complete response. Each chunk arrives as the model generates it.
The for chunk in response loop prints each piece as it arrives. flush=True forces Python to display the text immediately instead of buffering it.
- Save buddy.py.
- Run your script in the terminal by running:
python3 buddy.py
- Type a message and watch the response. You should see text appear word by word instead of all at once.
- Type quit to exit when you're done testing.
Text appearing all at once?
Make sure you have flush=True in both print() calls. Without it, Python buffers the output and dumps it all at the end.
Check that you're using send_message_stream (not send_message). The non-stream version waits for the full response before returning.
Why isn't my streaming working in BuddyAI?
Why stream instead of waiting?
AI models can take several seconds to generate a full response. Without streaming, the user stares at a blank screen the entire time. Streaming gives immediate feedback, making the conversation feel alive.
Add a welcome banner
A welcome banner gives users clear instructions when they first launch the app. It shows the chatbot's name and the available commands.
- In buddy.py, find the top of your main() function. Add this banner code directly below the docstring """Run the BuddyAI chatbot.""" and above the chat = client.chats.create(...) line:
print("\n" + "=" * 50)
print(" BuddyAI - Your AI Friend")
print("=" * 50)
print(" Type 'quit' to end the conversation")
print(" Type 'history' to see our chat history")
print("=" * 50 + "\n")
What does this code do?
"=" * 50 creates a line of 50 equals signs as a visual separator. The banner tells the user the app name and the two commands they can type. This is a small touch that makes your chatbot feel like a polished tool.
- Save buddy.py and run your script again:
python3 buddy.py
- You should see the welcome banner with separators, the app name, and the command instructions before BuddyAI's first message appears.
Banner not showing up?
Make sure the banner code is inside the main() function and above the chat = client.chats.create(...) line. If it's outside main(), it won't run when you execute the script.
My BuddyAI welcome banner isn't appearing when I run the script.
Test the complete chatbot
Your chatbot is now complete. Try a full conversation to see everything working together.
- Run the script and send a few messages. Watch the text stream in word by word.
- Tell BuddyAI your name, chat for a few messages, then ask "What's my name?" to confirm memory still works.
- Type history to see the full conversation log.
- Type quit to exit and confirm the goodbye message appears.
Experiment with your system prompt
Try changing SYSTEM_PROMPT to give BuddyAI a completely different personality. Make it sarcastic, overly enthusiastic, or speak like a pirate. This is prompt engineering in action. You are programming AI behavior with natural language.
✔️ Awesome, I've got everything!
Great. Double check you've saved buddy.py and that streaming, memory, history, and quit all work as expected.
ⓧ I'd like to double check the full code
Here is the complete buddy.py file. Compare it against yours:
import os
from google import genai
from google.genai import types
# Your Gemini API key - set as environment variable for security
# In terminal: export GEMINI_API_KEY="your-api-key-here"
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
# Design your friend's personality
SYSTEM_PROMPT = """You are BuddyAI, a warm and supportive friend. Here's how you behave:
- You talk casually, like a real friend would (use "hey", "dude", "honestly", etc.)
- You remember what was said earlier in our conversation and reference it
- You ask follow-up questions to show you care
- You share your own "thoughts" and "experiences" to make the conversation feel two-way
- You keep responses concise (2-4 sentences usually) unless asked to elaborate
- You celebrate wins, no matter how small
- You never judge or lecture
- If someone seems stressed, you acknowledge their feelings first before offering any advice
- You use occasional emojis but don't overdo it
You are NOT a generic AI assistant. You're a friend who happens to be AI.
Never say "How can I help you?" - instead say things like "What's on your mind?" or "How's your day going?"
"""
def main():
"""Run the BuddyAI chatbot."""
print("\n" + "=" * 50)
print(" BuddyAI - Your AI Friend")
print("=" * 50)
print(" Type 'quit' to end the conversation")
print(" Type 'history' to see our chat history")
print("=" * 50 + "\n")
# Create a chat session with the friend personality
chat = client.chats.create(
model="gemini-2.0-flash",
config=types.GenerateContentConfig(
system_instruction=SYSTEM_PROMPT
)
)
# Opening message
print("BuddyAI: Hey! What's on your mind today?\n")
while True:
# Get user input
user_input = input("You: ").strip()
if not user_input:
continue
if user_input.lower() == "quit":
print("\nBuddyAI: Take care! Always here when you need to talk.\n")
break
if user_input.lower() == "history":
print("\n--- Chat History ---")
for message in chat.get_history():
role = "You" if message.role == "user" else "BuddyAI"
print(f"{role}: {message.parts[0].text}")
print("--- End History ---\n")
continue
# Send message and stream the response word-by-word
print("BuddyAI: ", end="", flush=True)
response = chat.send_message_stream(user_input)
for chunk in response:
print(chunk.text, end="", flush=True)
print("\n")
if __name__ == "__main__":
main()
Secret mission
Add Mood Detection
What if BuddyAI could tell when you're having a bad day? In this extension, you'll teach your chatbot to pick up on emotional cues and respond with extra warmth when it matters most.
Clean Up Your Resources
Clean Up Your Resources
This project runs entirely locally and uses the Gemini API free tier, so there are no ongoing costs. Decide whether to keep your resources running, pause them to come back later, or delete them entirely.
Resources you used:
- buddy.py file (your chatbot script).
- google-genai Python package.
- Gemini API key in Google AI Studio.
Keep everything running
No action needed. Choose this if you plan to keep building on BuddyAI or experimenting with the Gemini API. The free tier has no charges, so your API key can stay active indefinitely.
Pause - I'll come back to this later
There are no running processes to stop. Your script only runs when you execute it manually. If you want to tidy up your terminal session, you can unset the environment variable.
- Unset the environment variable for this terminal session by running:
unset GEMINI_API_KEY
Your buddy.py file and installed package remain ready for next time. The API key stays active in Google AI Studio for when you return.
Delete - I don't want to use this again
Remove all project resources and start fresh. Follow these steps to clean up everything.
- Delete your buddy.py file. In your terminal, navigate to the folder containing the file and run:
rm buddy.py
- Uninstall the google-genai package by running:
pip uninstall google-genai
- Type y when prompted to confirm the uninstall.
- Delete your Gemini API key. Open the Google Cloud API Credentials page at 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 confirmation modal, click Delete. The key will stop working after a few minutes.
- Unset the environment variable by running:
unset GEMINI_API_KEY
Nice Work!
Nice Work!
You just built BuddyAI, a fully working AI friend chatbot powered by Google's Gemini model. It has a custom personality you designed, remembers your conversation, and streams responses word-by-word like a real person typing.
Here's what you accomplished:
- Connected to Google's Gemini API and sent your first AI-powered request from a Python script.
- Designed a custom personality using system prompts, the core skill of AI engineering: shaping AI behavior with natural language.
- Built a multi-turn chatbot with conversation memory and streaming responses, creating a natural chat experience in your terminal.
- Added mood detection so BuddyAI notices emotional cues and responds with extra warmth and empathy.
The skills you used in this project (API integration, prompt design, conversation management) are exactly what AI engineers do every day. You now have a real AI engineering project that shows you can build with AI, not just use it.
Ready to quiz yourself?