var chats = []; // Create an empty list to store chat messages
var lastSummary = ''; // Store the last summary to compare with the new one
// This function will be called whenever a message is sent by any player or bot
function chatReceived(sender, val) {
chats.push({ sender: sender, message: val }); // Add the chat message and sender to the list
}
// Function to append a message to the chat conversation
function appendToChatConversation(message, sender = 'User') {
// Create the formatted HTML string
let formattedMessage = `
${sender}: ${message}
`;
// Append the formatted message to the HTML element with the ID "chat_conversation"
document.getElementById('chat_conversation').innerHTML += formattedMessage;
// Log the message in the chat history
chatReceived(sender, message);
}
// Function to summarize and repeat the chat messages
function summarizeChats() {
if (chats.length > 0) {
let chatContent = chats.map(chat => chat.sender + ": " + chat.message).join('\n');
generateSummary(chatContent);
chats = []; // Clear the chat log after summarizing
}
}
// Function to generate a summary using OpenAI API
function generateSummary(chatContent) {
// Prepare the message payload
const message = {
role: 'user',
content: `Please summarize the following conversation:\n\n${chatContent}`
};
// Call the OpenAI function to get the summary
openai_chat_completions_create(message)
.then((summary) => {
// Ensure the summary is different from the last one
if (summary !== lastSummary) {
appendToChatConversation(summary, 'Summary Bot'); // Append the summary to the chatbox
lastSummary = summary; // Update the last summary
}
});
}
// This function calls OpenAI and handles the response
function openai_chat_completions_create(message, temperature = 0.7, model = 'gpt-3.5-turbo-0613') {
return fetch("https://volunteerscience.com/openai/chat/", {
method: "POST",
body: JSON.stringify({
message: message,
temperature: temperature,
model: model
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then((response) => {
return response.json(); // Parse the JSON from the response
})
.then((result) => {
console.log(result); // Log the result for debugging
return result.response; // Return the summary text from the response
})
.catch((error) => {
console.error('Error fetching summary:', error);
});
}
// Function to handle message sending
function handleMessageSend() {
const chatInput = document.getElementById('chat_input').value;
if (chatInput.trim()) {
appendToChatConversation(chatInput, 'User');
document.getElementById('chat_input').value = ''; // Clear the input field
}
}
// Initialize chat functionality
function initializeChat() {
document.getElementById('chat_send_button').addEventListener('click', handleMessageSend);
document.getElementById('chat_input').addEventListener('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 receiveMessage(event) {
// if we detect the survey is over, hide the iframe and end experiment.
if (event.data == "closeQSIWindow") {
document.getElementById("qualFrame").style.display = 'none';
experimentComplete();
}
// if researcher calls popupConsent in survey and user has not already consented before, pop up the experiment's consent form
if (event.data == "popupConsent") {
if (REQUEST_CONSENT) {
requestConsent();
}
}
// if researcher calls "payAMT" in survey and it's a turker, pay the base plus whatever bonus AMTBonus is set to.
if (event.data == "payAMT") {
if (IS_AMT){
payAMT(true, AMTBonus);
}
}
}
// Start the study
function initialize() {
initializeChat();
// place the title on the survey page
document.getElementById("survey_title").innerHTML = variables["title"];
// create a listener for qualtrics
window.addEventListener("message", receiveMessage, false);
// Create an iframe called "qualFrame" that goes to the qualtrics URL and pass the testId and subjectID variables in the URL
document.getElementById("qualFrame").setAttribute("src", variables["survey_link"] + "&testId=" + seed + "&subjectId=" + myid);
document.getElementById("qualFrame").style.height = variables["survey_height"];
document.getElementById("qualFrame").style.display = 'block';
}