Building a NKN chatbot with ChatGPT

Zheng "Bruce" Li
The Low End Disruptor
4 min readJan 19, 2023

We have all seen the memes and the surprisingly good responses out of openAI’s ChatGPT, and you are itching to add it as a chatbot for your favorite chat application. It could be used for times when you feel utterly bored, ask an innocent question if you are too lazy to google, or write your homework essay.

In this article, I will show you some simple Javascript code to build such a bot for NKN’s secure private chat app called nMobile that is powered by NKN’s global network of community servers.

The ChatGPT part

Getting started

If you want to build a chatbot with ChatGPT via Javascript API, here is the code snippet to get you started. But first you do need to install the OpenAI SDK, register on openai.com, get an API Key, and store in config.json.

Please follow OpenAI’s Quickstart Guide

Initialize OpenGPT

//OpenAI ChatGPT initialization
const { Configuration, OpenAIApi } = require("openai");
const { RC4 } = require('crypto-js');
const OPENAI_API_KEY = config.openai_key;
const configuration = new Configuration({
apiKey: OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

Feed the question to ChatGPT and get response

Notes: You can modify the “temperature” and “top_p” for flavor of the response, thus giving the chatbot a bit more personality. And “max_token” will limit the amount of letters in response: roughly one token for one letter. Since it is a chat app on phones, you probably don’t want too long winded responses.

In addition, you can use “user” to distinguish different chatbot users, while hashing to preserve their identity. This can be used for statistics, as well as to prevent spamming and abuse.

// Request completion from ChatGPT
var hash = crypto.createHash('sha256').update(src).digest('hex');
var response = await openai.createCompletion({
model: "text-davinci-003",
prompt: message.content,
temperature: 0.7,
max_tokens: 256,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0.6,
user: hash,
});

Get the text out of the response JSON

data = response.data.choices[0].text;

So it is actually very simple. You can use the above code snippets to test out if your ChatGPT API is working properly, before integrating with NKN’s nMobile chat app.

Connecting to nMobile

Create NKN ID

First you need to create a NKN ID (basically a public/private key pair) by using the nknc command. You can download the binary releases for your OS, or download the source code and compile yourself. I called my bot Rose.

./nknc wallet -c

Then you can find NKN ID which is like your phone number so other uers can talk to the chatbot. In addition, you will find the private key or seed that is used for authentication as well as encrytion.

./nknc wallet — list verbose

Now store this private key in config.json, along with the openAI API key.

const config = require('./config.json');
const nkn = require('nkn-sdk');
const RoseSeed = config.RoseSeed;

Start a NKN client

// Create Rose client
let fromClient = new nkn.MultiClient({
// neither of these are required, as shown in toClient below
identifier: 'Rose',
seed: RoseSeed,
// seedRpcServerAddr: seedRpcServerAddr,
// multi-client parameter
numSubClients: 3,
originalClient: false,
});

Putting all together

Basically the chatbot will listen to incoming messages from users, parse and relay them to the ChatGPT API, retrieve the response, and relay back again to the original user. Code samples are below:

fromClient.onMessage(async ({
src,
payload,
payloadType,
isEncrypted,
messageId,
noReply
}) => {
if (payloadType === nkn.pb.payloads.PayloadType.TEXT) {
var message = JSON.parse(payload);
if (message.contentType === 'text') {
var sendTime = new Date(message.timestamp);
// Request completion from ChatGPT
var hash = crypto.createHash('sha256').update(src).digest('hex');
var response = await openai.createCompletion({
model: "text-davinci-003",
prompt: message.content,
temperature: 0.7,
max_tokens: 256,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0.6,
user: hash,
});
// Post-process ChatGPT response
data = response.data.choices[0].text;
// Formating the d-chat message
var targetID = uuidv4();
var timestamp = Date.now();
var reply = data.toString();
var sendMsg = {
contentType: "text",
id: targetID,
timestamp: timestamp,
content: data,
isPrivate: true
};
var sendMsg_text = JSON.stringify(sendMsg);
// Sending formatted response
toClient.addr = src;
fromClient.send(
toClient.addr,
sendMsg_text,
).then((data) => {
timeReceived = new Date();
}).catch((e) => {
console.log(logPrefix + 'Catch: ', e);
});
timeSent = new Date();
} else {
console.log('Unknown message type, discard for now')
};
};
});
})();

Test time

So now you have a ChatGPT enabled chatbot that works over NKN network. In order to test it, you will need to install nMobile or d-chat from the links below.

In nMobile, you need to start a new “Direct Message” and enter your chatbot’s NKN ID. Same for d-chat except it was called “Private Message”. Then you are free to chat away!

And here is an example screenshot from Rose the chatbot on d-chat. My Android nMobile has such strong privacy that I cannot take a screenshot.

References

ChatGPT developer resources

https://beta.openai.com/docs/api-reference/making-requests

NKN Javascript SDK

https://github.com/nknorg/nkn-sdk-js

NKNc download page

https://github.com/nknorg/nkn

--

--