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.
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
We will start by creating the project and create our main file.
mkdir backendcd backendnpm inittouch index.j
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:
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 = 3000app.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 frontendcd 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