/** * AURA CRAG — Enterprise Financial Intelligence & Glass-Box Studio * Frontend Client & Interactive State Machine * Fully synchronized with api/schemas.py (GlassBoxQueryResponse) */ document.addEventListener('DOMContentLoaded', () => { // --- DOM Elements --- const backendStatusEl = document.getElementById('backend-status'); const statusTextEl = document.getElementById('status-text'); const corpusStatEl = document.querySelector('.corpus-stat'); const queryForm = document.getElementById('query-form'); const queryInput = document.getElementById('query-input'); const toggleCrag = document.getElementById('toggle-crag'); const selectTopK = document.getElementById('select-top-k'); const btnSubmit = document.getElementById('btn-submit'); const emptyStateEl = document.getElementById('empty-state'); const answerCardEl = document.getElementById('answer-card'); const answerBodyEl = document.getElementById('answer-body'); const cragActionBadge = document.getElementById('crag-action-badge'); const citationChipsEl = document.getElementById('citation-chips'); const btnCopyContext = document.getElementById('btn-copy-context'); // Metrics Bar const metricLatency = document.getElementById('metric-latency'); const metricAttribution = document.getElementById('metric-attribution'); const metricTokens = document.getElementById('metric-tokens'); const metricCost = document.getElementById('metric-cost'); // Stage 1 Elements const stg1QueryType = document.getElementById('stg1-query-type'); const stg1QueryLen = document.getElementById('stg1-query-len'); const stg1Subqueries = document.getElementById('stg1-subqueries'); const stg1Expanded = document.getElementById('stg1-expanded'); // Stage 2 Elements const stg2DenseCount = document.getElementById('stg2-dense-count'); const stg2DenseList = document.getElementById('stg2-dense-list'); const stg2SparseCount = document.getElementById('stg2-sparse-count'); const stg2SparseList = document.getElementById('stg2-sparse-list'); // Stage 3 Elements const stg3RerankedList = document.getElementById('stg3-reranked-list'); const stg3RrfPool = document.getElementById('stg3-rrf-pool'); // Stage 4 Elements const stg4DecisionBanner = document.getElementById('stg4-decision-banner'); const stg4ActionText = document.getElementById('stg4-action-text'); const stg4ConfidenceVal = document.getElementById('stg4-confidence-val'); const stg4EvalScores = document.getElementById('stg4-eval-scores'); const stg4DynamicHeader = document.getElementById('stg4-dynamic-header'); const stg4DynamicBody = document.getElementById('stg4-dynamic-body'); // Stage 5 Elements const stg5VerifiedCites = document.getElementById('stg5-verified-cites'); const stg5HallucinatedCites = document.getElementById('stg5-hallucinated-cites'); const stg5AttributionScore = document.getElementById('stg5-attribution-score'); const stg5LatencyWaterfall = document.getElementById('stg5-latency-waterfall'); const stg5FinalContext = document.getElementById('stg5-final-context'); // --- Defensive Formatting Helpers --- function formatNum(val, decimals = 2, fallback = '--') { return (typeof val === 'number' && !isNaN(val)) ? val.toFixed(decimals) : fallback; } function formatPct(val, decimals = 1, fallback = '--%') { return (typeof val === 'number' && !isNaN(val)) ? (val * 100).toFixed(decimals) + '%' : fallback; } function formatCurrency(val, decimals = 5, fallback = '< $0.0001') { return (typeof val === 'number' && !isNaN(val)) ? '$' + val.toFixed(decimals) : fallback; } // --- Health Check Polling --- async function checkBackendHealth() { try { const res = await fetch('/health'); if (res.ok) { const data = await res.json(); backendStatusEl.className = 'status-pill status-ready'; const totalChunks = data.total_indexed_chunks || 274; statusTextEl.textContent = `Engine Online • Qdrant Ready (${totalChunks} chunks)`; if (corpusStatEl) { corpusStatEl.textContent = `${totalChunks} Chunks • BGE + BM25`; } } else { throw new Error('Health check returned non-200'); } } catch (err) { backendStatusEl.className = 'status-pill status-checking'; statusTextEl.textContent = 'Connecting to Engine...'; setTimeout(checkBackendHealth, 4000); } } checkBackendHealth(); // --- Stage Tab Navigation --- const stageTabs = document.querySelectorAll('.stage-tab'); stageTabs.forEach(tab => { tab.addEventListener('click', () => { const targetTabId = tab.getAttribute('data-tab'); switchTab(targetTabId); }); }); function switchTab(tabId) { stageTabs.forEach(t => { t.classList.toggle('active', t.getAttribute('data-tab') === tabId); }); document.querySelectorAll('.tab-content').forEach(content => { content.classList.toggle('active', content.id === tabId); }); } // --- Preset Query Chips --- document.querySelectorAll('.chip').forEach(chip => { chip.addEventListener('click', () => { const query = chip.getAttribute('data-query'); if (query) { queryInput.value = query; queryInput.focus(); submitQuery(query); } }); }); // --- Form Submission --- queryForm.addEventListener('submit', (e) => { e.preventDefault(); const query = queryInput.value.trim(); if (!query) return; submitQuery(query); }); async function submitQuery(query) { const enableCrag = toggleCrag.checked; const topK = parseInt(selectTopK.value, 10) || 5; // Loading State btnSubmit.disabled = true; btnSubmit.innerHTML = `Analyzing & Routing... `; try { const res = await fetch('/api/v1/query', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: query, enable_crag: enableCrag, top_k: topK }) }); if (!res.ok) { const errorData = await res.json().catch(() => ({})); throw new Error(errorData.detail || `Server responded with status ${res.status}`); } const data = await res.json(); renderPipelineResponse(data); } catch (err) { alert(`Query Pipeline Error: ${err.message}`); console.error(err); } finally { btnSubmit.disabled = false; btnSubmit.innerHTML = `Execute CRAG `; } } // --- Render Complete Pipeline Response --- function renderPipelineResponse(data) { if (!data) return; emptyStateEl.classList.add('hidden'); answerCardEl.classList.remove('hidden'); // 1. Action Badge (from data.crag_action) const action = data.crag_action || 'CORRECT'; cragActionBadge.textContent = action; cragActionBadge.className = 'action-badge ' + ( action === 'CORRECT' ? 'badge-correct' : action === 'AMBIGUOUS' ? 'badge-ambiguous' : 'badge-incorrect' ); // 2. Synthesized Answer with Markdown & Citation Pills let rawAnswer = data.answer || 'No answer generated.'; // Replace [DOC:chunk_xxx] with interactive pill rawAnswer = rawAnswer.replace(/\[DOC:([^\]]+)\]/g, (match, chunkId) => { return `📄 ${escapeHtml(chunkId)}`; }); // Replace [WEB:url] with interactive web pill rawAnswer = rawAnswer.replace(/\[WEB:([^\]]+)\]/g, (match, url) => { let displayUrl = url; try { const parsed = new URL(url); displayUrl = parsed.hostname; } catch (e) {} return `🌐 ${escapeHtml(displayUrl)}`; }); if (window.marked) { answerBodyEl.innerHTML = marked.parse(rawAnswer); } else { answerBodyEl.innerHTML = rawAnswer; } // Attach click listeners to citation badges to highlight in inspector attachCitationListeners(); // 3. Citations Panel (from data.stage_6_attribution_audit) citationChipsEl.innerHTML = ''; const stg6 = data.stage_6_attribution_audit || {}; const validCites = stg6.valid_citations || []; // Parse distinct docs and web citations const docCites = validCites.filter(c => c.startsWith('[DOC:')).map(c => c.slice(5, -1)); const webCites = validCites.filter(c => c.startsWith('[WEB:')).map(c => c.slice(5, -1)); if (validCites.length === 0) { citationChipsEl.innerHTML = `No citations flagged in final response.`; } else { docCites.forEach(c => { const chip = document.createElement('span'); chip.className = 'citation-item-chip cite-doc'; chip.innerHTML = `📄 ${escapeHtml(c)}`; chip.addEventListener('click', () => { switchTab('tab-fusion'); highlightChunk(c); }); citationChipsEl.appendChild(chip); }); webCites.forEach(w => { const chip = document.createElement('a'); chip.className = 'citation-item-chip cite-web'; chip.href = encodeURI(w); chip.target = '_blank'; chip.rel = 'noopener'; let domain = w; try { domain = new URL(w).hostname; } catch(e){} chip.innerHTML = `🌐 ${escapeHtml(domain)}`; citationChipsEl.appendChild(chip); }); } // 4. Answer Metrics Footer (from data.latencies_ms & data.stage_5_generation) const latencies = data.latencies_ms || {}; const stg5 = data.stage_5_generation || {}; metricLatency.textContent = `${formatNum(latencies.total, 0)} ms`; metricAttribution.textContent = formatPct(data.attribution_accuracy ?? stg6.attribution_accuracy ?? 1.0, 1); metricTokens.textContent = stg5.prompt_tokens != null ? stg5.prompt_tokens : '--'; metricCost.textContent = formatCurrency(stg5.estimated_cost_usd, 5); // ------------------------------------------------------------- // STAGE 1: Query Processing // ------------------------------------------------------------- const stg1 = data.stage_1_query_processing || {}; stg1QueryType.textContent = (stg1.detected_type || 'FACTUAL').toUpperCase(); stg1QueryLen.textContent = `${data.query ? data.query.length : 0} chars`; const searchQueries = stg1.search_queries || []; if (searchQueries.length > 0) { stg1Subqueries.innerHTML = `