How to Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API

1. Sign up for a ChatGPT account.

2. Create a new project and select the “Custom Knowledge Base” option.

3. Upload your custom knowledge base to the project.

4. Train the AI chatbot using the ChatGPT API.

5. Test the AI chatbot with sample conversations.

6. Monitor the performance of the AI chatbot and make adjustments as needed.

7. Deploy the AI chatbot to your website or application.

In our earlier article, we demonstrated how to build an AI chatbot with the ChatGPT API and assign a role to personalize it. But what if you want to train the AI on your own data? For example, you may have a book, financial data, or a large set of databases, and you wish to search them with ease. In this article, we bring you an easy-to-follow tutorial on how to train an AI chatbot with your custom knowledge base with LangChain and ChatGPT API. We are deploying LangChain, GPT Index, and other powerful libraries to train the AI chatbot using OpenAI’s Large Language Model (LLM). So on that note, let’s check out how to train and create an AI Chatbot using your own dataset.

Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API, LangChain, and GPT Index (2023)

In this article, we have explained the steps to teach the AI chatbot with your own data in greater detail. From setting up tools and software to training the AI model, we have included all the instructions in an easy-to-understand language. It is highly recommended to follow the instructions from top to down without skipping any part.

Note: The tutorial has been updated with bug fixes on April 6. Now, you should not get “BaseGPTIndex” or “llm_predictor” error while running the code.

Notable Points Before You Train AI with Your Own Data

1. You can train the AI chatbot on any platform, whether Windows, macOS, Linux, or ChromeOS. In this article, I’m using Windows 11, but the steps are nearly identical for other platforms.

2. The guide is meant for general users, and the instructions are explained in simple language. So even if you have a cursory knowledge of computers and don’t know how to code, you can easily train and create a Q&A AI chatbot in a few minutes. If you followed our previous ChatGPT bot article, it would be even easier to understand the process.

3. Since we are going to train an AI Chatbot based on our own data, it’s recommended to use a capable computer with a good CPU and GPU. However, you can use any low-end computer for testing purposes, and it will work without any issues. I used a Chromebook to train the AI model using a book with 100 pages (~100MB). However, if you want to train a large set of data running into thousands of pages, it’s strongly recommended to use a powerful computer.

4. Finally, the data set should be in English to get the best results, but according to OpenAI, it will also work with popular international languages like French, Spanish, German, etc. So go ahead and give it a try in your own language.

Set Up the Software Environment to Train an AI Chatbot

Like our previous article, you should know that Python and Pip must be installed along with several libraries. In this article, we will set up everything from scratch so new users can also understand the setup process. To give you a brief idea, we will install Python and Pip. After that, we will install Python libraries, which include OpenAI, GPT Index, Gradio, and PyPDF2. Along the process, you will learn what each library does. Again, do not fret over the installation process, it’s pretty straightforward. On that note, let’s jump right in.

Install Python

1. First off, you need to install Python (Pip) on your computer. Open this link and download the setup file for your platform.

Set Up the Software Environment to Train an AI Chatbot

2. Next, run the setup file and make sure to enable the checkbox for “Add Python.exe to PATH.” This is an extremely important step. After that, click on “Install Now” and follow the usual steps to install Python.

Set Up the Software Environment to Train an AI Chatbot

3. To check if Python is properly installed, open the Terminal on your computer. I’m using Windows Terminal on Windows, but you can also use Command Prompt. Once here, run the below command below, and it will output the Python version. On Linux and macOS, you may have to use python3 --version instead of python --version.

python --version
Set Up the Software Environment to Train an AI Chatbot

Upgrade Pip

When you install Python, Pip is installed simultaneously on your system. So let’s upgrade it to the latest version. For those who are unaware, Pip is the package manager for Python. Basically, it lets you install thousands of Python libraries from the Terminal. With Pip, we can install OpenAI, gpt_index, gradio, and PyPDF2 libraries. Here are the steps to follow.

1. Open the Terminal of your choice on your computer. I’m using the Windows Terminal, but you can also use Command Prompt. Now, run the below command to update Pip. Again, you may have to use python3 and pip3 on Linux and macOS.

python -m pip install -U pip
Set Up the Software Environment to Train an AI Chatbot

2. To check if Pip was properly installed, run the below command. It will output the version number. If you get any errors, follow our dedicated guide on how to install Pip on Windows to fix PATH-related issues.

pip --version
Set Up the Software Environment to Train an AI Chatbot

Install OpenAI, GPT Index, PyPDF2, and Gradio Libraries

Once we have set up Python and Pip, it’s time to install the essential libraries that will help us train an AI chatbot with a custom knowledge base. Here are the steps to follow.

1. Open the Terminal and run the below command to install the OpenAI library. We will use it as the LLM (Large language model) to train and create an AI chatbot. And we will also import the LangChain framework from OpenAI. Note that, Linux and macOS users may have to use pip3 instead of pip.

pip install openai
Install OpenAI, GPT Index, PyPDF2, and Gradio Libraries

2. Next, let’s install GPT Index, which is also called LlamaIndex. It allows the LLM to connect to the external data that is our knowledge base. Here, we are installing an older version of gpt_index which is compatible with my code below. This will ensure that you don’t get any errors while running the code. If you have already installed gpt_index, run the below command again and it will override the latest one.

pip install gpt_index==0.4.24
How to Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API

3. After that, install PyPDF2 to parse PDF files. If you want to feed your data in PDF format, this library will help the program read the data effortlessly. Apart from that, install PyCryptodome by running the below command. This is again done to avoid any errors while parsing PDF files.

pip install PyPDF2
pip install PyCryptodome

4. Finally, install the Gradio library. This is meant for creating a simple UI to interact with the trained AI chatbot. We are now done installing all the required libraries to train an AI chatbot.

pip install gradio
How to Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API

Download a Code Editor

Finally, we need a code editor to edit some of the code. On Windows, I would recommend Notepad++ (Download). Simply download and install the program via the attached link. You can also use VS Code on any platform if you are comfortable with powerful IDEs. Other than VS Code, you can install Sublime Text (Download) on macOS and Linux.

For ChromeOS, you can use the excellent Caret app (Download) to edit the code. We are almost done setting up the software environment, and it’s time to get the OpenAI API key.

Download a Code Editor

Get the OpenAI API Key For Free

Now, to train and create an AI chatbot based on a custom knowledge base, we need to get an API key from OpenAI. The API key will allow you to use OpenAI’s model as the LLM to study your custom data and draw inferences. Currently, OpenAI is offering free API keys with $5 worth of free credit for the first three months to new users. If you created your OpenAI account earlier, you may have free $18 credit in your account. After the free credit is exhausted, you will have to pay for the API access. But for now, it’s available to all users for free.

1. Head to platform.openai.com/signup and create a free account. If you already have an OpenAI account, simply log in.

Get the OpenAI API Key For Free

2. Next, click on your profile in the top-right corner and select “View API keys” from the drop-down menu.

Get the OpenAI API Key For Free

3. Here, click on “Create new secret key” and copy the API key. Do note that you can’t copy or view the entire API key later on. So it’s strongly recommended to copy and paste the API key to a Notepad file immediately.

Get the OpenAI API Key For Free

4. Next, go to platform.openai.com/account/usage and check if you have enough credit left. If you have exhausted all your free credit, you can buy the OpenAI API from here. In case, you want to get more free credits, you can create a new OpenAI account with a new mobile number and get free API access ( up to $5 worth of free tokens). This will prevent you from facing Error 429 (You exceeded your current quota, please check your plan and billing details) while running the code.

How to Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API

5. Lastly, do not share or display the API key in public. It’s a private key meant only for access to your account. You can also delete API keys and create multiple private keys (up to five).

Train and Create an AI Chatbot With Custom Knowledge Base

Now that we have set up the software environment and got the API key from OpenAI, let’s train the AI chatbot. Here, we will use the “gpt-3.5-turbo” model because it’s cheaper and faster than other models. If you want to use the latest “gpt-4” model, you must have access to the GPT 4 API which you get by joining the waitlist here. With that out of the way, let’s jump to the instructions.

Add Your Documents to Train the AI Chatbot

1. First, create a new folder called docs in an accessible location like the Desktop. You can choose another location as well according to your preference. However, keep the folder name docs.

Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API, LangChain, and GPT Index (2023)

2. Next, move the documents you wish to use for training the AI inside the “docs” folder. You can add multiple text or PDF files (even scanned ones). If you have a large table in Excel, you can import it as a CSV or PDF file and then add it to the “docs” folder. You can even add SQL database files, as explained in this Langchain AI tweet. I haven’t tried many file formats besides the mentioned ones, but you can add and check on your own. For this article, I am adding one of my articles on NFT in PDF format.

Note: If you have a large document, it will take a longer time to process the data, depending on your CPU and GPU. In addition, it will quickly use your free OpenAI tokens. So in the beginning, start with a small document (30-50 pages or < 100MB files) to understand the process.

Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API, LangChain, and GPT Index (2023)

Make the Code Ready

1. Now, launch Notepad++ (or your choice of code editor) and paste the below code into a new file. Once again, I have taken great help from armrrs on Google Colab and tweaked the code to make it compatible with PDF files and create a Gradio interface on top.

from gpt_index import SimpleDirectoryReader, GPTListIndex, GPTSimpleVectorIndex, LLMPredictor, PromptHelper
from langchain.chat_models import ChatOpenAI
import gradio as gr
import sys
import os

os.environ["OPENAI_API_KEY"] = 'Your API Key'

def construct_index(directory_path):
    max_input_size = 4096
    num_outputs = 512
    max_chunk_overlap = 20
    chunk_size_limit = 600

    prompt_helper = PromptHelper(max_input_size, num_outputs, max_chunk_overlap, chunk_size_limit=chunk_size_limit)

    llm_predictor = LLMPredictor(llm=ChatOpenAI(temperature=0.7, model_name="gpt-3.5-turbo", max_tokens=num_outputs))

    documents = SimpleDirectoryReader(directory_path).load_data()

    index = GPTSimpleVectorIndex(documents, llm_predictor=llm_predictor, prompt_helper=prompt_helper)

    index.save_to_disk('index.json')

    return index

def chatbot(input_text):
    index = GPTSimpleVectorIndex.load_from_disk('index.json')
    response = index.query(input_text, response_mode="compact")
    return response.response

iface = gr.Interface(fn=chatbot,
                     inputs=gr.components.Textbox(lines=7, label="Enter your text"),
                     outputs="text",
                     title="Custom-trained AI Chatbot")

index = construct_index("docs")
iface.launch(share=True)

2. This is what the code looks like in the code editor.

Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API, LangChain, and GPT Index (2023)

3. Next, click on “File” in the top menu and select “Save As…” from the drop-down menu.

Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API, LangChain, and GPT Index (2023)

4. After that, set the file name app.py and change the “Save as type” to “All types” from the drop-down menu. Then, save the file to the location where you created the “docs” folder (in my case, it’s the Desktop). You can change the name to your liking, but make sure .py is appended.

How to Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API

5. Make sure the “docs” folder and “app.py” are in the same location, as shown in the screenshot below. The “app.py” file will be outside the “docs” folder and not inside.

Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API, LangChain, and GPT Index (2023)

6. Come back to the code again in Notepad++. Here, replace Your API Key with the one generated on OpenAI’s website above.

Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API, LangChain, and GPT Index (2023)

7. Finally, press “Ctrl + S” to save the code. You are now ready to run the code.

Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API, LangChain, and GPT Index (2023)

Create ChatGPT AI Bot with Custom Knowledge Base

1. First, open the Terminal and run the below command to move to the Desktop. It’s where I saved the “docs” folder and “app.py” file. If you saved both items in another location, move to that location via the Terminal.

cd Desktop
Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API, LangChain, and GPT Index (2023)

2. Now, run the below command. Linux and macOS users may have to use python3.

python app.py
Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API, LangChain, and GPT Index (2023)

3. Now, it will start analyzing the document using the OpenAI LLM model and start indexing the information. Depending on the file size and your computer’s capability, it will take some time to process the document. Once it’s done, an “index.json” file will be created on the Desktop. If the Terminal is not showing any output, do not worry, it might still be processing the data. For your information, it takes around 10 seconds to process a 30MB document.

Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API, LangChain, and GPT Index (2023)

4. Once the LLM has processed the data, you will find a local URL. Copy it.

How to Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API

5. Now, paste the copied URL into the web browser, and there you have it. Your custom-trained ChatGPT-powered AI chatbot is ready. To start, you can ask the AI chatbot what the document is about.

Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API, LangChain, and GPT Index (2023)

6. You can ask further questions, and the ChatGPT bot will answer from the data you provided to the AI. So this is how you can build a custom-trained AI chatbot with your own dataset. You can now train and create an AI chatbot based on any kind of information you want. The possibilities are endless.

7. You can also copy the public URL and share it with your friends and family. The link will be live for 72 hours, but you also need to keep your computer turned on since the server instance is running on your computer.

8. To stop the custom-trained AI chatbot, press “Ctrl + C” in the Terminal window. If it does not work, press “Ctrl + C” again.

How to Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API

9. To restart the AI chatbot server, simply move to the Desktop location again and run the below command. Keep in mind, the local URL will be the same, but the public URL will change after every server restart.

python app.py
Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API, LangChain, and GPT Index (2023)

10. If you want to train the AI chatbot with new data, delete the files inside the “docs” folder and add new ones. You can also add multiple files, but make sure to feed clean data to get a coherent response.

Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API, LangChain, and GPT Index (2023)

11. Now, run the code again in the Terminal, and it will create a new “index.json” file. Here, the old “index.json” file will be replaced automatically.

python app.py
Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API, LangChain, and GPT Index (2023)

12. To keep track of your tokens, head over to OpenAI’s online dashboard and check how much free credit is left.

Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API, LangChain, and GPT Index (2023)

13. Lastly, you don’t need to touch the code unless you want to change the API key or the OpenAI model for further customization.

Build a Custom AI Chatbot Using Your Own Data

So this is how you can train an AI chatbot with a custom knowledge base. I have used this code to train the AI on medical books, articles, data tables, and reports from old archives, and it has worked flawlessly. So go ahead and create your own AI chatbot using OpenAI’s Large Language Model and ChatGPY. Anyway, that is all from us. If you are looking for the best ChatGPT alternatives, head to our linked article. And to use ChatGPT on your Apple Watch, follow our in-depth tutorial. Finally, if you are facing any kind of issues, do let us know in the comment section below. We will definitely try to help you out.



How to Train an AI Chatbot With Custom Knowledge Base Using ChatGPT API

ChatGPT is an AI-powered chatbot platform that enables developers to create custom knowledge bases for their chatbot. With ChatGPT, developers can easily create a custom knowledge base for their chatbot, which can be used to train the chatbot to respond to user queries. In this tutorial, we will show you how to use the ChatGPT API to train an AI chatbot with a custom knowledge base.

Step 1: Create a Knowledge Base

The first step is to create a knowledge base for your chatbot. This knowledge base should contain all the information that your chatbot needs to respond to user queries. You can create a knowledge base using the ChatGPT API or by manually entering the information into the platform.

Step 2: Train the Chatbot

Once you have created the knowledge base, you can start training the chatbot. To do this, you will need to provide the chatbot with examples of conversations that it should be able to respond to. You can provide these examples by manually entering them into the platform or by using the ChatGPT API.

Step 3: Test the Chatbot

Once you have trained the chatbot, you can test it to see how well it responds to user queries. You can do this by manually entering queries into the platform or by using the ChatGPT API. Once you have tested the chatbot, you can make any necessary adjustments to the knowledge base or the training data.

Step 4: Deploy the Chatbot

Once you have tested and adjusted the chatbot, you can deploy it to your website or application. You can do this by using the ChatGPT API or by manually entering the necessary information into the platform.

Conclusion

In this tutorial, we have shown you how to use the ChatGPT API to train an AI chatbot with a custom knowledge base. We have also shown you how to test and deploy the chatbot. With the ChatGPT API, you can easily create a custom knowledge base for your chatbot and train it to respond to user queries.

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?