Building a WhatsApp Customer Service Representative with Lyzr, Flask, Twilio, and OpenAI
Published: 2024-04-30 07:48:34

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
```
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)
```
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

    )
```
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}"
```
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)
```
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)
```
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](https://www.lyzr.ai/)
{% embed https://github.com/harshit-lyzr/whatsapp-bot/ %}