Build a Serverless ChatGPT SMS Chatbot with the OpenAI API
Tags: serverless, openai, chatgpt, machinelearning
Published: 2023-01-09 20:48:02

---
title: Build a Serverless ChatGPT SMS Chatbot with the OpenAI API
published: true
description: Who needs a web browser? Learn to build a serverless ChatGPT SMS Chatbot using the OpenAI API, Twilio Programmable Messaging, and Node.js
tags: serverless, openai, chatgpt, ml
cover_image: https://assets.cdn.prod.twilio.com/images/K0fvviwaTy7qkBIFhxW7KYqfTrdo6hDBIqigKhSbAJbKQ.width-1616.png
# Use a ratio of 100:42 for best results.
# published_at: 2023-01-09 19:46 +0000
---
This blog post was written for [Twilio](https://www.twilio.com/) and [originally published on the Twilio blog](https://www.twilio.com/blog/sms-chatbot-openai-api-node).

[ChatGPT](https://openai.com/blog/chatgpt/) went viral recently! This conversational machine learning (ML) chatbot developed by [OpenAI](https://openai.com/) can answer questions, admit its mistakes, challenge incorrect premises, generate stories and poetry, and more. Read on to learn how to build a serverless SMS chatbot using ChatGPT and the OpenAI API, [Twilio Programmable Messaging](https://www.twilio.com/docs/sms), the [Twilio Serverless Toolkit](https://www.twilio.com/docs/labs/serverless-toolkit), and Node.js.
![gif example of SMS version of ChatGPT powered by Twilio with the OpenAI API](https://assets.cdn.prod.twilio.com/original_images/jUvA2cr6auC88298l8MJwVN_9ZpmI98Wkb80gt4-yflquLL-pl8YPI5_3PUxraJVnurWy91KsOa_KE)

You can test this chatbot out yourself by texting a question or prompt (like in the GIF above) to <strong>+17622490430</strong>.

Do you prefer learning via video more? Check out this [TikTok summarizing this tutorial](https://www.tiktok.com/@lizziepikachu/video/7185762349775621419) in under three minutes!
[![tiktok versiont](https://user-images.githubusercontent.com/8932430/211401718-be0abb93-92d7-43a0-a962-309478750f88.png)](https://www.tiktok.com/embed/7185762349775621419 "tiktok") 

### ChatGPT and Node.js
GPT-3 (short for “Generative Pre-training Transformer 3”) is a natural language processing (NLP) model trained on human-generated text. Given some text input, it can generate its own human-like text based in a variety of languages and styles. Here, I ask it to "give me some bars about SendGrid."
![gif of chatgpt in browser](https://assets.cdn.prod.twilio.com/original_images/_KfeYfEcgH8O8RaiYJERqMEHTlDIYjPIhZ-aCXfZIASdlpoC9M44fZly2_TrFWC0bgxQ93gepbVqY8)

You can [test out ChatGPT in the browser here](https://chat.openai.com/chat).

The GPT-3 model uses a [transformer architecture](https://machinelearningmastery.com/the-transformer-model/). This multi-layer neural network is good for processing sequential data, like text. Language-related tasks it can perform include translation, summarization, and question answering, as well as text generation comparable to human text generation.

To use ChatGPT in a Node.js application, you must use the [OpenAI API](https://beta.openai.com/dashboard).
### Prerequisites
1. A Twilio account - sign up for a free [Twilio Account here](https://www.twilio.com/try-twilio)
2. A Twilio Phone Number with SMS capabilities - [learn how to buy a Twilio Phone Number here](https://support.twilio.com/hc/en-us/articles/223135247-How-to-Search-for-and-Buy-a-Twilio-Phone-Number-from-Console)
3. OpenAI Account – [make an OpenAI Account here](https://openai.com/api/)
4. Node.js installed - [download Node.js here](https://nodejs.org/en/download/)
### Get Started with OpenAI
After making an OpenAI account, you'll need an API Key. You can [get an OpenAI API Key here](https://beta.openai.com/account/api-keys) by clicking on <strong>+ Create new secret key</strong>.
![api keys screenshot](https://assets.cdn.prod.twilio.com/images/1lHXDS_s-kB9Px2SGTFGmG8t57burs6xgiF0RAJsq9-wR.width-1600.png)
Save that API key for later to use the OpenAI client library in your Twilio Function.
### Get Started with the Twilio Serverless Toolkit
The Serverless Toolkit is CLI tooling that helps you develop Twilio Functions locally and deploy them to [Twilio Functions & Assets](https://www.twilio.com/docs/serverless/functions-assets). The best way to work with the Serverless Toolkit is through the Twilio CLI. If you don't have the [Twilio CLI](https://www.twilio.com/docs/twilio-cli/quickstart) installed yet, run the following commands on the command line to install it and the Serverless Toolkit:
```bash
npm install twilio-cli -g
twilio login
twilio plugins:install @twilio-labs/plugin-serverless
```
Afterwards, create your new project and install our lone requirement [`openai`](https://www.npmjs.com/package/openai):
```bash
twilio serverless:init chatgpt-sms --template=blank
cd chatgpt-sms
npm install -s openai
```
### Set an Environment Variable with Twilio Functions and Assets
Open up your .env file for your Functions project in your root directory and add the following line:
```bash
OPENAI_API_KEY=YOUR-OPENAI-API-KEY
```
Replace `YOUR-OPENAI-API-KEY` with the OpenAI API Key you took note off earlier. Now you can access this API Key if you'd like to do so in your code with `context.OPENAI_API_KEY`.
### Make a Twilio Function with JavaScript
Make a new file in the `/functions directory` called `chatgpt.js` containing the following code:
```javascript
const { Configuration, OpenAIApi } = require("openai");
exports.handler = async function(context, event, callback) {
  const twiml = new Twilio.twiml.MessagingResponse();
  const inbMsg = event.Body.toLowerCase().trim();
  const configuration = new Configuration({
    apiKey: process.env.OPENAI_API_KEY
  });
  const openai = new OpenAIApi(configuration);
  const response = await openai.createCompletion({
      model: "text-davinci-003",
      prompt: inbMsg,
      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.
    });
  twiml.message(response.data.choices[0].text);
  callback(null, twiml);
};
```
This code imports `openAI` and makes an async function containing a [Twilio Messaging Response object](https://www.twilio.com/docs/sms/api/message-resource) and a variable `inbMsg` from the inbound text message users will text in. It then initializes a `Configuration` object and passes it an object to the `Configuration` constructor containing the property `apiKey`. The function then calls the `openai.createCompletion` function to use one of their language models to generate text based on `inbMsg`.

In order to specify our completion, you need to pass in a configuration object containing two properties: `model` and `prompt`. `model` identifies the OpenAI language model used to generate an answer for the text which we assign to the `prompt` property. In this tutorial, you'll use the `text-davinci-003` language model. It's the same language model used in the background by ChatGPT. The OpenAI docs list the [other language models they offer for use](https://beta.openai.com/docs/models/overview).

Optional properties `max_tokens` and `frequency_penalty` specify the maximum completion length and the effort the model will make to not repeat itself. You can see more [optional properties for completion here in the OpenAI documentation](https://beta.openai.com/docs/api-reference/completions/create).

You can view the [complete source code on GitHub here](https://github.com/elizabethsiegle/chatGPT-SMS).
### Configure the Function with a Twilio Phone Number
To deploy your app to Twilio, run `twilio serverless:deploy` from the <em>chatgpt-sms</em> root directory. You should see the URL of your Function at the bottom of your terminal:
![deployed function with urls](https://assets.cdn.prod.twilio.com/images/fbQL11tAB_kdnOAog1aPiKLcLqIWNOox55CfMg6cK4m02.width-1000.png)
Grab the Function URL corresponding to your app (the one that ends with <em>/chatgpt</em>) and [configure a Twilio Phone Number](https://www.twilio.com/console/phone-numbers/incoming) with it as shown below: select the Twilio number you just purchased in your [Twilio Phone Numbers console](https://console.twilio.com/us1/develop/phone-numbers/manage/incoming) and scroll down to the <em>Messaging</em> section. Paste the link in the text field for <strong>A MESSAGE COMES IN</strong> webhook making sure that it's set to <strong>HTTP POST</strong>. When you click <strong>Save</strong>, it should look like this!
![twilio phone number configuration in console](https://assets.cdn.prod.twilio.com/images/r1ViXfhX01xjrXXa528-OynIzwLtOQxFWlX78CN4-T3IE.width-1000.png)
The [Service](https://www.twilio.com/docs/serverless/functions-assets/functions/create-service) is the Serverless project name, environment provides no other options, and Function Path is the file name. Now take out your phone and text a question or prompt to your Twilio number.
![sms example of chatgpt over sms answering how to get to machu picchu from sfo](https://assets.cdn.prod.twilio.com/images/sc0jURdMOhnzjwhlToJRWvAltGFwke7shO8VIXNBB8pTo.width-1000.jpg)
### What's Next for Twilio Serverless and ChatGPT?
The development possibilities offered by ChatGPT and Twilio are endless! You can build an [SMS chatbot with Python](https://www.twilio.com/blog/openai-gpt-3-chatbot-python-twilio-sms), [call an AI friend](https://www.twilio.com/blog/call-ai-friend-gpt-3-twilio-voice-functions), [chat with an AI chef over WhatsApp](https://www.twilio.com/blog/python-whatsapp-chef-bot-openai-gpt3), and more. Let me know what you're working on with OpenAI–I can't wait to see what you build.