Building a WhatsApp Chatbot that Understands: Integrating ChatGPT and Twilio

Prakhar Prakash Bhardwaj
GoGroup Tech Blog
Published in
7 min readFeb 7, 2023

--

Integrating a natural language processing (NLP) model like ChatGPT with a messaging platform like WhatsApp can help users to open up new possibilities more conveniently. In this article, we’ll learn to create a WhatsApp chatbot using OpenAI API and Twilio Programmable Messaging with Node.js.

To use this tutorial, you will need the following:

Before we begin the tutorial, it’s important to have a clear understanding of the tools and technologies we will be using:

  1. GPT-3
  2. Twilio

GPT-3

GPT-3 (short for “Generative Pre-trained Transformer 3”) is a state-of-the-art language model developed by OpenAI. It is based on the transformer architecture, which uses an attention mechanism to weigh the importance of different parts of the input while generating text.

GPT-3 has 175 billion parameters, which makes it one of the largest language models to date and able to perform a wide range of natural language processing tasks with high accuracy.

The model is exposed via the OpenAI API, which makes it easy to use with different programming languages including Node.js. It is also possible to use other libraries like Tensorflow.js to interact directly with the model if it is running on your server.

Twilio

Twilio is a cloud communication platform that enables developers to build, scale, and operate communications within their applications. It provides a set of APIs for sending and receiving messages, voice and video calls, and authentication.

Twilio Messaging is a feature of the Twilio platform that enables developers to send and receive messages (SMS, MMS, WhatsApp, and chat) via various messaging protocols and it allows them to interact with it via various languages such as Node.js, Python, Ruby, and C#.

Let’s get started

Obtain The OpenAI API Key

To access the OpenAI API, you will first need to create an account. Once you have done so, navigate to the API keys section and generate a new key by clicking on Create new secret key.

Copy and Save the API key, as it will be required in our Node.js project later.

Twilio Project Setup and Sandbox Activation

After creating your Twilio account, navigate to the Twilio console. Make a note of the Account SID and Auth Token that appears in the dashboard, as we will need them later in our code.

Next, navigate to the Messaging section on the left menu, click on the Try it out option, and then select Send a WhatsApp message to activate the WhatsApp sandbox.

On your WhatsApp-enabled device, send a text message with the unique join code to the provided WhatsApp number. Soon, you will receive a reply from Twilio confirming that your mobile number is now connected to the sandbox and you can start sending and receiving messages.

Code Time: Setting up the Node.js Server

Now that we’ve established a working connection between our setup and the Twilio Sandbox, it’s time to dive into writing code. You can find all the code required for this tutorial in this GitHub repository, so grab your keyboard and get ready to build!

Create a new folder to contain our project:

mkdir chatgpt-whatsapp

Open this folder in a terminal and run below the scripts:

cd chatgpt-whatsapp
npm init --yes

Next, we install the required packages:

npm install --save dotenv express opneai twilio

Here’s a brief explanation of each:

  • dotenv: Loads environment variables from the .env file
  • express: Setting up the minimalist web framework
  • openai: Accessing ChatGPT API for answering queries
  • twilio: Facilitates messaging through WhatsApp

Next, we are going to create the following files:

touch .env index.js
mkdir src && touch src/app.js src/chatgpt.js

The application structure should look similar to this:

.
|-- .env
|-- index.js
|-- package-lock.json
|-- package.json
`-- src
|-- app.js
`-- chatgpt.js

In the .env file, add the following variables:

TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXX
TWILIO_AUTH_TOKEN=XXXXXXXXXXXXXXXXXXXX
OPENAI_API_KEY=XXXXXXXXXXXXXXXXXXXXX

In the same .env file:

  1. Replace the values of TWILIO_ACCOUNT_SID & TWILIO_AUTH_TOKEN with Account SID and Auth Token, you copied earlier,
  2. Similarly, replace the value of OPEN_API_KEY with OpenAI API Key.

In the file ./index.js file, insert the below code:

const app = require("./src/app");
const port = process.env.PORT || 3000;

app.listen(port, () => console.log("Example app listening on port 3000!"));

In the file ./src/app.js, insert the below code:

const express = require("express");
const chatgpt = require("../src/chatgpt");

const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.get("/", (req, res) => res.send("Hello there"));

app.post("/chatgpt", chatgpt);

module.exports = app;

The code above sets up an Express application and integrates the chatgpt function as middleware for the /chatgpt route path.

In the file ./src/chatgpt.js, insert the below code:

const { Configuration, OpenAIApi } = require("openai");
const twilio = require("twilio");
require("dotenv").config();

const { TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, OPENAI_API_KEY } = process.env;

// Create a Twilio client and OpenAI client
twilio(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);
const configuration = new Configuration({ apiKey: OPENAI_API_KEY });
const openai = new OpenAIApi(configuration);

module.exports = async (req, res) => {
try {
// Create a new Twilio Response object and send a message
const twiml = new twilio.twiml.MessagingResponse();
const message = req.body.Body;

// Process message with OpenAI's GPT-3 API and return response
const response = await processMessageWithChatGPT(message);
twiml.message(response);

// Send the response back to Twilio
res.set("Content-Type", "text/xml");
res.status(200).send(twiml.toString());
} catch (error) {
console.error(error.response.data.error);
res.status(500).send({
message: "Something went wrong",
error: error.response.data.error
});
}
};

// Returns a response from OpenAI's GPT-3 API
const processMessageWithChatGPT = async (message) => {
const response = await openai.createCompletion({
model: "text-davinci-003",
prompt: message,
temperature: 0.7, //A number between 0 and 1 that determines how many creative risks the engine takes when generating text.
max_tokens: 3000, // Maximum completion length. max: 4000-prompt
frequency_penalty: 0.7 // # between 0 and 1. The higher this value, the bigger the effort the model will make in not repeating itself.
});
return response.data.choices[0].text;
};

The code above, exports a middleware function for the route /chatgpt. The function handles incoming messages from Twilio and processes them using OpenAI’s GPT-3 API.

  1. Upon receiving a message, it creates a new Twilio response object and retrieves the message from the incoming request body.
  2. It then calls the processMessageWithChatGPT function to get a response from OpenAI's GPT-3 API.
  3. The response is added to the Twilio response object, set as text/xml content, and sent back as the response to the incoming request.

The processMessageWithChatGPT function takes in a message and returns the response from OpenAI's API using the openai library. It creates a completion request with the following properties:

  • model: Identifies OpenAI language model for text generation, used in this tutorial is text-davinci-003
  • prompt: Property that holds the text for which the answer is generated

Additionally, the following optional properties are used to refine the outcome:

  • max_tokens: Specifies the maximum length of the completion
  • frequency_penalty: Specifies the effort made by the model to avoid repeating itself

More optional properties for completion are available in the OpenAI documentation.

We can now safely run our project by running the following command:

node index.js

To allow Twilio to send requests to your Node.js app, it must be accessible from the web. ngrok can be used for this purpose. To use ngrok, run the following command in a new terminal:

~/ngrok http 3000

You should see ngrok started with status online.

Copy the new ngrok https URL and let’s go back to the WhatsApp Sandbox and add it as our webhook URL.

NOTE: Webhook URL should have /chatgpt as a route path.

It’s time to test it!

Get your phone and send a question or prompt to your Twilio phone number so that OpenAI can answer it.

It’s a wrap!

Amazing job! You have successfully created your first chatbot! 🎉

In conclusion, ChatGPT and Twilio are powerful tools that can be used together to build sophisticated and intelligent chatbots. Offering endless possibilities for businesses, from automating customer service inquiries to creating virtual assistants that can help users with various tasks, and much more.

Thanks for reading, I hope this tutorial has effectively walked you through the process of integrating ChatGPT and Twilio for building intelligent chatbots.

Follow the GoGroup Tech Blog for more tech advice articles, and check out our job openings here.

Click here for more information on GoGroup!

--

--

I enjoy developing and contributing to the products that can make a beneficial impact on the dependent organization and audience.