I developed this node.js script to save every GPT-4 request and response into a JSON file.
It then sends the file content as conversation history with each new prompt.
// Import required modules
const fs = require('fs');
const axios = require('axios');
// Your OpenAI API key
const apiKey = 'your-openai-api-key';
// Function to interact with OpenAI API
async function interactWithAI(userPrompt) {
try {
// Define the message data structure
let messageData = { 'messages': [] };
// If requests.json exists, read and parse the file
if (fs.existsSync('requests.json')) {
let raw = fs.readFileSync('requests.json');
messageData = JSON.parse(raw);
}
// Format the conversation history and the new user request
let systemMessage = "Conversation history:\n" + messageData['messages'].map(m => `${m.role} [${m.timestamp}]: ${m.content}`).join("\n");
let userMessage = "New request: " + userPrompt;
// Make a POST request to OpenAI's chat API
let response = await axios({
method: 'post',
url: 'https://api.openai.com/v1/chat/completions',
headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
data: { 'model': 'gpt-4', 'messages': [ { "role": "system", "content": systemMessage }, { "role": "user", "content": userMessage } ] }
});
// Log the AI's response
console.log(response.data['choices'][0]['message']['content']);
// Get the current timestamp
let timestamp = new Date().toISOString();
// Add the new user request and the AI's response to the message history
messageData['messages'].push({ "role": "user", "content": userPrompt, "timestamp": timestamp });
messageData['messages'].push({ "role": "assistant", "content": response.data['choices'][0]['message']['content'], "timestamp": timestamp });
// Write the updated message history to requests.json
fs.writeFileSync('requests.json', JSON.stringify(messageData, null, 2));
// Return the AI's response
return response.data['choices'][0]['message']['content'];
} catch (e) {
// If an error occurred, log it to the console and return an error message
console.error('An error occurred:', e);
return 'An error occurred while interacting with the OpenAI API. Please check the console for more details.';
}
}
cc: @abdeldroid