Build a ChatGPT-Powered Python Chatbot: Step-by-Step Guide
This tutorial walks developers through setting up an OpenAI account, obtaining an API key, configuring the Python environment, and writing a complete Python script that uses the ChatGPT API to create an interactive chatbot, complete with code examples and execution tips.
Guide: This article shows developers how to create a Python program for a ChatGPT AI chatbot.
OpenAI has opened ChatGPT capabilities to everyone, allowing seamless integration of its powerful functions into applications at a low cost of $0.002 per 1,000 tokens.
The API currently offers features such as creating custom conversational agents, assisting developers with Python code, drafting emails or documents, integrating natural‑language interfaces into products, providing translation services, acting as a tutor for many subjects, and simulating video‑game characters.
OpenAI ChatGPT API: Getting Started Guide
Prerequisites
Visit https://chat.openai.com/ to create an account (Google or Microsoft login is supported). After creating an account, generate a personal API key at https://platform.openai.com/account/api-keys .
Creating the OpenAI API Key
Record the key and store it securely; it will not be visible again in the OpenAI account dashboard. Do not share the key and treat it as confidential, especially if it is linked to a paid plan.
Setting Up the Development Environment
Install Python and pip on your system. For Debian‑based Linux (e.g., Ubuntu): sudo apt-get install python3-pip For Fedora, RHEL, CentOS: sudo dnf install python3-pip For Arch Linux:
sudo pacman -S python-pipConfiguring the API Key
Best practice is to load the key from an environment variable or a file rather than hard‑coding it.
# Windows example
set API_KEY=your_key_here # Linux example (add to /etc/environment)
API_KEY="your_key_here" # In Python, load from file
openai.api_key_path = "/path/to/key.txt" # Direct assignment (not recommended)
openai.api_key = "your_key_here"Installing the OpenAI Python Library
pip install openaiWriting the Chatbot Program
import openai
# Load API key (choose one of the methods above)
openai.api_key = "your_key_here"
messages = []
system_message = input("What type of chatbot you want me to be?")
messages.append({"role": "system", "content": system_message})
print("Alright! I am ready to be your friendly chatbot
You can now type your messages.")
user_message = input()
messages.append({"role": "user", "content": user_message})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
reply = response["choices"][0]["message"]["content"]
print(reply)Running the Code
Execute the script from a Python IDE or the command line:
python OpenAIDemo2.pySample Unformatted JSON Output
{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "As an AI language model, I don't have personal opinions, but I can tell you that kindness is a very positive and essential trait...",
"role": "assistant"
}
}
],
"created": <removed>,
"id": "chatcmpl-<removed>",
"model": "gpt-3.5-turbo-0301",
"object": "chat.completion",
"usage": {
"completion_tokens": 91,
"prompt_tokens": 22,
"total_tokens": 113
}
}The formatted output presents the same information in a readable structure.
Full Python Code
import openai
openai.api_key = "<your key>"
messages = []
system_message = input("What type of chatbot you want me to be?")
messages.append({"role":"system","content":system_message})
print("Alright! I am ready to be your friendly chatbot
You can now type your messages.")
message = input("")
messages.append({"role":"user","content": message})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
reply = response["choices"][0]["message"]["content"]
print(reply)Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
