Implementing ChatGPT with PubNub Webhooks in Django

pubnubdevrel

PubNub Developer Relations

Posted on March 20, 2024

Implementing ChatGPT with PubNub Webhooks in Django

In today’s ever-expanding digital landscape, we have to constantly chase new updates and micro adjustments in order to strive for digital perfection. With such advancements, one gap that has always needed to be bridged is the need to give users better experiences in their conversations via chatbots. The objective has been to design intelligent interactions between businesses and individuals so that a user feels satisfied and emotionally connected to the product or brand. Chatbots have thus emerged as a versatile means to minimize the gap between the digital and real worlds and transform the way we communicate online with web apps, Android and Apple devices, and web browsers. 

Chatbots are meeting the growing demand for real-time communication and support that any user expects. It’s easy for businesses to lose out on potential clients and leads without a powerful chatbot since there are multiple options out there for them to choose from. The surge in expectations is thus driving the escalating battle of adaptation as chatbots are incorporated within digital products to create convenience for users and make their experience satisfactory.

Imagine: you’ve ordered some urgently needed groceries, but the order is delayed. You open the web app and see no movement in your tracking system. You need to get an update. Now, here are two possible scenarios:

First scenario: You dial the customer support number and are kept waiting since the lines are busy. Your frustration grows.

Second scenario: You have an option to live chat and are assisted almost immediately. You get an update that the delivery driver is on their way and about to reach your place in a few minutes. You are also given the option to connect with a representative online if you want any detailed updates.

Which experience would you prefer?

All users expect a certain level of convenience with their online activities. Whether it's shopping, queries, education, games, etc; instant sharing of information and resolving queries is one of the biggest triggers to generating positive online experience and interaction and therefore, necessary. 

The growing significance of chatbots 

A recent research report by Grand View Research, Inc., suggests that the chatbot market size is going to rise significantly in the coming years and will reach approximately USD 27.3 billion by 2030. This will amount to a CAGR OF 23.3% from the current year to 2030. An astonishing growth rate, to say the least! The projection underscores the critical role chatbots will play in building the future of digital communication as they continue bridging the gap between technology and users. 

Traditional communication methods struggle to provide immediate and responsive support, whereas intelligent chatbots, powered by technology including Django, PubNub webhooks, and the ChatGPT language model, excel at engaging users in meaningful interactions.

Businesses benefit from intelligent chatbots in various ways. They automate response rates, provide prompt customer support to predictable queries, and, when complex issues arise, the chatbot can forward the conversation to a human representative, whilst ensuring user comfort. Apart from rendering support, chatbots also drive sales, generate leads, and maintain the online reputation of brands. The automation chatbots offer also lowers the cost for businesses and streamlines processes. This especially benefits e-commerce by enhancing customer experiences with shopping suggestions, customized recommendations, repeat listings based on history and frequency, and so much more.

Designing intelligent chatbots is a complex task. It requires innovation and an understanding of human behavior online. Powerful frameworks like Django, real-time messaging platforms like PubNub, and sophisticated AI language models like ChatGPT, can work together to design an all-inclusive strategy to generate responsive and dynamic user experiences; complete with context, meaning, and stimulation. 

The Django framework and PubNub webhooks

The Django framework is one of the top Python frameworks, forming a foundation for chatbot software development. It also provides the essential logic in the framework that accommodates continual communication and engagement. Developers have the opportunity to create immersive applications where complex features can also be integrated within the toolkit to provide a rich ecosystem. Django streamlines the development process with an organized and more systematized approach to creating web applications that can be easily maintained. This can mainly be attributed to its powerful features, such as built-in URL routing, robust security mechanisms, and the Model-View-Controller (MVC) architecture.

PubNub webhooks, however, take the level of interaction to the next level by serving as a conduit between your Django backend and PubNub's messaging structure. Pubnub’s webhooks are able to respond to user messages in real time as its functionality gets immediately triggered on receipt of a message. It becomes capable of answering queries, suggesting recommendations, assisting users, and engaging in dialogue without any traceable delay. This prompt delivery of responses leads to a flow of conversation which, even though they are automated at the backend, seem natural to any user. We will be discussing in-depth how building a chatbot with PubNub and ChatGPT / OpenAI gives developers an edge in creating engaging AI-driven chatbots. 

The intelligence of a chatbot is measured in its ability to retrieve history and take references from past interactions, and thereby creating an ecosystem of meaningful and coherent conversations. PubNub's fetch_messages allows chatbots to deduce every interaction’s context by retrieving chat history. This feature enables personalized, coherent conversations that make users feel valued and understood.

PubNub’s ChatGPT integration will further enhance user experience. ChatGPT is an AI-based machine-learning language model that uses a deep learning algorithm to generate responses by understanding the context of queries. ChatGPT’s integration with PubNub's real-time framework ensures prompt responsiveness and maintains a natural flow of conversations.

Both Django and PubNub excel in handling high-traffic loads while accommodating a rising percentage of users.  The collaboration of Django's framework and PubNub's infrastructure enables personalization, domain-specific language understanding, and precise response generation. Regular updates and modifications in ChatGPT’s responses allow chatbots to gain an understanding of domain-specific language and meet user preferences with clear precision.

PubNub webhooks integration in Django tutorial

We’ll now provide a template for you to integrate PubNub webhooks into your Django application.

Setting up the environment

Before diving into the technical execution, let's make sure that the development environment is set up accurately. 

Install required dependencies: The first step is to install the essential software and libraries. Python and Django are mandatory for the backend as well as any additional packages or plugins required for the respective project. Creating a virtual environment helps manage dependencies. PubNub is cross-platform, supporting other SDKs from Java to React, and REST APIs to JavaScript / Node.js, but this tutorial will use Python.

Create a Django project: Once all the required packages are installed, create a new Django project. This will become the core foundation for your chatbot app.

Obtain API keys: API keys will be important to interact with peripheral services like PubNub and ChatGPT. Sign up and create accounts on these platforms to obtain the necessary keys required to authenticate your requests.

Create a Django webhook endpoint

Define a webhook endpoint that will receive PubNub events in your Django project. This endpoint should be configured to handle HTTP POST requests and process the incoming event payload.

Configure PubNub webhooks

In your PubNub account, configure the webhook settings to send relevant events to your Django webhook endpoint's URL. Specify the events you want to capture, such as new messages being published to a channel.

Process incoming events

In your Django webhook endpoint view, extract the necessary information from the received event payload. This includes parsing the message content, any associated metadata, and any additional context required for processing with ChatGPT.

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

      
 class PubNubOpenAIView(APIView):


def post(self, request):
        try:
            payload = request.data
            question = payload["event"]["eventPayload"]["message"]
            sender = payload["event"]["senderId"]
            channel = payload["event"]["channel"]

            pubnub_history = get_pubnub_history(channel)
            history_messages = [message.message for message in history.result.channels[channel]]  
            openai_response = get_openai_response(message, history_messages)
            pubnub_response = publish_message(
                channel, openai_response
            )

            if pubnub_response.status.status_code == status.HTTP_200_OK:
                return Response({"status": "success"}, status=status.HTTP_200_OK)
            else:
                return Response(
                    data={"error": "Error while sending back to pubnub"},
                    status=pubnub_response,
                )

        except Exception as pubnub_open_ai_error:
            return Response(
                {"message": pubnub_open_ai_error.args[0]},
                status=status.HTTP_400_BAD_REQUEST,
            )
Enter fullscreen mode Exit fullscreen mode

Implementing contextual conversations

PubNub provides a powerful feature called fetch_messages that allows you to retrieve chat history for a specific channel. This feature plays a pivotal role in creating more meaningful and engaging interactions, showcasing the chatbot's ability to remember history and personalize conversations by referencing previous communication.

Chat history plays a crucial role in creating a more meaningful and engaging interaction. It showcases the chatbot’s prowess in remembering history, thus solidifying its sense of memory. Additionally, it is able to personalize the conversations by referencing previous communications. This dynamic approach leads to the perception of having a natural conversation at the user’s end.

This step is an important part of the implementation process for maintaining meaningful communication throughout the chatbot environment.

Here's a Python tutorial on how you can implement contextual conversations using fetch_messages.

from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub


pnconfig = PNConfiguration()

pnconfig.subscribe_key = os.environ["PUBNUB_SUBSCRIBE_KEY"]
pnconfig.publish_key = os.environ["PUBNUB_PUBLISH_KEY"]
pubnub = PubNub(pnconfig)
history_count = 5         
    
 def get_pubnub_history(channel):
    envelope = pubnub.fetch_messages() \
        .channels([channel]) \
        .count(int(history_count)) \
        .include_meta(True) \
        .sync()
    return envelope
Enter fullscreen mode Exit fullscreen mode

Utilize ChatGPT for response generation

Pass the extracted message content to the ChatGPT model for response generation. Leverage the power of ChatGPT to generate coherent and contextually appropriate responses based on the input.

         

import openai


def get_openai_response(message: str, history: list):
 """
 This function connects to the OpenAI API and fetches a response for the given user request.
 """
 try:
     messages = []
     messages.extend(history) # adding previous context
     messages.append({"role": "system", "content": message})
     response = openai.ChatCompletion.create(
         model="gpt-3.5-turbo", messages=messages
     )
     return response["choices"][0].message.content

 except Exception as e:
     raise Exception(e)
Enter fullscreen mode Exit fullscreen mode

Send response via PubNub

Once the response is generated, use PubNub to send the response back to the desired channels or recipients, ensuring real-time delivery.

from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub


pnconfig = PNConfiguration()

pnconfig.subscribe_key = os.environ["PUBNUB_SUBSCRIBE_KEY"]
pnconfig.publish_key = os.environ["PUBNUB_PUBLISH_KEY"]
pubnub = PubNub(pnconfig)
         
            
 def publish_message(channel, message):
    """
        This function is used to send a message to PubNub.
        channel: Channel name where the message needs to be sent
        message: message that is to be sent back to user
    """
    response = pubnub.publish().\
        channel(channel).\
        message(message).\
        meta({'from': 'chatbot'}).\
        sync()
    return response
Enter fullscreen mode Exit fullscreen mode

Web development: When received, you will want to create some frontend HTML / CSS to parse the JSON returned by your PubNub subscribe call.

Providing Domain-Specific Prompts

Personalizing conversations with domain-specific prompts enhances the chatbot's capabilities. With the help of ChatGPT, we can strategize the responses with the help of domain-specific prompts. This also decreases the dependency on user-generated messages. The below tutorial can help with your integration process of domain-based prompts and subsequent ChatGPT execution: 

Prepend the Prompt

Instead of sending user messages directly to ChatGPT, establish context by adding domain-specific prompts, leading to responses aligned with desired outcomes. This helps to build a deep understanding of ChatGPT for structuring responses based on domain-specific prompts and delivering targeted responses. Let’s look at a few examples: 

  • For a dinner table reservation chatbot: "Hostess: [User's Message]"

  • In a customer support scenario: "Support Agent: [User's Message]"

  • For a hotel booking assistant: "Hotel Expert: [User's Message]"

Customized Response Generation

By including a domain-based prompt, you will be able to direct ChatGPT to generate responses that are perfectly aligned with your desired outcome. This method creates a coherent ecosystem that enables immersive communication and allows the chatbot to provide customized solutions. 

Here are a few instances:

  • An insurance advisory chatbot might prepend messages with "Insurance Advisor: [User's Message]" to keep responses relevant to messages to insurance-related inquiries.

  • A nutrition coach chatbot can use "Coach: [User's Message]" to offer personalized dietary advice and plans.

Prompt Variation and Experimentation

Making use of domain-specific prompts not only establishes context, but also enables learning and experimenting. You can reiterate the queries with varied prompts so as to optimize the ChatGPT responses. Here’s a way to experiment: 

  • Adjust the tone: For a formal setting, use "Greetings, I'm here to help you: [User's Message]", while for an informal tone, you can use "Hey there! Let's talk: [User's Message]".

  • Highlight expertise: For a medical consultation chatbot, in accordance with the emergency the industry caters to, you can initiate prompts with "Doctor: [User's Message]" to underline the authority of responses.

Integrating domain-based prompts allows your chatbot to interact with users efficiently and render focused support that is natural as an experience.  

Conclusion

The combination of Django, PubNub webhooks, and OpenAI’s ChatGPT offers an unmatched toolkit for creating intelligent, fully interactive chatbot apps. Developers can bridge the gap between the digital and real world, solidifying the dependency on the automation of communication.  

Django brings with it a robust web application framework that can lay a strong foundation for multi-featured scalable chatbot experiences that are meaningful. Meanwhile, PubNub’s real-time responding capacity ensures that the conversations stay flowy and leads to continuity that provides a natural and genuine experience to the users. Additionally, ChatGPT enables context-driven responses that make the users feel deeply understood.  

With the full implementation of Django’s potential, the real-time responsiveness of PubNub, and the utilization of ChatGPT's language expertise, the developers can deliver amazing results in the form of unique and innovative chatbot applications. These digital interfaces will streamline interactions whether it be assistance, rendering support, or suggesting prompts. All three together reshape the way any user interacts with AI-driven conversational chatbots.

You can discover more about the diverse ways PubNub's real-time capabilities are connected and its importance in empowering the scalability of apps. 

Contents

The growing significance of chatbotsThe Django framework and PubNub webhooksPubNub webhooks integration in Django tutorialSetting up the environmentCreate a Django webhook endpointConfigure PubNub webhooksProcess incoming eventsImplementing contextual conversationsUtilize ChatGPT for response generationSend response via PubNubProviding Domain-Specific PromptsPrepend the PromptCustomized Response GenerationPrompt Variation and ExperimentationConclusion

How can PubNub help you?

This article was originally published on PubNub.com

Our platform helps developers build, deliver, and manage real-time interactivity for web apps, mobile apps, and IoT devices.

The foundation of our platform is the industry's largest and most scalable real-time edge messaging network. With over 15 points-of-presence worldwide supporting 800 million monthly active users, and 99.999% reliability, you'll never have to worry about outages, concurrency limits, or any latency issues caused by traffic spikes.

Experience PubNub

Check out Live Tour to understand the essential concepts behind every PubNub-powered app in less than 5 minutes

Get Setup

Sign up for a PubNub account for immediate access to PubNub keys for free

Get Started

The PubNub docs will get you up and running, regardless of your use case or SDK

💖 💪 🙅 🚩
pubnubdevrel
PubNub Developer Relations

Posted on March 20, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related