Build a CLI AI Chatbot with Python & OpenAI
Learn how to connect to the OpenAI API and build a conversational chatbot that runs entirely in your terminal. You will manage chat history to keep context.
The Problem
Learn how to connect to the OpenAI API and build a conversational chatbot that runs entirely in your terminal. You will manage chat history to keep context.
Real-World Use Case
Learn how to connect to the OpenAI API and build a conversational chatbot that runs entirely in your terminal. You will manage chat history to keep context.
Technology Stack
Python 3.8+
Prerequisite
Basic API knowledge
Prerequisite
OpenAI API Key
Prerequisite
Architecture & Design
Folder Structure
chatbot/
├── main.py
├── .env
└── requirements.txtStep-by-Step Implementation
Load API key from .env
Create a virtual environment and install the `openai` and `python-dotenv` packages. `pip install openai python-dotenv`
import os
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
while True:
user_input = input('You: ')
if user_input.lower() in ['quit', 'exit']:
break
messages.append({'role': 'user', 'content': user_input})
response = client.chat.completions.create(model='gpt-3.5-turbo', messages=messages)
reply = response.choices[0].message.content
print('AI:', reply)
messages.append({'role': 'assistant', 'content': reply})Code Explanation
Implementation step
Initialize a message history array
Load the environment variables so you don't hardcode your API key. ```python import os from dotenv import load_dotenv load_dotenv() client = OpenAI(api_key=os.getenv('OPENAI_API_KEY')) ```
import os
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
while True:
user_input = input('You: ')
if user_input.lower() in ['quit', 'exit']:
break
messages.append({'role': 'user', 'content': user_input})
response = client.chat.completions.create(model='gpt-3.5-turbo', messages=messages)
reply = response.choices[0].message.content
print('AI:', reply)
messages.append({'role': 'assistant', 'content': reply})Code Explanation
Implementation step
Start a while loop for user input
Use a simple `while True` loop to accept `input()` from the user and format it as a user message dictionary.
import os
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
while True:
user_input = input('You: ')
if user_input.lower() in ['quit', 'exit']:
break
messages.append({'role': 'user', 'content': user_input})
response = client.chat.completions.create(model='gpt-3.5-turbo', messages=messages)
reply = response.choices[0].message.content
print('AI:', reply)
messages.append({'role': 'assistant', 'content': reply})Code Explanation
Implementation step
Send history to OpenAI API
Wrap the API call in a try/except block to catch network errors or quota limits gracefully.
import os
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
while True:
user_input = input('You: ')
if user_input.lower() in ['quit', 'exit']:
break
messages.append({'role': 'user', 'content': user_input})
response = client.chat.completions.create(model='gpt-3.5-turbo', messages=messages)
reply = response.choices[0].message.content
print('AI:', reply)
messages.append({'role': 'assistant', 'content': reply})Code Explanation
Implementation step
Print response and append to history
Wrap the API call in a try/except block to catch network errors or quota limits gracefully.
import os
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
while True:
user_input = input('You: ')
if user_input.lower() in ['quit', 'exit']:
break
messages.append({'role': 'user', 'content': user_input})
response = client.chat.completions.create(model='gpt-3.5-turbo', messages=messages)
reply = response.choices[0].message.content
print('AI:', reply)
messages.append({'role': 'assistant', 'content': reply})Code Explanation
Implementation step
Common Errors
Make sure your .env file is in the same directory and contains OPENAI_API_KEY=your_key
Security & Performance
Ask a question
Ask a follow up question to test context memory
Type 'exit' to quit
Add streaming responses
Save chat history to a JSON file
Interview Questions
Q: Does this cost money?
A: Yes, you need a funded OpenAI API account, though simple chats cost fractions of a cent.