Get Chatting with OpenAI GPT-3: How to Build a Messaging (SMS) Chatbot in Minutes

Build a Smart Chatbot for Your SMS Conversations in No Time with OpenAI GPT-3 and Fly.ioPhoto by Markus Spiske on UnsplashIn a previous article, we showed you how to build a Twitter chatbot using OpenAI GPT-3 and DALL-E 2.Creating a Twitter Chatbot Wit…


This content originally appeared on Level Up Coding - Medium and was authored by Shanaka DeSoysa

Build a Smart Chatbot for Your SMS Conversations in No Time with OpenAI GPT-3 and Fly.io

Photo by Markus Spiske on Unsplash

In a previous article, we showed you how to build a Twitter chatbot using OpenAI GPT-3 and DALL-E 2.

Creating a Twitter Chatbot With OpenAI and DALL-E 2

In this tutorial, we will show you how to build a messaging (SMS) chatbot using the OpenAI API and Twilio. We will also show you how to deploy the chatbot for free with Fly.io. By the end of this tutorial, you will have a chatbot that can answer questions and have a conversation with you via SMS.

Here are some examples of the chatbot in action:

SMS Chatbot Responses

As you can see, the chatbot is able to answer questions and have a conversation with the user via SMS.

TLDR; Show Me the Code

In this tutorial, we showed you how to build a messaging (SMS) chatbot using the OpenAI API and Twilio, and how to deploy the chatbot for free with Fly.io. You can find the code for the chatbot in the GitHub repository.

What You Will Need

To follow along with this tutorial, you will need the following:

  • An OpenAI API key. You can sign up for a free API key here.
  • A Twilio account and phone number. You can sign up for a free Twilio account here.
  • A Fly.io account. You can sign up for a free Fly.io account here.

Setting Up OpenAI and Twilio

First, you’ll need to sign up for an OpenAI account and get an API key.

Next, you’ll need to sign up for a Twilio account and purchase a phone number that can send and receive SMS messages.

Once you have an OpenAI API key and a Twilio account and phone number, you’re ready to start building the chatbot.

Building the Chatbot

We will use the FastAPI framework to build the chatbot. FastAPI is a modern, fast, web framework for building APIs with Python. It is easy to use and provides automatic validation and documentation for your API endpoints.

Create a virtual environment using python3 -m venv, and install packages:

  1. Make sure that you have Python 3 installed on your system.
  2. Navigate to the project directory in the terminal.
  3. Run the following command to create a virtual environment in the venv directory:
python3 -m venv venv

4. Activate the virtual environment:

source venv/bin/activate

5. Create a requirements.txt file in the project directory with the required package names, one per line. For example:

fastapi==0.88.0
uvicorn==0.20.0
openai==0.25.0
twilio==7.16.0
python-multipart==0.0.5
python-dotenv==0.21.0

6. Install the required packages:

pip install -r requirements.txt

Next, create a file named .env in the project directory. And add the environment variables and their values to the file, using the format VARNAME=value. For example:

OPENAI_API_KEY=your_api_key
TWILIO_AUTH_TOKEN=your_auth_token

Next, create a file called app.py and copy the following code into it:

import openai
import os
from dotenv import load_dotenv
from fastapi import FastAPI, Request, Response, Form, HTTPException
from twilio.twiml.messaging_response import MessagingResponse
from twilio.request_validator import RequestValidator
import logging

# Load environment variables from .env file
load_dotenv(".env")

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI()
# Use the OpenAI API to generate a response to the message
openai.api_key = os.environ["OPENAI_API_KEY"]

# Use the RequestValidator to verify that the request came from Twilio
validator = RequestValidator(os.environ["TWILIO_AUTH_TOKEN"])


@app.post("/sms")
async def sms_webhook(request: Request, From: str = Form(...), Body: str = Form(...)):
# Verify that the request came from Twilio
form_ = await request.form()
url = str(request.url).replace("http", "https")
sig = request.headers.get("X-Twilio-Signature", "")

if not validator.validate(
url,
form_,
sig,
):
logger.error("Error in Twilio Signature")
raise HTTPException(
status_code=403, detail="Error in Twilio Signature")

# Get the incoming message and phone number from the request body
message = Body
phone_number = From

logger.info(f"Message received from {phone_number}: {message}")

# Send the message to the OpenAI API
response_text = openai.Completion.create(
engine="text-davinci-003",
prompt=message,
max_tokens=128,
temperature=0.7,
).choices[0].text

logger.info(f"OpenAI response: {response_text}")

# Create a Twilio response object
twiml_response = MessagingResponse()

# Add the response text to the Twilio response
twiml_response.message(response_text)

# Return the Twilio response as the HTTP response
return Response(content=str(twiml_response), media_type="application/xml")

The code imports the necessary libraries and defines the sms_webhook function, which is the API endpoint for the chatbot. The function accepts a request object, as well as From and Body form fields. The From field is the phone number of the sender, and the Body field is the message body.

First, the code uses the RequestValidator class to verify that the request came from Twilio. The validate() method of the RequestValidator instance is called with the URL of the request, the form data, and the X-Twilio-Signature header as arguments. If the validation fails, an HTTPException is raised. This code ensures that only requests from Twilio are processed by the chatbot, helping to prevent abuse and spam.

If the request is valid, the code gets the incoming message and phone number from the request body, and then sends the message to the OpenAI API using the openai.Completion.create() method. The engine parameter specifies which OpenAI model to use, and the prompt parameter is the message to send to the model. The max_tokens parameter specifies the maximum number of tokens (words and punctuation) to generate in the response, and the temperature parameter controls the creativity of the response.

The OpenAI API returns a list of possible responses, and we choose the first response in the list. The response is then logged and sent back to the user as a Twilio SMS message using the twilio.twiml.messaging_response.MessagingResponse class.

Finally, the function returns an HTTP response with the Twilio SMS message as the content. This completes the chatbot’s handling of the incoming SMS message.

To run the FastAPI app locally, run following command in the virtual environment.

uvicorn app.main:app --host 0.0.0.0 --port 8124 --reload

Deploying the Chatbot with Fly.io

Now that we have built the chatbot, we can deploy it to the internet so that it can receive and respond to SMS messages from anyone. We will use Fly.io to deploy the chatbot for free.

Let’s create a Dockerfile to containerize the app.

FROM python:3.9-slim
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV LOG_LEVEL=INFO
WORKDIR /code
COPY ./requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
COPY ./app /code/app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"]

First, sign up for a Fly.io account and follow the instructions to install the Fly CLI. Then, run the following commands to create a new Fly app and deploy the chatbot:

# Create a new Fly app
fly launch

# Set secrets
fly secrets set --app my-sms-api \
TWILIO_AUTH_TOKEN=your_api_key \
OPENAI_API_KEY=your_openai_api_key

# Deploy the chatbot
fly deploy

The chatbot will be deployed to a unique URL, such as https://my-chatbot.fly.dev.

FastAPI Swagger Page

FastAPI automatically generates a Swagger page for your API under https://my-chatbot.fly.dev/docs, which provides documentation and examples for each API endpoint.

Here is an example of the Swagger page for the chatbot:

FastAPI Documentation

As you can see, the Swagger page provides a description of the /sms endpoint, as well as examples of the request and response payloads.

Setting up Twilio Messaging Webhook

To set up a Twilio webhook for incoming messages, you will need to do the following:

  1. In the Twilio console, navigate to the phone number’s configuration page and scroll down to the “Messaging” section.
  2. Under “A MESSAGE COMES IN”, enter the URL of your chatbot’s /sms endpoint in the "Webhook" field.
  3. Click “Save” to save the configuration.
Setting up Twilio Messaging Webhook

Now, when someone sends an SMS message to your Twilio phone number, Twilio will send a request to your chatbot’s /sms endpoint with the message details. The chatbot will then generate a response using the OpenAI API and send it back to the user via Twilio.

You can also set up additional webhooks for other events, such as when a call is received or when a message delivery status changes. For more information, see the Twilio documentation.

Conclusion

We hope you enjoyed this tutorial and learned how to build and deploy a messaging chatbot with OpenAI and Twilio. If you have any questions or feedback, please let us know in the comments below.

Thanks for reading! Follow us for more articles on coding, Machine Learning, and Data Science.

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job


Get Chatting with OpenAI GPT-3: How to Build a Messaging (SMS) Chatbot in Minutes was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Shanaka DeSoysa


Print Share Comment Cite Upload Translate Updates
APA

Shanaka DeSoysa | Sciencx (2023-01-30T17:28:37+00:00) Get Chatting with OpenAI GPT-3: How to Build a Messaging (SMS) Chatbot in Minutes. Retrieved from https://www.scien.cx/2023/01/30/get-chatting-with-openai-gpt-3-how-to-build-a-messaging-sms-chatbot-in-minutes/

MLA
" » Get Chatting with OpenAI GPT-3: How to Build a Messaging (SMS) Chatbot in Minutes." Shanaka DeSoysa | Sciencx - Monday January 30, 2023, https://www.scien.cx/2023/01/30/get-chatting-with-openai-gpt-3-how-to-build-a-messaging-sms-chatbot-in-minutes/
HARVARD
Shanaka DeSoysa | Sciencx Monday January 30, 2023 » Get Chatting with OpenAI GPT-3: How to Build a Messaging (SMS) Chatbot in Minutes., viewed ,<https://www.scien.cx/2023/01/30/get-chatting-with-openai-gpt-3-how-to-build-a-messaging-sms-chatbot-in-minutes/>
VANCOUVER
Shanaka DeSoysa | Sciencx - » Get Chatting with OpenAI GPT-3: How to Build a Messaging (SMS) Chatbot in Minutes. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/01/30/get-chatting-with-openai-gpt-3-how-to-build-a-messaging-sms-chatbot-in-minutes/
CHICAGO
" » Get Chatting with OpenAI GPT-3: How to Build a Messaging (SMS) Chatbot in Minutes." Shanaka DeSoysa | Sciencx - Accessed . https://www.scien.cx/2023/01/30/get-chatting-with-openai-gpt-3-how-to-build-a-messaging-sms-chatbot-in-minutes/
IEEE
" » Get Chatting with OpenAI GPT-3: How to Build a Messaging (SMS) Chatbot in Minutes." Shanaka DeSoysa | Sciencx [Online]. Available: https://www.scien.cx/2023/01/30/get-chatting-with-openai-gpt-3-how-to-build-a-messaging-sms-chatbot-in-minutes/. [Accessed: ]
rf:citation
» Get Chatting with OpenAI GPT-3: How to Build a Messaging (SMS) Chatbot in Minutes | Shanaka DeSoysa | Sciencx | https://www.scien.cx/2023/01/30/get-chatting-with-openai-gpt-3-how-to-build-a-messaging-sms-chatbot-in-minutes/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.