How to Build a Simple AI Chatbot with Python
Learn how to build a simple AI chatbot in Python using the OpenAI API, where your chatbot can interact conversationally by sending prompts to and receiving responses from the OpenAI models. This beginner-friendly guide shows how to set up your environment, integrate your API key, and write Python code to create an interactive AI assistant.
Sara Khan
Author
How to Build a Simple AI Chatbot with Python
So you want to build your own chatbot? Maybe you've been chatting with AI assistants and thought, "Hey, I could probably build something like this." And you know what? You absolutely can.
I remember my first chatbot project. It was a disaster—more like a confused parrot than an intelligent assistant. But that's exactly how I learned. Today, I'm going to walk you through building a simple AI chatbot with Python, and I promise to skip all the technical jargon that made my head spin when I was starting out.
Let's build something cool together.
What We're Building (And What We're Not)
Before we dive in, let's set realistic expectations. We're not building ChatGPT here. What we are building is a functional chatbot that can:
- Have basic conversations
- Remember context from earlier in the chat
- Give intelligent responses using AI
- Be customized for specific use cases
Think of it as your chatbot's MVP—the foundation you can build on later.
What You'll Need
Here's the shopping list:
Prerequisites:
- Basic Python knowledge (if you know what a variable and a function are, you're good)
- Python 3.8 or higher installed on your computer
- A text editor (VS Code, PyCharm, or even Notepad++ works)
- An OpenAI API key (don't worry, we'll cover this)
- About 30-45 minutes of your time
Cost heads-up: OpenAI's API isn't free, but it's cheap for testing. We're talking cents, not dollars, for your first experiments.
Step 1: Setting Up Your Environment
First things first—let's get your workspace ready.
Open your terminal (Command Prompt on Windows, Terminal on Mac/Linux) and create a new folder for your project:
mkdir my-chatbot
cd my-chatbot
Now, let's create a virtual environment. Think of this as a sandbox where we can install packages without messing up your main Python installation:
# On Windows
python -m venv venv
venv\Scripts\activate
# On Mac/Linux
python3 -m venv venv
source venv/bin/activate
You'll know it worked when you see (venv) appear before your command prompt. Nice!
Step 2: Installing the Good Stuff
Time to install the packages we need. Run this command:
pip install openai python-dotenv
What did we just install?
- openai: The official OpenAI library (our AI brain)
- python-dotenv: Helps us manage sensitive information securely
Step 3: Getting Your API Key
This is like getting the keys to a sports car. Here's how:
- Go to platform.openai.com
- Sign up or log in
- Navigate to API keys section
- Click "Create new secret key"
- Copy that key immediately (you won't see it again!)
Now, create a file called .env in your project folder and add:
OPENAI_API_KEY=your-api-key-here
Important: Never, ever commit this file to GitHub or share it publicly. This is your secret sauce.
Pro tip: Create a .gitignore file with this content:
.env
venv/
__pycache__/
Step 4: Building the Basic Chatbot
Alright, here's where the magic happens. Create a new file called chatbot.py and let's start coding.
Version 1: The Simple Chatbot
import os
from openai import OpenAI
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Initialize OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
def chat(user_message):
"""
Send a message to the AI and get a response
"""
response = client.chat.completions.create(
model="gpt-5.2-2025-12-11",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": user_message}
]
)
return response.choices[0].message.content
# Main chat loop
def main():
print("Chatbot: Hi! I'm your AI assistant. Type 'quit' to exit.
")
while True:
user_input = input("You: ")
if user_input.lower() in ['quit', 'exit', 'bye']:
print("Chatbot: Goodbye! Have a great day!")
break
response = chat(user_input)
print(f"Chatbot: {response}
")
if __name__ == "__main__":
main()
Run it with:
python chatbot.py
Congratulations! You just built a working AI chatbot. Seriously, give yourself a pat on the back.
But wait—there's a problem. Try asking it "What did I just say?" and watch it forget everything. That's because it has no memory. Let's fix that.
Step 5: Adding Memory (Conversation History)
This version remembers your conversation:
import os
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
class Chatbot:
def __init__(self, system_prompt="You are a helpful assistant."):
self.conversation_history = [
{"role": "system", "content": system_prompt}
]
def chat(self, user_message):
"""
Send a message and maintain conversation history
"""
# Add user message to history
self.conversation_history.append(
{"role": "user", "content": user_message}
)
# Get AI response
response = client.chat.completions.create(
model="gpt-5.2-2025-12-11",
messages=self.conversation_history
)
# Add AI response to history
assistant_message = response.choices[0].message.content
self.conversation_history.append(
{"role": "assistant", "content": assistant_message}
)
return assistant_message
def reset(self):
"""
Clear conversation history
"""
system_prompt = self.conversation_history[0]
self.conversation_history = [system_prompt]
def main():
# Create a chatbot with a custom personality
bot = Chatbot(
system_prompt="You are a friendly and enthusiastic coding tutor. "
"Help users learn programming with patience and clear examples."
)
print("Chatbot: Hey there! I'm your coding tutor. Ask me anything!")
print("Commands: 'quit' to exit, 'reset' to start fresh
")
while True:
user_input = input("You: ")
if user_input.lower() in ['quit', 'exit', 'bye']:
print("Chatbot: Happy coding! See you next time!")
break
if user_input.lower() == 'reset':
bot.reset()
print("Chatbot: Conversation reset! Let's start fresh.
")
continue
response = bot.chat(user_input)
print(f"Chatbot: {response}
")
if __name__ == "__main__":
main()
Now your chatbot has a memory and a personality! Test it out—ask it something, then follow up with "What did I just ask you?" Pretty cool, right?
Step 6: Making It Fancy (Optional But Fun)
Let's add some color and better formatting. Install this package:
pip install colorama
Now update your chatbot:
import os
from openai import OpenAI
from dotenv import load_dotenv
from colorama import Fore, Style, init
# Initialize colorama
init(autoreset=True)
load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
class Chatbot:
def __init__(self, system_prompt="You are a helpful assistant."):
self.conversation_history = [
{"role": "system", "content": system_prompt}
]
def chat(self, user_message):
self.conversation_history.append(
{"role": "user", "content": user_message}
)
try:
response = client.chat.completions.create(
model="gpt-5.2-2025-12-11",
messages=self.conversation_history,
max_tokens=500,
temperature=0.7
)
assistant_message = response.choices[0].message.content
self.conversation_history.append(
{"role": "assistant", "content": assistant_message}
)
return assistant_message
except Exception as e:
return f"Oops! Something went wrong: {str(e)}"
def reset(self):
system_prompt = self.conversation_history[0]
self.conversation_history = [system_prompt]
def main():
bot = Chatbot(
system_prompt="You are a friendly and helpful AI assistant."
)
print(Fore.CYAN + Style.BRIGHT + "╔════════════════════════════════════════╗")
print(Fore.CYAN + Style.BRIGHT + "║ AI CHATBOT - READY TO CHAT! ║")
print(Fore.CYAN + Style.BRIGHT + "╚════════════════════════════════════════╝
")
print(Fore.YELLOW + "Commands: 'quit' to exit, 'reset' to start over
")
while True:
user_input = input(Fore.GREEN + "You: " + Style.RESET_ALL)
if user_input.lower() in ['quit', 'exit', 'bye']:
print(Fore.CYAN + "Chatbot: Goodbye! Thanks for chatting! 👋")
break
if user_input.lower() == 'reset':
bot.reset()
print(Fore.MAGENTA + "Chatbot: Memory cleared! Fresh start! 🔄
")
continue
if not user_input.strip():
continue
print(Fore.BLUE + "Chatbot: ", end="")
response = bot.chat(user_input)
print(Style.RESET_ALL + response + "
")
if __name__ == "__main__":
main()
Look at that! Now you've got a chatbot with style.
Customization Ideas: Make It Your Own
Here's where things get fun. You can customize your chatbot for specific purposes:
Customer Support Bot
bot = Chatbot(
system_prompt="You are a customer support agent for TechStore. "
"Be helpful, professional, and try to resolve issues quickly. "
"If you can't help, suggest contacting a human agent."
)
Cooking Assistant
bot = Chatbot(
system_prompt="You are a professional chef. Help users with recipes, "
"cooking techniques, and ingredient substitutions. "
"Always provide clear, step-by-step instructions."
)
Study Buddy
bot = Chatbot(
system_prompt="You are a patient tutor. Help students understand concepts "
"by breaking them down into simple terms. Ask questions to "
"check understanding and provide examples."
)
Common Issues (And How to Fix Them)
"I'm getting an authentication error!"
Your API key is probably wrong or not loaded. Check:
- Is it in your
.envfile? - Did you activate your virtual environment?
- Is the
.envfile in the same directory as your script?
"The chatbot is too expensive!"
Try these:
- Use
gpt-3.5-turboinstead ofgpt-5(way cheaper) - Set
max_tokensto a lower number (like 150) - Clear conversation history more frequently
"Responses are slow!"
That's normal with API calls. You could add a "typing..." indicator:
import sys
def show_typing():
print(Fore.BLUE + "Chatbot is typing", end="")
for _ in range(3):
sys.stdout.write(".")
sys.stdout.flush()
time.sleep(0.3)
print("\r" + " " * 50 + "\r", end="")
Taking It Further
Want to level up? Here are some ideas:
1. Add a Web Interface Use Flask or Streamlit to create a web-based chatbot. Streamlit is super easy:
pip install streamlit
2. Save Conversation History Store chats in a JSON file or database so users can resume conversations.
3. Add Voice Input/Output
Use libraries like speech_recognition and pyttsx3 for voice interactions.
4. Create Specialized Tools Give your chatbot the ability to search the web, check weather, or access databases.
5. Deploy It Put it on a server so others can use it. Check out Heroku, Railway, or AWS.
The Complete Code
Here's everything in one clean file you can copy and paste:
"""
Simple AI Chatbot with Python
A beginner-friendly chatbot using OpenAI's API
"""
import os
from openai import OpenAI
from dotenv import load_dotenv
from colorama import Fore, Style, init
# Initialize
init(autoreset=True)
load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
class Chatbot:
"""A simple chatbot with conversation memory"""
def __init__(self, system_prompt="You are a helpful assistant."):
self.conversation_history = [
{"role": "system", "content": system_prompt}
]
def chat(self, user_message):
"""Send a message and get a response"""
self.conversation_history.append(
{"role": "user", "content": user_message}
)
try:
response = client.chat.completions.create(
model="gpt-5.2-2025-12-11",
messages=self.conversation_history,
max_tokens=500,
temperature=0.7
)
assistant_message = response.choices[0].message.content
self.conversation_history.append(
{"role": "assistant", "content": assistant_message}
)
return assistant_message
except Exception as e:
return f"Error: {str(e)}"
def reset(self):
"""Clear conversation history"""
system_prompt = self.conversation_history[0]
self.conversation_history = [system_prompt]
def get_history_length(self):
"""Get number of messages (excluding system prompt)"""
return len(self.conversation_history) - 1
def main():
"""Main function to run the chatbot"""
# Create chatbot instance
bot = Chatbot(
system_prompt="You are a friendly and helpful AI assistant. "
"Be conversational, concise, and engaging."
)
# Welcome message
print(Fore.CYAN + Style.BRIGHT + "
╔════════════════════════════════════════╗")
print(Fore.CYAN + Style.BRIGHT + "║ AI CHATBOT - READY TO CHAT! ║")
print(Fore.CYAN + Style.BRIGHT + "╚════════════════════════════════════════╝
")
print(Fore.YELLOW + "Commands:")
print(Fore.YELLOW + " • 'quit' or 'exit' - End conversation")
print(Fore.YELLOW + " • 'reset' - Clear chat history")
print(Fore.YELLOW + " • 'history' - Show message count
")
# Main conversation loop
while True:
user_input = input(Fore.GREEN + "You: " + Style.RESET_ALL)
# Handle commands
if user_input.lower() in ['quit', 'exit', 'bye']:
print(Fore.CYAN + "
Chatbot: Thanks for chatting! Goodbye! 👋
")
break
if user_input.lower() == 'reset':
bot.reset()
print(Fore.MAGENTA + "Chatbot: Memory cleared! Let's start fresh! 🔄
")
continue
if user_input.lower() == 'history':
count = bot.get_history_length()
print(Fore.MAGENTA + f"Chatbot: We've exchanged {count} messages so far.
")
continue
if not user_input.strip():
continue
# Get and display response
print(Fore.BLUE + "Chatbot: ", end="")
response = bot.chat(user_input)
print(Style.RESET_ALL + response + "
")
if __name__ == "__main__":
main()
Wrapping Up
And there you have it! You've just built your own AI chatbot from scratch. Pretty awesome, right?
The beautiful thing about this project is that it's a foundation. You can take it in a million different directions—add features, change the personality, integrate it with other apps, or even turn it into a business tool.
Remember when I said my first chatbot was a disaster? Well, that disaster taught me more than any tutorial ever could. So don't be afraid to break things, experiment, and make mistakes. That's how you learn.
What's next? Pick one of the customization ideas above and try it out. Build something weird. Build something useful. Just build something.
And hey, if you create something cool, I'd love to hear about it. Drop a comment below or share what you've built!
Now go forth and create some chatbot magic! 🚀
Quick Reference
Installation Commands
pip install openai python-dotenv colorama
Basic Usage
from openai import OpenAI
client = OpenAI(api_key="your-key")
response = client.chat.completions.create(
model="gpt-5.2-2025-12-11",
messages=[{"role": "user", "content": "Hello!"}]
)
Useful Links
Join the Verse
Get exclusive insights on Next.js, System Design, and Modern Web Development delivered straight to your inbox.
No spam. Unsubscribe at any time.