Skip to content

Instantly share code, notes, and snippets.

@iamrony777
Last active June 19, 2023 15:09
Show Gist options
  • Save iamrony777/301de13972945bb37d32de8582c8d667 to your computer and use it in GitHub Desktop.
Save iamrony777/301de13972945bb37d32de8582c8d667 to your computer and use it in GitHub Desktop.
// set type: module in package.json to use import statements
import Keyv from 'keyv' // https://www.npmjs.com/package/keyv
import { ChatGPTAPI } from "chatgpt"; // https://www.npmjs.com/package/chatgpt
// Set REDIS_URL to your Redis URL
const messageStore = new Keyv(`sqlite://history.db`)
import { v4, validate } from 'uuid'
/**
* [CORE] ChatGPT Function
* @param {string} name - username to identify previous and current conversation
* @param {string} prompt - message/prompt
*/
async function ask (name, prompt) {
// Check given username or generate a random UUID
const conversationName = name // or setup other ways to generate a conversation name,like string to a valid v5 uuid would be enough
const conversation = await messageStore.get(conversationName) || {}
const lastMessage = conversation.lastMessageId ? conversation[conversation.lastMessageId] : undefined
const parentMessageId = lastMessage ? lastMessage.id : v4()
const api = new ChatGPTAPI(
{
apiBaseUrl: 'https://api.pawan.krd/v1',
apiKey: 'pk-***',
debug: true,
timeoutMs: 15000,
completionParams: {
max_tokens: 1000,
temperature: 0.5,
presence_penalty: 0,
frequency_penalty: 0
},
getMessageById: async (id) => { return conversation[id] },
upsertMessage: async (message) => {
// Pawan's proxy generates a uuid (v4) as message id, but others don't
// so i'm overriding message.id with a random uuid
if (!validate(message.id)) {
message.id = v4()
if (message.detail) {
message.detail.id = message.id
}
}
conversation[message.id] = message
conversation.lastMessageId = message.id
await messageStore.set(conversationName, conversation) // set expiration time 5min -> await messageStore.set(conversationName, conversation, 5 * 60 * 1000)
}
})
return await api.sendMessage(prompt, { parentMessageId, name })
}
// Call
// for same username, using different prompts will automaticly fetch last messages and send them as an array
ask('RONY', 'who is nelson mandela').then(async (response) => {
console.log(response.text)
await messageStore.disconnect()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment