How to Build an AI Chatbot with a Chatbot API
![Maxwell Timothy](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fi6kpkyc7%2Fprod-dataset%2F2b822f2dbe4c7fcf222ceacd266b7871b1af2ca9-512x512.png&w=64&q=75&dpl=dpl_BMTcHdiw8bsSqPfUjghTawCD9Yv2)
Maxwell Timothy
on Jul 21, 202414 min read
Ever dreamt of building your very own ChatGPT-styled chatbot? Something that is trained on your own data, maybe your business data or unique data of any kind. You know, like a Custom GPT, but much more advanced, such that you can use it on your own website.
How did you find the whole process? A bit overwhelming, huh? Trust me, you're not alone. To build an AI chatbot like that, one of the first places to look would be OpenAI's ChatGPT API. Unfortunately, the ChatGPT API can be a bit tough to deal with if you are building a complex chatbot.
Don’t get this wrong—the default ChatGPT API is a powerhouse, no doubt, but let’s be real—navigating its complexities can be a pain, especially when your goal is to build a chatbot that dances to your own tune.
Picture this. You're a developer with a tight deadline. Your project lead has just tasked you with creating an AI-powered chatbot, and time is of the essence. Or perhaps you're a techie that's looking for a custom chatbot solution that is easy to implement and maintain. You know the drill—tweaking parameters, debugging code, and pulling your hair out over documentation. Getting everything to click just right isn't exactly a walk in the park.
But what if I told you there's a way to bypass all these headaches? In this guide, we’re going to demystify the process and show you how to harness the ChatGPT API through Chatbase. We'll break it down into bite-sized steps, making it ridiculously easy to implement a RAG-style system and build an AI chatbot with your own data that’s ready to roll in just 10 minutes.
But before we continue, let’s set the expectations straight….
At the end of this article, you’ll be able to create a powerful AI chatbot using:
- A GUI interface via Chatbase’s no-code chatbot builder
- Build your chatbot from scratch by writing your own code using any programming language of your choice, so you can customize the chatbot and have granular control of how it works.
Sounds like what you want to do? Yes? Then let’s get going.
What You’ll Need to Get Started
With a Chatbase account, you’ll need very little else to get started. Chatbase does most of the heavy lifting, so you can focus on customizing your AI chatbot in the way you want it.
To get started:
1. Head over to Chatbase.co and sign up for a free account.
2. After signing up, log into your account and you’ll be redirected to the bot creator page where you’ll be able to create your first chatbot.
3. To create your chatbot, you’ll need to provide the data you want to train your chatbot with.
This can be anything from text files and word documents to PDFs. You can also provide your website URL and let Chatbase crawl it and extract all the relevant information. You can also link your Notion account and let Chatbase train your chatbot on your Notion files. The variety of training data sources available on Chatbase ensures you can easily incorporate your information, regardless of its format or source.
For more information on how to train your new chatbot, check out our guide on How to train a chatbot on your data.
Interacting with Your Chatbot
To demonstrate how to use your trained chatbot via the Chatbase API, we’ll create a simple chatbot for an imaginary institution called “New Age World” University. In the training phase above, we train the chatbot with PDF files containing fake data about the imaginary university.
You can use any programming language of your choice to make API calls to Chatbase’s API. For this demo, we'll use JavaScript for API calls, along with HTML and CSS for a functional GUI.
Before we start coding, make sure you have:
- A Chatbase account
- Your API key
To try out training your first chatbot, you can create a free Chatbase account, train a chatbot and even embed it using Chatbase’s default embed code absolutely free of charge!
But to take things further, take total control of your chatbot and have access to the API, you’ll need to upgrade to a paid plan. But don’t worry, Chatbase premium plans start as low as $19 per month and you can get a discount if you sign up for a yearly plan.
Once you are on a premium plan, sign in and grab your Chatbase API Key.
To find your API key:
- Navigate to the Dashboard.
- Click Settings at the top of your dashboard.
- Click API Keys on the left sidebar of the page.
- Click on Create API Key to create an API key.
- Copy the generated API key.
With your API key in hand, we are ready to build our first ChatGPT-style chatbot using the Chatbase API.
1. Setting Up the HTML Structure
Start by creating a simple HTML structure to hold our chatbot interface. We'll include an input field for the user to type their messages, a button to send the messages, and a container to display the chat messages.
chatbot.html
1<!DOCTYPE html>2<html lang="en">3<head>4 <meta charset="UTF-8">5 <meta name="viewport" content="width=device-width, initial-scale=1.0">6 <title>Sample Chatbase Chatbot</title>7 <link rel="stylesheet" href="styles.css">8</head>9<body>10 <!-- Chat container that holds the entire chatbot UI -->11 <div class="chat-container">12 <!-- Chatbot header -->13 <h1>NawBot</h1>14 <!-- Chat window where messages will be displayed -->15 <div class="chat-window" id="chat-window">16 <div class="chat-message bot-message">Hi! What can I help you with?</div>17 </div>18 <!-- Input area for sending messages -->19 <div class="chat-input">20 <input type="text" id="message" placeholder="Message..." />21 <button onclick="sendMessage()">22 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-send">23 <line x1="22" y1="2" x2="11" y2="13"></line>24 <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>25 </svg>26 </button>27 </div>28 </div>29 <script src="chatbot.js"></script>30</body>31</html>32
2. Styling the Chatbot Interface
Next, we add CSS to style our chatbot interface. This includes making the chat window scrollable and styling the messages to look like chat bubbles.
styles.css
1/* General styles */2body {3 font-family: Arial, sans-serif;4 background-color: #f5f5f5;5 display: flex;6 justify-content: center;7 align-items: center;8 height: 100vh;9 margin: 0;10}1112/* Chat container styling */13.chat-container {14 width: 400px;15 max-width: 90%;16 background: white;17 border-radius: 8px;18 box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);19 overflow: hidden;20 display: flex;21 flex-direction: column;22}2324/* Chatbot header styling */25h1 {26 background: #a04bd1;27 color: white;28 padding: 10px;29 text-align: center;30 margin: 0;31}3233/* Chat window styling */34.chat-window {35 padding: 10px;36 flex-grow: 1;37 overflow-y: auto;38 border-bottom: 1px solid #ddd;39 display: flex;40 flex-direction: column;41 max-height: 400px; /* Fixed height to make it scrollable */42}4344/* Message bubble styling */45.chat-message {46 padding: 10px;47 margin: 10px 0;48 border-radius: 20px;49 max-width: 70%;50 word-wrap: break-word;51 display: inline-block;52}5354/* Bot message styling */55.bot-message {56 background: #f0f0f0;57 align-self: flex-start;58 border-radius: 20px 20px 20px 0;59}6061/* User message styling */62.user-message {63 background: #a04bd1;64 color: white;65 align-self: flex-end;66 border-radius: 20px 20px 0 20px;67}6869/* Input area styling */70.chat-input {71 display: flex;72 border-top: 1px solid #ddd;73 padding: 10px;74 align-items: center;75}7677/* Input field styling */78.chat-input input {79 flex-grow: 1;80 padding: 10px;81 border: none;82 border-radius: 20px;83 outline: none;84 background: #f5f5f5;85 margin-right: 10px;86}8788/* Placeholder text styling */89.chat-input input::placeholder {90 color: #aaa;91}9293/* Send button styling */94.chat-input button {95 background: none;96 border: none;97 cursor: pointer;98 padding: 10px;99 color: #a04bd1;100}101102/* Send button hover effect */103.chat-input button:hover {104 color: #ff00c3;105}106107/* Remove focus outline from button */108.chat-input button:focus {109 outline: none;110}111
3. Implementing the Chatbot Logic with JavaScript
Here, we’ll implement the JavaScript to handle sending messages to the Chatbase API and displaying the responses.
Before we dive into the JavaScript code, you can read up on the Chatbase API documentation to get acquainted with the Chatbase API. The API allows you to interact with your chatbots programmatically. Some endpoints let you create, update, message, and delete your chatbot. However, it's easier to create and train our chatbot using the chatbase GUI chatbot builder. We can then use the API to message our chatbot and get it responses.
To message a chatbot, the main endpoint is:
`POST https://www.chatbase.co/api/v1/chat`
You’ll need to include the following headers in your request:
- Authorization: Bearer <Your-Secret-Key> - for authenticating the API request.
- Content-Type: application/json - specifies the request payload format.
Your request body should contain:
- messages: An array of messages between the user and the assistant, with content and role fields.
- chatbotId: The ID of the chatbot you’re interacting with.
- stream (optional): If true, streams back partial progress.
- temperature (optional): Controls response randomness (0-1 scale).
- conversationId (optional): An ID to save the conversation to the dashboard.
- model (optional): Specify the model (e.g gpt-4-turbo or gpt-4o, defaults to gpt-4o).
To find your Chatbot ID:
- Navigate to the Dashboard.
- Click on the chatbot you want to message.
- Click Settings at the top of the page.
- Copy the chatbot ID.
Putting everything together, we can then make a call and use the response in our simple chatbot application. Here's the JavaScript code:
chatbot.js
1// Define API key and chatbot ID2const apiKey = '43753f0b-431a-4b1c-xxxxxxx-xxxxx';3const chatbotId = '_8PrL19i1s2zxxxxxxxx';45// Function to send a message to the chatbot6async function sendMessage() {7 const messageInput = document.getElementById('message');8 const message = messageInput.value;9 const chatWindow = document.getElementById('chat-window');1011 // Check if the input message is empty12 if (message.trim() === '') return;1314 // Create a div element for user message and append it to the chat window15 const userMessageDiv = document.createElement('div');16 userMessageDiv.classList.add('chat-message', 'user-message');17 userMessageDiv.innerText = message;18 chatWindow.appendChild(userMessageDiv);19 chatWindow.scrollTop = chatWindow.scrollHeight;2021 // Clear the input field after sending the message22 messageInput.value = '';2324 // Create a placeholder for the bot message25 const botMessageDiv = document.createElement('div');26 botMessageDiv.classList.add('chat-message', 'bot-message');27 chatWindow.appendChild(botMessageDiv);28 chatWindow.scrollTop = chatWindow.scrollHeight;2930 try {31 // Send the message to the chatbot API32 const response = await fetch('https://www.chatbase.co/api/v1/chat', {33 method: 'POST',34 headers: {35 'Authorization': `Bearer ${apiKey}`,36 'Content-Type': 'application/json',37 },38 body: JSON.stringify({39 messages: [40 { content: message, role: 'user' },41 ],42 chatbotId: chatbotId,43 stream: true,44 temperature: 0.5,45 model: 'gpt-4o',46 }),47 });4849 // Check if the response is OK50 if (!response.ok) {51 const errorData = await response.json();52 throw new Error(errorData.message);53 }5455 // Read the response stream and decode the text56 const reader = response.body.getReader();57 const decoder = new TextDecoder();58 let botMessage = '';5960 // Function to read the stream data61 function read() {62 reader.read().then(({ done, value }) => {63 if (done) {64 return;65 }6667 // Append the decoded text to the bot message and update the chat window68 botMessage += decoder.decode(value);69 botMessageDiv.innerText = botMessage;70 chatWindow.scrollTop = chatWindow.scrollHeight;71 read();72 });73 }7475 // Start reading the stream data76 read();77 } catch (error) {78 console.error('Error sending message to chatbot:', error);79 }80}8182// Add an event listener to send the message when the Enter key is pressed83document.getElementById('message').addEventListener('keypress', function (e) {84 if (e.key === 'Enter') {85 sendMessage();86 }87});88
This code demonstrates how to interact with the Chatbase API to send and receive messages from your chatbot, whether in a single response or as a stream of partial responses. It provides a foundation for building more complex chatbot interactions.