Step-by-Step Guide: Integrating a ChatGPT Chatbot in a Django Project

Chatbots have become increasingly popular in various applications, ranging from customer support to virtual assistants. OpenAI’s ChatGPT model provides a powerful framework for building conversational agents. In this tutorial, we will explore how to integrate a basic ChatGPT chatbot into a Django project.

Prerequisites:

Before we begin, make sure you have the following:

  1. Python 3.x installed on your system
  2. Django framework installed
  3. An OpenAI API key. (Get one from the OpenAI website).

Integrating ChatGPT Chatbot: Let’s dive into the details of each step.

Step 1: Set Up the Django Project

First, let’s set up a Django project. Assuming you have Django installed, open a terminal and navigate to the directory where you want to create your project. Run the following command:

$ django-admin startproject chatbot_project

This command will create a new Django project named chatbot_project. Navigate into the project directory:

$ cd chatbot_project

Or, you can obviously use your existing Django project.

Next, create a Django app within the project:

$ python manage.py startapp chatbot

This command will create a new Django app named chatbot. We will use this app to handle the chatbot functionality.

Step 2: Install OpenAI Python library

To use OpenAI’s ChatGPT model in our Django project, we need to install the OpenAI Python library. Open a terminal and run the following command to install:

$ pip install openai

The OpenAI Python library allows us to interact with the ChatGPT API and generate responses from the chatbot model.

Step 3: Create Django Views

In Django, views handle the logic of processing requests and generating responses. Open the chatbot/views.py file and define the following view function:

integrating chatgpt chatbot
from django.shortcuts import render
from openai import ChatCompletion
import openai

def chatbot_view(request):
    conversation = request.session.get('conversation', [])

    if request.method == 'POST':
        user_input = request.POST.get('user_input')

        # Define your chatbot's predefined prompts
        prompts = []

        # Append user input to the conversation
        if user_input:
            conversation.append({"role": "user", "content": user_input})

        # Append conversation messages to prompts
        prompts.extend(conversation)

        # Set up and invoke the ChatGPT model
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=prompts,
            api_key="Your Open AI Key"
        )
        
        # Extract chatbot replies from the response

        chatbot_replies = [message['message']['content'] for message in response['choices'] if message['message']['role'] == 'assistant']

        # Append chatbot replies to the conversation
        for reply in chatbot_replies:
            conversation.append({"role": "assistant", "content": reply})

        # Update the conversation in the session
        request.session['conversation'] = conversation

        return render(request, 'chat.html', {'user_input': user_input, 'chatbot_replies': chatbot_replies, 'conversation': conversation})
    else:
        request.session.clear()
        return render(request, 'chat.html', {'conversation': conversation})

The above code demonstrates a basic implementation of a chatbot using Django web framework and the OpenAI GPT-3.5 Turbo model. Let’s break down the code step by step:

  1. Importing necessary modules
  2. Defining the `chatbot_view` function:
    1. This function serves as the view that handles HTTP requests for the chatbot.
    2. It takes a `request` object as a parameter, which represents the HTTP request received from the client.
  3. Retrieving the conversation history:
    1. The code checks if there is an existing conversation stored in the user’s session (`request.session`) using `request.session.get(‘conversation’, [])`. If there is no conversation stored, it initializes an empty list.
  4. Handling POST requests:
    1.  If the request method is ‘POST’, it means the user has submitted a message.
    2.  The user’s input is extracted from the POST request using `request.POST.get(‘user_input’)`.
  5. Defining chatbot prompts and updating the conversation:
    1. The code initializes an empty list called `prompts` to store the chatbot’s predefined prompts.
    2.  If the user has entered an input, it appends the user’s input to the conversation list.
  6. Setting up and invoking the ChatGPT model:
    1.  The code calls `openai.ChatCompletion.create()` to interact with the ChatGPT model.
    2.  It passes the model name (`gpt-3.5-turbo`), the messages (which include both the user input and previous conversation), and the API key for authentication.
  7. Extracting chatbot replies:
    1.  The code extracts the chatbot’s replies from the API response by iterating over the response’s `choices`.
    2. It checks if the role of the message is ‘assistant’ and retrieves the content of the message.
  8. Appending chatbot replies to the conversation:
    1. The code appends the chatbot’s replies to the conversation list.
  9. Updating the conversation in the session:
    1. The code updates the conversation stored in the user’s session (`request.session[‘conversation’]`) with the latest messages.
  10. Rendering the chat template:
    1. The code renders the ‘chat.html’ template and passes it the user’s input, chatbot replies, and the conversation.
    2. This allows the template to display the chat history and provide an input field for the user.
  11. Handling GET requests:
    1. If the request method is not ‘POST’ (i.e., it’s a GET request), the code clears the conversation stored in the session using `request.session.clear()`.
    2. It then renders the ‘chat.html’ template, passing it the conversation.

Note: Don’t forget to import the chatbot_view function in your project’s urls.py file and define a URL pattern to map it to the desired endpoint.

Step 4: Design the HTML Template

Now, let’s design the HTML template for our chatbot. Create a new directory called templates within the chatbot directory. Inside the templates directory, create a new HTML file named chat.html. Open the file and add the following code:

<h1>Chatbot</h1>
<div id="conversation">
    {% for message in conversation %}
        {% if message.role == 'user' %}
            <div class="user-messages"><p>You: {{ message.content }}</p></div>
        {% elif message.role == 'assistant' %}
            <div class="chatbot-messages"><p>ChatBot: {{ message.content }}</p></div>
        {% endif %}
    {% endfor %}
</div>       
<form id="chat-form" method="POST" action="{% url 'chatbot' %}">
    {% csrf_token %}
    <div class="container">
        <textarea rows="3" class="centered-textarea" id="user-input" type="text" name="user_input" placeholder="Your message"></textarea>
        <input type="submit" value="Send">
    </div>
</form>

This HTML template includes a conversation container (<div id=”conversation”>) where the chatbot conversation will be displayed. The user messages are shown as “You: message” and the chatbot messages are shown as “ChatBot: message”. The chat form allows users to input their messages and submit them to interact with the chatbot.

Step 5: Write the JavaScript Code

In the HTML template, we have included some JavaScript code to handle the form submission and scrolling of the conversation container.

<script>
    document.addEventListener('DOMContentLoaded', () => {
        const chatForm = document.getElementById('chat-form');
        const userInput = document.getElementById('user-input');
        const conversation = document.getElementById('conversation');

        // Scroll conversation to the bottom
        conversation.scrollTop = conversation.scrollHeight;

        // Submit the form when the user presses Enter key
        userInput.addEventListener('keypress', (event) => {
            if (event.key === 'Enter') {
                event.preventDefault();
                chatForm.submit();
            }
        });

        // Focus on the user input field
        userInput.focus();
    });
</script> 

The above javascript code adds functionality to the chatbot interface by handling keypress events, setting the focus on the user input field, etc. These features enhance the user experience and make the chatbot interface more user-friendly.

Note: The code assumes that the relevant HTML elements have specific IDs assigned to them, such as “chat-form,” “user-input,” and “conversation.” Make sure these IDs match the corresponding elements in your HTML template for the code to work correctly.

Step 6: Code for styling

Here is an example of CSS code that can be used for basic styling.

<style>
        #conversation {
            height: 500px;
            border: 1px solid #000;
            margin-bottom: 10px;
            overflow-y: scroll;
            background-color: #424755;
        }
        .container {
            display: flex;
        }

        .container textarea {
            flex: 1;
            margin-right: 10px;
            font-size: 16px;
        }

        .container input[type="submit"] {
            flex-shrink: 0;
            background: #10a37f;
            color: #fff;
            border: 0px;
            padding: 8px 16px;
            font-size: 14px;
            cursor: pointer;
        }
        .user-messages{
            width: 100%;
            padding: 10px;
            background: #343541;
            color: #fff;
        }
        .chatbot-messages{
            width: 100%;
            padding: 10px;
            background: #444655;
            color: #fff;
        }

    </style>

Step 7: Test the Chatbot Integration

With the Django views and HTML template in place, we are ready to test the chatbot integration. Start the Django development server by running the following command in your project directory:

$ python manage.py runserver

Open your web browser and navigate to http://127.0.0.1:8000/chatbot/ to access the chatbot interface. You should see the chatbot conversation container, where you can type messages and interact with the chatbot.

Below is the interface that we have generated.

Test the chatbot by entering various user prompts and observe the chatbot’s responses. The conversation history will be preserved, and the chatbot’s replies will be displayed alongside the user’s messages. 

Conclusion

In this tutorial, we explored how to integrate ChatGPT chatbot into a Django project. We covered the steps of setting up the Django project, installing the OpenAI Python library, creating Django views, designing HTML template, and writing JavaScript code for handling user interactions. By following these steps, you can build a powerful chatbot interface within your Django application.

Remember that this tutorial provides a basic implementation, and you can further customize and enhance the chatbot based on your requirements. Consider adding more prompts, improving the user interface, and implementing additional features such as context handling and error management.

OpenAI’s ChatGPT model offers great potential for building interactive and appealing chatbots. With Django’s web development framework, you can create customized chatbot applications that serve a wide range of purposes. In the upcoming article, we will explore the process of building a chatbot using predefined prompts. The conversation flow will be determined based on the selected prompt. Happy coding!

For more ideas like these, be sure to subscribe divine.ai for further inspiration!

Leave a Reply

Your email address will not be published. Required fields are marked *