Upgrade Your Text Game: How to Build an SMS Chatbot that Will Blow Your Users' Minds using Twilio, Twilio Functions and...
Tags: api, openai, gpt3, twilio
Published: 2023-01-13 01:14:10

---
title: Upgrade Your Text Game: How to Build an SMS Chatbot that Will Blow Your Users' Minds using Twilio, Twilio Functions and...
published: true
date: 2023-01-12 12:12:53 UTC
tags: API,OpenAI,GPT3,Twilio
canonical_url: https://techdevblog.io/upgrade-your-text-game-how-to-build-an-sms-chatbot-that-will-blow-your-users-minds-using-twilio-twilio-functions-and-openai-gpt-3/
---

## Introduction:
 ![Upgrade Your Text Game: How to Build an SMS Chatbot that Will Blow Your Users' Minds using Twilio, Twilio Functions and OpenAI GPT-3](https://techdevblog.io/content/images/2023/01/image_0-11.jpg)

Remember how we said [APIs can help us create amazing things](https://techdevblog.io/api-magic-unlocking-the-power-of-data-and-functionality/)? In this tutorial, you'll learn how to use [Twilio](https://www.twilio.com), [Twilio Functions](https://www.twilio.com/en-us/serverless/functions), and [OpenAI's GPT-3 API](https://openai.com/api/) to create a chatbot that can have intelligent conversations with users via SMS. Whether you're a developer looking to build a chatbot for your business or an enthusiast looking to learn more about chatbot development, this introductory tutorial will provide you with the knowledge and tools you need to get started.

## Prerequisites

Before you begin, you'll need the following:

- **A Twilio account** : If you don't already have one, you can sign up for a free trial account at [twilio.com](https://www.twilio.com/try-twilio).
- **A Twilio phone number _with SMS capabilities_** : You can purchase one through your Twilio account dashboard.
- **An OpenAI API key** : You'll need an API key to access the GPT-3 API. You can sign up for a free API key at [https://beta.openai.com/](https://beta.openai.com/).

## Step 1: Set up a Twilio Service and Function

Twilio Functions are serverless, cloud-based functions that allow you to run code in response to incoming SMS messages. In this tutorial, we'll use a Twilio Function to handle the incoming SMS messages and send responses back to the user.

1. Log in to your Twilio account and go to the [Services page](https://www.twilio.com/console/functions/overview/services)
2. Click the "Create a Service" button.
3. Give your service a name (e.g., "awesome-sms-chatbot")
4. Click "Next"
5. You will be redirected to the service editor page

## Step 2: Setup the Twilio Function

1. In the top left corner, click "Add"
2. In the dropdown menu, select "Add a function"
3. Give your function a path (e.g., "/sms")
4. A code editor will open on the right
5. In the code editor, replace the existing sample with the following:

```
// function to make an API call to OpenAI and return a JSON response
function openaiAPI(prompt, model, apiKey, callback) {
    // create a data object with the parameters for the API call
    const data = JSON.stringify({
        temperature: 0.5,
        model,
        prompt,
        n: 1,
        max_tokens: 50
    });

    // create options for the HTTP request
    const httpTransport = require('https');
    const responseEncoding = 'utf8';
    const httpOptions = {
        hostname: 'api.openai.com',
        port: '443',
        path: '/v1/completions',
        method: 'POST',
        headers: {"Authorization":`Bearer ${apiKey}`,"Content-Type":"application/json"}
    };

    // make the API call and handle the response
    const request = httpTransport.request(httpOptions, (res) => {
        let responseBufs = [];
        let responseStr = '';
        
        res.on('data', (chunk) => {
            if (Buffer.isBuffer(chunk)) {
                responseBufs.push(chunk);
            }
            else {
                responseStr = responseStr + chunk;            
            }
        }).on('end', () => {
            responseStr = responseBufs.length > 0 ? 
                Buffer.concat(responseBufs).toString(responseEncoding) : responseStr;
            
            // pass the response to the callback
            callback(null, res.statusCode, res.headers, JSON.parse(responseStr));
        });
        
    })
    .setTimeout(0)
    .on('error', (error) => {
        callback(error);
    });
    request.write(data)
    request.end();
};

// function to generate a response from the OpenAI API call
function generateResponse(prompt, model, apiKey, callback) {
  const response = openaiAPI(prompt, model, apiKey, (error, statusCode, headers, data) => {
    const { choices: [{ text }] } = data;
    callback(null, text);
  })
};

// export the main function that handles the incoming SMS event
exports.handler = async (context, event, callback) => {
  const twiml = new Twilio.twiml.MessagingResponse();
  const from = event.From;
  const body = event.Body;

  // get the current Node.js version
  const nodeVersion = process.version;

  // generate a response using the OpenAI API
  generateResponse(body, process.env.GPT_3_MODEL, process.env.OPENAI_API_KEY, (error, response) => {
    twiml.message(`[MODEL] - process.env.GPT_3_MODEL`);
    twiml.message(`[NODE.JS] [VERSION] - ${nodeVersion}`);
    twiml.message(response);
    callback(null, twiml);
  });
};

```

> `http` request code generated thanks to [Paw (formerly RapidAPI)](https://paw.cloud), and made dynamic by yours truly.

1. At the bottom of the code editor, click "Save"
2. At the bottom of the left-hand menu, in the "Settings" section, click on "Environment Variables"
3. Set your `OPENAI_API_KEY` (from the prerequisites) and `GPT_3_MODEL` (`text-davinci-003 `) environment variables
4. At the very bottom of the left-hand menu, click "Deploy All"

## Step 3: Set up a Webhook

A webhook is a URL that Twilio will send a request to whenever an incoming SMS message is received. In this tutorial, we'll use a webhook to trigger the Twilio Function we created in the previous step.

1. Go to the phone numbers page in your Twilio account dashboard.
2. Click on the phone number you want to use for your chatbot.
3. Scroll down to the "Messaging" section and set the "A message comes in" webhook to the URL of your Twilio Function (you can find this URL under the "Function URL" heading on the Function's page).
4. Click the "Save" button to save your changes.

## Step 4: Test your chatbot

To test the chatbot, send an SMS message (e.g., "Hey! Who are you?") to the phone number you configured in Step 2. You should receive a response from the chatbot saying something along the lines of "My name is John" (or something completely different; who knows with GPT-3?). If you don't receive a response, check the logs in your Twilio Function to see if there were any errors.

## Step 5: Play around, and tear down

Once you are down playing around with GPT-3, and unless you want to keep your chatbot, remember to release your Twilio phone number & delete your Twilio service. Else you might incur some charges.

## Conclusion:

Congratulations! You have learned how to create an SMS chatbot using [Twilio](https://www.twilio.com), [Twilio Functions](https://www.twilio.com/en-us/serverless/functions), and [OpenAI's GPT-3 API](https://openai.com/api/). You have set up a [Twilio Functions](https://www.twilio.com/en-us/serverless/functions) to handle incoming SMS messages, configured a webhook to trigger the function, and wrote code to generate responses using GPT-3. With this knowledge and your new chatbot, you now have a powerful tool for interacting with users via SMS. You can customize your chatbot further by training it on your own dataset, by using a different GPT-3 model, or by integrating your new chatbot with your own backend or API.

I hope you found this tutorial helpful and fun, and I encourage you to continue learning about chatbot development and other cutting-edge technologies. Happy coding!

<!--kg-card-end: markdown-->