In this tutorial, you'll learn about Building a Chatbot with Python and the OpenAI API. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
What You'll Learn
Build a working AI chatbot in Python using the OpenAI API, with conversation memory and a clean CLI interface.
Why It Matters
Chatbots are the most common LLM application. Every developer should know how to integrate LLM APIs into their projects.
Real-World Use
Customer support bots, coding assistants, FAQ bots, and internal Q&A tools.
Prerequisites
pip install openai python-dotenv
Get an API key from platform.openai.com/api-keys.
Step 1: Basic Chat Completion
from openai import OpenAI
client = OpenAI() # Reads OPENAI_API_KEY from env
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "What is machine learning?"}
]
)
print(response.choices[0].message.content)
Expected output:
Machine learning is a branch of artificial intelligence that enables systems
to learn and improve from experience without being explicitly programmed.
Step 2: Chat with History
messages = [
{"role": "system", "content": "You are a helpful coding assistant."},
{"role": "user", "content": "Write a Python function to reverse a string."}
]
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
reply = response.choices[0].message.content
print(reply)
# Add to history for follow-up
messages.append({"role": "assistant", "content": reply})
messages.append({"role": "user", "content": "Now make it handle None inputs"})
Step 3: CLI Chatbot
from OpenAI import OpenAI
client = OpenAI()
messages = [{"role": "system", "content": "You are a helpful assistant."}]
print("Chatbot ready! Type 'quit' to exit.")
while True:
user_input = input("\nYou: ")
if user_input.lower() == "quit":
break
messages.append({"role": "user", "content": user_input})
response = client.chat.completions.create(
model="gpt-4o-mini", messages=messages
)
reply = response.choices[0].message.content
print(f"Bot: {reply}")
messages.append({"role": "assistant", "content": reply})
Managing Token Usage
# Count tokens roughly (4 chars ≈ 1 token)
total_chars = sum(len(m["content"]) for m in messages)
estimated_tokens = total_chars // 4
# Trim history when too long
if len(messages) > 20:
messages = [messages[0]] + messages[-10:]
Practice
Build a chatbot that:
- Remembers user preferences across the conversation
- Can search Wikipedia when asked for facts
- Formats code responses with language labels
← Previous
Prompt Engineering Guide: How to Talk to LLMs
Next →
Introduction to Neural Networks — How AI Learns
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro