Create a Chatbot with ChatGPT: A Beginner’s Guide to Building Your Own AI-Powered Chatbot

Mohammed Saad
4 min readFeb 25, 2023

Chatbots have become increasingly popular in recent years. They can be used for a wide range of applications, from customer support to language learning. In this tutorial, we’ll be creating a simple chatbot using ChatGPT, an AI-powered language model developed by OpenAI.

Prerequisites

Before we begin, you’ll need to have the following:

Step 1: Set up a Django project

First, we’ll create a new Django project and app: In Git Bash , move to the directory were you want to save all the files and run the following commands.

django-admin startproject chatbot_project
cd chatbot_project
python manage.py startapp chatbot_app

Step 2: Create a view

Next, Open sublime text and then open your project folder, here we’ll create a view that will handle the chatbot conversation. In chatbot_app/views.py, add the following code: change ‘YOUR_API_KEY’ with your chatgpt api key. You can create a new file to hide this key.

import openai
from django.shortcuts import render
from django.http import JsonResponse

openai.api_key = 'YOUR_API_KEY'

def chatbot(request):
if request.method == 'POST':
# Get user input
user_input = request.POST['user_input']

# Call the ChatGPT API to get a response
response = openai.Completion.create(
engine='davinci',
prompt=f"Conversation with a user:\nUser: {user_input}\nAI:",
max_tokens=60,
n=1,
stop=None,
temperature=0.7,
)

# Extract the response text from the API result
bot_response = response.choices[0].text.strip()

# Return the response as JSON
return JsonResponse({'bot_response': bot_response})

# If the request is not a POST, render the chatbot template
return render(request, 'chatbot.html')

This function uses the openai package to call the ChatGPT API and generate a response to the user input. It then returns the response as JSON.

Step 3: Create a template

In chatbot_app/templates/chatbot.html, create a form that will allow the user to input their message and see the chatbot's response. Here's an example:

<!DOCTYPE html>
<html>
<head>
<title>Chatbot</title>
<link rel="stylesheet" type="text/css" href="{% static 'chatbot.css' %}">
</head>
<body>
<h1>Chatbot</h1>
<div id="chatbot-container">
<div id="chatlog"></div>
<form id="chat-form">
<input type="text" id="user-input" placeholder="Say something...">
<button type="submit">Send</button>
</form>
</div>
<script src="{% static 'chatbot.js' %}"></script>
</body>
</html>

This template includes a form with an input field for the user to enter their message, and a div to display the chatbot’s responses. We’ll be using JavaScript to handle the form submission and display the chatbot’s responses.

Step 4: Create static files

In chatbot_app/static, create two files: chatbot.css and chatbot.js. example:

chatbot.css

#chatbot-container {
max-width: 500px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 10px;
}

#chatlog {
height: 300px;
overflow-y: scroll;
margin-bottom: 10px;
}

#chatlog p {
margin: 0;
}

#chat-form {
display: flex;
margin-top: 10px;
}

#user-input {
flex-grow: 1;
margin-right: 10px;
padding: 5px;
border-radius: 5px;
border: 1px solid #ddd;
}

#chatbot-container button {
padding: 5px 10px;
border-radius: 5px;
border: none;
background-color: #007bff;
color: white;
cursor: pointer;
}

#chatbot-container button:hover {
background-color: #0062cc;
}

chatbot.js:

document.addEventListener('DOMContentLoaded', function() {
const chatlog = document.getElementById('chatlog');
const chatForm = document.getElementById('chat-form');
const userInput = document.getElementById('user-input');

chatForm.addEventListener('submit', function(event) {
event.preventDefault();

// Get user input
const userMessage = userInput.value;

// Clear the input field
userInput.value = '';

// Add the user message to the chat log
chatlog.innerHTML += '<p class="user-message">' + userMessage + '</p>';

// Send the user message to the server and get the response
fetch('/chatbot', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: 'user_input=' + encodeURIComponent(userMessage)
})
.then(response => response.json())
.then(data => {
// Add the bot response to the chat log
chatlog.innerHTML += '<p class="bot-message">' + data.bot_response + '</p>';
// Scroll to the bottom of the chat log
chatlog.scrollTop = chatlog.scrollHeight;
});
});
});

This JavaScript code listens for the form submission event, sends the user input to the server using the fetch function, and displays the bot response in the chat log.

Step 5: Add URLs to chatbot_app/urls.py

In chatbot_app/urls.py, add a URL pattern for the chatbot view:

from django.urls import path
from . import views

urlpatterns = [
path('chatbot', views.chatbot, name='chatbot'),
]

Use following commands to start virtual environment in Git Bash and use localhost:8000 to check all changes to app before migrating to heroku.

python -m virtualenv venv
source venv/Scripts/activate
python manage.py migrate
python manage.py runserver

Step 6: Deploy the app

To deploy the app, you can use a hosting service like Heroku. Here’s how to deploy the app to Heroku:

  1. Create a new Heroku app with heroku create.
  2. Add the Heroku git remote with heroku git:remote -a YOUR_APP_NAME.
  3. Commit your code and push it to the Heroku remote with git push heroku main.
  4. Run the database migrations with heroku run python manage.py migrate.
  5. Open the app in your browser with heroku open.

That’s it! You should now have a simple chatbot integrated into your Django app, powered by ChatGPT. With a bit of customization, you can adapt this chatbot to suit your specific needs.

--

--

Mohammed Saad

I am open-minded, gritty, and a curious individual with significant practical and educational experience in data engineering and Cloud Computing.