TLDR;
I am going to show you how to create a notification library like on this website:
https://notifications.directory
I will show you how to create thousands of notifications with ChatGPT and render it with React.
Happy if you can help me out by pressing the "love" sign, it helps me to create more articles!
Things you need to know
At the moment, he ChatGPT API isn't available.
The latest model from OpenAI is "text-davinci-003".
If you're okay with using an older model, go ahead and give it a try!
But keep in mind that it's not as advanced as the current ChatGPT model "text-davinci-002-render". In this tutorial, I'm going to show you a solution that was created by someone in the open-source community.
It's a good option for now, but please keep in mind that it might not always be available. OpenAI hasn't released its ChatGPT API yet, so this is just a temporary solution, this solution can't be used for commercial purposes.
What data do we need?
I will teach you how to do the same things we do in The notification generator project, simplified.
We will create three hierarchies.
- Categories Website types like
- SaaS
- E-commerce
- Online marketplace
- Travel
- Etc..
- Notifications Types
- SaaS: "Payment is due"
- E-commerce: "Product out of stock", etc...
- Notifications
- āHi NAME, your payment is due for DATEā
- āHi NAME, product PRODUCT_NAME is out of stock.ā
To create each hierarchy, we must have the data of the previous hierarchy.
While in Novu, we store everything inside MongoDB here we will do everything with a simple array.
Novu - the first open-source notification infrastructure
Just a quick background about us. Novu is the first open-source notification infrastructure. We basically help to manage all the product notifications. It can be In-App (the bell icon like you have in Facebook), Emails, SMSs and so on.
I would be super happy if you could give us a star! And let me also know in the comments ā¤ļø
https://github.com/novuhq/novu
Register to ChatGPT
Go over to https://platform.openai.com/signup
Register to OpenAI, head over to this endpoint: https://chat.openai.com/api/auth/session,
and grab the accessToken from the JSON.
Setting up the project
We will start by creating the project and create our main file.
mkdir backend
cd backend
npm init
touch index.js
Letās install our chatgpt library.
npm install @waylaidwanderer/chatgpt-api --save
This library uses Esm and not CommonJS. Therefore, it might be problematic for you if you try to implement it with NestJS - if you need help, let me know in the comments.
I will not separate the code into multiple files, as I want to keep it simple for the sake of this tutorial. Open index.js, and let's start writing.
Let's initiate our ChatGPT. As you can see, the library is usingĀ "chatgpt.hato.ai*",Ā a solution one of the community members found to use ChatGPT and was kind enough to deploy it on his server. While using this, your ChatGPT account will be exposed to an external resource, so please make sure you don't add any credit card information and that you are using the free ChatGPT version.
**Please be advised that the API is limited to 10 requests per second.*
import { ChatGPTClient } from '@waylaidwanderer/chatgpt-api'
const api = new ChatGPTClient('YOUR ACCESS TOKEN FROM THE PREVIOUS STEP', {
reverseProxyUrl: 'https://chatgpt.hato.ai/completions',
modelOptions: {
model: 'text-davinci-002-render',
},
});
Letās create our database š¤£
const categories = []
Final result of ācategoriesā will look like this
[
{
"category": "SaaS",
"notificationTypes": [
{
"name": "Payment is due",
"notifications": [
"Hi {{name}}, your payment is due for. {{date}}"
]
}
]
}
]
Your code should look like this now:
import { ChatGPTClient } from '@waylaidwanderer/chatgpt-api'
const api = new ChatGPTClient('YOUR ACCESS TOKEN FROM THE PREVIOUS STEP', {
reverseProxyUrl: 'https://chatgpt.hato.ai/completions',
modelOptions: {
model: 'text-davinci-002-render',
},
});
const notifications = [];
Letās write the code that will generate all the categories.
We want the prompt and the result to look like this:
The thing is that everything will come to us as a plain text.
We need a function that will create an array from the list.
I have created a quick one.
If you have something more efficient, let me know in the comments:
const extractNumberedList = (text) => {
return text.split("\n").reduce((all, current) => {
const values = current.match(/\d+\.(.*)/);
if (values?.length > 1) {
return [...all, values[1].trim()];
}
return all;
}, []);
}
Now the fun part.
We need all the possible categories, then run it through our function and map it to our database:
const res = await api.sendMessage('Can you list 50 types of websites in the world send in-app notifications? just the category');
categories.push(...extractNumberedList(res.response).map(p => ({category: p, notificationTypes: []})));
Now we will iterate over the categories and start adding content to them. I am not going to use functional programming here for the first part.
I will use the āfor loopā as itās easier with async / await:
for (const category of categories) {
}
Letās start to create our notification types:
for (const category of categories) {
const notificationTypesRes = await api.sendMessage(`I have a website of type ${category}, What kind of notifications should I sent to my users? can you just write the type without context? give me 20`);
const notificationTypes = extractNumberedList(res.response).map(p => ({name: p, notifications: []}));
}
And now, letās add our notifications:
for (const category of categories) {
// get all the notifications type
const notificationTypesRes = await api.sendMessage(`I have a website of type ${category}, What kind of notifications should I sent to my users? can you just write the type without context? give me 20`);
// parse all the notification type and map them
const notificationTypes = extractNumberedList(notificationTypesRes.response).map(p => ({name: p, notifications: []}));
// get all the notifications for the notification type
const notifications = await Promise.all(notificationTypes.map(async p => {
const notificationRes = await api.sendMessage(`I have built a system about "${category}" and I need to create in-app notifications about "${notificationType}", can you maybe write me a 20 of those? just the notification without the intro, use lower-case double curly braces with no spaces and underscores for the variables, and avoid using quotation when writing the notifications`);
return {
...p,
notifications: extractNumberedList(notificationRes.response)
}
}));
// push it to the main array
notificationTypes.notifications.push(...notifications);
}
The final code will be looking like this:
import { ChatGPTClient } from '@waylaidwanderer/chatgpt-api'
const api = new ChatGPTClient('YOUR ACCESS TOKEN FROM THE PREVIOUS STEP', {
reverseProxyUrl: 'https://chatgpt.hato.ai/completions',
modelOptions: {
model: 'text-davinci-002-render',
},
});
const categories = [];
const extractNumberedList = (text) => {
return text.split("\n").reduce((all, current) => {
const values = current.match(/\d+\.(.*)/);
if (values?.length > 1) {
return [...all, values[1].trim()];
}
return all;
}, []);
}
const res = await api.sendMessage('Can you list 50 types of websites in the world send in-app notifications? just the category');
categories.push(...extractNumberedList(res.response).map(p => ({category: p, notificationTypes: []})));
for (const category of categories) {
// get all the notifications type
const notificationTypesRes = await api.sendMessage(`I have a website of type ${category}, What kind of notifications should I sent to my users? can you just write the type without context? give me 20`);
// parse all the notification type and map them
const notificationTypes = extractNumberedList(notificationTypesRes.response).map(p => ({name: p, notifications: []}));
// get all the notifications for the notification type
const notifications = await Promise.all(notificationTypes.map(async p => {
const notificationRes = await api.sendMessage(`I have built a system about "${category}" and I need to create in-app notifications about "${notificationType}", can you maybe write me a 20 of those? just the notification without the intro, use lower-case double curly braces with no spaces and underscores for the variables, and avoid using quotation when writing the notifications`);
return {
...p,
notifications: extractNumberedList(notificationRes.response)
}
}));
// push it to the main array
notificationTypes.notifications.push(...notifications);
}
It can run in the background forever š„³
We can quickly move it to a separate task / cron / queue, but we will not do it here.
While this thing is running in the background, letās add here the API that our frontend can use
Letās go back to our command line and write:
npm install express --save
We will do the simplest thing and just serve our categories variable.
Feel free to take it to the next level with an actual database:
import express from 'express';
const app = express()
const port = 3000
app.get('/', (req, res) => {
return categories;
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
And the complete code is as follows:
import { ChatGPTClient } from '@waylaidwanderer/chatgpt-api';
import express from 'express';
const categories = [];
const app = express();
const port = 3000;
const api = new ChatGPTClient('YOUR ACCESS TOKEN FROM THE PREVIOUS STEP', {
reverseProxyUrl: 'https://chatgpt.hato.ai/completions',
modelOptions: {
model: 'text-davinci-002-render',
},
});
const extractNumberedList = (text) => {
return text.split("\n").reduce((all, current) => {
const values = current.match(/\d+\.(.*)/);
if (values?.length > 1) {
return [...all, values[1].trim()];
}
return all;
}, []);
}
app.get('/', (req, res) => {
return categories;
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
});
const res = await api.sendMessage('Can you list 50 types of websites in the world send in-app notifications? just the category');
categories.push(...extractNumberedList(res.response).map(p => ({category: p, notificationTypes: []})));
for (const category of categories) {
// get all the notifications type
const notificationTypesRes = await api.sendMessage(`I have a website of type ${category}, What kind of notifications should I sent to my users? can you just write the type without context? give me 20`);
// parse all the notification type and map them
const notificationTypes = extractNumberedList(notificationTypesRes.response).map(p => ({name: p, notifications: []}));
// get all the notifications for the notification type
const notifications = await Promise.all(notificationTypes.map(async p => {
const notificationRes = await api.sendMessage(`I have built a system about "${category}" and I need to create in-app notifications about "${notificationType}", can you maybe write me a 20 of those? just the notification without the intro, use lower-case double curly braces with no spaces and underscores for the variables, and avoid using quotation when writing the notifications`);
return {
...p,
notifications: extractNumberedList(notificationRes.response)
}
}));
// push it to the main array
notificationTypes.notifications.push(...notifications);
}
NODE.JS ā
Now letās move over to react to display all of our categories.
I will do the simplest thing of aggregating everything inside of a <ul>
Letās right some bash commands:
cd ..
npx create-react-app frontend
cd frontend
I will be using axios to get all the results from the database, feel free to use fetch / react-query etcā¦
npm install axios
Letās open our main component at āsrc/App.jsā and add some imports
import {useState, useCallback, useEffect} from 'react';
import axios from 'axios';
Letās open our main component at āsrc/App.jsā and add a new state that will contain all of our database from the server:
const [categories, setCategories] = useState([]);
And now, we will write the function that will get all the information from the server
const serverInformation = useCallback(async () => {
const {data} = await axios.get('http://localhost:3000');
setCategories(data);
}, []);
Add it to our useEffect, that will run as soon as the component is loaded
useEffect(() => {
serverInformation();
}, []);
And now, we will render everything on the screen
<ul>
{categories.map(cat => (
<li>
{cat.category}
<ul>
{cat.notificationTypes.map(notificationType => (
<li>
{notificationType.name}
<ul>
{notificationType.notifications.map(notification => (
<li>
{notification}
<li>
)}
</ul>
<li>
)}
</ul>
<li>
)}
</ul>
And thatās it! We have rendered the entire list!!!
The full code of App.js would look like this:
import {useState, useCallback, useEffect} from 'react';
import axios from 'axios';
function App() {
const [categories, setCategories] = useState([]);
useEffect(() => {
serverInformation();
}, []);
const serverInformation = useCallback(async () => {
const {data} = await axios.get('http://localhost:3000');
setCategories(data);
}, []);
return (
<ul>
{categories.map(cat => (
<li>
{cat.category}
<ul>
{cat.notificationTypes.map(notificationType => (
<li>
{notificationType.name}
<ul>
{notificationType.notifications.map(notification => (
<li>
{notification}
<li>
)}
</ul>
<li>
)}
</ul>
<li>
)}
</ul>
);
}
Of course, this is the short version of the frontend.
You can find the complete frontend code (with the amazing design) here:
https://github.com/novuhq/notification-directory-react
I hope you have learned something. Until next time š
Help me out!
If you feel like this article helped you, I would be super happy if you could give us a star! And let me also know in the comments ā¤ļø