Now the most critical part — modifying `submitToAI()` to inject agent system prompts, add context threads, do debug logging, and check tokens. Let me find it:


2158:        async function submitToAI() {


  2158→        async function submitToAI() {
  2159→            const selectedProvidersList = getSelectedProviders();
  2160→
  2161→            if (selectedProvidersList.length === 0) {
  2162→                alert('Please select at least one AI provider');
  2163→                return;
  2164→            }
  2165→
  2166→            const question = document.getElementById('ai-question').value.trim();
  2167→            const context = document.getElementById('ai-context').value.trim();
  2168→            const contentMode = document.getElementById('content-mode').value;
  2169→            const additionalThreads = getSelectedThreads();
  2170→
  2171→            // Build models map for each selected provider
  2172→            const modelsMap = {};
  2173→            selectedProvidersList.forEach(provider => {
  2174→                const modelSelect = document.getElementById('model_' + provider);
  2175→                modelsMap[provider] = modelSelect ? modelSelect.value : '';
  2176→            });
  2177→
  2178→            // Show loading
  2179→            document.getElementById('loading-overlay').classList.add('active');
  2180→            document.getElementById('submit-ai-btn').disabled = true;
  2181→
  2182→            try {
  2183→                // Build the full content
  2184→                let fullContent = buildEmailContent();
  2185→
  2186→                // ADD CONVERSATION HISTORY FOR CONTEXT (ChatGPT-like memory)
  2187→                const conversationContext = buildConversationContext();
  2188→                if (conversationContext) {
  2189→                    fullContent += conversationContext;
  2190→                    console.log('Including conversation history:', conversationHistory.length, 'previous exchanges');
  2191→                }
  2192→
  2193→                // Add question if provided
  2194→                const actualQuestion = question || 'Please analyze this email conversation and provide insights on:\n1. Key points and summary\n2. Sentiment and tone analysis\n3. Any potential concerns or red flags\n4. Recommended next steps';
  2195→
  2196→                if (question) {
  2197→                    fullContent += '\n\nCURRENT USER QUESTION:\n' + question;
  2198→                } else {
  2199→                    fullContent += '\n\n' + actualQuestion;
  2200→                }
  2201→
  2202→                // Add context if provided
  2203→                if (context) {
  2204→                    fullContent += '\n\nADDITIONAL CONTEXT:\n' + context;
  2205→                }
  2206→
  2207→                // Fetch additional thread content if selected
  2208→                if (additionalThreads.length > 0) {
  2209→                    document.getElementById('loading-message').textContent = 'Loading additional threads...';
  2210→
  2211→                    for (const threadId of additionalThreads) {
  2212→                        const threadData = await fetch(`api.php?action=thread&thread_id=${threadId}`);
  2213→                        const thread = await threadData.json();
  2214→
  2215→                        if (thread.emails && thread.emails.length > 0) {
  2216→                            fullContent += '\n\n--- ADDITIONAL THREAD ---\n';
  2217→                            fullContent += 'Subject: ' + (thread.emails[0].subject || '(No Subject)') + '\n\n';
  2218→                            fullContent += processAdditionalThreadContent(thread.emails, contentMode);
  2219→                        }
  2220→                    }
  2221→                }
  2222→
  2223→                // Log what's being sent
  2224→                console.log('=== AI REQUEST LOG ===');
  2225→                console.log('Providers:', selectedProvidersList);
  2226→                console.log('Models:', modelsMap);
  2227→                console.log('Content Mode:', contentMode);
  2228→                console.log('Conversation History Entries:', conversationHistory.length);
  2229→                console.log('Content Length:', fullContent.length, 'characters');
  2230→                console.log('Estimated Tokens:', Math.ceil(fullContent.length / 4));
  2231→                console.log('Full Content Preview (first 500 chars):', fullContent.substring(0, 500));
  2232→                console.log('======================');
  2233→
  2234→                document.getElementById('loading-message').textContent = `Analyzing with ${selectedProvidersList.length} AI provider(s)...`;
  2235→
  2236→                // Build request body with all selected providers and their models
  2237→                const requestBody = {
  2238→                    user_content: fullContent,
  2239→                    providers: selectedProvidersList
  2240→                };
  2241→
  2242→                // Add model for each provider
  2243→                for (const [provider, model] of Object.entries(modelsMap)) {
  2244→                    requestBody['model_' + provider] = model;
  2245→                }
  2246→
  2247→                // Send to AI API
  2248→                const response = await fetch('../aiapi/api_opus/api/query.php', {
  2249→                    method: 'POST',
  2250→                    headers: { 'Content-Type': 'application/json' },
  2251→                    body: JSON.stringify(requestBody)
  2252→                });
  2253→
  2254→                const data = await response.json();
  2255→
  2256→                // Log response
  2257→                console.log('=== AI RESPONSE LOG ===');
  2258→                console.log('Success:', data.success);
  2259→                console.log('Query ID:', data.query_id);
  2260→                console.log('Total Cost:', data.total_cost);
  2261→                console.log('Response Keys:', Object.keys(data.responses || {}));
  2262→                console.log('=======================');
  2263→
  2264→                if (data.success) {
  2265→                    // Track if we've added to conversation history (only add once)
  2266→                    let addedToConversation = false;
  2267→                    let firstSuccessfulProvider = null;
  2268→                    let firstSuccessfulResponse = null;
  2269→
  2270→                    // Save to MongoDB for each provider
  2271→                    for (const provider of selectedProvidersList) {
  2272→                        const providerResponse = data.responses[provider + '_response'];
  2273→                        if (providerResponse && providerResponse.success) {
  2274→                            // Track first successful response for conversation history
  2275→                            if (!firstSuccessfulProvider) {
  2276→                                firstSuccessfulProvider = provider;
  2277→                                firstSuccessfulResponse = providerResponse;
  2278→                            }
  2279→
  2280→                            // Save to MongoDB via our API
  2281→                            await saveAIResponse({
  2282→                                thread_ids: [currentThreadId, ...additionalThreads],
  2283→                                contact_id: primaryContactId,
  2284→                                question: actualQuestion,
  2285→                                context: context,
  2286→                                content_mode: contentMode,
  2287→                                content_sent: fullContent, // Log what was sent
  2288→                                content_length: fullContent.length,
  2289→                                estimated_tokens: Math.ceil(fullContent.length / 4),
  2290→                                provider: provider,
  2291→                                model: modelsMap[provider],
  2292→                                query_id: data.query_id,
  2293→                                response: providerResponse,
  2294→                                total_cost: providerResponse.cost || 0,
  2295→                                all_providers: selectedProvidersList,
  2296→                                conversation_history_count: conversationHistory.length
  2297→                            });
  2298→                        }
  2299→                    }
  2300→
  2301→                    // ADD TO CONVERSATION HISTORY (first successful response)
  2302→                    // This creates the ChatGPT-like memory effect
  2303→                    if (firstSuccessfulProvider && firstSuccessfulResponse && firstSuccessfulResponse.response) {
  2304→                        addToConversation(
  2305→                            actualQuestion,
  2306→                            firstSuccessfulResponse.response,
  2307→                            firstSuccessfulProvider,
  2308→                            modelsMap[firstSuccessfulProvider],
  2309→                            context  // Pass context to conversation history
  2310→                        );
  2311→                        console.log('Added to conversation history:', firstSuccessfulProvider);
  2312→                    }
  2313→
  2314→                    // Clear the question field for next question
  2315→                    document.getElementById('ai-question').value = '';
  2316→
  2317→                    // Display response
  2318→                    displayAIResponse(data);
  2319→                } else {
  2320→                    alert('AI request failed: ' + (data.error || 'Unknown error'));
  2321→                }
  2322→            } catch (error) {
  2323→                console.error('AI request error:', error);
  2324→                alert('Error: ' + error.message);
  2325→            } finally {
  2326→                document.getElementById('loading-overlay').classList.remove('active');
  2327→                document.getElementById('submit-ai-btn').disabled = false;

        async function submitToAI() {
            const selectedProvidersList = getSelectedProviders();

            if (selectedProvidersList.length === 0) {
                alert('Please select at least one AI provider');
                return;
            }

            const question = document.getElementById('ai-question').value.trim();
            const context = document.getElementById('ai-context').value.trim();
            const contentMode = document.getElementById('content-mode').value;
            const additionalThreads = getSelectedThreads();

            // Build models map for each selected provider
            const modelsMap = {};
            selectedProvidersList.forEach(provider => {
                const modelSelect = document.getElementById('model_' + provider);
                modelsMap[provider] = modelSelect ? modelSelect.value : '';
            });

            // Show loading
            document.getElementById('loading-overlay').classList.add('active');
            document.getElementById('submit-ai-btn').disabled = true;

            try {
                // Build the full content
                let fullContent = buildEmailContent();

                // ADD CONVERSATION HISTORY FOR CONTEXT (ChatGPT-like memory)
                const conversationContext = buildConversationContext();
                if (conversationContext) {
                    fullContent += conversationContext;
                    console.log('Including conversation history:', conversationHistory.length, 'previous exchanges');
                }

                // Add question if provided
                const actualQuestion = question || 'Please analyze this email conversation and provide insights on:\n1. Key points and summary\n2. Sentiment and tone analysis\n3. Any potential concerns or red flags\n4. Recommended next steps';

                if (question) {
                    fullContent += '\n\nCURRENT USER QUESTION:\n' + question;
                } else {
                    fullContent += '\n\n' + actualQuestion;
                }

                // Add context if provided
                if (context) {
                    fullContent += '\n\nADDITIONAL CONTEXT:\n' + context;
                }

                // Fetch additional thread content if selected
                if (additionalThreads.length > 0) {
                    document.getElementById('loading-message').textContent = 'Loading additional threads...';

                    for (const threadId of additionalThreads) {
                        const threadData = await fetch(`api.php?action=thread&thread_id=${threadId}`);
                        const thread = await threadData.json();

                        if (thread.emails && thread.emails.length > 0) {
                            fullContent += '\n\n--- ADDITIONAL THREAD ---\n';
                            fullContent += 'Subject: ' + (thread.emails[0].subject || '(No Subject)') + '\n\n';
                            fullContent += processAdditionalThreadContent(thread.emails, contentMode);
                        }
                    }
                }

                // Log what's being sent
                console.log('=== AI REQUEST LOG ===');
                console.log('Providers:', selectedProvidersList);
                console.log('Models:', modelsMap);
                console.log('Content Mode:', contentMode);
                console.log('Conversation History Entries:', conversationHistory.length);
                console.log('Content Length:', fullContent.length, 'characters');
                console.log('Estimated Tokens:', Math.ceil(fullContent.length / 4));
                console.log('Full Content Preview (first 500 chars):', fullContent.substring(0, 500));
                console.log('======================');

                document.getElementById('loading-message').textContent = `Analyzing with ${selectedProvidersList.length} AI provider(s)...`;

                // Build request body with all selected providers and their models
                const requestBody = {
                    user_content: fullContent,
                    providers: selectedProvidersList
                };

                // Add model for each provider
                for (const [provider, model] of Object.entries(modelsMap)) {
                    requestBody['model_' + provider] = model;
                }

                // Send to AI API
                const response = await fetch('../aiapi/api_opus/api/query.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(requestBody)
                });

                const data = await response.json();

                // Log response
                console.log('=== AI RESPONSE LOG ===');
                console.log('Success:', data.success);
                console.log('Query ID:', data.query_id);
                console.log('Total Cost:', data.total_cost);
                console.log('Response Keys:', Object.keys(data.responses || {}));
                console.log('=======================');

                if (data.success) {
                    // Track if we've added to conversation history (only add once)
                    let addedToConversation = false;
                    let firstSuccessfulProvider = null;
                    let firstSuccessfulResponse = null;

                    // Save to MongoDB for each provider
                    for (const provider of selectedProvidersList) {
                        const providerResponse = data.responses[provider + '_response'];
                        if (providerResponse && providerResponse.success) {
                            // Track first successful response for conversation history
                            if (!firstSuccessfulProvider) {
                                firstSuccessfulProvider = provider;
                                firstSuccessfulResponse = providerResponse;
                            }

                            // Save to MongoDB via our API
                            await saveAIResponse({
                                thread_ids: [currentThreadId, ...additionalThreads],
                                contact_id: primaryContactId,
                                question: actualQuestion,
                                context: context,
                                content_mode: contentMode,
                                content_sent: fullContent, // Log what was sent
                                content_length: fullContent.length,
                                estimated_tokens: Math.ceil(fullContent.length / 4),
                                provider: provider,
                                model: modelsMap[provider],
                                query_id: data.query_id,
                                response: providerResponse,
                                total_cost: providerResponse.cost || 0,
                                all_providers: selectedProvidersList,
                                conversation_history_count: conversationHistory.length
                            });
                        }
                    }

                    // ADD TO CONVERSATION HISTORY (first successful response)
                    // This creates the ChatGPT-like memory effect
                    if (firstSuccessfulProvider && firstSuccessfulResponse && firstSuccessfulResponse.response) {
                        addToConversation(
                            actualQuestion,
                            firstSuccessfulResponse.response,
                            firstSuccessfulProvider,
                            modelsMap[firstSuccessfulProvider],
                            context  // Pass context to conversation history
                        );
                        console.log('Added to conversation history:', firstSuccessfulProvider);
                    }

                    // Clear the question field for next question
                    document.getElementById('ai-question').value = '';

                    // Display response
                    displayAIResponse(data);
                } else {
                    alert('AI request failed: ' + (data.error || 'Unknown error'));
                }
            } catch (error) {
                console.error('AI request error:', error);
                alert('Error: ' + error.message);
            } finally {
                document.getElementById('loading-overlay').classList.remove('active');
                document.getElementById('submit-ai-btn').disabled = false;


Now I'll replace the entire `submitToAI` function with the enhanced version that includes agent system prompt injection, context threads, token checking, and debug logging.


Edit

        async function submitToAI() {
            const selectedProvidersList = getSelectedProviders();

            if (selectedProvidersList.length === 0) {
                alert('Please select at least one AI provider');
                return;
            }

            const question = document.getElementById('ai-question').value.trim();
            const context = document.getElementById('ai-context').value.trim();
            const contentMode = document.getElementById('content-mode').value;
            const additionalThreads = getSelectedThreads();

            // Build models map for each selected provider
            const modelsMap = {};
            selectedProvidersList.forEach(provider => {
                const modelSelect = document.getElementById('model_' + provider);
                modelsMap[provider] = modelSelect ? modelSelect.value : '';
            });

            // Show loading
            document.getElementById('loading-overlay').classList.add('active');
            document.getElementById('submit-ai-btn').disabled = true;

            try {
                // Build the full content
                let fullContent = buildEmailContent();

                // ADD CONVERSATION HISTORY FOR CONTEXT (ChatGPT-like memory)
                const conversationContext = buildConversationContext();
                if (conversationContext) {
                    fullContent += conversationContext;
                    console.log('Including conversation history:', conversationHistory.length, 'previous exchanges');
                }

                // Add question if provided
                const actualQuestion = question || 'Please analyze this email conversation and provide insights on:\n1. Key points and summary\n2. Sentiment and tone analysis\n3. Any potential concerns or red flags\n4. Recommended next steps';

                if (question) {
                    fullContent += '\n\nCURRENT USER QUESTION:\n' + question;
                } else {
                    fullContent += '\n\n' + actualQuestion;
                }

                // Add context if provided
                if (context) {
                    fullContent += '\n\nADDITIONAL CONTEXT:\n' + context;
                }

                // Fetch additional thread content if selected
                if (additionalThreads.length > 0) {
                    document.getElementById('loading-message').textContent = 'Loading additional threads...';

                    for (const threadId of additionalThreads) {
                        const threadData = await fetch(`api.php?action=thread&thread_id=${threadId}`);
                        const thread = await threadData.json();

                        if (thread.emails && thread.emails.length > 0) {
                            fullContent += '\n\n--- ADDITIONAL THREAD ---\n';
                            fullContent += 'Subject: ' + (thread.emails[0].subject || '(No Subject)') + '\n\n';
                            fullContent += processAdditionalThreadContent(thread.emails, contentMode);
                        }
                    }
                }

                // Log what's being sent
                console.log('=== AI REQUEST LOG ===');
                console.log('Providers:', selectedProvidersList);
                console.log('Models:', modelsMap);
                console.log('Content Mode:', contentMode);
                console.log('Conversation History Entries:', conversationHistory.length);
                console.log('Content Length:', fullContent.length, 'characters');
                console.log('Estimated Tokens:', Math.ceil(fullContent.length / 4));
                console.log('Full Content Preview (first 500 chars):', fullContent.substring(0, 500));
                console.log('======================');

                document.getElementById('loading-message').textContent = `Analyzing with ${selectedProvidersList.length} AI provider(s)...`;

                // Build request body with all selected providers and their models
                const requestBody = {
                    user_content: fullContent,
                    providers: selectedProvidersList
                };

                // Add model for each provider
                for (const [provider, model] of Object.entries(modelsMap)) {
                    requestBody['model_' + provider] = model;
                }

                // Send to AI API
                const response = await fetch('../aiapi/api_opus/api/query.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(requestBody)
                });

                const data = await response.json();

                // Log response
                console.log('=== AI RESPONSE LOG ===');
                console.log('Success:', data.success);
                console.log('Query ID:', data.query_id);
                console.log('Total Cost:', data.total_cost);
                console.log('Response Keys:', Object.keys(data.responses || {}));
                console.log('=======================');

                if (data.success) {
                    // Track if we've added to conversation history (only add once)
                    let addedToConversation = false;
                    let firstSuccessfulProvider = null;
                    let firstSuccessfulResponse = null;

                    // Save to MongoDB for each provider
                    for (const provider of selectedProvidersList) {
                        const providerResponse = data.responses[provider + '_response'];
                        if (providerResponse && providerResponse.success) {
                            // Track first successful response for conversation history
                            if (!firstSuccessfulProvider) {
                                firstSuccessfulProvider = provider;
                                firstSuccessfulResponse = providerResponse;
                            }

                            // Save to MongoDB via our API
                            await saveAIResponse({
                                thread_ids: [currentThreadId, ...additionalThreads],
                                contact_id: primaryContactId,
                                question: actualQuestion,
                                context: context,
                                content_mode: contentMode,
                                content_sent: fullContent, // Log what was sent
                                content_length: fullContent.length,
                                estimated_tokens: Math.ceil(fullContent.length / 4),
                                provider: provider,
                                model: modelsMap[provider],
                                query_id: data.query_id,
                                response: providerResponse,
                                total_cost: providerResponse.cost || 0,
                                all_providers: selectedProvidersList,
                                conversation_history_count: conversationHistory.length
                            });
                        }
                    }

                    // ADD TO CONVERSATION HISTORY (first successful response)
                    // This creates the ChatGPT-like memory effect
                    if (firstSuccessfulProvider && firstSuccessfulResponse && firstSuccessfulResponse.response) {
                        addToConversation(
                            actualQuestion,
                            firstSuccessfulResponse.response,
                            firstSuccessfulProvider,
                            modelsMap[firstSuccessfulProvider],
                            context  // Pass context to conversation history
                        );
                        console.log('Added to conversation history:', firstSuccessfulProvider);
                    }

                    // Clear the question field for next question
                    document.getElementById('ai-question').value = '';

                    // Display response
                    displayAIResponse(data);
                } else {
                    alert('AI request failed: ' + (data.error || 'Unknown error'));
                }
            } catch (error) {
                console.error('AI request error:', error);
                alert('Error: ' + error.message);
            } finally {
                document.getElementById('loading-overlay').classList.remove('active');
                document.getElementById('submit-ai-btn').disabled = false;

        async function submitToAI() {
            var selectedProvidersList = getSelectedProviders();

            if (selectedProvidersList.length === 0) {
                alert('Please select at least one AI provider');
                return;
            }

            var question = document.getElementById('ai-question').value.trim();
            var context = document.getElementById('ai-context').value.trim();
            var contentMode = document.getElementById('content-mode').value;
            var additionalThreads = getSelectedThreads();
            // Also include context builder threads
            var contextThreadIds = contextThreads.map(function(ct) { return ct.threadId; });
            var allAdditionalThreads = additionalThreads.concat(contextThreadIds);

            // Build models map for each selected provider
            var modelsMap = {};
            selectedProvidersList.forEach(function(provider) {
                var modelSelect = document.getElementById('model_' + provider);
                modelsMap[provider] = modelSelect ? modelSelect.value : '';
            });

            // Token check
            var estimatedTokens = estimateCurrentTokens();
            var modelLimit = getSmallestModelLimit();
            if (estimatedTokens > modelLimit * 0.95) {
                if (!confirm('Estimated tokens (' + estimatedTokens.toLocaleString() + ') may exceed model limit (' + modelLimit.toLocaleString() + '). Continue anyway?')) {
                    return;
                }
            }

            // Show loading
            document.getElementById('loading-overlay').classList.add('active');
            document.getElementById('submit-ai-btn').disabled = true;

            try {
                // Build the full content - start with agent system prompt
                var agentPrompt = '';
                if (selectedAgent && AI_AGENTS[selectedAgent]) {
                    agentPrompt = '=== AI AGENT INSTRUCTIONS ===\n' + AI_AGENTS[selectedAgent].systemPrompt + '\n=== END AGENT INSTRUCTIONS ===\n\n';
                }

                // Inject contact memories if available
                var memoryBlock = '';
                if (contactMemories.length > 0 && primaryContactName) {
                    memoryBlock = '=== KNOWN FACTS ABOUT ' + primaryContactName.toUpperCase() + ' ===\n';
                    contactMemories.forEach(function(m) {
                        memoryBlock += '- ' + (m.fact || m) + '\n';
                    });
                    memoryBlock += '=== END KNOWN FACTS ===\n\n';
                }

                var fullContent = agentPrompt + memoryBlock + buildEmailContent();

                // ADD CONVERSATION HISTORY FOR CONTEXT (ChatGPT-like memory)
                var conversationContext = buildConversationContext();
                if (conversationContext) {
                    fullContent += conversationContext;
                    console.log('Including conversation history:', conversationHistory.length, 'previous exchanges');
                }

                // Add question if provided
                var actualQuestion = question || 'Please analyze this email conversation and provide insights on:\n1. Key points and summary\n2. Sentiment and tone analysis\n3. Any potential concerns or red flags\n4. Recommended next steps';

                if (question) {
                    fullContent += '\n\nCURRENT USER QUESTION:\n' + question;
                } else {
                    fullContent += '\n\n' + actualQuestion;
                }

                // Add context if provided
                if (context) {
                    fullContent += '\n\nADDITIONAL CONTEXT:\n' + context;
                }

                // Fetch additional thread content (checkboxes + context builder threads)
                if (allAdditionalThreads.length > 0) {
                    document.getElementById('loading-message').textContent = 'Loading additional threads...';

                    for (var i = 0; i < allAdditionalThreads.length; i++) {
                        var tid = allAdditionalThreads[i];
                        var threadData = await fetch('api.php?action=thread&thread_id=' + tid);
                        var thread = await threadData.json();

                        if (thread.emails && thread.emails.length > 0) {
                            fullContent += '\n\n--- ADDITIONAL THREAD ' + (i + 1) + ' OF ' + allAdditionalThreads.length + ' ---\n';
                            fullContent += 'Subject: ' + (thread.emails[0].subject || '(No Subject)') + '\n\n';
                            fullContent += processAdditionalThreadContent(thread.emails, contentMode);
                        }
                    }
                }

                var finalTokens = Math.ceil(fullContent.length / 3.5);

                // Log to debug file BEFORE sending
                logAiDebug({
                    type: 'request',
                    thread_id: currentThreadId,
                    agent: selectedAgent,
                    providers: selectedProvidersList,
                    models: modelsMap,
                    content_length: fullContent.length,
                    estimated_tokens: finalTokens,
                    question: actualQuestion,
                    context_threads: allAdditionalThreads,
                    full_content: fullContent
                });

                // Console log
                console.log('=== AI REQUEST LOG ===');
                console.log('Agent:', selectedAgent);
                console.log('Providers:', selectedProvidersList);
                console.log('Models:', modelsMap);
                console.log('Content Mode:', contentMode);
                console.log('Context Threads:', allAdditionalThreads.length);
                console.log('Conversation History:', conversationHistory.length);
                console.log('Content Length:', fullContent.length, 'chars');
                console.log('Estimated Tokens:', finalTokens);
                console.log('======================');

                document.getElementById('loading-message').textContent = 'Analyzing with ' + selectedProvidersList.length + ' AI provider(s)...';

                // Build request body with all selected providers and their models
                var requestBody = {
                    user_content: fullContent,
                    providers: selectedProvidersList
                };

                // Add model for each provider
                for (var provider in modelsMap) {
                    requestBody['model_' + provider] = modelsMap[provider];
                }

                // Send to AI API
                var response = await fetch('../aiapi/api_opus/api/query.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(requestBody)
                });

                var data = await response.json();

                // Log response to debug file
                var responsePreview = '';
                if (data.responses) {
                    for (var rk in data.responses) {
                        if (data.responses[rk] && data.responses[rk].response) {
                            responsePreview = data.responses[rk].response.substring(0, 500);
                            break;
                        }
                    }
                }
                logAiDebug({
                    type: 'response',
                    thread_id: currentThreadId,
                    agent: selectedAgent,
                    providers: selectedProvidersList,
                    models: modelsMap,
                    estimated_tokens: finalTokens,
                    question: actualQuestion,
                    response: responsePreview
                });

                console.log('=== AI RESPONSE LOG ===');
                console.log('Success:', data.success);
                console.log('Query ID:', data.query_id);
                console.log('Total Cost:', data.total_cost);
                console.log('=======================');

                if (data.success) {
                    var firstSuccessfulProvider = null;
                    var firstSuccessfulResponse = null;

                    // Save to MongoDB for each provider
                    for (var pi = 0; pi < selectedProvidersList.length; pi++) {
                        var prov = selectedProvidersList[pi];
                        var providerResponse = data.responses[prov + '_response'];
                        if (providerResponse && providerResponse.success) {
                            if (!firstSuccessfulProvider) {
                                firstSuccessfulProvider = prov;
                                firstSuccessfulResponse = providerResponse;
                            }

                            // Save to MongoDB via our API
                            await saveAIResponse({
                                thread_ids: [currentThreadId].concat(allAdditionalThreads),
                                contact_id: primaryContactId,
                                question: actualQuestion,
                                context: context,
                                agent: selectedAgent,
                                content_mode: contentMode,
                                content_sent: fullContent,
                                content_length: fullContent.length,
                                estimated_tokens: finalTokens,
                                provider: prov,
                                model: modelsMap[prov],
                                query_id: data.query_id,
                                response: providerResponse,
                                total_cost: providerResponse.cost || 0,
                                all_providers: selectedProvidersList,
                                conversation_history_count: conversationHistory.length
                            });
                        }
                    }

                    // ADD TO CONVERSATION HISTORY (first successful response)
                    if (firstSuccessfulProvider && firstSuccessfulResponse && firstSuccessfulResponse.response) {
                        addToConversation(
                            actualQuestion,
                            firstSuccessfulResponse.response,
                            firstSuccessfulProvider,
                            modelsMap[firstSuccessfulProvider],
                            context
                        );
                    }

                    // Clear the question field for next question
                    document.getElementById('ai-question').value = '';
                    updateTokenEstimate();

                    // Display response
                    displayAIResponse(data);
                } else {
                    alert('AI request failed: ' + (data.error || 'Unknown error'));
                }
            } catch (error) {
                console.error('AI request error:', error);
                alert('Error: ' + error.message);
            } finally {
                document.getElementById('loading-overlay').classList.remove('active');
                document.getElementById('submit-ai-btn').disabled = false;