~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
Cleanup/remove temp js files (#533)
LearningCircuit6dd481a9506e
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 4550189e29..02f3b30212 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -145,7 +145,7 @@ jobs:node-version: '18'- name: Install UI test dependencies- run: npm install+ run: cd tests && npm install- name: Install infrastructure test dependenciesrun: |diff --git a/.github/workflows/ui-tests.yml b/.github/workflows/ui-tests.ymlindex a4cdcfcbce..4e442f364f 100644--- a/.github/workflows/ui-tests.yml+++ b/.github/workflows/ui-tests.yml@@ -43,7 +43,7 @@ jobs:run: |pdm installpdm install -d- npm install+ cd tests && npm install- name: Install browser dependenciesrun: |diff --git a/app.py b/app.pydeleted file mode 100644index 6fc0ce44fa..0000000000--- a/app.py+++ /dev/null@@ -1,11 +0,0 @@-#!/usr/bin/env python-"""-Main entry point for the Local Deep Research application.-"""--import local_deep_research # noqa-from local_deep_research.utilities.log_utils import config_logger # noqa--if __name__ == "__main__":- config_logger("ldr_web")- local_deep_research.main()diff --git a/debug_pytest.py b/scripts/dev/debug_pytest.pysimilarity index 100%rename from debug_pytest.pyrename to scripts/dev/debug_pytest.pydiff --git a/kill_servers.py b/scripts/dev/kill_servers.pysimilarity index 83%rename from kill_servers.pyrename to scripts/dev/kill_servers.pyindex 6faff1230c..6370aeec25 100644--- a/kill_servers.py+++ b/scripts/dev/kill_servers.py@@ -20,7 +20,11 @@ def kill_flask_servers():if (cmdlineand "python" in proc.info["name"].lower()- and any("main.py" in arg for arg in cmdline if arg)+ and any(+ "local_deep_research.web.app" in arg+ for arg in cmdline+ if arg+ )):pid = proc.info["pid"]print(f"Found Flask server process {pid}, killing...")@@ -66,7 +70,11 @@ def check_flask_servers():if (cmdlineand "python" in proc.info["name"].lower()- and any("main.py" in arg for arg in cmdline if arg)+ and any(+ "local_deep_research.web.app" in arg+ for arg in cmdline+ if arg+ )):pid = proc.info["pid"]running_servers.append(pid)@@ -85,9 +93,25 @@ def start_flask_server(port=5000):print(f"Starting Flask server on port {port}...")# Get the virtual environment Python executable- venv_path = os.path.join(".venv", "Scripts", "python.exe")- if not os.path.exists(venv_path):- print(f"Error: Could not find Python executable at {venv_path}")+ # Try multiple common venv locations+ venv_paths = [+ os.path.join("venv_dev", "bin", "python"), # Linux/Mac+ os.path.join("venv", "bin", "python"), # Linux/Mac+ os.path.join(".venv", "Scripts", "python.exe"), # Windows+ os.path.join("venv_dev", "Scripts", "python.exe"), # Windows+ os.path.join("venv", "Scripts", "python.exe"), # Windows+ ]++ venv_path = None+ for path in venv_paths:+ if os.path.exists(path):+ venv_path = path+ break++ if not venv_path:+ print(+ "Error: Could not find Python executable in any common venv location"+ )return Nonetry:@@ -105,7 +129,13 @@ def start_flask_server(port=5000):# Start the Flask server directly without background flags# to better catch any startup errorsprocess = subprocess.Popen(- [venv_path, "main.py", "--port", str(port)],+ [+ venv_path,+ "-m",+ "local_deep_research.web.app",+ "--port",+ str(port),+ ],stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True, # Use text mode for easier output reading@@ -203,15 +233,29 @@ def start_flask_server_windows(port=5000):)# Get the virtual environment Python executable- venv_path = os.path.join(".venv", "Scripts", "python.exe")- if not os.path.exists(venv_path):- print(f"Error: Could not find Python executable at {venv_path}")+ # Try multiple common venv locations+ venv_paths = [+ os.path.join("venv_dev", "Scripts", "python.exe"), # Windows+ os.path.join("venv", "Scripts", "python.exe"), # Windows+ os.path.join(".venv", "Scripts", "python.exe"), # Windows+ ]++ venv_path = None+ for path in venv_paths:+ if os.path.exists(path):+ venv_path = path+ break++ if not venv_path:+ print(+ "Error: Could not find Python executable in any common venv location"+ )return Nonetry:# Use Windows 'start' command to launch in a new window# This is more reliable on Windows for Flask apps- cmd = f'start "Flask Server" /MIN "{venv_path}" main.py --port {port}'+ cmd = f'start "Flask Server" /MIN "{venv_path}" -m local_deep_research.web.app --port {port}'subprocess.run(cmd, shell=True, check=True)print(f"Flask server starting on port {port}")diff --git a/run_tests.py b/scripts/dev/run_tests.pysimilarity index 100%rename from run_tests.pyrename to scripts/dev/run_tests.pydiff --git a/temp_js_check.js b/temp_js_check.jsdeleted file mode 100644index 9a14e6577b..0000000000--- a/temp_js_check.js+++ /dev/null@@ -1,441 +0,0 @@-// Cost Analytics JavaScript-(function() {- let currentPeriod = '7d';- let costData = null;- let trendsChart = null;- let modelChart = null;-- // Initialize the page- document.addEventListener('DOMContentLoaded', function() {- setupEventListeners();- loadCostData();- });-- function setupEventListeners() {- // Time period buttons- document.querySelectorAll('.time-range-btn').forEach(btn => {- btn.addEventListener('click', function() {- // Update active state- document.querySelectorAll('.time-range-btn').forEach(b => b.classList.remove('active'));- this.classList.add('active');-- // Update period and reload data- currentPeriod = this.dataset.period;- loadCostData();- });- });- }-- async function loadCostData() {- try {- showLoading();-- const response = await fetch(`/metrics/api/cost-analytics?period=${currentPeriod}`);- if (!response.ok) {- throw new Error(`API failed: ${response.status}`);- }-- const data = await response.json();-- if (data.status === 'success') {- costData = data;-- if (data.overview.total_calls > 0) {- displayCostData();- showContent();- } else {- showNoData();- }- } else {- throw new Error(data.message || 'Unknown error');- }- } catch (error) {- console.error('Error loading cost data:', error);- showError();- }- }-- function displayCostData() {- const overview = costData.overview;-- // Update overview cards- document.getElementById('total-cost').textContent = formatCurrency(overview.total_cost);- document.getElementById('avg-research-cost').textContent = formatCurrency(overview.avg_cost_per_call);-- // Find most expensive model and calculate local savings- const models = Object.entries(overview.model_breakdown || {});- if (models.length > 0) {- // Most expensive by total cost- const mostExpensive = models.reduce((max, [name, data]) =>- data.total_cost > max[1].total_cost ? [name, data] : max- );- document.getElementById('most-expensive-model').textContent = mostExpensive[0];- document.getElementById('most-expensive-model-cost').textContent =- `${formatCurrency(mostExpensive[1].total_cost)} total`;-- // Calculate local model savings- let localTokens = 0;- let localCalls = 0;-- for (const [modelName, data] of models) {- if (data.total_cost === 0) { // Local models have zero cost- localTokens += data.prompt_tokens + data.completion_tokens;- localCalls += data.calls;- }- }-- // Estimate savings using GPT-3.5 pricing as baseline- const estimatedSavings = (localTokens / 1000) * 0.0015; // ~$0.0015 per 1K tokens average-- if (localTokens > 0) {- document.getElementById('local-savings').textContent = formatCurrency(estimatedSavings);- document.getElementById('local-savings-subtitle').textContent =- `${localTokens.toLocaleString()} tokens, ${localCalls} calls`;- } else {- document.getElementById('local-savings').textContent = '$0.00';- document.getElementById('local-savings-subtitle').textContent = 'No local model usage';- }- }-- // Load additional data for charts- loadChartsData();- displayExpensiveResearch();- displayOptimizationTips();- }-- async function loadChartsData() {- // For now, create sample chart data- // In a real implementation, you'd fetch time-series cost data- createCostTrendsChart();- createProviderChart();- createModelCostChart();- }-- function createCostTrendsChart() {- const ctx = document.getElementById('cost-trends-chart');- if (!ctx) return;-- if (trendsChart) {- trendsChart.destroy();- }-- // Sample data - replace with real time-series data- const labels = ['Week 1', 'Week 2', 'Week 3', 'Week 4'];- const costs = [0.02, 0.035, 0.028, 0.041];-- trendsChart = new Chart(ctx, {- type: 'line',- data: {- labels: labels,- datasets: [{- label: 'Weekly Cost',- data: costs,- borderColor: '#4CAF50',- backgroundColor: 'rgba(76, 175, 80, 0.1)',- borderWidth: 3,- fill: true,- tension: 0.4- }]- },- options: {- responsive: true,- maintainAspectRatio: false,- scales: {- y: {- beginAtZero: true,- ticks: {- callback: function(value) {- return formatCurrency(value);- }- }- }- },- plugins: {- tooltip: {- callbacks: {- label: function(context) {- return `Cost: ${formatCurrency(context.parsed.y)}`;- }- }- }- }- }- });- }-- function createProviderChart() {- const ctx = document.getElementById('provider-chart');- if (!ctx) return;-- if (window.providerChart) {- window.providerChart.destroy();- }-- // Calculate provider usage from model breakdown- const models = Object.entries(costData.overview.model_breakdown || {});- const providerStats = {};-- for (const [modelName, data] of models) {- // Determine provider from model cost (0 = local, >0 = commercial)- let provider = 'Unknown';- if (data.total_cost === 0) {- provider = 'Local (Ollama/LM Studio)';- } else if (modelName.toLowerCase().includes('gpt')) {- provider = 'OpenAI';- } else if (modelName.toLowerCase().includes('claude')) {- provider = 'Anthropic';- } else if (modelName.toLowerCase().includes('gemini')) {- provider = 'Google';- }-- if (!providerStats[provider]) {- providerStats[provider] = { calls: 0, tokens: 0, cost: 0 };- }-- providerStats[provider].calls += data.calls;- providerStats[provider].tokens += data.prompt_tokens + data.completion_tokens;- providerStats[provider].cost += data.total_cost;- }-- const labels = Object.keys(providerStats);- const tokens = Object.values(providerStats).map(p => p.tokens);- const colors = {- 'Local (Ollama/LM Studio)': '#4CAF50',- 'OpenAI': '#00A67E',- 'Anthropic': '#FF6B35',- 'Google': '#4285F4',- 'Unknown': '#9E9E9E'- };-- window.providerChart = new Chart(ctx, {- type: 'doughnut',- data: {- labels: labels,- datasets: [{- label: 'Token Usage',- data: tokens,- backgroundColor: labels.map(label => colors[label] || '#9E9E9E'),- borderWidth: 2,- borderColor: '#fff'- }]- },- options: {- responsive: true,- maintainAspectRatio: false,- plugins: {- legend: {- position: 'bottom',- labels: {- padding: 20,- usePointStyle: true- }- },- tooltip: {- callbacks: {- label: function(context) {- const provider = context.label;- const stats = providerStats[provider];- return [- `${provider}`,- `Tokens: ${stats.tokens.toLocaleString()}`,- `Calls: ${stats.calls}`,- `Cost: ${formatCurrency(stats.cost)}`- ];- }- }- }- }- }- });- }-- function createModelCostChart() {- const ctx = document.getElementById('model-cost-chart');- if (!ctx) return;-- if (modelChart) {- modelChart.destroy();- }-- const models = Object.entries(costData.overview.model_breakdown || {});- const labels = models.map(([name, data]) => {- // Add provider info to label- let provider = data.total_cost === 0 ? '(Local)' : '(Commercial)';- return `${name} ${provider}`;- });- const costs = models.map(([, data]) => data.total_cost);-- modelChart = new Chart(ctx, {- type: 'bar',- data: {- labels: labels,- datasets: [{- label: 'Total Cost',- data: costs,- backgroundColor: [- '#4CAF50',- '#2196F3',- '#FF9800',- '#9C27B0',- '#F44336'- ].slice(0, labels.length),- borderWidth: 1- }]- },- options: {- responsive: true,- maintainAspectRatio: false,- scales: {- y: {- beginAtZero: true,- ticks: {- callback: function(value) {- return formatCurrency(value);- }- }- }- },- plugins: {- tooltip: {- callbacks: {- label: function(context) {- return `Cost: ${formatCurrency(context.parsed.y)}`;- }- }- }- }- }- });- }-- function displayExpensiveResearch() {- const container = document.getElementById('expensive-research-list');- const expensiveResearch = costData.top_expensive_research || [];-- if (expensiveResearch.length === 0) {- container.innerHTML = '<p style="text-align: center; color: var(--text-secondary); padding: 2rem;">No research cost data available</p>';- return;- }-- container.innerHTML = '';- expensiveResearch.slice(0, 10).forEach((item, index) => {- const div = document.createElement('div');- div.className = 'cost-item';- div.innerHTML = `- <div class="cost-item-info">- <div class="cost-item-name">- <a href="/research/results/${item.research_id}" class="research-link">- Research Session #${item.research_id}- </a>- </div>- <div class="cost-item-details">Rank #${index + 1} most expensive</div>- </div>- <div class="cost-item-value">${formatCurrency(item.total_cost)}</div>- `;- container.appendChild(div);- });- }-- function displayOptimizationTips() {- const container = document.getElementById('optimization-tips');- const tips = generateOptimizationTips();-- container.innerHTML = '';- tips.forEach(tip => {- const li = document.createElement('li');- li.textContent = tip;- container.appendChild(li);- });- }-- function generateOptimizationTips() {- const tips = [];- const overview = costData.overview;- const models = Object.entries(overview.model_breakdown || {});-- // Count local vs commercial usage- let localTokens = 0;- let commercialTokens = 0;- let hasLocalModels = false;-- for (const [modelName, data] of models) {- if (data.total_cost === 0) {- localTokens += data.prompt_tokens + data.completion_tokens;- hasLocalModels = true;- } else {- commercialTokens += data.prompt_tokens + data.completion_tokens;- }- }-- // Generate provider-aware tips- if (!hasLocalModels && overview.total_cost > 0) {- tips.push('Consider using local models like Ollama for zero-cost inference while maintaining quality');- }-- if (hasLocalModels && commercialTokens > localTokens) {- tips.push('You\'re using local models! Try shifting more workloads to local models to reduce costs');- }-- if (overview.total_cost > 0.1) {- tips.push('Consider using more cost-effective models or local alternatives for routine research tasks');- }-- if (overview.avg_cost_per_call > 0.01) {- tips.push('Try quick research mode for simple queries to reduce token usage');- }-- if (models.length > 1) {- tips.push('Compare model performance vs cost to optimize your model selection');- }-- if (hasLocalModels && overview.total_cost === 0) {- tips.push('Excellent! You're using 100% local models with zero inference costs');- tips.push('Local models provide privacy benefits while keeping costs at $0.00');- }-- if (tips.length === 0) {- tips.push('Your research costs are well optimized!');- tips.push('Consider local models like Ollama for even lower costs');- }-- return tips;- }-- function formatCurrency(amount) {- if (amount < 0.001) {- return `$${amount.toFixed(6)}`;- } else if (amount < 0.1) {- return `$${amount.toFixed(4)}`;- } else {- return `$${amount.toFixed(2)}`;- }- }-- function showLoading() {- document.getElementById('loading').style.display = 'block';- document.getElementById('cost-content').style.display = 'none';- document.getElementById('error').style.display = 'none';- document.getElementById('no-data').style.display = 'none';- }-- function showContent() {- document.getElementById('loading').style.display = 'none';- document.getElementById('cost-content').style.display = 'block';- document.getElementById('error').style.display = 'none';- document.getElementById('no-data').style.display = 'none';- }-- function showError() {- document.getElementById('loading').style.display = 'none';- document.getElementById('cost-content').style.display = 'none';- document.getElementById('error').style.display = 'block';- document.getElementById('no-data').style.display = 'none';- }-- function showNoData() {- document.getElementById('loading').style.display = 'none';- document.getElementById('cost-content').style.display = 'none';- document.getElementById('error').style.display = 'none';- document.getElementById('no-data').style.display = 'block';- }-})();diff --git a/temp_js_check_fixed.js b/temp_js_check_fixed.jsdeleted file mode 100644index 7373d24e0a..0000000000--- a/temp_js_check_fixed.js+++ /dev/null@@ -1,441 +0,0 @@-// Cost Analytics JavaScript-(function() {- let currentPeriod = '7d';- let costData = null;- let trendsChart = null;- let modelChart = null;-- // Initialize the page- document.addEventListener('DOMContentLoaded', function() {- setupEventListeners();- loadCostData();- });-- function setupEventListeners() {- // Time period buttons- document.querySelectorAll('.time-range-btn').forEach(btn => {- btn.addEventListener('click', function() {- // Update active state- document.querySelectorAll('.time-range-btn').forEach(b => b.classList.remove('active'));- this.classList.add('active');-- // Update period and reload data- currentPeriod = this.dataset.period;- loadCostData();- });- });- }-- async function loadCostData() {- try {- showLoading();-- const response = await fetch(`/metrics/api/cost-analytics?period=${currentPeriod}`);- if (!response.ok) {- throw new Error(`API failed: ${response.status}`);- }-- const data = await response.json();-- if (data.status === 'success') {- costData = data;-- if (data.overview.total_calls > 0) {- displayCostData();- showContent();- } else {- showNoData();- }- } else {- throw new Error(data.message || 'Unknown error');- }- } catch (error) {- console.error('Error loading cost data:', error);- showError();- }- }-- function displayCostData() {- const overview = costData.overview;-- // Update overview cards- document.getElementById('total-cost').textContent = formatCurrency(overview.total_cost);- document.getElementById('avg-research-cost').textContent = formatCurrency(overview.avg_cost_per_call);-- // Find most expensive model and calculate local savings- const models = Object.entries(overview.model_breakdown || {});- if (models.length > 0) {- // Most expensive by total cost- const mostExpensive = models.reduce((max, [name, data]) =>- data.total_cost > max[1].total_cost ? [name, data] : max- );- document.getElementById('most-expensive-model').textContent = mostExpensive[0];- document.getElementById('most-expensive-model-cost').textContent =- `${formatCurrency(mostExpensive[1].total_cost)} total`;-- // Calculate local model savings- let localTokens = 0;- let localCalls = 0;-- for (const [modelName, data] of models) {- if (data.total_cost === 0) { // Local models have zero cost- localTokens += data.prompt_tokens + data.completion_tokens;- localCalls += data.calls;- }- }-- // Estimate savings using GPT-3.5 pricing as baseline- const estimatedSavings = (localTokens / 1000) * 0.0015; // ~$0.0015 per 1K tokens average-- if (localTokens > 0) {- document.getElementById('local-savings').textContent = formatCurrency(estimatedSavings);- document.getElementById('local-savings-subtitle').textContent =- `${localTokens.toLocaleString()} tokens, ${localCalls} calls`;- } else {- document.getElementById('local-savings').textContent = '$0.00';- document.getElementById('local-savings-subtitle').textContent = 'No local model usage';- }- }-- // Load additional data for charts- loadChartsData();- displayExpensiveResearch();- displayOptimizationTips();- }-- async function loadChartsData() {- // For now, create sample chart data- // In a real implementation, you'd fetch time-series cost data- createCostTrendsChart();- createProviderChart();- createModelCostChart();- }-- function createCostTrendsChart() {- const ctx = document.getElementById('cost-trends-chart');- if (!ctx) return;-- if (trendsChart) {- trendsChart.destroy();- }-- // Sample data - replace with real time-series data- const labels = ['Week 1', 'Week 2', 'Week 3', 'Week 4'];- const costs = [0.02, 0.035, 0.028, 0.041];-- trendsChart = new Chart(ctx, {- type: 'line',- data: {- labels: labels,- datasets: [{- label: 'Weekly Cost',- data: costs,- borderColor: '#4CAF50',- backgroundColor: 'rgba(76, 175, 80, 0.1)',- borderWidth: 3,- fill: true,- tension: 0.4- }]- },- options: {- responsive: true,- maintainAspectRatio: false,- scales: {- y: {- beginAtZero: true,- ticks: {- callback: function(value) {- return formatCurrency(value);- }- }- }- },- plugins: {- tooltip: {- callbacks: {- label: function(context) {- return `Cost: ${formatCurrency(context.parsed.y)}`;- }- }- }- }- }- });- }-- function createProviderChart() {- const ctx = document.getElementById('provider-chart');- if (!ctx) return;-- if (window.providerChart) {- window.providerChart.destroy();- }-- // Calculate provider usage from model breakdown- const models = Object.entries(costData.overview.model_breakdown || {});- const providerStats = {};-- for (const [modelName, data] of models) {- // Determine provider from model cost (0 = local, >0 = commercial)- let provider = 'Unknown';- if (data.total_cost === 0) {- provider = 'Local (Ollama/LM Studio)';- } else if (modelName.toLowerCase().includes('gpt')) {- provider = 'OpenAI';- } else if (modelName.toLowerCase().includes('claude')) {- provider = 'Anthropic';- } else if (modelName.toLowerCase().includes('gemini')) {- provider = 'Google';- }-- if (!providerStats[provider]) {- providerStats[provider] = { calls: 0, tokens: 0, cost: 0 };- }-- providerStats[provider].calls += data.calls;- providerStats[provider].tokens += data.prompt_tokens + data.completion_tokens;- providerStats[provider].cost += data.total_cost;- }-- const labels = Object.keys(providerStats);- const tokens = Object.values(providerStats).map(p => p.tokens);- const colors = {- 'Local (Ollama/LM Studio)': '#4CAF50',- 'OpenAI': '#00A67E',- 'Anthropic': '#FF6B35',- 'Google': '#4285F4',- 'Unknown': '#9E9E9E'- };-- window.providerChart = new Chart(ctx, {- type: 'doughnut',- data: {- labels: labels,- datasets: [{- label: 'Token Usage',- data: tokens,- backgroundColor: labels.map(label => colors[label] || '#9E9E9E'),- borderWidth: 2,- borderColor: '#fff'- }]- },- options: {- responsive: true,- maintainAspectRatio: false,- plugins: {- legend: {- position: 'bottom',- labels: {- padding: 20,- usePointStyle: true- }- },- tooltip: {- callbacks: {- label: function(context) {- const provider = context.label;- const stats = providerStats[provider];- return [- `${provider}`,- `Tokens: ${stats.tokens.toLocaleString()}`,- `Calls: ${stats.calls}`,- `Cost: ${formatCurrency(stats.cost)}`- ];- }- }- }- }- }- });- }-- function createModelCostChart() {- const ctx = document.getElementById('model-cost-chart');- if (!ctx) return;-- if (modelChart) {- modelChart.destroy();- }-- const models = Object.entries(costData.overview.model_breakdown || {});- const labels = models.map(([name, data]) => {- // Add provider info to label- let provider = data.total_cost === 0 ? '(Local)' : '(Commercial)';- return `${name} ${provider}`;- });- const costs = models.map(([, data]) => data.total_cost);-- modelChart = new Chart(ctx, {- type: 'bar',- data: {- labels: labels,- datasets: [{- label: 'Total Cost',- data: costs,- backgroundColor: [- '#4CAF50',- '#2196F3',- '#FF9800',- '#9C27B0',- '#F44336'- ].slice(0, labels.length),- borderWidth: 1- }]- },- options: {- responsive: true,- maintainAspectRatio: false,- scales: {- y: {- beginAtZero: true,- ticks: {- callback: function(value) {- return formatCurrency(value);- }- }- }- },- plugins: {- tooltip: {- callbacks: {- label: function(context) {- return `Cost: ${formatCurrency(context.parsed.y)}`;- }- }- }- }- }- });- }-- function displayExpensiveResearch() {- const container = document.getElementById('expensive-research-list');- const expensiveResearch = costData.top_expensive_research || [];-- if (expensiveResearch.length === 0) {- container.innerHTML = '<p style="text-align: center; color: var(--text-secondary); padding: 2rem;">No research cost data available</p>';- return;- }-- container.innerHTML = '';- expensiveResearch.slice(0, 10).forEach((item, index) => {- const div = document.createElement('div');- div.className = 'cost-item';- div.innerHTML = `- <div class="cost-item-info">- <div class="cost-item-name">- <a href="/research/results/${item.research_id}" class="research-link">- Research Session #${item.research_id}- </a>- </div>- <div class="cost-item-details">Rank #${index + 1} most expensive</div>- </div>- <div class="cost-item-value">${formatCurrency(item.total_cost)}</div>- `;- container.appendChild(div);- });- }-- function displayOptimizationTips() {- const container = document.getElementById('optimization-tips');- const tips = generateOptimizationTips();-- container.innerHTML = '';- tips.forEach(tip => {- const li = document.createElement('li');- li.textContent = tip;- container.appendChild(li);- });- }-- function generateOptimizationTips() {- const tips = [];- const overview = costData.overview;- const models = Object.entries(overview.model_breakdown || {});-- // Count local vs commercial usage- let localTokens = 0;- let commercialTokens = 0;- let hasLocalModels = false;-- for (const [modelName, data] of models) {- if (data.total_cost === 0) {- localTokens += data.prompt_tokens + data.completion_tokens;- hasLocalModels = true;- } else {- commercialTokens += data.prompt_tokens + data.completion_tokens;- }- }-- // Generate provider-aware tips- if (!hasLocalModels && overview.total_cost > 0) {- tips.push('Consider using local models like Ollama for zero-cost inference while maintaining quality');- }-- if (hasLocalModels && commercialTokens > localTokens) {- tips.push('You are using local models! Try shifting more workloads to local models to reduce costs');- }-- if (overview.total_cost > 0.1) {- tips.push('Consider using more cost-effective models or local alternatives for routine research tasks');- }-- if (overview.avg_cost_per_call > 0.01) {- tips.push('Try quick research mode for simple queries to reduce token usage');- }-- if (models.length > 1) {- tips.push('Compare model performance vs cost to optimize your model selection');- }-- if (hasLocalModels && overview.total_cost === 0) {- tips.push('Excellent! You are using 100% local models with zero inference costs');- tips.push('Local models provide privacy benefits while keeping costs at $0.00');- }-- if (tips.length === 0) {- tips.push('Your research costs are well optimized!');- tips.push('Consider local models like Ollama for even lower costs');- }-- return tips;- }-- function formatCurrency(amount) {- if (amount < 0.001) {- return `$${amount.toFixed(6)}`;- } else if (amount < 0.1) {- return `$${amount.toFixed(4)}`;- } else {- return `$${amount.toFixed(2)}`;- }- }-- function showLoading() {- document.getElementById('loading').style.display = 'block';- document.getElementById('cost-content').style.display = 'none';- document.getElementById('error').style.display = 'none';- document.getElementById('no-data').style.display = 'none';- }-- function showContent() {- document.getElementById('loading').style.display = 'none';- document.getElementById('cost-content').style.display = 'block';- document.getElementById('error').style.display = 'none';- document.getElementById('no-data').style.display = 'none';- }-- function showError() {- document.getElementById('loading').style.display = 'none';- document.getElementById('cost-content').style.display = 'none';- document.getElementById('error').style.display = 'block';- document.getElementById('no-data').style.display = 'none';- }-- function showNoData() {- document.getElementById('loading').style.display = 'none';- document.getElementById('cost-content').style.display = 'none';- document.getElementById('error').style.display = 'none';- document.getElementById('no-data').style.display = 'block';- }-})();diff --git a/temp_js_final_check.js b/temp_js_final_check.jsdeleted file mode 100644index 7373d24e0a..0000000000--- a/temp_js_final_check.js+++ /dev/null@@ -1,441 +0,0 @@-// Cost Analytics JavaScript-(function() {- let currentPeriod = '7d';- let costData = null;- let trendsChart = null;- let modelChart = null;-- // Initialize the page- document.addEventListener('DOMContentLoaded', function() {- setupEventListeners();- loadCostData();- });-- function setupEventListeners() {- // Time period buttons- document.querySelectorAll('.time-range-btn').forEach(btn => {- btn.addEventListener('click', function() {- // Update active state- document.querySelectorAll('.time-range-btn').forEach(b => b.classList.remove('active'));- this.classList.add('active');-- // Update period and reload data- currentPeriod = this.dataset.period;- loadCostData();- });- });- }-- async function loadCostData() {- try {- showLoading();-- const response = await fetch(`/metrics/api/cost-analytics?period=${currentPeriod}`);- if (!response.ok) {- throw new Error(`API failed: ${response.status}`);- }-- const data = await response.json();-- if (data.status === 'success') {- costData = data;-- if (data.overview.total_calls > 0) {- displayCostData();- showContent();- } else {- showNoData();- }- } else {- throw new Error(data.message || 'Unknown error');- }- } catch (error) {- console.error('Error loading cost data:', error);- showError();- }- }-- function displayCostData() {- const overview = costData.overview;-- // Update overview cards- document.getElementById('total-cost').textContent = formatCurrency(overview.total_cost);- document.getElementById('avg-research-cost').textContent = formatCurrency(overview.avg_cost_per_call);-- // Find most expensive model and calculate local savings- const models = Object.entries(overview.model_breakdown || {});- if (models.length > 0) {- // Most expensive by total cost- const mostExpensive = models.reduce((max, [name, data]) =>- data.total_cost > max[1].total_cost ? [name, data] : max- );- document.getElementById('most-expensive-model').textContent = mostExpensive[0];- document.getElementById('most-expensive-model-cost').textContent =- `${formatCurrency(mostExpensive[1].total_cost)} total`;-- // Calculate local model savings- let localTokens = 0;- let localCalls = 0;-- for (const [modelName, data] of models) {- if (data.total_cost === 0) { // Local models have zero cost- localTokens += data.prompt_tokens + data.completion_tokens;- localCalls += data.calls;- }- }-- // Estimate savings using GPT-3.5 pricing as baseline- const estimatedSavings = (localTokens / 1000) * 0.0015; // ~$0.0015 per 1K tokens average-- if (localTokens > 0) {- document.getElementById('local-savings').textContent = formatCurrency(estimatedSavings);- document.getElementById('local-savings-subtitle').textContent =- `${localTokens.toLocaleString()} tokens, ${localCalls} calls`;- } else {- document.getElementById('local-savings').textContent = '$0.00';- document.getElementById('local-savings-subtitle').textContent = 'No local model usage';- }- }-- // Load additional data for charts- loadChartsData();- displayExpensiveResearch();- displayOptimizationTips();- }-- async function loadChartsData() {- // For now, create sample chart data- // In a real implementation, you'd fetch time-series cost data- createCostTrendsChart();- createProviderChart();- createModelCostChart();- }-- function createCostTrendsChart() {- const ctx = document.getElementById('cost-trends-chart');- if (!ctx) return;-- if (trendsChart) {- trendsChart.destroy();- }-- // Sample data - replace with real time-series data- const labels = ['Week 1', 'Week 2', 'Week 3', 'Week 4'];- const costs = [0.02, 0.035, 0.028, 0.041];-- trendsChart = new Chart(ctx, {- type: 'line',- data: {- labels: labels,- datasets: [{- label: 'Weekly Cost',- data: costs,- borderColor: '#4CAF50',- backgroundColor: 'rgba(76, 175, 80, 0.1)',- borderWidth: 3,- fill: true,- tension: 0.4- }]- },- options: {- responsive: true,- maintainAspectRatio: false,- scales: {- y: {- beginAtZero: true,- ticks: {- callback: function(value) {- return formatCurrency(value);- }- }- }- },- plugins: {- tooltip: {- callbacks: {- label: function(context) {- return `Cost: ${formatCurrency(context.parsed.y)}`;- }- }- }- }- }- });- }-- function createProviderChart() {- const ctx = document.getElementById('provider-chart');- if (!ctx) return;-- if (window.providerChart) {- window.providerChart.destroy();- }-- // Calculate provider usage from model breakdown- const models = Object.entries(costData.overview.model_breakdown || {});- const providerStats = {};-- for (const [modelName, data] of models) {- // Determine provider from model cost (0 = local, >0 = commercial)- let provider = 'Unknown';- if (data.total_cost === 0) {- provider = 'Local (Ollama/LM Studio)';- } else if (modelName.toLowerCase().includes('gpt')) {- provider = 'OpenAI';- } else if (modelName.toLowerCase().includes('claude')) {- provider = 'Anthropic';- } else if (modelName.toLowerCase().includes('gemini')) {- provider = 'Google';- }-- if (!providerStats[provider]) {- providerStats[provider] = { calls: 0, tokens: 0, cost: 0 };- }-- providerStats[provider].calls += data.calls;- providerStats[provider].tokens += data.prompt_tokens + data.completion_tokens;- providerStats[provider].cost += data.total_cost;- }-- const labels = Object.keys(providerStats);- const tokens = Object.values(providerStats).map(p => p.tokens);- const colors = {- 'Local (Ollama/LM Studio)': '#4CAF50',- 'OpenAI': '#00A67E',- 'Anthropic': '#FF6B35',- 'Google': '#4285F4',- 'Unknown': '#9E9E9E'- };-- window.providerChart = new Chart(ctx, {- type: 'doughnut',- data: {- labels: labels,- datasets: [{- label: 'Token Usage',- data: tokens,- backgroundColor: labels.map(label => colors[label] || '#9E9E9E'),- borderWidth: 2,- borderColor: '#fff'- }]- },- options: {- responsive: true,- maintainAspectRatio: false,- plugins: {- legend: {- position: 'bottom',- labels: {- padding: 20,- usePointStyle: true- }- },- tooltip: {- callbacks: {- label: function(context) {- const provider = context.label;- const stats = providerStats[provider];- return [- `${provider}`,- `Tokens: ${stats.tokens.toLocaleString()}`,- `Calls: ${stats.calls}`,- `Cost: ${formatCurrency(stats.cost)}`- ];- }- }- }- }- }- });- }-- function createModelCostChart() {- const ctx = document.getElementById('model-cost-chart');- if (!ctx) return;-- if (modelChart) {- modelChart.destroy();- }-- const models = Object.entries(costData.overview.model_breakdown || {});- const labels = models.map(([name, data]) => {- // Add provider info to label- let provider = data.total_cost === 0 ? '(Local)' : '(Commercial)';- return `${name} ${provider}`;- });- const costs = models.map(([, data]) => data.total_cost);-- modelChart = new Chart(ctx, {- type: 'bar',- data: {- labels: labels,- datasets: [{- label: 'Total Cost',- data: costs,- backgroundColor: [- '#4CAF50',- '#2196F3',- '#FF9800',- '#9C27B0',- '#F44336'- ].slice(0, labels.length),- borderWidth: 1- }]- },- options: {- responsive: true,- maintainAspectRatio: false,- scales: {- y: {- beginAtZero: true,- ticks: {- callback: function(value) {- return formatCurrency(value);- }- }- }- },- plugins: {- tooltip: {- callbacks: {- label: function(context) {- return `Cost: ${formatCurrency(context.parsed.y)}`;- }- }- }- }- }- });- }-- function displayExpensiveResearch() {- const container = document.getElementById('expensive-research-list');- const expensiveResearch = costData.top_expensive_research || [];-- if (expensiveResearch.length === 0) {- container.innerHTML = '<p style="text-align: center; color: var(--text-secondary); padding: 2rem;">No research cost data available</p>';- return;- }-- container.innerHTML = '';- expensiveResearch.slice(0, 10).forEach((item, index) => {- const div = document.createElement('div');- div.className = 'cost-item';- div.innerHTML = `- <div class="cost-item-info">- <div class="cost-item-name">- <a href="/research/results/${item.research_id}" class="research-link">- Research Session #${item.research_id}- </a>- </div>- <div class="cost-item-details">Rank #${index + 1} most expensive</div>- </div>- <div class="cost-item-value">${formatCurrency(item.total_cost)}</div>- `;- container.appendChild(div);- });- }-- function displayOptimizationTips() {- const container = document.getElementById('optimization-tips');- const tips = generateOptimizationTips();-- container.innerHTML = '';- tips.forEach(tip => {- const li = document.createElement('li');- li.textContent = tip;- container.appendChild(li);- });- }-- function generateOptimizationTips() {- const tips = [];- const overview = costData.overview;- const models = Object.entries(overview.model_breakdown || {});-- // Count local vs commercial usage- let localTokens = 0;- let commercialTokens = 0;- let hasLocalModels = false;-- for (const [modelName, data] of models) {- if (data.total_cost === 0) {- localTokens += data.prompt_tokens + data.completion_tokens;- hasLocalModels = true;- } else {- commercialTokens += data.prompt_tokens + data.completion_tokens;- }- }-- // Generate provider-aware tips- if (!hasLocalModels && overview.total_cost > 0) {- tips.push('Consider using local models like Ollama for zero-cost inference while maintaining quality');- }-- if (hasLocalModels && commercialTokens > localTokens) {- tips.push('You are using local models! Try shifting more workloads to local models to reduce costs');- }-- if (overview.total_cost > 0.1) {- tips.push('Consider using more cost-effective models or local alternatives for routine research tasks');- }-- if (overview.avg_cost_per_call > 0.01) {- tips.push('Try quick research mode for simple queries to reduce token usage');- }-- if (models.length > 1) {- tips.push('Compare model performance vs cost to optimize your model selection');- }-- if (hasLocalModels && overview.total_cost === 0) {- tips.push('Excellent! You are using 100% local models with zero inference costs');- tips.push('Local models provide privacy benefits while keeping costs at $0.00');- }-- if (tips.length === 0) {- tips.push('Your research costs are well optimized!');- tips.push('Consider local models like Ollama for even lower costs');- }-- return tips;- }-- function formatCurrency(amount) {- if (amount < 0.001) {- return `$${amount.toFixed(6)}`;- } else if (amount < 0.1) {- return `$${amount.toFixed(4)}`;- } else {- return `$${amount.toFixed(2)}`;- }- }-- function showLoading() {- document.getElementById('loading').style.display = 'block';- document.getElementById('cost-content').style.display = 'none';- document.getElementById('error').style.display = 'none';- document.getElementById('no-data').style.display = 'none';- }-- function showContent() {- document.getElementById('loading').style.display = 'none';- document.getElementById('cost-content').style.display = 'block';- document.getElementById('error').style.display = 'none';- document.getElementById('no-data').style.display = 'none';- }-- function showError() {- document.getElementById('loading').style.display = 'none';- document.getElementById('cost-content').style.display = 'none';- document.getElementById('error').style.display = 'block';- document.getElementById('no-data').style.display = 'none';- }-- function showNoData() {- document.getElementById('loading').style.display = 'none';- document.getElementById('cost-content').style.display = 'none';- document.getElementById('error').style.display = 'none';- document.getElementById('no-data').style.display = 'block';- }-})();diff --git a/temp_js_high_cost_check.js b/temp_js_high_cost_check.jsdeleted file mode 100644index 219b84f204..0000000000--- a/temp_js_high_cost_check.js+++ /dev/null@@ -1,501 +0,0 @@-// Cost Analytics JavaScript-(function() {- let currentPeriod = '7d';- let costData = null;- let trendsChart = null;- let modelChart = null;-- // Initialize the page- document.addEventListener('DOMContentLoaded', function() {- setupEventListeners();- loadCostData();- });-- function setupEventListeners() {- // Time period buttons- document.querySelectorAll('.time-range-btn').forEach(btn => {- btn.addEventListener('click', function() {- // Update active state- document.querySelectorAll('.time-range-btn').forEach(b => b.classList.remove('active'));- this.classList.add('active');-- // Update period and reload data- currentPeriod = this.dataset.period;- loadCostData();- });- });- }-- async function loadCostData() {- try {- showLoading();-- const response = await fetch(`/metrics/api/cost-analytics?period=${currentPeriod}`);- if (!response.ok) {- throw new Error(`API failed: ${response.status}`);- }-- const data = await response.json();-- if (data.status === 'success') {- costData = data;-- if (data.overview.total_calls > 0) {- displayCostData();- showContent();- } else {- showNoData();- }- } else {- throw new Error(data.message || 'Unknown error');- }- } catch (error) {- console.error('Error loading cost data:', error);- showError();- }- }-- function displayCostData() {- const overview = costData.overview;-- // Update overview cards with cost-based styling- const totalCostElement = document.getElementById('total-cost');- const avgCostElement = document.getElementById('avg-research-cost');-- totalCostElement.textContent = formatCurrency(overview.total_cost);- avgCostElement.textContent = formatCurrency(overview.avg_cost_per_call);-- // Apply warning colors based on cost levels- const totalCost = overview.total_cost;- const avgCost = overview.avg_cost_per_call;-- // Reset classes- totalCostElement.className = 'cost-value';- avgCostElement.className = 'cost-value';-- // Add warning classes for high costs- if (totalCost > 50.0) {- totalCostElement.className += ' cost-very-high';- } else if (totalCost > 10.0) {- totalCostElement.className += ' cost-high';- } else if (totalCost > 1.0) {- totalCostElement.className += ' cost-moderate';- }-- if (avgCost > 1.0) {- avgCostElement.className += ' cost-very-high';- } else if (avgCost > 0.1) {- avgCostElement.className += ' cost-high';- } else if (avgCost > 0.01) {- avgCostElement.className += ' cost-moderate';- }-- // Find most expensive model and calculate local savings- const models = Object.entries(overview.model_breakdown || {});- if (models.length > 0) {- // Most expensive by total cost- const mostExpensive = models.reduce((max, [name, data]) =>- data.total_cost > max[1].total_cost ? [name, data] : max- );- document.getElementById('most-expensive-model').textContent = mostExpensive[0];- document.getElementById('most-expensive-model-cost').textContent =- `${formatCurrency(mostExpensive[1].total_cost)} total`;-- // Calculate local model savings- let localTokens = 0;- let localCalls = 0;-- for (const [modelName, data] of models) {- if (data.total_cost === 0) { // Local models have zero cost- localTokens += data.prompt_tokens + data.completion_tokens;- localCalls += data.calls;- }- }-- // Estimate savings using GPT-3.5 pricing as baseline- const estimatedSavings = (localTokens / 1000) * 0.0015; // ~$0.0015 per 1K tokens average-- if (localTokens > 0) {- document.getElementById('local-savings').textContent = formatCurrency(estimatedSavings);- document.getElementById('local-savings-subtitle').textContent =- `${localTokens.toLocaleString()} tokens, ${localCalls} calls`;- } else {- document.getElementById('local-savings').textContent = '$0.00';- document.getElementById('local-savings-subtitle').textContent = 'No local model usage';- }- }-- // Load additional data for charts- loadChartsData();- displayExpensiveResearch();- displayOptimizationTips();- }-- async function loadChartsData() {- // For now, create sample chart data- // In a real implementation, you'd fetch time-series cost data- createCostTrendsChart();- createProviderChart();- createModelCostChart();- }-- function createCostTrendsChart() {- const ctx = document.getElementById('cost-trends-chart');- if (!ctx) return;-- if (trendsChart) {- trendsChart.destroy();- }-- // Sample data - replace with real time-series data- const labels = ['Week 1', 'Week 2', 'Week 3', 'Week 4'];- const costs = [0.02, 0.035, 0.028, 0.041];-- trendsChart = new Chart(ctx, {- type: 'line',- data: {- labels: labels,- datasets: [{- label: 'Weekly Cost',- data: costs,- borderColor: '#4CAF50',- backgroundColor: 'rgba(76, 175, 80, 0.1)',- borderWidth: 3,- fill: true,- tension: 0.4- }]- },- options: {- responsive: true,- maintainAspectRatio: false,- scales: {- y: {- beginAtZero: true,- ticks: {- callback: function(value) {- return formatCurrency(value);- }- }- }- },- plugins: {- tooltip: {- callbacks: {- label: function(context) {- return `Cost: ${formatCurrency(context.parsed.y)}`;- }- }- }- }- }- });- }-- function createProviderChart() {- const ctx = document.getElementById('provider-chart');- if (!ctx) return;-- if (window.providerChart) {- window.providerChart.destroy();- }-- // Calculate provider usage from model breakdown- const models = Object.entries(costData.overview.model_breakdown || {});- const providerStats = {};-- for (const [modelName, data] of models) {- // Determine provider from model cost (0 = local, >0 = commercial)- let provider = 'Unknown';- if (data.total_cost === 0) {- provider = 'Local (Ollama/LM Studio)';- } else if (modelName.toLowerCase().includes('gpt')) {- provider = 'OpenAI';- } else if (modelName.toLowerCase().includes('claude')) {- provider = 'Anthropic';- } else if (modelName.toLowerCase().includes('gemini')) {- provider = 'Google';- }-- if (!providerStats[provider]) {- providerStats[provider] = { calls: 0, tokens: 0, cost: 0 };- }-- providerStats[provider].calls += data.calls;- providerStats[provider].tokens += data.prompt_tokens + data.completion_tokens;- providerStats[provider].cost += data.total_cost;- }-- const labels = Object.keys(providerStats);- const tokens = Object.values(providerStats).map(p => p.tokens);- const colors = {- 'Local (Ollama/LM Studio)': '#4CAF50',- 'OpenAI': '#00A67E',- 'Anthropic': '#FF6B35',- 'Google': '#4285F4',- 'Unknown': '#9E9E9E'- };-- window.providerChart = new Chart(ctx, {- type: 'doughnut',- data: {- labels: labels,- datasets: [{- label: 'Token Usage',- data: tokens,- backgroundColor: labels.map(label => colors[label] || '#9E9E9E'),- borderWidth: 2,- borderColor: '#fff'- }]- },- options: {- responsive: true,- maintainAspectRatio: false,- plugins: {- legend: {- position: 'bottom',- labels: {- padding: 20,- usePointStyle: true- }- },- tooltip: {- callbacks: {- label: function(context) {- const provider = context.label;- const stats = providerStats[provider];- return [- `${provider}`,- `Tokens: ${stats.tokens.toLocaleString()}`,- `Calls: ${stats.calls}`,- `Cost: ${formatCurrency(stats.cost)}`- ];- }- }- }- }- }- });- }-- function createModelCostChart() {- const ctx = document.getElementById('model-cost-chart');- if (!ctx) return;-- if (modelChart) {- modelChart.destroy();- }-- const models = Object.entries(costData.overview.model_breakdown || {});- const labels = models.map(([name, data]) => {- // Add provider info to label- let provider = data.total_cost === 0 ? '(Local)' : '(Commercial)';- return `${name} ${provider}`;- });- const costs = models.map(([, data]) => data.total_cost);-- modelChart = new Chart(ctx, {- type: 'bar',- data: {- labels: labels,- datasets: [{- label: 'Total Cost',- data: costs,- backgroundColor: [- '#4CAF50',- '#2196F3',- '#FF9800',- '#9C27B0',- '#F44336'- ].slice(0, labels.length),- borderWidth: 1- }]- },- options: {- responsive: true,- maintainAspectRatio: false,- scales: {- y: {- beginAtZero: true,- ticks: {- callback: function(value) {- return formatCurrency(value);- }- }- }- },- plugins: {- tooltip: {- callbacks: {- label: function(context) {- return `Cost: ${formatCurrency(context.parsed.y)}`;- }- }- }- }- }- });- }-- function displayExpensiveResearch() {- const container = document.getElementById('expensive-research-list');- const expensiveResearch = costData.top_expensive_research || [];-- if (expensiveResearch.length === 0) {- container.innerHTML = '<p style="text-align: center; color: var(--text-secondary); padding: 2rem;">No research cost data available</p>';- return;- }-- container.innerHTML = '';- expensiveResearch.slice(0, 10).forEach((item, index) => {- const div = document.createElement('div');- div.className = 'cost-item';- div.innerHTML = `- <div class="cost-item-info">- <div class="cost-item-name">- <a href="/research/results/${item.research_id}" class="research-link">- Research Session #${item.research_id}- </a>- </div>- <div class="cost-item-details">Rank #${index + 1} most expensive</div>- </div>- <div class="cost-item-value">${formatCurrency(item.total_cost)}</div>- `;- container.appendChild(div);- });- }-- function displayOptimizationTips() {- const container = document.getElementById('optimization-tips');- const tips = generateOptimizationTips();-- container.innerHTML = '';- tips.forEach(tip => {- const li = document.createElement('li');- li.textContent = tip;- container.appendChild(li);- });- }-- function generateOptimizationTips() {- const tips = [];- const overview = costData.overview;- const models = Object.entries(overview.model_breakdown || {});-- // Count local vs commercial usage- let localTokens = 0;- let commercialTokens = 0;- let hasLocalModels = false;-- for (const [modelName, data] of models) {- if (data.total_cost === 0) {- localTokens += data.prompt_tokens + data.completion_tokens;- hasLocalModels = true;- } else {- commercialTokens += data.prompt_tokens + data.completion_tokens;- }- }-- // Generate provider-aware tips with cost-based warnings- const totalCost = overview.total_cost;- const avgCostPerCall = overview.avg_cost_per_call;-- // High cost warnings (red alerts)- if (totalCost > 50.0) {- tips.push('🚨 VERY HIGH COSTS: $' + totalCost.toFixed(2) + ' spent! Consider immediate cost reduction measures');- tips.push('⚠️ Switch to local models (Ollama) or smaller commercial models to reduce spending');- } else if (totalCost > 10.0) {- tips.push('🔴 HIGH COSTS: $' + totalCost.toFixed(2) + ' spent this period. Review your model usage');- tips.push('💡 Consider using local models like Ollama for significant cost savings');- } else if (totalCost > 1.0) {- tips.push('🟡 MODERATE COSTS: $' + totalCost.toFixed(2) + ' spent. Monitor usage closely');- tips.push('📊 Evaluate if local models could handle some of your workloads');- }-- // Per-call cost warnings- if (avgCostPerCall > 1.0) {- tips.push('💸 Very expensive per research ($' + avgCostPerCall.toFixed(3) + ' average). Consider model alternatives');- } else if (avgCostPerCall > 0.1) {- tips.push('💰 High per-research cost ($' + avgCostPerCall.toFixed(3) + ' average). Try quick mode or local models');- } else if (avgCostPerCall > 0.01) {- tips.push('📈 Try quick research mode for simple queries to reduce token usage');- }-- // Provider-specific tips- if (!hasLocalModels && totalCost > 0) {- tips.push('🏠 Consider using local models like Ollama for zero-cost inference while maintaining quality');- }-- if (hasLocalModels && commercialTokens > localTokens) {- tips.push('✨ You are using local models! Try shifting more workloads to local models to reduce costs');- }-- // Model optimization tips- if (models.length > 1) {- tips.push('⚖️ Compare model performance vs cost to optimize your model selection');- }-- // Find most expensive model for specific advice- if (models.length > 0 && totalCost > 0.1) {- const mostExpensive = models.reduce((max, [name, data]) =>- data.total_cost > max[1].total_cost ? [name, data] : max- );- if (mostExpensive[1].total_cost > totalCost * 0.6) {- tips.push('🎯 "' + mostExpensive[0] + '" is your most expensive model ($' + mostExpensive[1].total_cost.toFixed(3) + ')');- }- }-- // Excellent usage patterns- if (hasLocalModels && totalCost === 0) {- tips.push('✅ Excellent! You are using 100% local models with zero inference costs');- tips.push('🔒 Local models provide privacy benefits while keeping costs at $0.00');- } else if (totalCost < 0.01) {- tips.push('👍 Very low costs! Your research spending is well optimized');- }-- // Default tips for edge cases- if (tips.length === 0) {- tips.push('📊 Your research costs are well optimized!');- tips.push('🏠 Consider local models like Ollama for even lower costs');- }-- return tips;- }-- function formatCurrency(amount) {- if (amount < 0.001) {- return `$${amount.toFixed(6)}`;- } else if (amount < 0.1) {- return `$${amount.toFixed(4)}`;- } else {- return `$${amount.toFixed(2)}`;- }- }-- function showLoading() {- document.getElementById('loading').style.display = 'block';- document.getElementById('cost-content').style.display = 'none';- document.getElementById('error').style.display = 'none';- document.getElementById('no-data').style.display = 'none';- }-- function showContent() {- document.getElementById('loading').style.display = 'none';- document.getElementById('cost-content').style.display = 'block';- document.getElementById('error').style.display = 'none';- document.getElementById('no-data').style.display = 'none';- }-- function showError() {- document.getElementById('loading').style.display = 'none';- document.getElementById('cost-content').style.display = 'none';- document.getElementById('error').style.display = 'block';- document.getElementById('no-data').style.display = 'none';- }-- function showNoData() {- document.getElementById('loading').style.display = 'none';- document.getElementById('cost-content').style.display = 'none';- document.getElementById('error').style.display = 'none';- document.getElementById('no-data').style.display = 'block';- }-})();diff --git a/temp_js_neutral_check.js b/temp_js_neutral_check.jsdeleted file mode 100644index cb9e17d60f..0000000000--- a/temp_js_neutral_check.js+++ /dev/null@@ -1,453 +0,0 @@-// Cost Analytics JavaScript-(function() {- let currentPeriod = '7d';- let costData = null;- let trendsChart = null;- let modelChart = null;-- // Initialize the page- document.addEventListener('DOMContentLoaded', function() {- setupEventListeners();- loadCostData();- });-- function setupEventListeners() {- // Time period buttons- document.querySelectorAll('.time-range-btn').forEach(btn => {- btn.addEventListener('click', function() {- // Update active state- document.querySelectorAll('.time-range-btn').forEach(b => b.classList.remove('active'));- this.classList.add('active');-- // Update period and reload data- currentPeriod = this.dataset.period;- loadCostData();- });- });- }-- async function loadCostData() {- try {- showLoading();-- const response = await fetch(`/metrics/api/cost-analytics?period=${currentPeriod}`);- if (!response.ok) {- throw new Error(`API failed: ${response.status}`);- }-- const data = await response.json();-- if (data.status === 'success') {- costData = data;-- if (data.overview.total_calls > 0) {- displayCostData();- showContent();- } else {- showNoData();- }- } else {- throw new Error(data.message || 'Unknown error');- }- } catch (error) {- console.error('Error loading cost data:', error);- showError();- }- }-- function displayCostData() {- const overview = costData.overview;-- // Update overview cards- document.getElementById('total-cost').textContent = formatCurrency(overview.total_cost);- document.getElementById('avg-research-cost').textContent = formatCurrency(overview.avg_cost_per_call);-- // Find most expensive model and calculate local savings- const models = Object.entries(overview.model_breakdown || {});- if (models.length > 0) {- // Most expensive by total cost- const mostExpensive = models.reduce((max, [name, data]) =>- data.total_cost > max[1].total_cost ? [name, data] : max- );- document.getElementById('most-expensive-model').textContent = mostExpensive[0];- document.getElementById('most-expensive-model-cost').textContent =- `${formatCurrency(mostExpensive[1].total_cost)} total`;-- // Calculate local model savings- let localTokens = 0;- let localCalls = 0;-- for (const [modelName, data] of models) {- if (data.total_cost === 0) { // Local models have zero cost- localTokens += data.prompt_tokens + data.completion_tokens;- localCalls += data.calls;- }- }-- // Estimate savings using GPT-3.5 pricing as baseline- const estimatedSavings = (localTokens / 1000) * 0.0015; // ~$0.0015 per 1K tokens average-- if (localTokens > 0) {- document.getElementById('local-savings').textContent = formatCurrency(estimatedSavings);- document.getElementById('local-savings-subtitle').textContent =- `${localTokens.toLocaleString()} tokens, ${localCalls} calls`;- } else {- document.getElementById('local-savings').textContent = '$0.00';- document.getElementById('local-savings-subtitle').textContent = 'No local model usage';- }- }-- // Load additional data for charts- loadChartsData();- displayExpensiveResearch();- displayOptimizationTips();- }-- async function loadChartsData() {- // For now, create sample chart data- // In a real implementation, you'd fetch time-series cost data- createCostTrendsChart();- createProviderChart();- createModelCostChart();- }-- function createCostTrendsChart() {- const ctx = document.getElementById('cost-trends-chart');- if (!ctx) return;-- if (trendsChart) {- trendsChart.destroy();- }-- // Sample data - replace with real time-series data- const labels = ['Week 1', 'Week 2', 'Week 3', 'Week 4'];- const costs = [0.02, 0.035, 0.028, 0.041];-- trendsChart = new Chart(ctx, {- type: 'line',- data: {- labels: labels,- datasets: [{- label: 'Weekly Cost',- data: costs,- borderColor: '#4CAF50',- backgroundColor: 'rgba(76, 175, 80, 0.1)',- borderWidth: 3,- fill: true,- tension: 0.4- }]- },- options: {- responsive: true,- maintainAspectRatio: false,- scales: {- y: {- beginAtZero: true,- ticks: {- callback: function(value) {- return formatCurrency(value);- }- }- }- },- plugins: {- tooltip: {- callbacks: {- label: function(context) {- return `Cost: ${formatCurrency(context.parsed.y)}`;- }- }- }- }- }- });- }-- function createProviderChart() {- const ctx = document.getElementById('provider-chart');- if (!ctx) return;-- if (window.providerChart) {- window.providerChart.destroy();- }-- // Calculate provider usage from model breakdown- const models = Object.entries(costData.overview.model_breakdown || {});- const providerStats = {};-- for (const [modelName, data] of models) {- // Determine provider from model cost (0 = local, >0 = commercial)- let provider = 'Unknown';- if (data.total_cost === 0) {- provider = 'Local (Ollama/LM Studio)';- } else if (modelName.toLowerCase().includes('gpt')) {- provider = 'OpenAI';- } else if (modelName.toLowerCase().includes('claude')) {- provider = 'Anthropic';- } else if (modelName.toLowerCase().includes('gemini')) {- provider = 'Google';- }-- if (!providerStats[provider]) {- providerStats[provider] = { calls: 0, tokens: 0, cost: 0 };- }-- providerStats[provider].calls += data.calls;- providerStats[provider].tokens += data.prompt_tokens + data.completion_tokens;- providerStats[provider].cost += data.total_cost;- }-- const labels = Object.keys(providerStats);- const tokens = Object.values(providerStats).map(p => p.tokens);- const colors = {- 'Local (Ollama/LM Studio)': '#4CAF50',- 'OpenAI': '#00A67E',- 'Anthropic': '#FF6B35',- 'Google': '#4285F4',- 'Unknown': '#9E9E9E'- };-- window.providerChart = new Chart(ctx, {- type: 'doughnut',- data: {- labels: labels,- datasets: [{- label: 'Token Usage',- data: tokens,- backgroundColor: labels.map(label => colors[label] || '#9E9E9E'),- borderWidth: 2,- borderColor: '#fff'- }]- },- options: {- responsive: true,- maintainAspectRatio: false,- plugins: {- legend: {- position: 'bottom',- labels: {- padding: 20,- usePointStyle: true- }- },- tooltip: {- callbacks: {- label: function(context) {- const provider = context.label;- const stats = providerStats[provider];- return [- `${provider}`,- `Tokens: ${stats.tokens.toLocaleString()}`,- `Calls: ${stats.calls}`,- `Cost: ${formatCurrency(stats.cost)}`- ];- }- }- }- }- }- });- }-- function createModelCostChart() {- const ctx = document.getElementById('model-cost-chart');- if (!ctx) return;-- if (modelChart) {- modelChart.destroy();- }-- const models = Object.entries(costData.overview.model_breakdown || {});- const labels = models.map(([name, data]) => {- // Add provider info to label- let provider = data.total_cost === 0 ? '(Local)' : '(Commercial)';- return `${name} ${provider}`;- });- const costs = models.map(([, data]) => data.total_cost);-- modelChart = new Chart(ctx, {- type: 'bar',- data: {- labels: labels,- datasets: [{- label: 'Total Cost',- data: costs,- backgroundColor: [- '#4CAF50',- '#2196F3',- '#FF9800',- '#9C27B0',- '#F44336'- ].slice(0, labels.length),- borderWidth: 1- }]- },- options: {- responsive: true,- maintainAspectRatio: false,- scales: {- y: {- beginAtZero: true,- ticks: {- callback: function(value) {- return formatCurrency(value);- }- }- }- },- plugins: {- tooltip: {- callbacks: {- label: function(context) {- return `Cost: ${formatCurrency(context.parsed.y)}`;- }- }- }- }- }- });- }-- function displayExpensiveResearch() {- const container = document.getElementById('expensive-research-list');- const expensiveResearch = costData.top_expensive_research || [];-- if (expensiveResearch.length === 0) {- container.innerHTML = '<p style="text-align: center; color: var(--text-secondary); padding: 2rem;">No research cost data available</p>';- return;- }-- container.innerHTML = '';- expensiveResearch.slice(0, 10).forEach((item, index) => {- const div = document.createElement('div');- div.className = 'cost-item';- div.innerHTML = `- <div class="cost-item-info">- <div class="cost-item-name">- <a href="/research/results/${item.research_id}" class="research-link">- Research Session #${item.research_id}- </a>- </div>- <div class="cost-item-details">Rank #${index + 1} most expensive</div>- </div>- <div class="cost-item-value">${formatCurrency(item.total_cost)}</div>- `;- container.appendChild(div);- });- }-- function displayOptimizationTips() {- const container = document.getElementById('optimization-tips');- const tips = generateOptimizationTips();-- container.innerHTML = '';- tips.forEach(tip => {- const li = document.createElement('li');- li.textContent = tip;- container.appendChild(li);- });- }-- function generateOptimizationTips() {- const tips = [];- const overview = costData.overview;- const models = Object.entries(overview.model_breakdown || {});-- // Count local vs commercial usage- let localTokens = 0;- let commercialTokens = 0;- let hasLocalModels = false;-- for (const [modelName, data] of models) {- if (data.total_cost === 0) {- localTokens += data.prompt_tokens + data.completion_tokens;- hasLocalModels = true;- } else {- commercialTokens += data.prompt_tokens + data.completion_tokens;- }- }-- // Generate informative tips (no judgmental cost warnings)- const totalCost = overview.total_cost;- const avgCostPerCall = overview.avg_cost_per_call;-- // Informative tips for local model users- if (hasLocalModels && totalCost === 0) {- tips.push('✅ Excellent! You are using 100% local models with zero inference costs');- tips.push('🔒 Local models provide privacy benefits while keeping costs at $0.00');- tips.push('🌟 You have complete control over your AI infrastructure');- }-- // Mixed usage insights- if (hasLocalModels && commercialTokens > 0) {- const localPercent = Math.round((localTokens / (localTokens + commercialTokens)) * 100);- tips.push('📊 You are using ' + localPercent + '% local models and ' + (100-localPercent) + '% commercial models');- tips.push('💡 Consider evaluating which workloads could be shifted to local models');- }-- // Pure commercial usage - neutral suggestion- if (!hasLocalModels && totalCost > 0) {- tips.push('💼 You are using commercial LLM APIs for all research');- tips.push('🏠 Local models like Ollama are available as a zero-cost alternative');- }-- // General optimization tips (no cost judgments)- if (models.length > 1) {- tips.push('⚖️ Compare model performance vs cost to optimize your model selection');- }-- // Informative model breakdown- if (models.length > 0 && totalCost > 0) {- const mostUsed = models.reduce((max, [name, data]) =>- (data.prompt_tokens + data.completion_tokens) > (max[1].prompt_tokens + max[1].completion_tokens) ? [name, data] : max- );- tips.push('📈 "' + mostUsed[0] + '" is your most used model (' + mostUsed[1].calls + ' calls)');- }-- // Default neutral tips- if (tips.length === 0) {- tips.push('📊 Track your research costs and model usage over time');- tips.push('💡 Explore different models to find the best fit for your use case');- }-- return tips;- }-- function formatCurrency(amount) {- if (amount < 0.001) {- return `$${amount.toFixed(6)}`;- } else if (amount < 0.1) {- return `$${amount.toFixed(4)}`;- } else {- return `$${amount.toFixed(2)}`;- }- }-- function showLoading() {- document.getElementById('loading').style.display = 'block';- document.getElementById('cost-content').style.display = 'none';- document.getElementById('error').style.display = 'none';- document.getElementById('no-data').style.display = 'none';- }-- function showContent() {- document.getElementById('loading').style.display = 'none';- document.getElementById('cost-content').style.display = 'block';- document.getElementById('error').style.display = 'none';- document.getElementById('no-data').style.display = 'none';- }-- function showError() {- document.getElementById('loading').style.display = 'none';- document.getElementById('cost-content').style.display = 'none';- document.getElementById('error').style.display = 'block';- document.getElementById('no-data').style.display = 'none';- }-- function showNoData() {- document.getElementById('loading').style.display = 'none';- document.getElementById('cost-content').style.display = 'none';- document.getElementById('error').style.display = 'none';- document.getElementById('no-data').style.display = 'block';- }-})();diff --git a/package.json b/tests/package.jsonsimilarity index 100%rename from package.jsonrename to tests/package.jsondiff --git a/test_simple_cost.js b/tests/ui_tests/test_simple_cost.jssimilarity index 100%rename from test_simple_cost.jsrename to tests/ui_tests/test_simple_cost.js