Build a Simple ChatGPT Bot with Python and OpenAI API in Minutes

This tutorial walks you through registering on OpenAI, installing required Python packages, setting up API keys, and writing a Jupyter Notebook that defines a chat function and an interactive loop to create a functional GPT‑3.5 chatbot.

21CTO
21CTO
21CTO
Build a Simple ChatGPT Bot with Python and OpenAI API in Minutes

The article introduces a beginner-friendly tutorial for building a simple chatbot using Python and the OpenAI API, emphasizing the importance of learning to collaborate with large language models.

First, register at platform.openai.com , create an API key, and add billing information (a $10 credit is usually enough for GPT‑3.5 trial). Save the key securely.

Install the required libraries in a Jupyter Notebook cell: !pip install openai python-dotenv --quiet Import the modules and load environment variables:

import openai
import os
from dotenv import load_dotenv

Create a .env file to store the API key safely:

api_key = "sk-proj-api-key-here"
# Save the key to a .env file
with open(".env", "w") as f:
    f.write(f"OPENAI_API_KEY={api_key}")
print(".env file created.")

Load the key and configure the OpenAI client:

load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")

Define a function that sends a list of messages to the GPT‑3.5‑turbo model and returns the assistant’s reply:

def chat_with_gpt(messages):
    response = openai.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=messages,
        temperature=0.7,
    )
    return response.choices[0].message.content

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello, who are you?"}
]

The temperature parameter (0‑1) controls response randomness; 0.7 offers a good balance.

Run an interactive chat loop that continuously prompts the user, sends input to the model, and prints the assistant’s response until the user types "exit" or "quit":

while True:
    user_input = input("You: ")
    if user_input.lower() in ["exit", "quit"]:
        print("Goodbye!")
        break
    messages.append({"role": "user", "content": user_input})
    reply = chat_with_gpt(messages)
    messages.append({"role": "assistant", "content": reply})
    print(f"Assistant: {reply}")

This loop maintains conversation history, allowing GPT‑3.5 to reference earlier messages for more coherent replies.

By following these steps, you now have a working chatbot and a foundation for more advanced AI development.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonChatGPTTutorialChatbotGPT-3.5OpenAI API
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.