The way I solved for it was by initializing the first system and user messages. I would then take the user input and api response and store the array as a local storage item. Each time a new question/response pair was made, this would be appended to the previous data, and then the new array passed along.
Here is my code example:
// Messages payload
// Check if the messages item exists in localStorage
if (!localStorage.getItem("messages")) {
// If it does not exist, create an array with the initial messages
const iMessages = [
{ role: 'system', content: "You are Eva. You have access to previous chats and responses. You also have access to updated real-time news and information. You will keep conversation to a minimum and answer to the best of your abilities." },
{ role: 'user', content: selPers.value + " " + dateContents },
];
// Store the initial messages in localStorage
localStorage.setItem("messages", JSON.stringify(iMessages));
}
// Create a new array to store the messages
let newMessages = [];
//const cleanedQuestion = sQuestion.replace(/<div[^>]*>|<\/div>| /gi, '');
const cleanedQuestion = sQuestion.replace(/<div[^>]*>|<\/div>| |<span[^>]*>|<\/span>/gi, '');
// Push the messages to the new array
newMessages.push({ role: 'assistant', content: lastResponse.replace(/\n/g, ' ') });
newMessages.push({ role: 'user', content: cleanedQuestion.replace(/\n/g, '') });
...
// Append the new messages to the existing messages in localStorage
let existingMessages = JSON.parse(localStorage.getItem("messages")) || [];
existingMessages = existingMessages.concat(newMessages);
localStorage.setItem("messages", JSON.stringify(existingMessages));
// Retrieve messages from local storage
var cStoredMessages = localStorage.getItem("messages");
kMessages = cStoredMessages ? JSON.parse(cStoredMessages) : [];
// API Payload
var data = {
model: sModel,
messages: kMessages,
max_tokens: iMaxTokens,
temperature: dTemperature,
frequency_penalty: eFrequency_penalty,
presence_penalty: cPresence_penalty,
stop: hStop
}
// Sending API Payload
oHttp.send(JSON.stringify(data));
It works pretty well for me I hope this might help!
For the full context of the code, please feel free to take a look at the full code via github:
Chat GPT API does not “remember” your responses like when using it in the browser. To have a conversation with it, you need to constantly update and provide the previous conversation to it for context.
You achieve this by saving the previous response and adding it to the messages array every time you make a new API request / chat message.
To learn more about the basics of ChatGPT, check out the FAQ in this guide