// Initialize an empty array to store chat messages var chats = []; // Function to handle incoming chat messages function chatReceived(from, val, to_parts) { chats.push(val); // Add the received chat message to the chats array } // Function to append a message to the chat conversation on the webpage function appendToChatConversation(message, sender = 'User') { let formattedMessage = `
${sender}: ${message}
`; $('#chat_conversation').append(formattedMessage); // Append the formatted message to the chat conversation } // Function to handle sending chat messages function handleMessageSend() { const chatInput = $('#chat_input').val(); if (chatInput.trim()) { appendToChatConversation(chatInput); chatReceived('User', chatInput); $('#chat_input').val(''); // Clear the chat input field } } // Function to summarize the chats by calling OpenAI async function summarizeChats() { if (chats.length > 0) { // Join all the chats together const chatContent = chats.join('\n'); // Create the message payload const conversation = [ { role: 'system', content: 'Please summarize the following chat conversation.' }, { role: 'user', content: chatContent } ]; // Call OpenAI API to summarize the chat const summary = await openai_chat_completions_create(conversation); appendToChatConversation(`Summary of the last 3 minutes:\n${summary}`, 'Summary Bot'); } // Clear the chat log after summarizing chats = []; } // Simulated function to call OpenAI API async function openai_chat_completions_create(messages) { // This function would actually call the OpenAI API in a real implementation // Below is a simulated response for demonstration purposes const response = "This is a simulated summary of the chat conversation."; return response; } // Function to initialize the chat functionality function initializeChat() { $('#chat_send_button').on('click', handleMessageSend); $('#chat_input').on('keypress', function(event) { if (event.key === 'Enter') { handleMessageSend(); } }); // Set an interval to summarize the chat every 3 minutes setInterval(() => { summarizeChats(); }, 180000); // 3 minutes = 180000 milliseconds } // Function to receive messages from an external source (e.g., survey platform) function receiveMessage(event) { if (event.data == "closeQSIWindow") { $("#qualFrame").hide(); experimentComplete(); } if (event.data == "popupConsent") { if (REQUEST_CONSENT) { requestConsent(); } } if (event.data == "payAMT") { if (IS_AMT){ payAMT(true, AMTBonus); } } } // Function to initialize the entire study function initialize() { initializeChat(); $("#survey_title").html(variables["title"]); window.addEventListener("message", receiveMessage, false); $("#qualFrame").attr("src", variables["survey_link"] + "&testId=" + seed + "&subjectId=" + myid); $("#qualFrame").height(variables["survey_height"]); $("#qualFrame").show(); }