Build Your First AI Chatbot with Python
Connect Python to Google Gemini AI and build a multi-turn terminal chatbot.
Introduction
30 Second Summary
Every time you ask ChatGPT a question or talk to a virtual assistant, there is code behind the scenes connecting your words to an AI brain. That code is simpler than you think.
In this project, you will build your own AI chatbot using Python and Google's Gemini AI. You will type messages in your terminal and get real AI responses, just like a mini ChatGPT you built yourself.
What You'll Build
A Python script that connects to Google's Gemini AI and holds real multi-turn conversations in your terminal.
By the end of this project, you'll have:
- A working AI chatbot that responds to your messages in real time.
- Hands-on experience connecting Python to a real AI model using an API.
- A clear understanding of how AI applications work behind the scenes.
- Secret Mission: Give your chatbot a custom personality so it responds in character.
Do I need to know Python already?
You should be comfortable with basic Python concepts like variables, printing, and running a script. No advanced knowledge is needed.
Set Up Your Tools
Before you can chat with AI from your own code, you need three things: an API key that gives your code permission to talk to Google's AI, a Python package that handles the connection, and a file to write your chatbot in.
In this step, you will grab all three so you are ready to start building in the next step.
In this step, get ready to:
- Get your free Gemini API key.
- Install the Google GenAI package.
- Create your project folder and file.
Get your free Gemini API key
An API key is like a password that lets your Python code talk to Google's Gemini AI. Without it, Google would not know who is sending requests.
- Open your web browser and go to https://aistudio.google.com.
- Sign in with your Google account.
- In the left sidebar, click Get API key.
- Click Create API key.
- Copy the key that appears and paste it somewhere safe, like a temporary text file on your Desktop. You will need it in the next step.
What is an API key?
An API key is a unique code that identifies your application to a service. Think of it like a library card. The library (Google's AI) only lets you borrow books (get AI responses) if you show your card first.
The Gemini API is completely free to use with a Google account. No credit card required.
Keep your API key private
Never share your API key publicly or commit it to a public repository. Anyone with your key could use your quota.
Install the Google GenAI package
Python does not know how to talk to Google's AI on its own. You need to install a package called google-genai that provides all the connection tools.
- In VS Code, click Terminal in the top menu bar, then click New Terminal.
- Install the Google GenAI package by running this command:
pip install google-genai
You should see output ending with a line like Successfully installed google-genai-... followed by a version number.
- Confirm the package installed correctly by running this test command:
python -c "from google import genai; print('Ready!')"
You should see Ready! printed in your terminal.
Not seeing Ready! in your terminal?
- If you see ModuleNotFoundError, the package did not install. Try running pip install google-genai again and check for error messages in the output.
- If you see a message about python not being recognized, try using python3 instead in the command.
- Make sure you are running the command in the VS Code terminal, not in a browser or file.
Still stuck? Help me fix my google-genai installation.
Create your project folder and file
Now you need a folder to hold your chatbot project and an empty Python file to write your code in.
- Move to your Desktop by running this command:
cd ~/Desktop
- Create your project folder and move into it by running these commands:
mkdir my-ai-chatbot
cd my-ai-chatbot
- Create your empty Python file by running this command:
macOS
touch chatbot.py
Windows
New-Item chatbot.py
- Confirm the file exists by running:
ls
You should see chatbot.py listed in the output.
- Open your project folder in VS Code by clicking File in the top menu bar.
- Click Open Folder.
- Navigate to your Desktop, select the my-ai-chatbot folder, and click Select Folder.
Why open the folder in VS Code?
Opening the folder sets VS Code's workspace to your project. This means the file explorer on the left shows your project files, and any new terminal opens directly inside my-ai-chatbot.
If VS Code asks whether you trust the authors of the files in this folder, click Yes, I trust the authors.
You should see chatbot.py in the Explorer sidebar on the left side of VS Code.
Don't see chatbot.py in the sidebar?
- Make sure you selected the my-ai-chatbot folder itself, not the Desktop. The folder name should appear at the top of the Explorer sidebar.
- If the Explorer sidebar is hidden, click View in the menu bar, then click Explorer.
Still stuck? Help me find my chatbot.py file in VS Code.
Your workspace is ready. Next up, you will write your first lines of code and send a message to Google's AI.
Send Your First Message to AI
Your environment is ready and your tools are installed. Now for the exciting part: making your Python code talk to an actual AI.
The google-genai library you installed gives you a simple way to send text to Google's Gemini AI and get a response back. Let's send your very first message.
In this step, get ready to:
- Import the genai library and connect to Google's AI service.
- Send a prompt to Gemini and print its response in your terminal.
Import the library and create a client
Before you can talk to Google's AI, your script needs two things: the genai library imported, and a client object that knows how to connect using your API key.
- In VS Code, switch to your chatbot.py file and add the following code:
from google import genai
# Replace this with the API key you saved earlier
API_KEY = "your-api-key-here"
# Create a client that connects to Google's AI
client = genai.Client(api_key=API_KEY)
- Replace your-api-key-here with the actual Gemini API key you saved in Step 1.
- Keep the quotation marks around it.
What does this code do?
- from google import genai loads the Google GenAI library so you can use its tools.
- API_KEY stores your personal key that proves you have permission to use Gemini.
- genai.Client(api_key=API_KEY) creates a client object. Think of it as opening a phone line to Google's AI. Every message you send will go through this client.
What is an API key?
An API key is like a password that identifies your app to a service. It tells Google "this person has permission to use Gemini."
Never share your API key publicly or commit it to GitHub. For this beginner project, pasting it directly in code is fine. In production apps, developers store keys in environment variables instead.
You won't see any output yet. The next chunk sends your first message and prints the AI's response.
Send a message and print the response
Now that your client is connected, you can ask Gemini a question. The generate_content() method sends a prompt to the AI and returns its answer.
- Add the following code below your existing code in chatbot.py:
# Send a prompt to Gemini and store the response
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="Explain what an API is in one sentence."
)
# Print the AI's reply
print(response.text)
What does this code do?
- client.models.generate_content() sends your text prompt to the Gemini AI model and waits for a reply.
- model="gemini-3.5-flash" tells the SDK which AI model to use. Gemini 3.5 Flash is fast and free.
- contents is the actual question or instruction you want the AI to answer.
- response.text pulls out the AI's text reply from the response object so you can print it.
- Save chatbot.py.
- Run your script in the terminal by entering:
python chatbot.py
You should see the AI's response printed in your terminal. It will be a one-sentence explanation of what an API is.
Seeing an error instead of a response?
- If you see a message mentioning "API key not valid", double-check that you pasted your key correctly inside the quotation marks with no extra spaces.
- If you see ModuleNotFoundError: No module named 'google', run pip install google-genai again in your terminal.
- If you see a 403 permission error, go back to Google AI Studio and generate a fresh API key.
Still stuck? Help me debug my chatbot.py script. I'm getting an error when I run it.
✔️ Awesome, I've got everything!
Great. Double check you have saved chatbot.py and move on to the next step.
ⓧ I'd like to double check the full code
Here is the complete chatbot.py file at the end of this step:
from google import genai
API_KEY = "your-api-key-here"
client = genai.Client(api_key=API_KEY)
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="Explain what an API is in one sentence."
)
print(response.text)
You just talked to an AI from your own code. Next up, you will turn this into a real chatbot that holds back-and-forth conversations.
Build a Conversation Loop
In the last step, you sent a single message to Gemini and got a response. That proved your connection works. But a real chatbot does not stop after one reply.
In this step, you will turn your script into an interactive chatbot that keeps the conversation going. The AI will remember everything you have said so far, so you can have real back-and-forth exchanges.
In this step, get ready to:
- Create a chat session that remembers your conversation.
- Build an interactive loop so you can keep chatting with the AI.
- Add welcome and goodbye messages for a polished experience.
Create a chat session
Right now your script sends a single message and prints the reply. There is no way to follow up or ask another question. A chat session solves this by giving you an object that tracks the full conversation history automatically.
- In chatbot.py, find these lines:
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="Explain what an API is in one sentence."
)
print(response.text)
- Delete all of these lines and replace them with this:
# Create a chat session that remembers our conversation
chat = client.chats.create(model="gemini-3.5-flash")
What does this code do?
The client.chats.create() method creates a chat session tied to the gemini-3.5-flash model. Unlike generate_content() which forgets everything after each call, the chat object stores every message you send and every reply the AI gives back.
This means the AI can reference earlier parts of the conversation. It is how chatbots like ChatGPT know what you said five messages ago.
Build the conversation loop
A chatbot needs to keep asking for input until the user decides to leave. A while True loop runs forever until you explicitly tell it to stop, which makes it perfect for an ongoing conversation.
- Add this loop below the chat = client.chats.create(...) line:
while True:
user_input = input("You: ")
# Exit the loop if the user types 'quit'
if user_input.lower() == "quit":
print("\nGoodbye! Thanks for chatting.")
break
# Skip empty messages
if not user_input.strip():
continue
# Send the message and print the AI's reply
response = chat.send_message(user_input)
print(f"\nAI: {response.text}")
print()
What does this code do?
- input("You: ") pauses the program and waits for the user to type something. The text they enter gets stored in user_input.
- user_input.lower() == "quit" checks if the user wants to leave. The .lower() means typing "Quit" or "QUIT" also works.
- if not user_input.strip() skips blank messages so the AI does not get confused by empty input.
- chat.send_message(user_input) sends the message through the chat session. The session automatically includes all previous messages so the AI has full context.
Add a welcome message
When someone starts the chatbot, they need to know how it works. A welcome message tells the user what to do and how to exit.
- Add these lines between the chat = client.chats.create(...) line and the while True: loop:
print("=" * 50)
print(" Welcome to My AI Chatbot!")
print(" Type your message and press Enter.")
print(" Type 'quit' to exit.")
print("=" * 50)
print()
What does this code do?
These print statements create a friendly banner when the chatbot starts. The "=" * 50 repeats the equals sign 50 times to create a visual border. The empty print() at the end adds a blank line before the conversation begins.
- Save chatbot.py.
- Run your chatbot by entering this command in the terminal:
python chatbot.py
- You should see the welcome banner appear, followed by a You: prompt waiting for your input.
- Type I have 2 cats and press Enter.
- After the AI responds, type How many legs do my pets have? and press Enter.
- The AI should remember your first message and answer correctly (8 legs). This proves multi-turn conversation is working.
- Type quit to exit the chatbot.
Chatbot not responding or crashing?
- If you see an indentation error, make sure the code inside your while True: loop is indented with 4 spaces.
- If the chatbot freezes without showing You:, check that your welcome message prints are above the while True: line, not inside the loop.
- If you see an API error, make sure you still have the API_KEY and client lines at the top of your file from the previous step.
Still stuck? Ask for help.
✔️ Awesome, I've got everything!
Great. Double check you have saved chatbot.py and your chatbot is working with multi-turn conversations.
ⓧ I'd like to double check the full code
Here is the complete chatbot.py file. Compare it with yours to spot any differences.
from google import genai
API_KEY = "your-api-key-here"
client = genai.Client(api_key=API_KEY)
chat = client.chats.create(model="gemini-3.5-flash")
print("=" * 50)
print(" Welcome to My AI Chatbot!")
print(" Type your message and press Enter.")
print(" Type 'quit' to exit.")
print("=" * 50)
print()
while True:
user_input = input("You: ")
if user_input.lower() == "quit":
print("\nGoodbye! Thanks for chatting.")
break
if not user_input.strip():
continue
response = chat.send_message(user_input)
print(f"\nAI: {response.text}")
print()
Secret mission
Give Your Chatbot a Custom Personality
Your chatbot works, but it sounds like every other AI assistant out there. What if you could give it a unique personality that stays in character for the entire conversation? This is exactly how companies build custom AI products like tutoring assistants and customer service bots.
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 and uses the free Gemini API tier, so there are no ongoing costs.
Resources you used:
- my-ai-chatbot folder with your chatbot.py file.
- google-genai Python package installed via pip.
- Gemini API key created in Google AI Studio.
Keep everything running
No action needed. Choose this if you are still actively building or plan to extend your chatbot soon.
- Your chatbot only runs when you execute the script. There are no background processes or ongoing costs.
- Your API key remains active but costs nothing on the free tier.
- The google-genai package stays installed and ready for future projects.
Pause - I'll come back to this later
Since this project has no running processes or paid resources, there is nothing to pause. Your files and API key stay safely in place until you return.
- Close the VS Code window to free up memory on your machine.
- Your my-ai-chatbot folder, installed package, and API key all remain ready for when you come back.
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 the project folder. Open your terminal and run:
macOS
rm -rf ~/Desktop/my-ai-chatbot
Windows
rmdir /s /q %USERPROFILE%\Desktop\my-ai-chatbot
- Uninstall the google-genai package by running:
pip uninstall google-genai
Type y and press Enter when prompted to confirm.
- Delete your API key. Go to https://aistudio.google.com and click Get an API key to open the key management section. Find the key you created for this project and delete it.
Nice Work!
Nice Work!
You just built a fully functional AI chatbot from scratch using Python and Google's Gemini AI. Every message you sent, every response you received, that was your code talking to a real AI model in real time.
Here's what you accomplished:
- Installed a Python package and connected it to a real AI service using an API key.
- Learned what an API is by using one. It is how your code talks to Google's AI brain.
- Built a working chatbot that holds real multi-turn conversations with memory across messages.
- Customized your AI with a unique personality using system instructions (Secret Mission).
Ready to quiz yourself?