![](https://crypto4nerd.com/wp-content/uploads/2023/02/11EuH0ycArrFn7qdr8OWKUw.png)
https://elearningindustry.com/rise-ai-powered-chatbots-elearning
Chatbots have become essential to many businesses’ digital strategies, providing 24/7 customer service and automating repetitive tasks. The latest advancements in AI have made it possible to create chatbots that can mimic human conversation more accurately than ever before. With the recent hype surrounding ChatGPT, the advanced language model from OpenAI, there’s never been a better time to explore the potential of AI-powered chatbots.
Table of content
– Introduction
– Understanding Rasa
– Google Sheets Integration
– Implementing ChatGPT
– Component integration, training and evaluation the Chatbot
– Conclusion
Introduction
This guide will walk you through the steps to create your own basic chatbot using Rasa, ChatGPT, and Google Sheets Integration. I’ll provide a detailed explanation of each component and show you how to integrate them to build an interactive chatbot that can choose structured answers through Google Sheets or reference ChatGPT’s responses. My goal is to make this process accessible to everyone and show that anyone can create their own chatbot with these powerful AI tools.
Understanding Rasa
Rasa is an open-source framework that provides tools for building advanced chatbots. Rasa provides Natural Language Understanding (NLU) and Dialogue Management to understand user inputs and respond with appropriate actions. NLU is understanding the user’s input and extracting relevant information, such as intent and entities. Dialogue management decides what actions to take based on the user’s input and the chatbot’s current state. Rasa also provides tools for training and evaluating your chatbot’s performance.
To get started with Rasa, you will need to install it on your system. Create a virtual environment using tools like Anaconda. A simulated environment is a self-contained environment that allows you to install and manage packages separately from your system Python installation.
Create a new environment using Anaconda, and run the following command:
conda create --name myenv python=3.8
Activate your chat environment by running the following commands:
conda activate myenv
pip install openai==0.4.0
pip install pandas==1.1.5
pip install pathlib==1.0.1
pip install requests==2.25.1
pip install ruamel.yaml==0.16.12
Install Rasa and its dependencies. Once Rasa is installed, you can create a new Rasa project using the following command:
pip install rasa
rasa init
This command will create a new Rasa project in your current directory with the following files:
actions/
: This directory contains Python scripts that define custom actions for your chatbot.config.yml
: This file contains the configuration settings for your Rasa project, such as the language model to use and the pipeline for processing user inputs.credentials.yml
: This file contains the credentials for external services, such as API keys for ChatGPT or Google Sheets.data/
: This directory contains the training data for your chatbot, including stories and NLU data.domain.yml
: This file defines the domain of your chatbot, including the intents, entities, and responses it can understand and generate.endpoints.yml
: This file defines the endpoints for external services, such as the API endpoint for ChatGPT or the Google Sheets API.
After installing Rasa using the Rasa CLI, you can start building your chatbot project by defining the intents, entities, and responses in your domain file, training the language model with your training data, and defining custom actions for your chatbot.
The Rasa CLI provides tools for training and evaluating your chatbot and generating the necessary files for deployment.
Implementing ChatGPT
Now that we have set up Rasa and created a basic chatbot, we can integrate ChatGPT to provide more sophisticated responses. In this section, I’ll show you how to implement ChatGPT in the actions.py file of your Rasa project.
ChatGPT is a language model developed by OpenAI that uses machine learning to generate human-like responses to user inputs. It is based on the GPT (Generative Pre-trained Transformer) architecture, which has achieved state-of-the-art results in various natural language processing tasks.
First, we need to import the necessary libraries and modules. These include io, os, openai, random, requests, pandas, and the load_dotenv function from the dotenv module. We will also import the Action, Tracker, CollectingDispatcher, Text, Dict, Any, and List classes from the Rasa SDK.
֫import io
import os
import openai
import random
import requests
import pandas as pd
from dotenv import load_dotenv
from rasa_sdk import Action, Tracker
from typing import Any, Text, Dict, List
from rasa_sdk.executor import CollectingDispatcher
Next, we will define a function called get_answers_from_chatgpt. This function takes user_text as input and returns the response generated by ChatGPT.
To get a response from ChatGPT, we first need to set our OpenAI API key using the os.getenv function. We will then create a new instance of the OpenAI Completion API and set the engine to “text-davinci-003”, which is one of the most advanced language models available.
def get_answers_from_chatgpt(user_text):# OpenAI API Key
openai.api_key = os.getenv("GPT_API_KEY")
# Use OpenAI API to get the response for the given user text and intent
response = openai.Completion.create(
engine="text-davinci-003",
prompt= user_text,
max_tokens=1024,
n=1,
stop=None,
temperature=0.5,
).choices[0].text
# Return the response from OpenAI
return response
We will then use the OpenAI API to generate a response to the user_text input. The max_tokens parameter controls the maximum number of tokens (words) in the response, and the n parameter controls the number of responses generated. The stop parameter controls the stopping sequence (if any) for the response generation, and the temperature parameter controls the “creativity” of the response.
Once we have the response from ChatGPT, we will return it to the calling function.
Next, we will define a new class called Simple_ChatGPT_Action. This class will inherit from the Action class and implement a run method that takes in a dispatcher, tracker, and domain as inputs.
֫class Simple_ChatGPT_Action(Action):"""Rasa action to parse user text and pulls a corresponding answer
from ChatGPT."""
def name(self) -> Text:
return "action_gpt_default_fallback"
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
# Get the latest user text
user_text = tracker.latest_message.get('text')
# Dispatch the response from OpenAI to the user
dispatcher.utter_message('ChatGPT (custom_action): ' + get_answers_from_chatgpt(user_text))
return []
The run method will get the tracker object’s latest user text and intent. We will then pass the user text to the get_answers_from_chatgpt function and use the CollectingDispatcher object to send the response generated by ChatGPT to the user.
Finally, we will return an empty list indicating the completed action. Once we have integrated this code into our actions.py
file, we can use it to generate responses to user queries using ChatGPT.
Google Sheets Integration
Google Sheets is a web-based spreadsheet program that allows users to create and edit spreadsheets online while collaborating in real-time with other users. It can be used as a database for your chatbot to store responses for various intents and entities.
To set up Google Sheets integration with Rasa and ChatGPT, create a new Google Sheet and add your intents, entities, and responses to the sheet.
Once you have added the information, you need to make the sheet public by clicking “Share” and selecting “Anyone with the link can view.” Once the Google Sheet is created, the URL of the sheet needs to be added to the .env
file in the Rasa project.
Next, you need to set up your Rasa environment to read the contents of the Google Sheet. You can do this by adding the following code to your actions.py
file:
class Simple_Google_sheet_or_ChatGPT_Action(Action):"""Rasa action to parse user text and pulls a corresponding answer
from google sheet based on the intent and entities.
If there is no answer in the google sheet, it will use the ChatGPT API"""
def name(self) -> Text:
return "simple_google_sheet_or_chatgpt_action"
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
# Get the latest user text and intent
user_text = tracker.latest_message.get('text')
intent = tracker.latest_message.get('intent').get('name')
entities = tracker.latest_message.get('entities')
# Dispatch the response from OpenAI to the user
dispatcher.utter_message('Google Sheets (custom_action): ' + str(self.get_answers_from_sheets(intent, entities, user_text)))
return []
def get_answers_from_sheets(self, intent, entity, user_text):
# Connect to Google Sheets
sheet_url = os.getenv("SHEET_URL")
GOOGLE_SHEET_URL = f"https://docs.google.com/spreadsheets/d/{sheet_url}/export?format=csv&gid=0"
s = requests.get(GOOGLE_SHEET_URL).content
# Read the contents of the URL as a CSV file and store it in a dataframe
proxy_df = pd.read_csv(io.StringIO(s.decode('utf-8')))
if entity:
# Filter the dataframe by the intent column and retrieve the answer list
filtered_df = proxy_df[(proxy_df['Intent'] == intent) & (proxy_df['Entity'] == entity[0]['value'])]
if filtered_df.empty:
answer = get_answers_from_chatgpt(user_text)
else:
answers = filtered_df['Answer'].tolist()
answer = random.choice(answers)
else:
answer = get_answers_from_chatgpt(user_text)
# Return the answer list
return answer
The Simple_Google_sheet_or_ChatGPT_Action class is used to parse the user text and retrieve a corresponding answer from the Google Sheet based on the intent and entities.
To use Google Sheets as a database for your chatbot, the get_answers_from_sheets function is used to connect to the Google Sheet and retrieve the answer list. The function filters the data frame by the intent column and retrieves the answer list. If an entity exists in the user query, the function filters the data frame by the entity column. If there is a match, the function retrieves the answer list. If there is no match, the ChatGPT API is used to retrieve a response.
With Google Sheets Integration, chatbots can be easily updated with new responses without having to modify the code. This makes it easy for non-technical users to maintain and update the chatbot.
Component integration, training, and evaluation
We must first design the conversation flow to build and test the chatbot. This involves creating the chatbot’s stories, intents, entities, and responses. Once our conversation flow is designed, we can integrate Rasa, ChatGPT, and Google Sheets to create a fully functional chatbot that can respond to user inputs and queries.
In order to create a fully functional chatbot, the YAML files for stories, rules, nlu, and domain need to be adjusted. The file nlu.yml
contains examples of user inputs with their corresponding intents, such as “utter_intent” and “what_is_x”. The stories.ym
file contains a sequence of actions and intents used to test the chatbot’s conversation flow. The domain.ym
file lists the intents, entities, and responses used in the chatbot and the available actions.
ֶ֫nlu:
- intent: utter_intent
examples: |
- can you utter?
- do you know how to utter?
- show me an example of utter?
- how to utter?
- intent: what_is_x
examples: |
- what is a [dog](object_entity)?
- what is a [chair](object_entity)?
- what a [dog](object_entity) is?
- what a [chair](object_entity) is
domain:
intents:
- greet
- utter_intent
- what_is_xentities:
- object_entity
responses:
utter_response:
- text: "This is direct utter, no custom action"
actions:
- utter_response
- simple_action_hello_world
- simple_google_sheet_or_chatgpt_action
- action_gpt_default_fallback
session_config:
session_expiration_time: 60
carry_over_slots_to_new_session: true
stories:
- story: simple utter
steps:
- intent: utter_intent
- action: utter_response- story: simple action use - 'hello_world'
steps:
- intent: greet
- action: simple_action_hello_world
- story: simple google sheet action use
steps:
- intent: what_is_x
- action: simple_google_sheet_or_chatgpt_action
rules:
- rule: out-of-scope
steps:
- intent: nlu_fallback
- action: action_gpt_default_fallback
After creating the necessary YAML files, the Rasa, ChatGPT, and Google Sheets components must be integrated. For example, the simple_google_sheet_or_chatgpt_action function pulls answers from Google Sheets or ChatGPT based on the user’s intent and entities. The chatbot can then be trained on this integrated model using the Rasa framework and evaluated for any issues or errors.
To train the bot with the new configuration, we can run the following command:
rasa train
In order to allow access to the server of the actions, you need to activate it in a separate terminal window. To do this, navigate to the main directory and run the following command:
rasa run actions --actions actions
After training, we can test the bot in the shell using the following:
rasa shell
This will open up the chat interface where we can interact with the bot and test its responses.
To access the chat on an HTML page, you can include the Rasa Chat Widget code in your HTML file. Create a new index.html
file in the main folder and add the following content:
֫<!DOCTYPE html>
<html>
<head>
<style>
body {
padding: 0;
width: 100vw;
height: 100vh;
margin: 0;
background-image: url('https://www.w3schools.com/w3images/ocean.jpg');
background-size: contain;
}
</style>
</head>
<body>
<div
id="rasa-chat-widget"
data-websocket-url="http://localhost:5005/"
data-height=475>
</div>
<script src="https://unpkg.com/@rasahq/rasa-chat" type="application/javascript"></script>
</body>
</html>
The code creates a div element with the id “rasa-chat-widget” and specifies the URL of the Rasa server using the data-websocket-url attribute. You can also adjust the chat window’s height by changing the data-height attribute’s value. Finally, we can test the bot using the REST API by running the following command:
֫rasa run -m models --enable-api --cors "*"
This will start the Rasa server, and we can send HTTP requests to the server to interact with the bot.
Once the index.html
is included, you can access the chat widget by opening the HTML file in a web browser. The chat widget should appear as a window on the bottom right corner of the page.
If you have deployed the chatbot on a server and want to access it via requests, you can use the requests
library in Python.
First, you need to specify the URL of the Rasa server using the rasa_url
variable. Then, you can create a dictionary containing the message information with the keys “sender” and “message”.
Finally, you can use the requests.post()
method to send a POST request to the Rasa server with the message information and headers containing the content type and accept type.
The server will then return a response, which you can print out as a JSON object using response.json()
. In the example code you provided, the message
variable contains a test message “hello” sent by a user with ID “test”.
import requestsrasa_url = 'http:/localhost:5005/webhooks/rest/webhook'
header = {'Content-Type': 'application/json',
'Accept': 'application/json'}
message = {'sender': 'test',
'message': 'hello'}
response = request.post(rasa_url, header, message)
print(response.json())
Conclusion
In this guide, we have covered the basics of Rasa, Google sheets, and ChatGPT integration, including setting up a Rasa project, defining intents, entities, and responses, training the language model, and implementing ChatGPT to provide more sophisticated responses. By following the steps outlined in this guide, anyone can develop their own advanced chatbot.
As AI technology continues to evolve, the possibilities for chatbots are endless. In the future, we can expect to see chatbots with more advanced natural language processing capabilities, as well as the ability to understand emotions and respond accordingly. The use of AI chatbots is also likely to expand into new industries, such as healthcare and finance, providing even more benefits to businesses and their customers.
If you’re interested in developing your own advanced chatbot, I encourage you to explore Rasa, ChatGPT, and other AI tools and technologies.
By doing so, you can create a chatbot that not only provides excellent customer service but also sets your business apart from the competition.