Build an AI Chatbot with Python and Groq
Build a terminal AI chatbot with Python fundamentals and Groq's free API.
Introduction
30 Second Summary
Every time you ask ChatGPT or Claude a question, your message travels to an AI model through an API and comes back as a response. That request/response pattern is the foundation of every AI automation tool being built today.
In this project, you will build a conversational AI chatbot that runs in your terminal, powered by Llama 3.3 70B. Along the way, you'll practice every Python fundamental an AI Automation Specialist needs: variables, strings, lists, dictionaries, loops, conditionals, and functions.
What You'll Build
A terminal-based chatbot that connects to Groq's free API, maintains conversation memory, and responds to custom commands.
By the end of this project, you'll have:
- A working Python script that sends messages to Llama 3.3 70B (a model as capable as GPT-4) and displays intelligent responses.
- A conversation memory system using lists and dictionaries that gives the chatbot context across multiple messages.
- A command system (/help, /clear, /history) built with conditionals and functions.
- Secret Mission: Add model switching and conversation export commands to your chatbot.
Are there any prerequisites?
This project assumes you already have Python and VS Code (or Cursor) installed on your computer. No prior Python experience is required. This is Part 1 of a 3-project series that takes you from Python fundamentals to building agentic AI workflows.
Set Up Your Project and Groq Account
Before you can talk to an AI model, you need a workspace for your code and a way to authenticate with the AI provider.
In this step, you'll create a project folder, set up an isolated Python environment, and connect to Groq for free access to Llama 3.3 70B.
In this step, get ready to:
- Create your project folder and virtual environment.
- Create a Groq account and get your API key.
- Install packages and store your key safely.
Create your project folder and virtual environment
A virtual environment is an isolated space where your project's packages live without affecting the rest of your system.
- Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
- Type VS Code and press Enter to open it.
- Open the integrated terminal by pressing Ctrl+`.
- Move to your Desktop by running this command:
cd ~/Desktop
- Create your project folder and move into it by running these commands:
mkdir ai-chatbot
cd ai-chatbot
- Create and activate your virtual environment by running the commands for your operating system:
macOS
python3 -m venv .venv
source .venv/bin/activate
Windows
python -m venv .venv
.venv\Scripts\activate
You should see (.venv) at the beginning of your terminal prompt.
What is a virtual environment?
A virtual environment keeps your project's packages separate from your system Python.
Without one, installing packages for this project could conflict with packages used by other projects on your machine.
Don't see (.venv) in your prompt?
Make sure you ran the activation command for your operating system. macOS uses source .venv/bin/activate and Windows uses .venv\Scripts\activate.
If you see a permissions error on Windows, try running Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned in PowerShell first, then retry the activate command.
Help me activate my virtual environment
Create a Groq account and get your API key
Groq provides free access to powerful AI models like Llama 3.3 70B. No credit card is required.
- Go to console.groq.com in your browser.
- Sign up with Google or email.
- Once logged in, click API Keys in the left sidebar.
- Click Create API Key.
- Give your key a name like chatbot-project.
- Copy the key that appears. You will not be able to see it again after closing this dialog.
Why Groq?
Groq runs AI models on custom hardware that delivers extremely fast responses. Their free tier gives you 30 requests per minute with access to all available models.
The Groq SDK follows the same pattern as other AI providers like OpenAI. Learning it once means switching providers later takes minimal effort.
Keep this tab open
You'll paste your API key in the next substep. Keep the Groq console tab open or paste the key somewhere safe temporarily.
Install packages and store your key
Your chatbot needs two packages: the Groq SDK to talk to the AI model, and python-dotenv to load your API key from a file.
- Install both packages by running this command:
pip install groq==1.2.0 python-dotenv==1.1.0
You should see Successfully installed messages in your terminal output.
What do these packages do?
- groq is the official Groq SDK. It handles authentication and sends your messages to Llama 3.3 70B.
- python-dotenv reads values from a .env file and loads them into your environment. This keeps secrets out of your code.
Seeing an install error?
Make sure (.venv) is visible in your prompt. If it disappeared, re-run the activation command from the previous substep.
If you see a network error, check your internet connection and try again.
Help me fix my pip install error
- Create a new file called .env in your ai-chatbot folder by clicking the new file icon in the VS Code Explorer sidebar.
- Name the file .env (including the dot at the start).
- Paste the following into your .env file, replacing your-api-key-here with the API key you copied from Groq:
GROQ_API_KEY=your-api-key-here
Why use a .env file?
Storing your API key in a .env file keeps it separate from your code. If you ever share your code or push it to GitHub, the key stays private as long as you add .env to your .gitignore.
- Save .env by pressing Cmd+S (macOS) or Ctrl+S (Windows).
File not appearing in Explorer?
Files starting with a dot are sometimes hidden by default. In VS Code's Explorer sidebar, check that the file appears in your ai-chatbot folder. If you accidentally created it outside the folder, drag it into ai-chatbot.
Help me find my .env file
✔️ Awesome, I've got everything!
Great. Double check you've saved your .env file with your actual Groq API key pasted in.
ⓧ I'd like to double check the full code
Here is the complete .env file. Replace your-api-key-here with your actual Groq API key.
GROQ_API_KEY=your-api-key-here
Your workspace is ready. You have a virtual environment, the Groq SDK installed, and your API key stored safely. Next up, you'll write your first Python script and make your first AI API call.
Make Your First AI API Call
Your project folder is ready and your API key is safely stored. Now it's time to write actual Python code that talks to an AI model.
In this step, you'll create a script that sends a message to Llama 3.3 70B and prints the response. This introduces the core pattern behind every AI automation: send a request, get a response.
In this step, get ready to:
- Create chatbot.py with imports and configuration.
- Send a message to Llama 3.3 70B and print the response.
- Run the script to see AI respond in your terminal.
Create your chatbot script
Every Python script starts with imports. Your chatbot needs two things: the Groq SDK to talk to the AI, and python-dotenv to load your API key from the .env file.
- In the VS Code Explorer sidebar, hover over the AI-CHATBOT heading and click the New File icon.
- Name the file chatbot.py and press Enter.
- Add the following imports and setup code to chatbot.py:
from groq import Groq
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Create the Groq client (reads GROQ_API_KEY automatically)
client = Groq()
What does this code do?
- from groq import Groq brings in the Groq client class from the SDK you installed.
- from dotenv import load_dotenv brings in the function that reads your .env file.
- load_dotenv() reads .env and makes GROQ_API_KEY available as an environment variable.
- client = Groq() creates a client that automatically picks up your API key from the environment.
You won't see any output yet. The next chunk sends your first message to the AI.
Send a message to the AI
With the client ready, you can now call the API. The pattern is simple: build a list of messages, send them to a model, and read the response.
- Add the following code below client = Groq() in chatbot.py:
# Send a single message to the API
response = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[
{"role": "user", "content": "Hello! What can you help me with?"}
],
max_tokens=1024
)
# Extract and print the response text
print(response.choices[0].message.content)
What does this code do?
This is the core API call pattern you'll use in every AI project:
- client.chat.completions.create() sends a chat request to Groq's servers.
- model specifies which AI model to use. llama-3.3-70b-versatile is a 70-billion-parameter model as capable as GPT-4.
- messages is a list of dictionaries. Each dictionary has a "role" (who's speaking) and "content" (what they said).
- max_tokens limits how long the AI's response can be.
- response.choices[0].message.content drills into the response object to extract the actual text the AI wrote.
The response comes back as a structured object. choices is a list (the API can return multiple options), [0] grabs the first one, and .message.content gets the text string.
- Save chatbot.py by pressing Cmd+S (macOS) or Ctrl+S (Windows).
Seeing a red underline on an import?
If VS Code shows a squiggly line under from groq import Groq, your editor might not be using the virtual environment's Python interpreter.
- Press Cmd+Shift+P (macOS) or Ctrl+Shift+P (Windows) to open the Command Palette.
- Type Python: Select Interpreter and select the one that includes .venv in its path.
Help me fix import errors in VS Code with my virtual environment.
✔️ 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 complete chatbot.py so far:
from groq import Groq
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Create the Groq client (reads GROQ_API_KEY automatically)
client = Groq()
# Send a single message to the API
response = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[
{"role": "user", "content": "Hello! What can you help me with?"}
],
max_tokens=1024
)
# Extract and print the response text
print(response.choices[0].message.content)
Run your chatbot script
Your script is complete. Time to see it in action.
- Run your script by entering this command in the terminal:
python chatbot.py
After a moment, you should see the AI's response printed in your terminal. It will be a helpful message introducing what it can assist with.
What just happened?
Your Python script sent a request over the internet to Groq's servers. Groq ran your message through Llama 3.3 70B (a 70-billion-parameter AI model) and returned the response. You just wrote working Python that communicates with an AI model.
This request-response pattern is the foundation of every AI automation workflow. The same structure works with OpenAI, Anthropic, and other providers.
Seeing an error instead of a response?
- If you see an authentication error, double-check that your .env file contains GROQ_API_KEY= followed by your actual key (no spaces, no quotes around the value).
- If you see ModuleNotFoundError, make sure your virtual environment is active. You should see (.venv) in your terminal prompt.
- If you see a rate limit error, wait a minute and try again. The free tier allows 30 requests per minute.
Help me debug my chatbot.py script that isn't returning a response from Groq.
You just made a 70-billion-parameter AI model respond to your Python code. Next up, you'll turn this single exchange into a full conversation loop where the chatbot remembers what you've said.
Build the Chat Loop
Your chatbot can talk, but only once. Right now it sends a single hardcoded message and exits. A real chatbot needs to keep listening, responding, and remembering what you said.
In this step, you'll transform your script into an interactive conversation loop. You'll use a while loop to keep the chatbot running, a list to store the full conversation, and conditionals to handle edge cases like empty input.
In this step, get ready to:
- Add a while loop that keeps the chatbot running until you say "quit".
- Build conversation memory using a list of dictionaries.
- Handle edge cases like empty input with conditionals.
Add user input with a while loop
Right now your script fires one API call and exits. To make the chatbot interactive, you need a loop that keeps asking the user for input until they decide to leave.
- In chatbot.py, find the last section of your file starting with this comment:
# Send a single message to the API
- Delete everything from that comment to the end of the file. This removes the old hardcoded API call and the print statement below it.
- Replace it with the following code to create the loop structure:
# Current model
current_model = "llama-3.3-70b-versatile"
# Main chat loop
while True:
# Get user input
user_input = input("You: ")
# Check for exit
if user_input.lower() in ["quit", "exit"]:
print("\n Goodbye! Happy coding!")
break
What does this code do?
This introduces three key Python concepts:
- current_model stores the model name in a variable so you can change it in one place later.
- while True: creates an infinite loop. The chatbot keeps running until something tells it to stop.
- input("You: ") pauses the program and waits for the user to type something. Whatever they type gets stored in user_input.
- if user_input.lower() in ["quit", "exit"]: checks if the user typed "quit" or "exit" (case-insensitive). If they did, break exits the loop.
- Save chatbot.py and test the loop by running:
python chatbot.py
You should see a You: prompt. Type anything and press Enter. The prompt reappears (nothing else happens yet). Type quit and press Enter to exit. You should see "Goodbye! Happy coding!" printed.
Stuck in the loop?
If typing quit doesn't exit, check that the if statement is indented inside the while True: block. Python uses indentation to determine which code belongs inside a loop.
If the program never starts, check for a syntax error. Make sure while True: has a colon at the end and the lines inside are indented with four spaces.
Press Ctrl+C in the terminal to force-stop the program if needed.
Help me fix my while loop
Add conversation memory with a list
Your loop runs, but it doesn't send messages to the AI yet. To make a real conversation, you need to track every message exchanged. AI APIs are stateless. They don't remember previous messages unless you send the full history with each request.
- In chatbot.py, add this line between the current_model variable and the # Main chat loop comment:
# Store conversation history as a list of dictionaries
conversation_history = []
- Now add the conversation turn logic inside the loop. Place this code after the break statement (at the same indentation level as the if check above it):
# Add user message to history
conversation_history.append({
"role": "user",
"content": user_input
})
# Send message to Groq API
response = client.chat.completions.create(
model=current_model,
messages=conversation_history,
max_tokens=1024
)
# Extract the response text
assistant_message = response.choices[0].message.content
# Add assistant response to history
conversation_history.append({
"role": "assistant",
"content": assistant_message
})
# Display the response
print(f"\nBot: {assistant_message}\n")
What does this code do?
This is the core conversation pattern used in every AI API:
- conversation_history is an empty list that stores every message as a dictionary. Each dictionary has a "role" (who said it) and "content" (what they said).
- append() adds the user's message to the history before sending it to the API.
- The entire conversation_history list gets passed to messages= in the API call. This is how the AI "remembers" the conversation. It sees every previous message each time.
- After the AI responds, its message gets appended too. Both sides of the conversation are tracked.
- Save chatbot.py and run it again:
python chatbot.py
Type a question like "What is Python?" and press Enter. The AI should respond. Try a follow-up question that references the first (like "Can you give me an example?") to confirm the chatbot remembers context.
Getting an API error?
If you see an authentication error, check that your .env file contains your actual Groq API key (not the placeholder text).
If you see an indentation error, make sure all the code inside the while True: loop is indented with exactly four spaces. The conversation_history.append( line should be at the same level as the if user_input.lower() line above it.
Help me fix my chatbot API call
Handle edge cases with conditionals
If the user accidentally presses Enter without typing anything, the chatbot would send an empty string to the API. That wastes an API call and returns a confusing response. You can guard against this with a conditional check.
- In chatbot.py, find the break line inside the exit check. Look at the code directly after it:
if user_input.lower() in ["quit", "exit"]:
print("\n Goodbye! Happy coding!")
break
# Add user message to history
conversation_history.append({
- Add this empty-input check between the exit check and the append, so the code now looks like this:
if user_input.lower() in ["quit", "exit"]:
print("\n Goodbye! Happy coding!")
break
# Skip empty input
if not user_input.strip():
continue
# Add user message to history
conversation_history.append({
What does this code do?
strip() removes whitespace from both ends of a string. If the user pressed Enter without typing anything, user_input.strip() returns an empty string.
In Python, an empty string is "falsy". So not user_input.strip() evaluates to True when the input is blank. The continue keyword skips the rest of the loop and jumps back to the input() prompt.
- Save chatbot.py and run it one more time:
python chatbot.py
Press Enter a few times without typing anything. The You: prompt should reappear each time without sending anything to the AI. Then type a real message to confirm it still works.
Empty Enter still sends a message?
Make sure the if not user_input.strip(): check comes BEFORE the conversation_history.append line. If it comes after, the empty message has already been added to history.
Help me fix my empty input check
✔️ 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
Here is the complete chatbot.py at this point:
from groq import Groq
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Create the Groq client (reads GROQ_API_KEY automatically)
client = Groq()
# Current model
current_model = "llama-3.3-70b-versatile"
# Store conversation history as a list of dictionaries
conversation_history = []
# Main chat loop
while True:
# Get user input
user_input = input("You: ")
# Check for exit
if user_input.lower() in ["quit", "exit"]:
print("\n Goodbye! Happy coding!")
break
# Skip empty input
if not user_input.strip():
continue
# Add user message to history
conversation_history.append({
"role": "user",
"content": user_input
})
# Send message to Groq API
response = client.chat.completions.create(
model=current_model,
messages=conversation_history,
max_tokens=1024
)
# Extract the response text
assistant_message = response.choices[0].message.content
# Add assistant response to history
conversation_history.append({
"role": "assistant",
"content": assistant_message
})
# Display the response
print(f"\nBot: {assistant_message}\n")
Your chatbot now runs as a full interactive conversation with memory. Next up, you'll give it a personality with a system prompt and add commands like /help and /clear using functions.
Add a System Prompt and Command System
Your chatbot works, but it has no personality. Every response comes from the model's generic defaults, and the only way to interact is by typing messages or quitting.
In this step, you'll give your chatbot a defined personality using a system prompt, then build a command system so users can type /help, /clear, and /history to control the conversation. This introduces Python functions, for loops, and f-strings.
In this step, get ready to:
- Add a system prompt that shapes your chatbot's personality.
- Build command functions using def, for loops, and f-strings.
- Wire commands into the main loop with an if/elif chain.
Create a system prompt
A system prompt is a special message you send to the AI before the conversation starts. It defines the chatbot's personality, expertise, and response style.
- In chatbot.py, find the two lines that define current_model and conversation_history (right after client = Groq()).
- Replace that entire section with the following code:
# System prompt - defines the chatbot's personality
system_prompt = """You are a helpful AI assistant specializing in teaching Python and AI concepts.
You explain things clearly with short examples when helpful.
You are encouraging and patient with beginners.
Keep responses concise - aim for 2-3 paragraphs max unless asked for more detail."""
# Store conversation history as a list of dictionaries
conversation_history = []
# Current model
current_model = "llama-3.3-70b-versatile"
What does this code do?
The triple-quoted string """...""" is a Python multi-line string. It lets you write text that spans multiple lines without needing special characters.
This system prompt tells the AI to act as a Python teacher who is encouraging and concise. You can change this text to anything you want. Try making it a pirate, a poet, or a strict professor.
The system prompt is defined, but the API call doesn't use it yet. You need to prepend it to the messages you send.
- Scroll down to the # Send message to Groq API section inside the while loop.
- Find this line:
messages=conversation_history,
- Replace it with this:
messages=[
{"role": "system", "content": system_prompt}
] + conversation_history,
What changed?
Instead of sending just the conversation history, you now create a list with the system message first, then combine it with conversation_history using the + operator. The AI reads the system prompt before every response, keeping its personality consistent.
- Save chatbot.py.
- Run your chatbot by entering this in the terminal:
python chatbot.py
- Ask it a Python question like What is a list in Python? and notice how it responds as a patient Python teacher instead of a generic assistant.
- Type quit to exit.
Chatbot not acting differently?
Make sure the messages= line starts with the system dict in a list, followed by + conversation_history. If you forgot the + or the square brackets, the system prompt won't reach the model.
Help me debug my system prompt
Build command functions
Python functions let you package a block of code under a name, then call it whenever you need it. You'll create three functions that each handle a different command.
- In chatbot.py, add the following function below the current_model line (and above the while loop). This is the /help command:
def show_help():
"""Display available commands."""
print("\n Available Commands:")
print(" /help - Show this help message")
print(" /clear - Clear conversation history")
print(" /history - Show conversation history")
print(" quit - Exit the chatbot")
print()
What does this code do?
def show_help(): defines a function called show_help. Everything indented beneath it is the function's body. When you call show_help() later, Python runs all those print() statements.
The triple-quoted line right after def is called a docstring. It documents what the function does. It's good practice to include one in every function.
- Add the /clear command function directly below show_help():
def clear_history():
"""Clear the conversation history."""
conversation_history.clear()
print("\n Conversation cleared! Starting fresh.\n")
What does this code do?
conversation_history.clear() empties the list entirely. After calling this, the AI forgets everything from the current session and responds as if the conversation just started.
- Add the /history command function directly below clear_history():
def show_history():
"""Display the conversation history."""
if not conversation_history:
print("\n No conversation history yet.\n")
return
print("\n Conversation History:")
print("-" * 40)
for message in conversation_history:
role = "You" if message["role"] == "user" else "Bot"
print(f" [{role}]: {message['content'][:80]}...")
print("-" * 40)
print()
What does this code do?
This function uses a for loop to iterate through every message in conversation_history. Each message is a dictionary with "role" and "content" keys.
The f"..." syntax is an f-string. It lets you embed variables inside curly braces directly within a string. The [:80] slice truncates long messages to 80 characters so the output stays readable.
- Save chatbot.py. You won't test the functions yet. The next substep wires them into the main loop.
Seeing an IndentationError?
Python uses indentation (spaces) to determine what code belongs inside a function. Make sure every line inside each def block is indented with 4 spaces. Mixing tabs and spaces will also cause this error.
Help me fix my indentation
Wire commands into the main loop
The functions exist, but nothing calls them yet. You need to add a welcome message and route user commands to the correct function using conditionals.
- Add a welcome message block between your functions and the # Main chat loop comment. Copy this code above the while True: line:
# Welcome message
print("=" * 50)
print(" AI Chatbot - Powered by Llama 3.3 70B")
print(" Type /help for commands, 'quit' to exit")
print("=" * 50)
print()
What does this code do?
This prints a banner when the chatbot starts. The "=" * 50 expression repeats the = character 50 times, creating a visual separator. It runs once before the loop starts, so the user immediately sees what commands are available.
Now you need to add command routing inside the while loop. Commands start with /, so you'll check for them before sending anything to the AI.
- Inside the while loop, find the # Skip empty input section. Add the following command checks between the exit check and the empty input check:
# Check for commands
if user_input.strip() == "/help":
show_help()
continue
if user_input.strip() == "/clear":
clear_history()
continue
if user_input.strip() == "/history":
show_history()
continue
What does this code do?
Each if block checks whether the user typed a specific command. The .strip() removes any accidental spaces around the input.
The continue keyword skips the rest of the loop body and jumps back to the top. This means if the user typed a command, it gets handled and the message is never sent to the AI.
- Save chatbot.py.
- Run your chatbot by entering this in the terminal:
python chatbot.py
- You should see the welcome banner with AI Chatbot - Powered by Llama 3.3 70B displayed.
- Type /help and verify you see the list of available commands.
- Ask the chatbot a question, then type /history to confirm your messages are being tracked.
- Type /clear then /history again to verify the history was erased.
- Type quit to exit.
Commands not working?
Make sure the command checks appear BEFORE the # Skip empty input section in your while loop. If they come after the conversation_history.append() line, the command text gets sent to the AI instead of being intercepted.
Also check that each command check ends with continue. Without it, the loop will keep running and try to send the command as a chat message.
Help me debug my command routing
✔️ 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:
from groq import Groq
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Create the Groq client (reads GROQ_API_KEY automatically)
client = Groq()
# System prompt - defines the chatbot's personality
system_prompt = """You are a helpful AI assistant specializing in teaching Python and AI concepts.
You explain things clearly with short examples when helpful.
You are encouraging and patient with beginners.
Keep responses concise - aim for 2-3 paragraphs max unless asked for more detail."""
# Store conversation history as a list of dictionaries
conversation_history = []
# Current model
current_model = "llama-3.3-70b-versatile"
def show_help():
"""Display available commands."""
print("\n Available Commands:")
print(" /help - Show this help message")
print(" /clear - Clear conversation history")
print(" /history - Show conversation history")
print(" quit - Exit the chatbot")
print()
def clear_history():
"""Clear the conversation history."""
conversation_history.clear()
print("\n Conversation cleared! Starting fresh.\n")
def show_history():
"""Display the conversation history."""
if not conversation_history:
print("\n No conversation history yet.\n")
return
print("\n Conversation History:")
print("-" * 40)
for message in conversation_history:
role = "You" if message["role"] == "user" else "Bot"
print(f" [{role}]: {message['content'][:80]}...")
print("-" * 40)
print()
# Welcome message
print("=" * 50)
print(" AI Chatbot - Powered by Llama 3.3 70B")
print(" Type /help for commands, 'quit' to exit")
print("=" * 50)
print()
# Main chat loop
while True:
# Get user input
user_input = input("You: ")
# Check for exit
if user_input.lower() in ["quit", "exit"]:
print("\n Goodbye! Happy coding!")
break
# Check for commands
if user_input.strip() == "/help":
show_help()
continue
if user_input.strip() == "/clear":
clear_history()
continue
if user_input.strip() == "/history":
show_history()
continue
# Skip empty input
if not user_input.strip():
continue
# Add user message to history
conversation_history.append({
"role": "user",
"content": user_input
})
# Send message to Groq API
response = client.chat.completions.create(
model=current_model,
messages=[
{"role": "system", "content": system_prompt}
] + conversation_history,
max_tokens=1024
)
# Extract the response text
assistant_message = response.choices[0].message.content
# Add assistant response to history
conversation_history.append({
"role": "assistant",
"content": assistant_message
})
# Display the response
print(f"\nBot: {assistant_message}\n")
Your chatbot now has a personality, a command system, and conversation memory. You've used every Python fundamental an AI automation specialist needs: variables, strings, lists, dictionaries, while loops, for loops, conditionals, and functions.
Secret mission
Model Switching and Chat Export
Your chatbot is locked to one model. What if you could switch between Llama 3.3 70B and Llama 3.1 8B mid-conversation? And what if you could save your best conversations to a file? Time to find out.
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, so there are no ongoing costs.
Resources you used:
- The ai-chatbot project folder on your Desktop (contains chatbot.py, .env, .venv, and any exported chat files).
- Python packages installed inside the virtual environment (groq, python-dotenv).
Keep everything running
No action needed. Choose this if you're still actively building or plan to continue with Part 2 of this series.
- Your ai-chatbot folder stays on your Desktop ready for the next session.
- Your Groq account remains active with free API access (no credit card on file, no charges).
- Your virtual environment stays ready. Next time, just activate it again with .venv\Scripts\activate (Windows) or source .venv/bin/activate (macOS/Linux).
Pause - I'll come back to this later
Shut down running processes to free up memory. Your files and account stay intact for when you return.
- If your chatbot is still running in the terminal, type quit and press Enter to exit.
- Deactivate your virtual environment by running:
deactivate
- Close VS Code. Everything will be exactly as you left it when you reopen the folder.
Delete - I don't want to use this again
Remove all project files from your computer. Your Groq account is free and stays active separately.
- If your chatbot is still running, type quit and press Enter to exit.
- Deactivate your virtual environment by running:
deactivate
- Navigate to your Desktop and delete the project folder. On macOS/Linux, run:
cd ~/Desktop
rm -rf ai-chatbot
On Windows, run:
cd ~\Desktop
rmdir /s /q ai-chatbot
- This removes chatbot.py, your .env file, the .venv virtual environment, and all installed packages inside it.
- Any exported chat files (like chat_2026-05-23_14-30-00.txt) inside the folder are also removed.
That's a Wrap!
That's a Wrap!
Nice work! You just built a fully functional AI chatbot in Python, powered by Llama 3.3 70B running on Groq's free API.
You've learned how to:
- Called an AI model via the Groq API using the request/response pattern (client.chat.completions.create()) that every AI provider shares.
- Built conversation memory as a list of dictionaries, the exact data structure used in every AI API.
- Created an interactive command system using while loops, conditionals, and functions to route user input, validate data, and organize code into reusable pieces.
- Added model switching and conversation export to let users change AI models mid-conversation and save chats to timestamped files.
Ready to quiz yourself?