const API_URL = 'https://tatooine.cantina.cloud/aichat'; // Change this to your actual API URL const PROJECT_ID = '1234'; const TOKEN = '4321'; const CONFIG_URL = 'https://developer:seekret@tatooine.cantina.cloud/ai/chat_prompts/sia.yaml'; const CONVERSATION_TIMEOUT = 900; // 15 minutes in seconds const INPUT_TIMEOUT = 0; const TIMER_ON_LOAD = false; let currentConvoId = null; let inputTimer = null; let conversationStarted = false; // Function to generate a UUID function generateUUID() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } // Function to get or create a conversation ID function getOrCreateConversationId() { let convoId = localStorage.getItem('currentConvoId'); if (!convoId) { convoId = generateUUID(); localStorage.setItem('currentConvoId', convoId); } return convoId; } // Get or create the conversation ID when the script loads currentConvoId = getOrCreateConversationId(); async function jsonRpcRequest(method, params) { const response = await fetch(API_URL, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ jsonrpc: '2.0', method: method, params: params, id: Date.now().toString() }), }); return await response.json(); } function appendMessage(role, message) { const chatBox = document.getElementById('chatBox'); const messageElement = document.createElement('p'); messageElement.innerHTML = `${role}: ${message}`; if (role.toLowerCase() === 'you' || role.toLowerCase() === 'user') { messageElement.classList.add('user-message'); } else if (role.toLowerCase() === 'ai' || role.toLowerCase() === 'assistant') { messageElement.classList.add('ai-message'); } else { messageElement.classList.add('system-message'); } chatBox.appendChild(messageElement); chatBox.scrollTop = chatBox.scrollHeight; } async function createConversation() { const result = await jsonRpcRequest('create_conversation', { project_id: PROJECT_ID, token: TOKEN, config_url: CONFIG_URL, reinit: false, id: currentConvoId, conversation_timeout: CONVERSATION_TIMEOUT }); if (result.result && result.result.status) { appendMessage('System', `Conversation ${result.result.status}: ${currentConvoId}`); if (result.result.initial_message) { appendMessage('AI', result.result.initial_message); } conversationStarted = true; startInputTimer(); console.log('Conversation created, starting input timer'); } else if (result.error) { appendMessage('Error', result.error.message || 'Unknown error'); } } async function sendMessage(message, role = 'user', silent = false) { if (!message) return; console.log(`Sending message: ${message}, Role: ${role}, Silent: ${silent}`); if (!silent) { appendMessage('You', message); } const result = await jsonRpcRequest('chat', { project_id: PROJECT_ID, token: TOKEN, id: currentConvoId, message: message, role: role, config_url: CONFIG_URL, conversation_timeout: CONVERSATION_TIMEOUT }); if (result.result && result.result.response) { appendMessage('AI', result.result.response); } else if (result.error) { appendMessage('Error', result.error.message || 'Unknown error'); } if (!conversationStarted) { conversationStarted = true; } startInputTimer(); //console.log('Message sent, restarting input timer'); } function startInputTimer() { if (!conversationStarted && !TIMER_ON_LOAD) { console.log('Conversation not started and TIMER_ON_LOAD is false, not setting input timer'); return; } if (inputTimer) { clearTimeout(inputTimer); //console.log('Cleared existing input timer'); } if (INPUT_TIMEOUT > 0) { //console.log(`Setting new input timer for ${INPUT_TIMEOUT}ms`); inputTimer = setTimeout(() => { console.log('Input timer triggered, sending system message'); sendMessage("The user has not responded, try to get their attention", 'system', true); }, INPUT_TIMEOUT); } } async function endConversation() { const result = await jsonRpcRequest('end_conversation', { project_id: PROJECT_ID, token: TOKEN, id: currentConvoId }); if (result.result && result.result.status) { appendMessage('System', `Conversation ended: ${result.result.status}`); localStorage.removeItem('currentConvoId'); currentConvoId = generateUUID(); localStorage.setItem('currentConvoId', currentConvoId); conversationStarted = false; } else if (result.error) { appendMessage('Error', result.error.message || 'Unknown error'); } if (inputTimer) { clearTimeout(inputTimer); //console.log('Cleared input timer on conversation end'); } } function clearChat() { document.getElementById('chatBox').innerHTML = ''; console.log('Chat cleared'); } // Event listener for user input document.getElementById('userInput').addEventListener('keypress', function(e) { if (e.key === 'Enter') { const userInput = this.value.trim(); if (userInput) { sendMessage(userInput); this.value = ''; console.log('User input sent, input field cleared'); } } }); // Event listener for input changes document.getElementById('userInput').addEventListener('input', function() { if (conversationStarted) { startInputTimer(); //console.log('User is typing, restarting input timer'); } }); // Initialize the conversation when the page loads async function initializeConversation() { currentConvoId = getOrCreateConversationId(); console.log('Page loaded, conversation ID initialized:', currentConvoId); // Check if the conversation already exists if (localStorage.getItem('currentConvoId') === currentConvoId) { console.log('Existing conversation detected, sending return message'); sendMessage("The user has returned to the chat after being away", 'system', true); conversationStarted = true; } // Start the timer on page load if TIMER_ON_LOAD is true and INPUT_TIMEOUT > 0 if (TIMER_ON_LOAD && INPUT_TIMEOUT > 0) { console.log('TIMER_ON_LOAD is true and INPUT_TIMEOUT > 0, starting input timer on page load'); startInputTimer(); } else { console.log('Timer not started on page load due to configuration'); } } // Call initializeConversation when the page loads initializeConversation();