DEV Community

Cover image for Building a WhatsApp Customer Service Representative with Lyzr, Flask, Twilio, and OpenAI
harshit-lyzr
harshit-lyzr

Posted on

Building a WhatsApp Customer Service Representative with Lyzr, Flask, Twilio, and OpenAI

In today's digital age, chatbots have become an integral part of many businesses, providing instant responses to customer inquiries and enhancing user experience. In this blog post, we'll walk through the process of building a simple WhatsApp chatbot using Lyzr SDK,Flask, Twilio for messaging, and OpenAI for generating responses.

Setting Up the Environment
Imports:

pip install lyzr streamlit flask twilio
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
from dotenv import load_dotenv
import os
from openai import OpenAI
from lyzr import QABot
Enter fullscreen mode Exit fullscreen mode

Flask: Enables building the web application framework.
MessagingResponse: Used to create response messages for Twilio.
dotenv: Allows loading environment variables from a .env file.
os: Provides access to environment variables.
OpenAI: Provides access to OpenAI's API (not fully implemented).
Lyzr: Library for building RAG Chatbot.

app = Flask(__name__)
load_dotenv()

my_key = os.getenv("OPENAI_API_KEY")
client = OpenAI(api_key=my_key)
Enter fullscreen mode Exit fullscreen mode

app is a Flask instance representing the web application.
load_dotenv() reads environment variables from a .env file (likely containing the OpenAI API key).
my_key stores the OpenAI API key retrieved from the environment.
client is an OpenAI client object used to interact with the API (not fully utilized).

QABot Configuration with Policy Document:

prompt=f"""
You are a customer service chatbot for amazon's return policy.
Your Task is to provide quick assistance to customer inquiries regarding amazon's return policy.
Familiarize yourself with Amazon's return policy thoroughly. This includes understanding what items are eligible for return, the timeframe for returns, and any special conditions for specific product categories.
"""

chat = QABot.pdf_qa(
        input_files=["Amazon-policy.pdf"],
        system_prompt=prompt

    )
Enter fullscreen mode Exit fullscreen mode

A prompt defines the role of the chatbot as an Amazon return policy assistant.
chat is a QABot object initialized with QABot.pdf_qa.
input_files=["Amazon-policy.pdf"] specifies the Amazon return policy PDF as the knowledge source for answering questions.
system_prompt provides the defined prompt to guide the QABot's understanding of its role.

Generate Answer Function:

def generate_answer(question):
    try:
        response = chat.query(question)
        return response.response
    except Exception as e:
        return f"Error generating answer: {e}"
Enter fullscreen mode Exit fullscreen mode

generate_answer(question) takes a question as input.
It tries to use chat.query(question) to get an answer from the QABot using the loaded policy PDF.
If the QABot fails to answer (try...except), an error message is returned.

ChatGPT Route:

@app.route('/chatgpt', methods=['POST'])
def chatgpt():
    incoming_que = request.values.get('Body', '').lower()
    print(incoming_que)

    answer = generate_answer(incoming_que)
    print(answer)

    bot_resp = MessagingResponse()
    msg = bot_resp.message()
    msg.body(answer)

    return str(bot_resp)
Enter fullscreen mode Exit fullscreen mode

This route (/chatgpt) handles text message requests sent through Twilio (POST method).
incoming_que = request.values.get('Body', '').lower() retrieves the question from the request body and converts it to lowercase.
answer = generate_answer(incoming_que) calls the generate_answer function to get a response for the question based on the policy PDF.
A Twilio MessagingResponse object (bot_resp) is created to structure the response message.
The answer is set as the message body using msg.body(answer).
Finally, the MessagingResponse object is converted to a string and returned.

Running the App:

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
Enter fullscreen mode Exit fullscreen mode

The if name == 'main': block ensures the code below only runs when the script is executed directly.
app.run(host='0.0.0.0', port=5000) starts the Flask application, making it accessible on port 5000 (any IP address can connect).

try it on whatsapp: +14155238886 then send join nearby-slipped
For more information explore the website: Lyzr

Top comments (0)