Write a Python program to build a chatbot using GPT-based APIs.
- User
Write a Python program to build a chatbot using GPT-based APIs.
- Assistant
Write a Python program to build a chatbot using GPT-based APIs.
Clarifying API integration
I need to address how the model generically uses "gpt-based APIs" and clarify that this pattern can apply to Azure OpenAI with some modifications. It’s essential to focus on one clear example. I want to ensure my response includes a complete program, complete with a docstring header and comments for clarity. Also, I'll incorporate reading environment variables through os.getenv. Let’s get started on crafting that final answer! Below is a minimal but complete Python console chatbot using GPT-based APIs via the OpenAI Python client.
pip install openai
Set your API key as an environment variable:
Linux / macOS:
export OPENAI_API_KEY="your_api_key_here"
Windows (PowerShell):
$env:OPENAI_API_KEY = "your_api_key_here"
chatbot.py#!/usr/bin/env python3
"""
Simple GPT-based chatbot using the OpenAI API.
Usage:
python chatbot.py
"""
import os
import sys
from openai import OpenAI, OpenAIError
# Make sure the API key is set
if not os.getenv("OPENAI_API_KEY"):
sys.stderr.write("ERROR: Please set the OPENAI_API_KEY environment variable.\n")
sys.exit(1)
# Initialize client (uses OPENAI_API_KEY env var)
client = OpenAI()
# Choose a model (adjust as needed, e.g., "gpt-4.1", "gpt-4o-mini", etc.)
MODEL_NAME = "gpt-4.1-mini"
SYSTEM_PROMPT = (
"You are a helpful, concise chatbot. "
"Answer clearly and avoid unnecessary verbosity."
)
def get_chat_completion(messages):
"""
Call the GPT-based API with the full conversation history.
`messages` should be a list of dicts with role: user/assistant/system.
"""
try:
response = client.chat.completions.create(
model=MODEL_NAME,
messages=messages,
temperature=0.7,
)
return response.choices[0].message.content.strip()
except OpenAIError as e:
# Basic error handling
return f"[Error from model: {e}]"
def main():
print("GPT Chatbot")
print("Type 'exit', 'quit', or Ctrl+C to stop.\n")
# Conversation history (sent every time so the model has context)
messages = [
{"role": "system", "content": SYSTEM_PROMPT}
]
while True:
try:
user_input = input("You: ").strip()
except (KeyboardInterrupt, EOFError):
print("\nExiting.")
break
if not user_input:
continue
if user_input.lower() in {"exit", "quit"}:
print("Goodbye!")
break
# Add user message to history
messages.append({"role": "user", "content": user_input})
# Get model response
assistant_reply = get_chat_completion(messages)
# Show and store assistant reply
print(f"Bot: {assistant_reply}\n")
messages.append({"role": "assistant", "content": assistant_reply})
if __name__ == "__main__":
main()
python chatbot.py
You now have a simple stateful chatbot in the terminal.
If you’d like, I can also show a streaming version (token-by-token output) or a web (Flask/FastAPI) version.