
Upgrade Your Text Game: How to Build an SMS Chatbot that Will Blow Your Users' Minds using Twilio, Twilio Functions and OpenAI GPT-3
Upgrade Your Text Game: How to Build an SMS Chatbot that Will Blow Your Users' Minds using Twilio, Twilio Functions and OpenAI GPT-3 was initially published on Thursday January 12 2023 on the Tech Dev Blog. For the latest up-to-date content, fresh out of the oven, visit https://techdevblog.io and subscribe to our newsletter!
Introduction:
Remember how we said APIs can help us create amazing things? In this tutorial, you'll learn how to use Twilio, Twilio Functions, and OpenAI's GPT-3 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.
- 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/.
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.
- Log in to your Twilio account and go to the Services page
- Click the "Create a Service" button.
- Give your service a name (e.g., "awesome-sms-chatbot")
- Click "Next"
- You will be redirected to the service editor page
Step 2: Setup the Twilio Function
- In the top left corner, click "Add"
- In the dropdown menu, select "Add a function"
- Give your function a path (e.g., "/sms")
- A code editor will open on the right
- 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), and made dynamic by yours truly.
- At the bottom of the code editor, click "Save"
- At the bottom of the left-hand menu, in the "Settings" section, click on "Environment Variables"
- Set your
OPENAI_API_KEY
(from the prerequisites) andGPT_3_MODEL
(text-davinci-003
) environment variables - 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.
- Go to the phone numbers page in your Twilio account dashboard.
- Click on the phone number you want to use for your chatbot.
- 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).
- 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, Twilio Functions, and OpenAI's GPT-3 API. You have set up a Twilio 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!
Upgrade Your Text Game: How to Build an SMS Chatbot that Will Blow Your Users' Minds using Twilio, Twilio Functions and OpenAI GPT-3 was initially published on Thursday January 12 2023 on the Tech Dev Blog. For the latest up-to-date content, fresh out of the oven, visit https://techdevblog.io and subscribe to our newsletter!