SpaCy Alternatives For Entity Extraction (NER)

spaCy has been a de facto standard for every company willing to launch an entity extraction project for several years. What made spaCy so popular? And are there good spaCy alternatives in 2023 for anyone trying to start an entity extraction project? Let’s discuss these points in this article.

SpaCy For Entity Extraction

The first spaCy version was released in 2015 and it quickly became a standard framework for enterprise grade entity extraction (also known as NER).

If you have a piece of unstructured text (coming from the web for example) and you want to extract structured data from it, like dates, names, places, etc. spaCy is a very good solution.

spaCy is interesting because several pre-trained models are available in around 20 languages (see more here). It means that you do not necessarily have to train your own model for entity extraction. It also means that, if you want to train your own model, you can start from a pre-trained model instead of starting from scratch, which might save you a lot of time.

spaCy is considered as a “production grade” framework because it is very fast, reliable, and comes with a comprehensive documentation.

However if the default entities supported by spaCy pre-trained models are not enough, you will need to work on “data annotation” (also known as “data labelling”) in order to train your own model. This process is extremely time consuming and many enterprise entity extraction projects fail because of this challenge.

Let’s say that you want to extract job titles from a piece of text (from a resume for example, or from a company web page). As spaCy pre-trained models do not support such an entity by default, you will need to teach spaCy how to recognize job titles. You will need to create a training dataset that contains several thousands of job titles extractions examples (and maybe even many more!). You may use a paid annotation software like Prodigy (made by the spaCy team), but it still involves a lot of human work. It is actually quite common to see companies hire a bunch of contractors for several months in order to carry out a data annotation project. Such a job is so repetitive and boring that the resulting datasets often contain a lot of mistakes…

Data Annotation Example

Data Annotation Example

Let’s see which alternative solutions you could try in 2023!

Stanford CoreNLP

The first version of Stanford CoreNLP was released in 2013. It is a Java framework (while spaCy is a Python one) that allows you to perform entity extraction with very good results.

Stanford CoreNLP proposes pre-trained models too, but less than spaCy (see more here).

The accuracy of this framework is similar to spaCy, but it depends on the data you are analyzing. For example Stanford CoreNLP is giving better results on legal data. Also it is worth noting that some entities are addressed slightly differently compared to spaCy (this is the case of the GPE entity for example).

When it comes to performance, Stanford clearly seems slower than spaCy, which might be a problem if you are trying to reach a very high throughput.

Flair

Flair is a more recent Python framework (released in 2018) based on the PyTorch deep learning framework.

It is gaining a lot of popularity because it reaches a higher accuracy in many languages compared to spaCy. Several pre-trained models are proposed (see more here).

However this accuracy improvement comes at the cost of speed. Your throughput will be much lower compared to spaCy.

Generative AI Models (GPT-J, GPT-3…)

A couple of years ago, a new sort of AI models started to appear: generative models. These models were initially created for text generation (writing the beginning of a piece of text and letting the model generate the rest) but people quickly realized that these models were very good at all sorts of natural language processing use cases, including entity extraction.

The most popular generative models today are GPT-3, GPT-J, GPT-NeoX, T5, and Bloom. All these deep learning models use the Transformer architecture, invented by Google in 2017.

This new generation of AI model is very heavy and expensive to run. They usually require high-end hardware based on one or several GPUs. Also they are slower than frameworks like spaCy. But thanks to these models it is now possible to extract any kind of entity without training a dedicated model!

Extracting any entity without creating a dedicated model is possible thanks to few-shot learning. This technique is about quickly showing the model what you want to do by only making a couple of examples at runtime.

Getting back to my job titles extraction example, if you want to extract job titles with a model like GPT-J you will not need to annotate any data. It will then save you weeks or months of human work. And accuracy will most likely be much higher than any entity extraction with spaCy.

Conclusion

spaCy is a great natural language processing framework that is used in production by many companies today for entity extraction tasks.

However, spaCy and alternatives like Stanford CoreNLP or Flair are limited in terms of accuracy, and they require tedious annotation work in order to extract new entities. In 2023 several alternative models based on text generation can be used for entity extraction without any annotation, like GPT-J, GPT-NeoX, GPT-3… These new models will really help more and more companies succeed in their entity extraction projects.

The ChatGPT Open-Source Alternatives

ChatGPT is an advanced chatbot engine, based on the GPT-3 model from OpenAI. There are good open-source alternatives available today like GPT-J, GPT-NeoX, Bloom, and OPT. I will look at these alternatives.

ChatGPT: Features And Pricing

ChatGPT, released in December 2022, is an advanced chatbot engine created by OpenAI. ChatGPT is based on the very popular GPT-3 model, released in 2020. ChatGPT and GPT-3 were trained on huge amounts of data coming from the internet (Wikipedia, blogs, forums…).

What makes ChatGPT so powerful, compared to other traditional engines, is its size. Training such a huge AI model was very expensive, but the result is breathtaking: ChatGPT has a deep knowledge about many topics. For example ChatGPT can generate advanced scientific reports, it can code a whole application for a programmer, it can write news articles… and much more.

Fluency is also a great strength of ChatGPT. This AI model is able to talk very fluently like a human, even in many non English languages.

And last of all, ChatGPT is very good at understanding emotions and adapting its own tone accordingly.

For the moment OpenAI is still beta testing ChatGPT, so they did not announce any pricing for this product. No SLAs have been announced either. So ChatGPT is definitely not a production-ready product for the moment.

Try ChatGPT here!

Generative AI Models: How They Work

ChatGPT is derived from GPT-3, a modern generative AI model based on the Transformer architecture. The transformer architecture is a specific type of neural network invented by Google in 2017. See more here.

Generative AI models are basically good at generating some text based on a specific input. Depending on your input, you can tell your AI model to do various things for you. For example you can ask your model to categorize a piece of text, extract specific entities from a piece of text, summarize large contents, paraphrase some content, answer questions… and of course act as a chatbot.

ChatGPT is a GPT model that has been specifically instructed to behave like a chatbot. In the rest of this article I am going to explore open-source alternatives to ChatGPT. In order to use them in conversational mode you will either need to use few-shot learning for conversational AI or fine-tuning.

GPT-J And GPT-NeoX

GPT-J and GPT-NeoX are 2 open-source AI models created by a collective of researchers called EleutherAI, in 2021 and 2022.

GPT-J has 6 billions parameters, and GPT-NeoX 20B has 20 billions parameters. In comparison, GPT-3 from OpenAI has 175 billions parameters.

These were the 2 first open-source AI models considered as “large language models”, and both gave impressive results. They were very complex and expensive to train. The server costs needed to train these models was in hundreds of thousands of dollars.

These models give very good results. Especially, GPT-J is a very good compromise between size and accuracy.

Use this Github repo to install GPT-J on your own server. In order to install GPT-J you will need a GPU with at least 16G of VRAM.

OPT

OPT was released by Facebook in 2022. See more here.

This is a 175 billions parameters AI model (same size as GPT-3) that also has smaller distilled versions (66 billions, 30 billions, 13 billions, 6.7 billions, 2.7 billions, 1.3 billions, 350 millions, and 125 millions). These distilled versions try to keep decent levels of accuracy despite their smaller sizes. But of course the most impressive results can only be achieved with OPT 175 billions.

You can download the small distilled versions and install them by yourself. However the 175 billion version cannot be downloaded freely: a specific access must be requested and Facebook will only allow you to download and use the model for research purposes.

See the installation instructions here.

Bloom

Bloom is a 175 billion parameters AI model released by BigScience, a collective of researchers associated with the Hugging Face company. See more details here.

Bloom is interesting for 2 reasons.

First, it is a collective effort made by more than 1000 people (researchers, industrials, …) in order to prove that the open-source community is able to create large language models equivalent to GPT-3. It was trained in Paris on the Jean Zay supercomputer, and it cost around 3 millions dollars to train.

Secondly, Bloom is the first true multilingual large language model ever created. It was trained on 46 different languages which makes it very good at generating text in multiple languages.

Bloom has several smaller distilled versions (7 billions parameters, 3 billions parameters, 1 billions parameters, and 560 millions parameters).

Installing the full 175B version is a challenge though as it requires around 350GB of GPU VRAM, which is not something one can easily afford.

Conclusion

ChatGPT is an amazing chatbot engine that is able to answer very advanced questions. This AI engine is actually even more relevant than most humans in many fields.

However, ChatGPT is only a mere demo for the moment, and one has no information about a future pricing or SLA… It is interesting to compare ChatGPT to open-source alternatives: GPT-J, GPT-NeoX, OPT, and Bloom. And no doubt that new open-source AI models are going to be released soon, with even better accuracy.

How To Install And Deploy Whisper, The Best Open-Source Alternative To Google Speech-To-Text

OpenAI Whisper is the best open-source alternative to Google speech-to-text as of today. It works natively in 100 languages (automatically detected), it adds punctuation, and it can even translate the result if needed. In this article I will show you how to install Whisper and deploy it into production.

Google Speech-To-Text

Google’s automatic speech recognition (speech-to-text) API is very popular. This API is able to transcribe audio and video files in 125 languages, and it proposes specific AI models for phone calls transcription, medical transcription, and more.

This API also has nice additional features like content filtering, automatic punctuation (in beta only for the moment), and speaker diarization (in beta too).

Last of all, their API can be installed on premises. But it’s important to note that the on-prem AI model will keep sending data to Google in order to report API usage, which might be a concern from a privacy standpoint.

Google’s pricing is basically $0.006 / 15 seconds for basic speech-to-text, and $0.009 / 15 seconds for specific use cases like video transcription or phone transcription.

Let’s say you want to automatically analyze phone calls made to your support team (in order to later perform sentiment analysis or entity extraction on them for example). If you have 5 support agents spending 4h each per day on the phone with customers, Google’s speech-to-text API will cost you $1,400 per month.

If you are concerned about costs or privacy, you might want to switch to an open-source alternative: OpenAI Whisper.

Whisper: The Best Alternative To Google Speech-To-Text

Whisper is an open-source AI model that has just been released by OpenAI.

OpenAI has a history of open-sourcing great AI projects. For example GPT-2 was developed by OpenAI a couple of years ago. At the time it was the best generative natural language processing model ever created, and it paved the way for much more advanced models like GPT-3, GPT-J, OPT, Bloom… Recently, they also released a nice CUDA programming framework called Triton.

Not all OpenAI’s models have been open-sourced though. Their 2 most exciting models: GPT-3 and DALL-E, are still private models that can only be used through their paid API.

Whisper is taking the speech-to-text ecosystem by storm: it can automatically detect the input language, then transcribe text in around 100 languages, automatically punctuate the result, and even translate the result if needed. Accuracy is very good, and you can apply this model to any kind of input (audio, video, phone calls, medical discussions, etc.).

And of course, another great advantage of Whisper is that you can deploy it by yourself on your own servers, which is great from a privacy standpoint.

Whisper is free of course, but if you want to install it by yourself you will need to spend some human time on it, and pay for the underlying servers and GPUs.

Installing And Deploying OpenAI Whisper

You have 2 options if you want to install and deploy Whisper for the moment. The first one is to use OpenAI’s whisper Python library, and the second one is to use the Hugging Face Transformers implementation of Whisper. Let’s explore both solutions.

Using the whisper Python lib

This solution is the simplest one. You basically need to follow OpenAI’s instructions on the Github repository of the Whisper project.

First install the whisper Python lib:

pip install git+https://github.com/openai/whisper.git

Then install ffmpeg on your system if it is not the case yet:

# on Ubuntu or Debian
sudo apt update && sudo apt install ffmpeg

# on Arch Linux
sudo pacman -S ffmpeg

# on MacOS using Homebrew (https://brew.sh/)
brew install ffmpeg

# on Windows using Chocolatey (https://chocolatey.org/)
choco install ffmpeg

# on Windows using Scoop (https://scoop.sh/)
scoop install ffmpeg

Several flavors of Whisper are available: tiny, base, small, medium, and large. Of course the bigger the better, so if you are looking for state of the art results I recommend the large version. Here is a very simple Python script that opens an mp3 audio file stored on your disk, automatically detects the input language, and transcribes it:

import whisper

model = whisper.load_model("large")
result = model.transcribe("audio.mp3")
print(result["text"])

Simple isn’t it?

Using the Hugging Face implementation

In order to use Hugging Face’s implementation of Whisper you will first need to install HF Transformers, librosa, and Pytorch:

pip install transformers
pip install librosa
pip install torch

You also need to install ffmpeg (see above).

Now, here is a Python script that does transcription in English:

from transformers import WhisperProcessor, WhisperForConditionalGeneration
import librosa

speech, _ = librosa.load("audio.mp3")

processor = WhisperProcessor.from_pretrained("openai/whisper-large")
model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-large")

model.config.forced_decoder_ids = processor.get_decoder_prompt_ids(language = "en", task = "transcribe")
input_features = processor(speech, return_tensors="pt").input_features 
predicted_ids = model.generate(input_features)
transcription = processor.batch_decode(predicted_ids)

print(processor.batch_decode(predicted_ids, skip_special_tokens = True))

There are 2 limitations with this Hugging Face implementation. First you need to manually set the source language (no automatic input language detection is implemented yet). And secondly no automatic chunking is applied, which means that you cannot transcribe content that is larger than 30 seconds…

Maybe these limitations will be solved in future releases?

A nice thing though is that there is a Tensorflow implementation available too, which means that you can use XLA compilation and get much faster response times.

Hardware Requirements

As I showed above, Whisper is fairly easy to install. However it requires advanced hardware. A GPU is recommended if you want to use the large version of the model.

If you use the whisper Python lib (see above) you will need around 10GB of RAM and 11GB of VRAM. It means that in practice you will need a 16GB GPU at least. It could be a NVIDIA Tesla T4 for example, or an NVIDIA A10.

On a Tesla T4, you will transcribe 30 seconds of audio in around 6 seconds.

Performance Considerations

If you want to improve the default performance mentioned above, here are several strategies you can explore:

  • Use a higher end GPU. For example you will get a better response time with GPUs using the Ampere platform like A10, A40, or A100.
  • Work on batch inference in order to improve the throughput
  • Leverage XLA compilation with Tensorflow or Jax
  • Export the model to ONNX or TensorRT, and then serve it through the NVIDIA Triton Inference Server

Conclusion

OpenAI Whisper is a revolution in the speech-to-text world. For the first time, anyone can easily access state-of-the-art automatic speech recognition thanks to this open-source model, which makes Whisper a good alternative to Google speech-to-text API.

Installing and deploying such an AI model is still a challenge though because of the hardware required under the hood. The large version of Whisper cannot really run on consumer hardware.

No-Code AI: Integrate the NLP Cloud API Into A Bubble.io App

Thanks to the rise of no-code platforms like Bubble.io and the creation of brand new cutting-edge AI models based on Transformers, like GPT-3, GPT-J, GPT-NeoX, Bart, and more, it is now possible to create advanced AI applications without writing a single line of code. In this article, I will show how to connect the NLP Cloud API to a Bubble.io application in order to perform advanced AI operations like summarization, paraphrasing, NER, question answering, blog post generation, product description creation, and much more.

No-Code AI: What Is It Exactly?

No-code platforms are more and more popular these days. Understandably! Programming is getting more and more complex every year, hiring good programmers is hard and expensive, and at the same time less and less projects can live without a good web application these days…

It’s no surprise that no-code services look so attractive. These platforms provide advanced WYSIWYG interfaces to build your own application without writing a single line of code. Thanks to these modern UI based tools, you can now reach an impressive level of sophistication and ship your new MVP in no time.

These last couple of years, AI technologies have made a lot of progress, especially when it comes to natural language processing. You can now easily perform advanced text understanding and text generation tasks like chatbots, summarization, paraphrasing, entity extraction, question answering, automatic blog post generation, automatic product description creation, and much more. The rise of large language models like GPT-3, GPT-J, and GPT-NeoX really helped!

So it’s now easier than ever to build a fully-fledged AI product that is built on AI and no-code technologies!

Bubble.io And NLP Cloud

There are several good no-code platforms out there. They do not all have the same level of sophistication or the same expertise. Some are very good at building beautiful interfaces. Others are good at building advanced backend logic…

Bubble.io is a popular no-code platform that allows for very advanced customization. It takes some practice to master it, but then you can achieve impressive results without any programming skills.

NLP Cloud is an API for natural language processing that serves cutting-edge AI models for text understanding and text generation (GPT-3, GPT-J, GPT-NeoX, Bart, and more).

NLP Cloud is an API, so it usually takes a developer to integrate it into your product. But when combined with Bubble.io, it’s not the case anymore.

Automatic Blog Post Generation With NLP Cloud And Bubble.io

Let’s create a simple Bubble.io project that leverages NLP Cloud in order to generate a whole blog post article out of a mere title. This feature is based on the GPT-J AI model, an open-source alternative to GPT-3. The most important part is about setting the Bubble.io’s API connector.

First, create a new project on Bubble.io:

Create a project on Bubble.io

Then follow the application assistant:

Bubble.io assistant

Bubble.io assistant

Bubble.io assistant

Based on your project settings, at some point, the assistant should propose you to add an API connection. If it doesn’t, no worry, you can still do it later by going to the “Plugins” section. Search for the API Connector and install it:

Bubble.io install API connector

Now that your project is successfully created, go to the “Plugins” section, and in the API Connector click “Add another API”:

Bubble.io create API connection

It’s now time to set up the actual connection to the NLP Cloud API. First set the authentication as “self-handled”:

Bubble.io authentication self-handled

Set the following POST URL: https://api.nlpcloud.io/v1/gpu/fast-gpt-j/article-generation

Set 2 headers. The first one has key = Authorization, value = Token <your API token>, and tick the Private box. The second one has key = Content-Type, and value = application/json.

In the JSON body box, paste the following example: {“title”: “How to become an entrepreneur”}. The goal here is to generate a whole article that talks about how to become an entrepreneur.

Then simply click “Initialize call” to check that the call to NLP Cloud for article generation worked. It will take some time (from 10 to 30 seconds) as generating a whole blog article is extremely computation intensive:

Bubble.io NLP Cloud API connection

You should now get something like the following, that confirms that the connection works:

Bubble.io check connection

Congratulations! You can now use the NLP Cloud API anywhere in your Bubble.io project! For example, if you want to display a blog post article in a text box, here is what you could do:

Bubble.io use API connection

This example was about using NLP Cloud’s blog post generation API, but you can of course use all the API endpoints available on NLP Cloud. In Bubble.io’s API Connector, simply change the POST URL and the JSON body.

Security Considerations

Don’t forget that your NLP Cloud API token should be kept secret. Do not share it with anyone, and if several persons are working in parallel on the same AI project, you can simply invite them to your team in your NLP Cloud dashboard. In that case, each member will receive its own API token, and you can easily revoke an access if needed (if a person leaves the project for example).

Keep in mind that your API token should not be exposed on the frontend side of your Bubble.io application. If an API token is used somewhere in the user’s browser, it means that anyone can retrieve it and use it without control.

Performance Considerations

Some AI models respond within milliseconds while others can take 20 to 30 seconds to respond. If the response time is critical to your users, I encourage you to use the NLP Cloud models on GPUs, which usually makes the response time around 10x faster.

Also, once your Bubble.io application is deployed and used in production (i.e. by real users), you will need to make sure that your NLP Cloud’s plan allows for enough requests, and especially enough parallel requests. If not, some of your requests might be rejected.

Conclusion

In 2022, it is possible to create cutting edge AI applications without writing a single line of code thanks to Bubble.io and NLP Cloud.

This combination opens the door to many exciting new possibilities. Sky is the limit here!

Bubble.io proposes a free plan, and on NLP Cloud all the AI models can be tested for free too.

Build a GPT-J/GPT-NeoX Discord Chatbot With NLP Cloud

It is very easy to build a chatbot in a Discord server thanks to great AI models like GPT-3, GPT-J, and GPT-NeoX. In this article, I show you how to code your own conversational bot in Node.js by using GPT-J and GPT-NeoX through the NLP Cloud API.

A Discord Chatbot?

Discord is a widely adopted messaging platform. It is more and more common to see people create their own Discord server for their project in order for a community to easily get together. Many companies have actually created their own Discord server in order to foster their own user community.

Discord can either be self-hosted or used through the Discord web application. A great thing with Discord is that it has an extensive API to interact with the server, and it is very easy to create a chatbot that will interact with users on Discord.

Many people create chatbots on Discord so users can discuss with an AI about many things. It is very easy to integrate a chatbot into your Discord server. Let’s see how to do that!

GPT-3, GPT-J, and GPT-NeoX

Over these last 2 years, several great AI models have been released: GPT-3, GPT-J, and GPT-NeoX. These models are very impressive and are especially good at dealing with conversational AI (i.e. chatbots).

You can have a great discussion about literally anything with these models, and it is fairly easy to adapt the models to a specific situation. For example you can configure your GPT-based chatbot to be empathetic, sarcastic, or even good at answering specific questions about your own industry (medical, legal, marketing, etc.).

The only problem is that these models require a lot of computation power, so few people can actually afford to deploy them on their own server. NLP Cloud both proposes GPT-J and GPT-NeoX through an API, so I am going to use these models through the NLP Cloud API in the following example.

Get Discord and NLP Cloud API Keys

Let’s assume you have created an account on Discord.com. Go to the developer portal: here. Select “New Application”, name your application, and create it:

New Discord Application

Now click “Add a bot”, and retrieve your bot token.

Last step: link your bot to your Discord server. In order to do this, first click the “OAuth2” menu and retrieve your client ID:

Discord OAuth2

Then allow your bot to access your server by visiting the following URL: https://discord.com/oauth2/authorize?scope=bot&permissions=8&client_id=CLIENT_ID (replace CLIENT_ID with your own client ID retrieved earlier).

Everything is ok on the Discord side. Now let’s retrieve an NLP Cloud API token!

Let’s assume you have created an account on NLP Cloud. Simply retrieve your API token in your dashboard:

NLP Cloud Account

Then subscribe to the pay-as-you-go plan that will give you access to the GPT-J and GPT-NeoX models (the first 100k tokens are free which will make your tests easier).

You can now start coding your Node.js bot!

Code the Node.js Server

Both Discord and NLP Cloud have Node.js clients, so the development will be very easy.

Here is a first version:

const NLPCloudClient = require('nlpcloud');
const { Client, Intents } = require('discord.js');

// Load NLP Cloud token and Discord Bot token.
const nlpcloudToken = process.env.NLPCLOUD_TOKEN;
if (nlpcloudToken == null) {
    console.error('No NLP Cloud token received');
    process.exit();
}
const discordBotToken = process.env.DISCORD_BOT_TOKEN;
if (discordBotToken == null) {
    console.error('No Discord bot token received');
    process.exit();
}

// Initialize the NLP Cloud and Discord clients.
const nlpCloudClient = new NLPCloudClient('fast-gpt-j', nlpcloudToken, true)
const discordClient = new Client({intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]});

let history = [];

discordClient.on("messageCreate", function(message) {
    if (message.author.bot) return;

    (async () => {
        // Send request to NLP Cloud.
        const response = await nlpCloudClient.chatbot(`${message.content}`, '', history);

        // Send response to Discord bot.
        message.reply(`${response.data['response']}`);

        // Add the request and response to the chat history.
        history.push({'input':`${message.content}`,'response':`${response.data['response']}`});
        
    })();
});

As you can see I first retrieve the Discord and NLP Cloud token from environment variables. So first export your tokens in 2 environment variables called “NLPCLOUD_TOKEN” and “DISCORD_BOT_TOKEN”. You can also simply copy paste your token directly in the code during your tests if you prefer.

I am using NLP Cloud’s Fast GPT-J model - a faster implementation of GPT-J - which is interesting for chatbots as I usually want the response time to be as short as possible. If you want to use GPT-NeoX 20B, simply use “gpt-neox-20b” instead of “fast-gpt-j”.

The NLP Cloud “chatbot()” function makes it easy to handle a chatbot based on a GPT model without bothering with complex parameters, prompting, few-shot learning, etc (see below for another example using the generation() function instead of the chatbot() function). The only trick is that after each chatbot response I must keep the response in memory and add it to the history for the following requests. If I don’t do that, the chatbot will never remember the history of the conversation!

My chatbot is now working. Simply launch your script (with “node my_script.js” for example) and you should see that your chatbot is online on your Discord server. You can start talking to it for real!

Automatically Truncate History

My example works but there is a weakness: GPT models cannot handle more than 2048 tokens at the same time (2048 tokens are more or less equal to 1700 words). So at some point your chatbot history might become too large and you will need to truncate it! Here is how you could do that:

const NLPCloudClient = require('nlpcloud');
const { Client, Intents } = require('discord.js');

// Load NLP Cloud token and Discord Bot token.
const nlpcloudToken = process.env.NLPCLOUD_TOKEN;
if (nlpcloudToken == null) {
    console.error('No NLP Cloud token received');
    process.exit();
}
const discordBotToken = process.env.DISCORD_BOT_TOKEN;
if (discordBotToken == null) {
    console.error('No Discord bot token received');
    process.exit();
}

// Initialize the NLP Cloud and Discord clients.
const nlpCloudClient = new NLPCloudClient('fast-gpt-j', nlpcloudToken, true)
const discordClient = new Client({intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]});

let history = [];
let charsCount = 0;

discordClient.on("messageCreate", function(message) {
    if (message.author.bot) return;

    (async () => {
        charsCount += `${message.content}`.length;

        // Send request to NLP Cloud.
        const response = await nlpCloudClient.chatbot(`${message.content}`, '', history);

        charsCount += `${response.data['response']}`.length;

        // Send response to Discord bot.
        message.reply(`${response.data['response']}`);

        // Add the request and response to the chat history.
        history.push({'input':`${message.content}`,'response':`${response.data['response']}`});
        
        // If the chat history is bigger than 1500 tokens, we remove the oldest elements from
        // the history. We consider that 1 token = 4 characters.
        // The theoretical GPT context limit is 2048 tokens but we choose 1500 tokens instead
        // in order to be safe since the tokens count is not perfectly accurate.
        while (charsCount > 1500 * 4) {
            charsCount -= history[0]['input'].length + history[0]['response'].length;
            history.shift();  
        }
    })();
});


discordClient.login(discordBotToken);

As you can see I am simply making sure that the history is not too large, and when it is I remove the oldest elements!

In practice it’s rarely a problem because oldest elements in the history are rarely relevant to the conversation. But if they are, you can also implement a more advanced strategy that is selectively keeping and removing some elements based on their relevance.

Using Text Generation

The above example used the chatbot() function that is a wrapper around the generation() function. The generation() function is a bit harder to use, but it gives you more control over your chatbot. Here is an example:

const NLPCloudClient = require('nlpcloud');
const { Client, Intents } = require('discord.js');

// Load NLP Cloud token and Discord Bot token.
const nlpcloudToken = process.env.NLPCLOUD_TOKEN;
if (nlpcloudToken == null) {
    console.error('No NLP Cloud token received');
    process.exit();
}
const discordBotToken = process.env.DISCORD_BOT_TOKEN;
if (discordBotToken == null) {
    console.error('No Discord bot token received');
    process.exit();
}

// Initialize the NLP Cloud and Discord clients.
const nlpCloudClient = new NLPCloudClient('fast-gpt-j', nlpcloudToken, true)
const discordClient = new Client({intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]});

let history = `Input: Hey, how are you today?
Response: Very well thank you, what about you?
###
Input: I am great.
Response: What are you going to do?
###
Input: Most likely read a couple of book and relax.
Response: Fantastic!`;

discordClient.on("messageCreate", function(message) {
    if (message.author.bot) return;

    (async () => {
        if (history != '') {
            history += '\n###\n'
        }
        let finalContent = history+'Input: '+`${message.content}`+'\nResponse:';

        // Send request to NLP Cloud.
        const response = await nlpCloudClient.generation(finalContent,0,200,true,'###',true,true)
        
        // Remove end_sequence from response.
        let cleanedResponse = response.data['generated_text'].replace('###','').trim();

        // Send response to Discord bot.
        message.reply(cleanedResponse);

        // Add the request and response to the chat history.
        history = finalContent+cleanedResponse;

        // If the chat history is bigger than 1500 tokens, we remove the oldest elements from
        // the history. We consider that 1 token = 4 characters.
        // The theoretical GPT context limit is 2048 tokens but we choose 1500 tokens instead
        // in order to be safe since the tokens count is not perfectly accurate.
        if (history.length > 1500 * 4) {
            history = history.slice(charsCount-(1500 * 4));
        }

    })();
 });


discordClient.login(discordBotToken);

You noticed that I need to manually initialize a chat discussion with some chitchat. The idea here is to show the text generation model that I want to be in a conversational mode. This chitchat is insignificant and should be as neutral as possible in order not to have any impact on the rest of the conversation.

Also note that I force the model to add “###” at the end of each generated response. This way, I can easily stop the text generation when these characters are met.

Once again, this example is for advanced usage only!

Conclusion

Building an advanced chatbot has never been so easy thanks to Discord and GPT models.