Chatbot Project Guide
Chatbot Project Guide
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
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)
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
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)
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
The Procfile tells Heroku which command to run to start the application.
After creating these files, start your virtual environment and run the application with:
python chatbot.py
1. **Initialize Git**:
git init
git add .
git commit -m "Initial commit for chatbot project"
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!