Skip to content

ChatGPT - Build a Chatbot

Building an Interactive Chatbot with ChatGPT and Python

Section titled “Building an Interactive Chatbot with ChatGPT and Python”

Chatbots have become ubiquitous, enhancing user engagement across various applications. OpenAI’s powerful language models, like GPT-3.5-turbo and GPT-4o, enable developers to create sophisticated chatbots capable of understanding context and generating human-like text responses.

In this chapter, we’ll guide you through building a basic conversational chatbot using the OpenAI API with Python. We’ll focus on modern best practices and the latest API versions.

Step 1: Set Up Your OpenAI Account and API Key

Section titled “Step 1: Set Up Your OpenAI Account and API Key”

Before you start, you need an OpenAI account and an API key. Visit the OpenAI website (https://platform.openai.com), sign up or log in, and navigate to the API key section in your account settings to generate a new secret key.

Important: Treat your API key like a password. Do not share it publicly or embed it directly in client-side code. It’s best practice to use environment variables to store your API key.

To interact with the OpenAI API from Python, install the official library. Ensure you have Python 3.7.1 or newer. Open your terminal or command prompt and run:

pip install --upgrade openai

This command installs the latest version of the openai library.

In your Python script, you’ll primarily need the openai library. You might also want os if you’re using environment variables for your API key.

from openai import OpenAI
import os

Configure the OpenAI client with your API key. It’s highly recommended to store your API key in an environment variable (e.g., OPENAI_API_KEY).

# Load the API key from an environment variable (recommended)
# api_key = os.getenv("OPENAI_API_KEY")
# if not api_key:
# raise ValueError("OPENAI_API_KEY environment variable not set.")
# For this example, we'll assign it directly.
# In a real application, use environment variables or a secure vault.
api_key = 'YOUR_OPENAI_API_KEY' # Replace with your actual API key
client = OpenAI(api_key=api_key)

Step 5: Define the Conversation History and System Message

Section titled “Step 5: Define the Conversation History and System Message”

The Chat Completions API works with a list of messages representing the conversation history. It’s good practice to start with a ‘system’ message to set the behavior of the assistant.

conversation_history = [
{"role": "system", "content": "You are a helpful and knowledgeable assistant."}
]

You can customize the system message to define your chatbot’s persona, e.g., “You are a witty pirate chatbot who loves to talk about treasure.”

Create a loop that takes user input, appends it to the conversation history, sends it to the API, gets the response, and then appends the assistant’s response to the history.

def get_chatbot_response(current_conversation):
try:
response = client.chat.completions.create(
model="gpt-3.5-turbo", # Or use "gpt-4o" for more advanced capabilities
messages=current_conversation,
max_tokens=150, # Adjust as needed
temperature=0.7, # Adjust for creativity vs. determinism
n=1 # Number of choices to generate
)
assistant_message = response.choices[0].message.content.strip()
return assistant_message
except Exception as e:
print(f"Error communicating with OpenAI API: {e}")
return "Sorry, I'm having trouble connecting right now."
print("Chatbot: Hello! How can I help you today? (Type 'exit' to end the chat)")
while True:
user_input = input("You: ")
if user_input.lower() == 'exit':
print("Chatbot: Goodbye!")
break
# Add user's message to conversation history
conversation_history.append({"role": "user", "content": user_input})
# Get chatbot's response
chatbot_reply = get_chatbot_response(conversation_history)
print(f"Chatbot: {chatbot_reply}")
# Add chatbot's response to conversation history
conversation_history.append({"role": "assistant", "content": chatbot_reply})
# Optional: Trim conversation history to manage token limits for very long conversations
# For example, keep only the last N messages plus the system message.

Let’s combine all the steps into a single runnable script:

from openai import OpenAI
import os
# --- Configuration ---
# It's highly recommended to use environment variables for your API key.
# api_key = os.getenv("OPENAI_API_KEY")
# if not api_key:
# raise ValueError("Error: OPENAI_API_KEY environment variable not set.")
# For demonstration, replace 'YOUR_OPENAI_API_KEY' with your actual key.
# In production, use environment variables or a secure key management system.
API_KEY = 'YOUR_OPENAI_API_KEY'
MODEL_NAME = "gpt-3.5-turbo" # Consider "gpt-4o" for more advanced features
client = OpenAI(api_key=API_KEY)
conversation_history = [
{"role": "system", "content": "You are a friendly and helpful AI assistant. Provide concise and accurate information."}
]
# --- Helper Function to Get Chatbot Response ---
def get_chatbot_response(current_conversation):
try:
response = client.chat.completions.create(
model=MODEL_NAME,
messages=current_conversation,
max_tokens=200, # Adjust based on expected response length
temperature=0.7, # 0.0 (deterministic) to 2.0 (very creative)
n=1
)
assistant_message = response.choices[0].message.content.strip()
return assistant_message
except Exception as e:
print(f"API Error: {e}")
return "I'm currently unable to respond. Please try again later."
# --- Main Chat Loop ---
if __name__ == "__main__":
print(f"Chatbot ({MODEL_NAME}): Hello! Ask me anything. (Type 'exit' to quit)")
while True:
user_input = input("You: ")
if user_input.lower() == 'exit':
print(f"Chatbot ({MODEL_NAME}): Goodbye! Have a great day!")
break
conversation_history.append({"role": "user", "content": user_input})
# To prevent exceeding token limits in very long conversations,
# you might implement a strategy to truncate older messages.
# For this basic example, we'll send the full history.
chatbot_reply = get_chatbot_response(conversation_history)
print(f"Chatbot ({MODEL_NAME}): {chatbot_reply}")
conversation_history.append({"role": "assistant", "content": chatbot_reply})

Note: Replace 'YOUR_OPENAI_API_KEY' with your actual OpenAI API key. For production applications, always use secure methods like environment variables to manage your API key.

Here’s how a conversation with your new chatbot might look in the terminal:

Chatbot (gpt-3.5-turbo): Hello! Ask me anything. (Type 'exit' to quit)
You: Hi there! What is Artificial Intelligence?
Chatbot (gpt-3.5-turbo): Hello! Artificial Intelligence (AI) refers to the simulation of human intelligence in machines that are programmed to think like humans and mimic their actions. This can include learning, problem-solving, decision-making, and understanding natural language.
You: Can you suggest some good resources to learn Python for AI?
Chatbot (gpt-3.5-turbo): Certainly! For learning Python for AI, I'd recommend:
1. **Official Python Documentation:** Always a great starting point.
2. **Coursera:** Courses like "Python for Everybody" by University of Michigan or "AI For Everyone" by Andrew Ng.
3. **edX:** MIT's "Introduction to Computer Science and Programming Using Python."
4. **Kaggle Learn:** Offers hands-on courses for Data Science and Machine Learning with Python.
5. **Books:** "Python Crash Course" by Eric Matthes or "Automate the Boring Stuff with Python" by Al Sweigart for fundamentals.
Is there a specific area of AI you're interested in (e.g., machine learning, deep learning, NLP)? That might help narrow down more specific resources.
You: Thanks, that's helpful!
Chatbot (gpt-3.5-turbo): You're welcome! Let me know if you have any more questions.
You: exit
Chatbot (gpt-3.5-turbo): Goodbye! Have a great day!

You’ve now built a functional command-line chatbot using the OpenAI API and Python! This is a foundational example. You can enhance it further by:

  • Implementing more sophisticated conversation history management (e.g., summarization or fixed window size to manage token limits).
  • Adding error handling and input validation.
  • Integrating it into a web application (e.g., using Flask or Django) or a messaging platform.
  • Experimenting with different system messages to create specialized chatbots.
  • Exploring advanced API features like function calling to connect your chatbot to external tools or APIs.

Continue experimenting with prompts, model parameters, and different conversation flows to tailor the chatbot to your specific needs. The OpenAI documentation is an excellent resource for exploring more advanced capabilities.