Building your own A.I. Chatbot

46elks
13 min readOct 11, 2023

Today we are going to be creating an A.I.-powered chatbot that you can use for numerous purposes

You can implement it on your website as a virtual assistant for your product/service or you can implement it on your business Whatsapp for Airbnb business (+ any other services that are in need of guidance).

Tools we are going to be using are:

  • Botpress (Free up to 1K monthly messages — should be enough for most small/medium businesses)
  • Stack AI (Free up to 100 runs per month — we can work without this one if paid structure for your business is not an option)
  • 46elks (We will need the phone number to connect to our Whatsapp business account)
  • Meta Developer (Whatsapp integration)
  • Meta Business (Permanent access token)

Here is the final product we will get: A.I. Chatbot (this one is a bit modified and few questions added but with same principles used in this tutorial)

Let’s start.

Setting up the bot

First of all, navigate to the Botpress site and create a free account.

You should have something like this:

Click on the “Create chatbot” on the left-hand side of the navigation.

Once that is done, click edit and go ahead and choose Start from the template option. (Choose “Basic (empty)”)

For this example, I am going to be creating a “Talk to the God” chat since this will allow me to demonstrate all of the functions you need to create a successful A.I. Chatbot.

Understanding the node structure

The whole principle of Botpress works around nodes and nodes are always read from top to bottom.

What does that mean?

In the picture above you can see that the first node is “Start” and is directed toward the next node called “Hello” (btw., always name your nodes!).

In the node “Hello” information is read from top to bottom. So if the top event (action) is true it continues to the next event and so on.

In this tutorial, we are going to start off with a basic node structure where the user picks an option and is directed to the node based on the choice. At one point we are going to be using a Knowledge base and A.I. to power up this system and gain more leverage in response.

Building the Bot

Go ahead and right-click on empty space and choose “Standard node”.

Connect “Start” and your first node by dragging from one circle to the other at the end and beginning of the node.

On the left-hand side, you can hover over cards to find the ones we will be using.

Choose “Text” and drag and drop it to the new node you created (and labeled!).

Add the text you want your bot to start with.

Add one more of those “Text” cards if you want to send multiple messages.

Next, we are going to be using capture cards. That means information that is chosen (or written) is stored in our database to be used for future references.

Choose a “Single Choice” capture card and add choices to your bot.

In this example, we are going to go with 2 choices only (but this can be more complex, based on your need).

By choosing “Advanced Configuration” go with the “Choice” option.

Add 2 items, in this example “To know” and “Not to know”.

The most important thing here is to create a variable in which we store the info.

Select/Create a variable and enter “choices”. Hit create “choices” and the variable “workflow.choices” will be created. (note that the name depends on you, it does not matter as long as you know what you are writing)

From two choices on our first node you have 2 circles which you can pull to the side and a new node will be created.

We won’t be using those because with more complex situations we would have a mess of nodes and it would be hard to navigate.

I am going to show you how to use simple .js code which you can use to answer multiple choices in one node.

Navigate to the cards section and choose “Flow logic” -> Expression.

As we mentioned before nodes are read from top to bottom. So if choices are not leading to any node it will skip that and lead to the Expression.

The Expression is configured automatically and from there, you can just pull the little circle to create a single node (rather than 2 nodes as we would need before).

In the cards section select “Execute code” and add it to the new node.

This is the piece of code we need to execute the answer based on the choice the user made.

// Check if the choices variable is 'To know'
if (workflow.choices === 'To know') {
// Create a new message in the workflow with the given text
workflow.nextMsg += 'Life and Death are same motion.'
}
// Check if the choices variable is 'Not to know'
else if (workflow.choices === 'Not to know') {
// Create a new message in the workflow with the given text
workflow.nextMsg += 'To Die is to Live!'
}// Check if the choices variable is ‘To know’

So what’s going on in the code?

We are using if/else if command to call the variable we created (workflow.choices) to generate an appropriate response.

If the customer chooses “To know” we are going to display one type of msg, if the customer chooses “Not to know” we are going to be displaying different msg.

One more thing, as you see we are using one more variable (workflow.nextMsg). This variable will help us to send specific msg to the customer based on the choice they made.

So go ahead and create a new variable on the left-hand side of the menu.

Name that variable @workflow.nextMsg.

Next, add a normal “Text” card but this time write @nextMsg to the field. This simply means the variable from the code will be executed and sent to the customer.

Through this, we saved time and space (and our nerves) in trying to figure out which node is what 😀.

We are going to finish this node with one more Expression node and redirect that node to the new standard node.

Adding A.I. to the workflow

Okay, you should have a basic idea of how this works.

In this section, I am going to show you how to create a Knowledge base, and if no info is found in the Knowledge base we are going to be using StackAI to pull up ChatGPT and answer the question in a specific format.

Select the AInode we just created and enable the Knowledge base.

You should have a book icon on that node if you did everything correctly.

On the left-hand side of the menu, you have an option to add your own Knowledge base.

This can be a website of your business (or any other website) or it can be a .doc, .pdf, or .excel file with all the information you usually provide to the customers.

For this one, I went with “Text Document” to demonstrate in simple terms.

But let’s start the node workflow with a “Text” card so we can let our customers know that they can ask anything.

Also, in the same way as before, we need to store that input info into a variable so our friend ChatGPT knows what gets to be answered.

Go ahead and add the capture card “Raw input” + create a new variable workflow.question.

This means our customers will enter anything they want and we will store that info in our database and feed it to the Knowledge base. If we don’t get the answer we will point that same question to StackAI and get the answer from ChatGPT.

In addition to this, we are going to create a loop where after our customers get the answer they will be asked if they want to continue to ask more questions.

Let’s do the node setup first and we can explain everything when we have that ready.

The knowledge base node should look like this:

So we have a “Text” card and a “Raw input” card + we need to add two Expression cards.

If no answer is found in the knowledge base we created it will send our customer to the Stack AI node but if it finds the answer it will skip “No answer from knowledge base” and go to always and redirect the customer to a new node where they will be asked if they want to continue questions.

For the Expression card (no answer from the knowledge base) this is the condition you need to enter:

As for the two extra nodes we created this is how they should look like.

Continue QA:

It is a simple Yes/No single choice option where Yes leads back to the Knowledge base node and No leads to the end of the Chatbot.

Stack AI

Above we can see what the StackAI node structure should look like.

We have “Execute code” which will connect our Stack AI account with Botpress.

Then the variable (response from ChatGPT) and at the end “Expression” leading to the “Continue QA” node.

Before we start with Stack AI just go ahead and create a variable called apiReposne. We will need this to fetch the answer from ChatGPT and send it to our Botpress through the same workflow as before @workflow.apiReposne

Here is the piece of code we are going to be using to execute this task.

// Add your stack AI endpoint URL in place of “YOUR_STACK_AI_ENDPOINT_URL”
const endpoint = "https://www.stack-inference.com/run_deployed_flow?flow_id=64bfd17326bcb58340d45190&org=1838c13c-1e62-4b05-b34d-cbf93473423c"
// Add your stack AI API key in place of "YOUR_API_KEY_HERE"
const headers = {
Authorization: `Bearer YOUR_API_KEY_HERE`,
"Content-Type": "application/json"
}
const data = {
"in-0": workflow.question,
}
try {
const response = await axios.post(endpoint, data, { headers })
workflow.apiResponse = response.data["out-0"]
} catch (error) {
throw new Error(`stack-error: ${error}`)
}

So what does this mean?

We are pulling up our Stack AI flow which we created through the link and connecting into Botpress with API.

“In-0” is our input variable from Botpress (workflow.question) and we are collecting the response into the variable called apiResponse.

Cool right?

Let’s jump to the Stack AI and finish the setup there.

After creating the account go ahead and select New Project and select Document Q&A.

This will create a workflow for us.

Since this will be automatically created for you, here is the breakdown of the flow so you understand what is what.

In-0 is the variable that will come from Botpress and will be sent to ChatGPT.

I used gpt 3.5 turbo since it consumes a lot fewer tokens, meaning more questions for free!

Also, I have provided a simple prompt for ChatGPT so it knows how to act.

Here is the prompt I used:

You are the wise sage. Whatever you are asked, reply in 7 words maximum. Be wise, and use Mooji and Krishnamurti as a reference and their style.

On the bottom, you have Documents + Search. Here you can upload your Knowledge base document (same as in Botpress) but it is not essential.

That’s it for the setup.

Go ahead and hit Publish.

After that, click Export and head down to the APIendpoints.

Copy the APIurl + Barer token and paste it into the code I provided above.

P.s. don’t use the code they provided since it will create conflict inside of Botpress.

That’s it. Your Chatbot is now powered by ChatGPT. Sweet!

Node Structure and Testing

Your final node structure should look like this.

On the right-hand side of the Botpress interface, you have Emulator where you can test out if everything runs smoothly.

Works great!

Botpress has an option to export/import the bots. So here is the Google Drive link for the bot we created so you can import it and explore it. Download link.

You can import the bot once you created your first bot on the left-hand side of the menu.

Go ahead and click “Publish” and we are ready to connect the bot with WhatsApp.

Connecting the bot to WhatsApp

In the main menu of Botpress select the bot you have created and go to the Integrations.

Click on “Browse in Hub” and install WhatsApp.

Before we go to the Meta for Business, we will need a number to use for our Business purposes.

46elks is just the perfect solution for this.

Create an account, add your credits, and buy a number.

You will need to check the verification code from Meta Business later on.

You can do this by navigating to “Logs” and clicking on the received message.

It should look like this.

But more on that later on.

Head to Meta for Developers.

Select Create App and select “Other”

Select an app type -> Business, and add the app name, contact email, and business account.

On the home screen click “Set up” for WhatsApp.

Here you will be asked to connect your WhatsApp with your Meta Business Account.

WhatsApp has 1000 messages for free per month and this should be enough for small/medium businesses.

First off, we need to connect our Chatbot to WhatsApp.

Click on API Setup.

Copy that temporary access token and paste it into Botpress + copy the Phone number ID and do the same.

Click on Configuration.

In the Botpress interface create Verify token name (I just went with “Test Bot”) and copy the given link.

Paste those variables in Meta.

Before saving the webhook in Meta, you need to save the configuration in Botpress.

It should look something like this:

Okay, next off verify and save webhook in Meta.

Perfecto, almost there.

Click on Manage (under webhook fields) and subscribe for the following “messages”

Now is a good time to test the connection.

Go to API Setup in the Meta account and add your number to receive the test.

Click Manage phone number list. Enter your phone number and verify it.

You can click Send message and you should receive the test message following with Botpress first message we created.

The bot should be working if you follow all the instructions.

To finish everything we need to connect our 46elks phone number and go live with the app we created in Meta for devs.

For that, we need to create a Permanent Access token.

Click on My Apps and click on your business name.

Under System users, we need to add new users.

Click add and accept the terms.

The system username can be Chatbot (or whatever you want) and for the system user role choose Admin.

Create a system user.

Click Add Assets -> Select Apps -> Select Created App -> and enable Full control -> Save changes

Select the asset and click Generate Token.

From the list select:

Almost there!

Click Generate token copy that token and enter it into the Botpress Access token.

Now you have a permanent access token (whereas before you only had 23 hours for the test token).

The last thing, connect the business number.

Under API Setup in Meta developer, under step 5. Click add a phone number.

Enter your Business name, web address, and country click next and fill out the rest of the info.

Choose the country of the phone number and enter the number.

Click next and finish off by going to the “Logs” in 46elks dashboard.

Final Thoughts

Wow. This ended up being THE tutorial 😀

I hope you had fun, learned something new, and most of all, see some value in this + see the way to integrate it with your business.

If you have any questions, please feel free to contact me at luka@luminary.hr or reach out to help@46elks.com

Thank you for your time and patience.

--

--

46elks

Telecom infrastructure for web. Built by happy developers in Uppsala, Sweden.