Step-by-Step Guide: Chatbot Integrated with OpenAI’s ChatGPT API
This guide provides a comprehensive walkthrough for building a chatbot using OpenAI's
ChatGPT API. It includes setting up the environment, writing the code, and deploying the
project on a cloud platform such as Heroku. The steps include code examples, configuration
files, and optional HTML for a frontend interface.
Project Structure
Let’s create a well-organized file structure for the chatbot project:
chatbot_project/
├── chatbot.py # Main Flask application
├── config.py # Configuration file for storing API keys and settings
├── requirements.txt # File for dependencies
├── Procfile # For deployment on Heroku
└── templates/
└── index.html # Simple HTML file to interact with the chatbot (optional)
1. config.py: Configuration File
This file will store sensitive information like API keys. Never commit this file to public
repositories. It’s good to load it from environment variables for security in production.
# config.py
import os
# Load the OpenAI API key from an environment variable
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# Set default response parameters
MODEL = "text-davinci-003"
MAX_TOKENS = 150
TEMPERATURE = 0.7
2. chatbot.py: Main Application Code
This is the main application code for the chatbot server. It uses Flask to handle HTTP
requests and interact with OpenAI’s API.
# chatbot.py
import openai
from flask import Flask, request, jsonify, render_template
from config import OPENAI_API_KEY, MODEL, MAX_TOKENS, TEMPERATURE
app = Flask(__name__)
openai.api_key = OPENAI_API_KEY
@app.route('/')
def index():
return render_template("index.html")
@app.route('/chat', methods=['POST'])
def chat():
try:
user_input = request.json.get("message")
if not user_input:
return jsonify({"error": "No message provided"}), 400
response = openai.Completion.create(
model=MODEL,
prompt=user_input,
max_tokens=MAX_TOKENS,
temperature=TEMPERATURE
)
chatbot_response = response.choices[0].text.strip()
return jsonify({"response": chatbot_response})
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == "__main__":
app.run(debug=True)
3. templates/index.html: Optional HTML Interface
This HTML file provides a simple frontend to interact with the chatbot. You can access it by
opening the root URL after running the Flask app.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chatbot</title>
<style>
body { font-family: Arial, sans-serif; margin: 50px; }
#chatbox { width: 300px; border: 1px solid #ccc; padding: 10px; }
#messages { list-style-type: none; padding: 0; }
#messages li { padding: 8px; margin: 4px 0; }
#input { width: calc(100% - 22px); }
</style>
</head>
<body>
<h1>Chatbot Interface</h1>
<div id="chatbox">
<ul id="messages"></ul>
<input id="input" type="text" placeholder="Type a message..." autofocus>
<button onclick="sendMessage()">Send</button>
</div>
<script>
async function sendMessage() {
const input = document.getElementById("input");
const message = input.value;
if (message.trim() === "") return;
addMessage("User: " + message);
input.value = "";
const response = await fetch("/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message })
});
const data = await response.json();
addMessage("Chatbot: " + (data.response || data.error));
}
function addMessage(text) {
const messages = document.getElementById("messages");
const li = document.createElement("li");
li.textContent = text;
messages.appendChild(li);
}
</script>
</body>
</html>
4. requirements.txt: Dependencies
This file lists the packages required for this project. You can create it by running pip freeze >
requirements.txt in your virtual environment after installing the libraries.
flask
openai
5. Procfile: Deployment Configuration for Heroku
The Procfile tells Heroku which command to run to start the application.
web: python chatbot.py
Step 6: Run the Application Locally
After creating these files, start your virtual environment and run the application with:
python chatbot.py
Open http://127.0.0.1:5000 to access the HTML interface.
Step 7: Deployment on Heroku
1. **Initialize Git**:
git init
git add .
git commit -m "Initial commit for chatbot project"
2. **Create a Heroku App**:
heroku create
3. **Set OpenAI API Key as Config Var**:
heroku config:set OPENAI_API_KEY=your_openai_api_key_here
4. **Push to Heroku**:
git push heroku master
Your chatbot is now live on Heroku and should be accessible at the URL provided by
Heroku!