What You'll Build
In this tutorial, you'll build a simple but fully functional AI chatbot using Python and the OpenAI API. By the end, you'll have a command-line chatbot that maintains conversation history — the foundation for any more complex AI application.
Prerequisites
- Basic Python knowledge (variables, functions, loops)
- Python 3.8 or higher installed
- An OpenAI account (free tier is sufficient to start)
Step 1: Set Up Your Environment
First, install the OpenAI Python library using pip:
pip install openai
Next, get your API key from the OpenAI platform. Store it as an environment variable — never hardcode API keys in your scripts.
export OPENAI_API_KEY="your-api-key-here"
Step 2: Write the Core Chatbot Script
Create a new file called chatbot.py and add the following code:
from openai import OpenAI
import os
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
conversation_history = [
{"role": "system", "content": "You are a helpful assistant."}
]
def chat(user_message):
conversation_history.append({"role": "user", "content": user_message})
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=conversation_history
)
assistant_message = response.choices[0].message.content
conversation_history.append({"role": "assistant", "content": assistant_message})
return assistant_message
# Main loop
print("AI Chatbot ready. Type 'quit' to exit.")
while True:
user_input = input("You: ")
if user_input.lower() == "quit":
break
response = chat(user_input)
print(f"Bot: {response}\n")
Step 3: Understanding What's Happening
Let's break down the key parts of this code:
- conversation_history: A list that stores the full conversation. This is what gives the chatbot memory — each API call includes the entire history so the model has context.
- system message: The first entry with
role: "system"sets the chatbot's persona and behavior. You can customize this to create specialized bots. - gpt-4o-mini: A cost-effective model ideal for experimentation. Swap to
gpt-4ofor higher quality responses.
Step 4: Run and Test Your Chatbot
python chatbot.py
You should see a prompt asking for your input. Try asking follow-up questions to confirm the chatbot remembers earlier parts of the conversation.
Step 5: Customize Your Bot
Once the basic chatbot works, here are easy ways to extend it:
- Change the persona: Modify the system message to create a specialized assistant (e.g., "You are a Python coding tutor who explains things simply.")
- Add streaming: Use
stream=Truein the API call to display responses word by word for a more natural feel - Save conversations: Write the conversation history to a JSON file so sessions persist
- Build a web UI: Wrap the logic with a Flask or FastAPI server and connect a simple HTML front-end
Cost Considerations
The OpenAI API is priced per token (roughly 750 words = 1,000 tokens). The gpt-4o-mini model is extremely affordable for experimentation. Monitor your usage in the OpenAI dashboard and set spending limits to avoid surprises.
You now have the building blocks of a functional AI chatbot. From here, the possibilities are endless — customer support bots, tutoring assistants, writing helpers, and more.