Moving to a proper app.
Browse files- .gitignore +1 -0
- chat-copil-web.html β attempts/chat-copil-web.html +0 -0
- chat-copil2-web.html β attempts/chat-copil2-web.html +0 -0
- chat-full.html β attempts/chat-full.html +0 -0
- chat-full.js β attempts/chat-full.js +0 -0
- chat-gemin.html β attempts/chat-gemin.html +0 -0
- chat.html β attempts/chat.html +0 -0
- chat.js β attempts/chat.js +0 -0
- chat3.html β attempts/chat3.html +0 -0
- chat4.html β attempts/chat4.html +0 -0
- chat5.html β attempts/chat5.html +0 -0
- chat5.js β attempts/chat5.js +0 -0
- attempts/index.html +1043 -0
- index.html +6 -1037
- package-lock.json +0 -0
- package.json +8 -3
- src/app/app.css +39 -0
- src/app/boot-app.js +21 -0
- src/app/clean-body.js +8 -0
- src/app/init-html.js +28 -0
- src/app/init-milkdown.js +35 -0
- src/app/output-message.js +38 -0
- src/index.js +8 -0
.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
/node_modules
|
chat-copil-web.html β attempts/chat-copil-web.html
RENAMED
|
File without changes
|
chat-copil2-web.html β attempts/chat-copil2-web.html
RENAMED
|
File without changes
|
chat-full.html β attempts/chat-full.html
RENAMED
|
File without changes
|
chat-full.js β attempts/chat-full.js
RENAMED
|
File without changes
|
chat-gemin.html β attempts/chat-gemin.html
RENAMED
|
File without changes
|
chat.html β attempts/chat.html
RENAMED
|
File without changes
|
chat.js β attempts/chat.js
RENAMED
|
File without changes
|
chat3.html β attempts/chat3.html
RENAMED
|
File without changes
|
chat4.html β attempts/chat4.html
RENAMED
|
File without changes
|
chat5.html β attempts/chat5.html
RENAMED
|
File without changes
|
chat5.js β attempts/chat5.js
RENAMED
|
File without changes
|
attempts/index.html
ADDED
|
@@ -0,0 +1,1043 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>TinyLLM In-Browser Chat with RAG</title>
|
| 7 |
+
<style>
|
| 8 |
+
body {
|
| 9 |
+
font-family: Arial, sans-serif;
|
| 10 |
+
margin: 0;
|
| 11 |
+
padding: 0;
|
| 12 |
+
background-color: #f0f2f5;
|
| 13 |
+
display: flex;
|
| 14 |
+
justify-content: center;
|
| 15 |
+
align-items: center;
|
| 16 |
+
min-height: 100vh;
|
| 17 |
+
color: #333;
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
#chat-container {
|
| 21 |
+
background-color: #fff;
|
| 22 |
+
border-radius: 10px;
|
| 23 |
+
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
|
| 24 |
+
width: 100vw;
|
| 25 |
+
max-width: none;
|
| 26 |
+
display: flex;
|
| 27 |
+
flex-direction: column;
|
| 28 |
+
overflow: hidden;
|
| 29 |
+
min-height: 80vh;
|
| 30 |
+
max-height: 95vh;
|
| 31 |
+
position: relative;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
h1 {
|
| 35 |
+
text-align: center;
|
| 36 |
+
color: #4a4a4a;
|
| 37 |
+
padding: 15px;
|
| 38 |
+
margin: 0;
|
| 39 |
+
border-bottom: 1px solid #eee;
|
| 40 |
+
font-size: 1.5em;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
.status-message {
|
| 44 |
+
text-align: center;
|
| 45 |
+
padding: 10px;
|
| 46 |
+
background-color: #e0f7fa;
|
| 47 |
+
color: #00796b;
|
| 48 |
+
font-weight: bold;
|
| 49 |
+
border-bottom: 1px solid #b2ebf2;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
#chat-box {
|
| 53 |
+
flex-grow: 1;
|
| 54 |
+
padding: 20px;
|
| 55 |
+
overflow-y: auto;
|
| 56 |
+
display: flex;
|
| 57 |
+
flex-direction: column;
|
| 58 |
+
gap: 10px;
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
.message-container {
|
| 62 |
+
display: flex;
|
| 63 |
+
flex-direction: column;
|
| 64 |
+
max-width: 80%;
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
.message-container.user {
|
| 68 |
+
align-self: flex-end;
|
| 69 |
+
align-items: flex-end;
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
.message-container.assistant {
|
| 73 |
+
align-self: flex-start;
|
| 74 |
+
align-items: flex-start;
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
.message-container.system {
|
| 78 |
+
align-self: center; /* Center system messages */
|
| 79 |
+
align-items: center;
|
| 80 |
+
font-size: 0.85em;
|
| 81 |
+
color: #666;
|
| 82 |
+
text-align: left;
|
| 83 |
+
padding: 5px 10px;
|
| 84 |
+
border-radius: 10px;
|
| 85 |
+
background-color: #f0f0f0;
|
| 86 |
+
margin: 5px 0;
|
| 87 |
+
white-space: pre-wrap; /* preserve markdown line breaks */
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
.message-bubble {
|
| 91 |
+
padding: 10px 15px;
|
| 92 |
+
border-radius: 20px;
|
| 93 |
+
line-height: 1.4;
|
| 94 |
+
word-wrap: break-word;
|
| 95 |
+
white-space: pre-wrap; /* Preserve whitespace and line breaks */
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
.message-container.user .message-bubble {
|
| 99 |
+
background-color: #007bff;
|
| 100 |
+
color: white;
|
| 101 |
+
border-bottom-right-radius: 5px;
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
.message-container.assistant .message-bubble {
|
| 105 |
+
background-color: #e9e9eb;
|
| 106 |
+
color: #333;
|
| 107 |
+
border-bottom-left-radius: 5px;
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
.chat-input-container {
|
| 111 |
+
display: flex;
|
| 112 |
+
padding: 15px;
|
| 113 |
+
border-top: 1px solid #eee;
|
| 114 |
+
background-color: #fff;
|
| 115 |
+
gap: 10px;
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
#user-input {
|
| 119 |
+
flex-grow: 1;
|
| 120 |
+
padding: 10px 15px;
|
| 121 |
+
border: 1px solid #ddd;
|
| 122 |
+
border-radius: 20px;
|
| 123 |
+
font-size: 1em;
|
| 124 |
+
outline: none;
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
#user-input:focus {
|
| 128 |
+
border-color: #007bff;
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
#send {
|
| 132 |
+
padding: 10px 20px;
|
| 133 |
+
background-color: #007bff;
|
| 134 |
+
color: white;
|
| 135 |
+
border: none;
|
| 136 |
+
border-radius: 20px;
|
| 137 |
+
cursor: pointer;
|
| 138 |
+
font-size: 1em;
|
| 139 |
+
transition: background-color 0.2s;
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
#send:hover:not(:disabled) {
|
| 143 |
+
background-color: #0056b3;
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
#send:disabled {
|
| 147 |
+
background-color: #a0c9ff;
|
| 148 |
+
cursor: not-allowed;
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
.chat-stats {
|
| 152 |
+
font-size: 0.8em;
|
| 153 |
+
color: #666;
|
| 154 |
+
text-align: right;
|
| 155 |
+
padding: 5px 20px;
|
| 156 |
+
background-color: #f9f9f9;
|
| 157 |
+
border-top: 1px solid #eee;
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
.hidden {
|
| 161 |
+
display: none!important;
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
.controls {
|
| 165 |
+
padding: 8px 12px;
|
| 166 |
+
background:#fafafa;
|
| 167 |
+
border-bottom:1px solid #eee;
|
| 168 |
+
display:flex;
|
| 169 |
+
flex-wrap:wrap;
|
| 170 |
+
gap:8px;
|
| 171 |
+
align-items:center;
|
| 172 |
+
font-size:0.75rem;
|
| 173 |
+
}
|
| 174 |
+
.controls input[type=text] {
|
| 175 |
+
padding:4px 8px;
|
| 176 |
+
border:1px solid #ccc;
|
| 177 |
+
border-radius:6px;
|
| 178 |
+
font-size:0.75rem;
|
| 179 |
+
}
|
| 180 |
+
.controls button, .controls select {
|
| 181 |
+
padding:4px 10px;
|
| 182 |
+
font-size:0.7rem;
|
| 183 |
+
border:1px solid #ccc;
|
| 184 |
+
border-radius:6px;
|
| 185 |
+
background:#fff;
|
| 186 |
+
cursor:pointer;
|
| 187 |
+
}
|
| 188 |
+
.controls button:hover { background:#f0f0f0; }
|
| 189 |
+
#diagnostics {
|
| 190 |
+
max-height:120px;
|
| 191 |
+
overflow:auto;
|
| 192 |
+
font-family:monospace;
|
| 193 |
+
background:#1e1e1e;
|
| 194 |
+
color:#c9d1d9;
|
| 195 |
+
padding:6px 8px;
|
| 196 |
+
font-size:0.65rem;
|
| 197 |
+
border-top:1px solid #333;
|
| 198 |
+
display:none;
|
| 199 |
+
white-space:pre-wrap;
|
| 200 |
+
}
|
| 201 |
+
#diagnostics.show { display:block; }
|
| 202 |
+
</style>
|
| 203 |
+
</head>
|
| 204 |
+
<body>
|
| 205 |
+
<div id="chat-container">
|
| 206 |
+
<h1>In-Browser LLM Chat with RAG</h1>
|
| 207 |
+
<div class="controls">
|
| 208 |
+
<label>HF Token:
|
| 209 |
+
<input type="text" id="hf-token" placeholder="hf_... (optional)" size="18" autocomplete="off" />
|
| 210 |
+
</label>
|
| 211 |
+
<button id="apply-token" title="Store token (localStorage) & reload">Apply Token + Reload</button>
|
| 212 |
+
<label style="display:flex;align-items:center;gap:4px;">Models:
|
| 213 |
+
<input type="text" id="model-candidates" placeholder="comma-separated model ids" size="26" />
|
| 214 |
+
</label>
|
| 215 |
+
<button id="apply-models" title="Store custom model list & reload">Apply Models</button>
|
| 216 |
+
<label style="display:flex;align-items:center;gap:4px;">Skip RAG:
|
| 217 |
+
<input type="checkbox" id="skip-rag" title="If checked, no retrieval augmented context will be gathered." />
|
| 218 |
+
</label>
|
| 219 |
+
|
| 220 |
+
<select id="preferred-backend" title="Preferred first backend">
|
| 221 |
+
<option value="transformers-webgpu">TF WebGPU</option>
|
| 222 |
+
<option value="transformers-webgl">TF WebGL</option>
|
| 223 |
+
<option value="webllm">WebLLM</option>
|
| 224 |
+
<option value="transformers-wasm">TF WASM</option>
|
| 225 |
+
</select>
|
| 226 |
+
<button id="force-reload" title="Reinitialize models">Reload Models</button>
|
| 227 |
+
<button id="trial-models" title="Try/test multiple small models">Trial Models</button>
|
| 228 |
+
<button id="toggle-diagnostics" title="Show/Hide diagnostics">Diagnostics</button>
|
| 229 |
+
<span id="active-backend" style="margin-left:auto;font-weight:bold;">backend: -</span>
|
| 230 |
+
</div>
|
| 231 |
+
<div id="download-status" class="status-message">Loading model...</div>
|
| 232 |
+
<div id="chat-box">
|
| 233 |
+
</div>
|
| 234 |
+
<div id="chat-stats" class="chat-stats hidden"></div>
|
| 235 |
+
<div id="diagnostics"></div>
|
| 236 |
+
<div id="trial-results" style="display:none;padding:12px;"></div>
|
| 237 |
+
<div class="chat-input-container">
|
| 238 |
+
<input type="text" id="user-input" placeholder="Loading models for RAG..." disabled>
|
| 239 |
+
<button id="send" disabled>Send</button>
|
| 240 |
+
</div>
|
| 241 |
+
</div>
|
| 242 |
+
|
| 243 |
+
<script type="module">
|
| 244 |
+
import * as webllm from "https://esm.run/@mlc-ai/web-llm";
|
| 245 |
+
import { pipeline, env } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.14.0';
|
| 246 |
+
|
| 247 |
+
// ---- Console Log Filtering (suppress noisy ONNX optimizer warnings) ----
|
| 248 |
+
const LOG_FILTER_PATTERNS = [
|
| 249 |
+
/CleanUnusedInitializersAndNodeArgs/i,
|
| 250 |
+
/graph\.cc:\d+ CleanUnusedInitializersAndNodeArgs/i,
|
| 251 |
+
/Removing initializer '\/transformer\//i
|
| 252 |
+
];
|
| 253 |
+
const originalConsole = { log: console.log, warn: console.warn };
|
| 254 |
+
function shouldSuppress(args) {
|
| 255 |
+
return args.some(a => typeof a === 'string' && LOG_FILTER_PATTERNS.some(p => p.test(a)));
|
| 256 |
+
}
|
| 257 |
+
console.warn = (...args) => {
|
| 258 |
+
if (shouldSuppress(args)) { return; }
|
| 259 |
+
originalConsole.warn(...args);
|
| 260 |
+
};
|
| 261 |
+
console.log = (...args) => {
|
| 262 |
+
if (shouldSuppress(args)) { return; }
|
| 263 |
+
originalConsole.log(...args);
|
| 264 |
+
};
|
| 265 |
+
|
| 266 |
+
/*************** WebLLM Logic & RAG Components ***************/
|
| 267 |
+
|
| 268 |
+
// System message for the LLM to understand its role and tool use
|
| 269 |
+
const systemMessageContent = `
|
| 270 |
+
You are an intelligent person with honesty and broad knowledge.
|
| 271 |
+
|
| 272 |
+
Although you also know about SQL queries.
|
| 273 |
+
|
| 274 |
+
You have access to a special "lookup" tool. If you need more specific details about tables or concepts to answer a user's question, you MUST respond with a JSON object in this exact format:
|
| 275 |
+
|
| 276 |
+
\`\`\`json
|
| 277 |
+
{
|
| 278 |
+
"action": "lookup_schema_info",
|
| 279 |
+
"query": "concise natural language phrase describing what schema information you need"
|
| 280 |
+
}
|
| 281 |
+
\`\`\`
|
| 282 |
+
|
| 283 |
+
Examples of "query" for the lookup_schema_info action:
|
| 284 |
+
- "details about the Users and Products tables"
|
| 285 |
+
- "columns in the Orders table and its related tables"
|
| 286 |
+
- "how Categories table relates to Products"
|
| 287 |
+
|
| 288 |
+
If you can answer the question directly with your existing knowledge or after using the tool, provide the natural language answer or SQL query. Do NOT use the lookup tool if you already have enough information.
|
| 289 |
+
`.trim(); // Trim to remove leading/trailing whitespace
|
| 290 |
+
|
| 291 |
+
const messages = [{ role: "system", content: systemMessageContent }];
|
| 292 |
+
|
| 293 |
+
const chatBox = document.getElementById("chat-box");
|
| 294 |
+
const userInput = document.getElementById("user-input");
|
| 295 |
+
const sendButton = document.getElementById("send");
|
| 296 |
+
const downloadStatus = document.getElementById("download-status");
|
| 297 |
+
const chatStats = document.getElementById("chat-stats");
|
| 298 |
+
const diagnosticsEl = document.getElementById('diagnostics');
|
| 299 |
+
const tokenInput = document.getElementById('hf-token');
|
| 300 |
+
const applyTokenBtn = document.getElementById('apply-token');
|
| 301 |
+
const forceReloadBtn = document.getElementById('force-reload');
|
| 302 |
+
const toggleDiagBtn = document.getElementById('toggle-diagnostics');
|
| 303 |
+
const backendSelect = document.getElementById('preferred-backend');
|
| 304 |
+
const activeBackendLabel = document.getElementById('active-backend');
|
| 305 |
+
const trialModelsBtn = document.getElementById('trial-models');
|
| 306 |
+
const skipRagCheckbox = document.getElementById('skip-rag');
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
let currentAssistantMessageElement = null; // To update the streaming message
|
| 310 |
+
let embedder = null; // In-browser embedding model
|
| 311 |
+
|
| 312 |
+
// Fix: Declare engine as 'let' at module scope. It will be instantiated inside initializeModels.
|
| 313 |
+
let engine;
|
| 314 |
+
// Backend selection flow (priority):
|
| 315 |
+
// 1. transformers:webgpu 2. transformers:webgl 3. webllm:webgpu 4. transformers:wasm
|
| 316 |
+
let chatBackend = null;
|
| 317 |
+
let textGenPipeline = null; // transformers.js pipeline instance
|
| 318 |
+
// Candidate models (ordered). We rotate until one loads. Prefer fully open, ungated models first.
|
| 319 |
+
let TRANSFORMERS_MODEL_CANDIDATES = [];
|
| 320 |
+
const DEFAULT_TRANSFORMERS_MODEL_CANDIDATES = [
|
| 321 |
+
// Force GPT2 first as requested, with a tiny fallback.
|
| 322 |
+
'Xenova/gpt2', // preferred primary model for chat
|
| 323 |
+
'Xenova/distilgpt2' // tiny fallback
|
| 324 |
+
// (Removed larger models to avoid long downloads / gated issues without token)
|
| 325 |
+
];
|
| 326 |
+
const SMALLER_MODEL_HINT = 'Xenova/distilgpt2';
|
| 327 |
+
const modelCandidatesInput = document.getElementById('model-candidates');
|
| 328 |
+
const applyModelsBtn = document.getElementById('apply-models');
|
| 329 |
+
const storedModels = localStorage.getItem('MODEL_CANDIDATES');
|
| 330 |
+
if (storedModels) {
|
| 331 |
+
TRANSFORMERS_MODEL_CANDIDATES = storedModels.split(',').map(s=>s.trim()).filter(Boolean);
|
| 332 |
+
modelCandidatesInput.value = TRANSFORMERS_MODEL_CANDIDATES.join(',');
|
| 333 |
+
} else {
|
| 334 |
+
TRANSFORMERS_MODEL_CANDIDATES = [...DEFAULT_TRANSFORMERS_MODEL_CANDIDATES];
|
| 335 |
+
modelCandidatesInput.value = TRANSFORMERS_MODEL_CANDIDATES.join(',');
|
| 336 |
+
}
|
| 337 |
+
let chosenTransformersModel = null;
|
| 338 |
+
// Load skip RAG preference
|
| 339 |
+
const storedSkipRag = localStorage.getItem('SKIP_RAG') === '1';
|
| 340 |
+
skipRagCheckbox.checked = storedSkipRag;
|
| 341 |
+
skipRagCheckbox.addEventListener('change', () => {
|
| 342 |
+
localStorage.setItem('SKIP_RAG', skipRagCheckbox.checked ? '1' : '0');
|
| 343 |
+
appendDiagnostic('Skip RAG set to ' + skipRagCheckbox.checked);
|
| 344 |
+
});
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
// Allow user to inject HF token before loading (e.g., window.HF_TOKEN = 'hf_xxx'; before this script)
|
| 348 |
+
if (window.HF_TOKEN) {
|
| 349 |
+
env.HF_ACCESS_TOKEN = window.HF_TOKEN;
|
| 350 |
+
}
|
| 351 |
+
// Load token from localStorage if present
|
| 352 |
+
const savedToken = localStorage.getItem('HF_TOKEN');
|
| 353 |
+
if (savedToken && !env.HF_ACCESS_TOKEN) {
|
| 354 |
+
env.HF_ACCESS_TOKEN = savedToken;
|
| 355 |
+
tokenInput.value = savedToken.slice(0,12) + 'β¦';
|
| 356 |
+
}
|
| 357 |
+
// Ensure remote huggingface URL (avoid accidental local mirror attempts). Can be customized.
|
| 358 |
+
env.remoteURL = 'https://huggingface.co';
|
| 359 |
+
// Disable local model resolution attempts to avoid 404 on /models/* when self-hosting without copies.
|
| 360 |
+
env.allowLocalModels = false;
|
| 361 |
+
|
| 362 |
+
let miniTableIndexEmbeddings = []; // Stores { tableId: "users", text: "...", embedding: [...] }
|
| 363 |
+
let detailedSchemaEmbeddings = []; // Stores { tableId: "users", chunkId: "col_details", text: "...", embedding: [...] }
|
| 364 |
+
|
| 365 |
+
// --- Your SQL Table Data ---
|
| 366 |
+
// This static data represents your knowledge base. In a real app, this might come from a file.
|
| 367 |
+
const rawSqlSchema = [
|
| 368 |
+
{
|
| 369 |
+
name: "Users",
|
| 370 |
+
summary: "Stores user account details including authentication and profile information.",
|
| 371 |
+
details: [
|
| 372 |
+
"Table `Users` has columns: UserID (PRIMARY KEY, INTEGER), Username (TEXT UNIQUE), Email (TEXT UNIQUE), PasswordHash (TEXT), RegistrationDate (DATETIME).",
|
| 373 |
+
"Purpose of `Users` table: Manages user login, identifies individuals, and stores core contact info.",
|
| 374 |
+
"Relationships of `Users`: One-to-many with `Orders` (UserID in `Orders` references UserID in `Users`)."
|
| 375 |
+
]
|
| 376 |
+
},
|
| 377 |
+
{
|
| 378 |
+
name: "Products",
|
| 379 |
+
summary: "Lists all available products with descriptions, pricing, and stock.",
|
| 380 |
+
details: [
|
| 381 |
+
"Table `Products` has columns: ProductID (PRIMARY KEY, INTEGER), ProductName (TEXT), Description (TEXT), CategoryID (FOREIGN KEY to Categories.CategoryID, INTEGER).",
|
| 382 |
+
"Table `Products` also has columns: Price (DECIMAL), StockQuantity (INTEGER), CreatedDate (DATETIME), LastUpdatedDate (DATETIME).",
|
| 383 |
+
"Table `Products` also has columns: ImageURL (TEXT), Weight (DECIMAL), Dimensions (TEXT), ProductStatus (TEXT).",
|
| 384 |
+
"Relationships of `Products`: One-to-many with `OrderItems` (ProductID in `OrderItems` references ProductID in `Products`)."
|
| 385 |
+
]
|
| 386 |
+
},
|
| 387 |
+
{
|
| 388 |
+
name: "Orders",
|
| 389 |
+
summary: "Records customer purchase transactions.",
|
| 390 |
+
details: [
|
| 391 |
+
"Table `Orders` has columns: OrderID (PRIMARY KEY, INTEGER), UserID (FOREIGN KEY to Users.UserID, INTEGER), OrderDate (DATETIME), TotalAmount (DECIMAL).",
|
| 392 |
+
"Purpose of `Orders` table: Tracks individual customer purchases and their aggregated cost.",
|
| 393 |
+
"Relationships of `Orders`: One-to-many with `OrderItems` (OrderID in `OrderItems` references OrderID in `Orders`)."
|
| 394 |
+
]
|
| 395 |
+
},
|
| 396 |
+
{
|
| 397 |
+
name: "OrderItems",
|
| 398 |
+
summary: "Details each item within a specific customer order.",
|
| 399 |
+
details: [
|
| 400 |
+
"Table `OrderItems` has columns: OrderItemID (PRIMARY KEY, INTEGER), OrderID (FOREIGN KEY to Orders.OrderID, INTEGER), ProductID (FOREIGN KEY to Products.ProductID, INTEGER).",
|
| 401 |
+
"Table `OrderItems` also has columns: Quantity (INTEGER), UnitPriceAtPurchase (DECIMAL), SubtotalItemAmount (DECIMAL).",
|
| 402 |
+
"Purpose of `OrderItems` table: Breaks down an order into its constituent products and quantities."
|
| 403 |
+
]
|
| 404 |
+
},
|
| 405 |
+
{
|
| 406 |
+
name: "Categories",
|
| 407 |
+
summary: "Classifies products into various categories.",
|
| 408 |
+
details: [
|
| 409 |
+
"Table `Categories` has columns: CategoryID (PRIMARY KEY, INTEGER), CategoryName (TEXT UNIQUE), CategoryDescription (TEXT).",
|
| 410 |
+
"Purpose of `Categories` table: Helps organize products for easier browsing and filtering.",
|
| 411 |
+
"Relationships of `Categories`: One-to-many with `Products` (CategoryID in `Products` references CategoryID in `Categories`)."
|
| 412 |
+
]
|
| 413 |
+
}
|
| 414 |
+
];
|
| 415 |
+
|
| 416 |
+
appendDiagnostic(messages[0].content);
|
| 417 |
+
|
| 418 |
+
// --- Helper Functions ---
|
| 419 |
+
|
| 420 |
+
// Callback function for initializing WebLLM progress.
|
| 421 |
+
function updateEngineInitProgressCallback(report) {
|
| 422 |
+
console.log("WebLLM Init:", report.progress, report.text);
|
| 423 |
+
downloadStatus.textContent = report.text;
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
// Helper function to append messages to the chat box
|
| 427 |
+
function appendMessage(message, isStreaming = false) {
|
| 428 |
+
const messageContainer = document.createElement("div");
|
| 429 |
+
messageContainer.classList.add("message-container", message.role);
|
| 430 |
+
|
| 431 |
+
// Only create a message bubble for user and assistant messages
|
| 432 |
+
if (message.role === "user" || message.role === "assistant") {
|
| 433 |
+
const messageBubble = document.createElement("div");
|
| 434 |
+
messageBubble.classList.add("message-bubble");
|
| 435 |
+
messageBubble.textContent = message.content;
|
| 436 |
+
messageContainer.appendChild(messageBubble);
|
| 437 |
+
} else {
|
| 438 |
+
// For system messages, just set the text content directly on the container
|
| 439 |
+
messageContainer.textContent = message.content;
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
chatBox.appendChild(messageContainer);
|
| 443 |
+
chatBox.scrollTop = chatBox.scrollHeight; // Scroll to bottom
|
| 444 |
+
|
| 445 |
+
if (isStreaming && message.role === "assistant") {
|
| 446 |
+
currentAssistantMessageElement = messageContainer.querySelector(".message-bubble");
|
| 447 |
+
}
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
// Helper function to update the content of the last assistant message (for streaming)
|
| 451 |
+
function updateLastAssistantMessage(newContent) {
|
| 452 |
+
if (currentAssistantMessageElement) {
|
| 453 |
+
currentAssistantMessageElement.textContent = newContent;
|
| 454 |
+
chatBox.scrollTop = chatBox.scrollHeight; // Scroll to bottom
|
| 455 |
+
}
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
// Cosine Similarity Function for RAG lookup
|
| 459 |
+
function cosineSimilarity(vec1, vec2) {
|
| 460 |
+
if (vec1.length !== vec2.length) {
|
| 461 |
+
return 0;
|
| 462 |
+
}
|
| 463 |
+
let dotProduct = 0;
|
| 464 |
+
let magnitude1 = 0;
|
| 465 |
+
let magnitude2 = 0;
|
| 466 |
+
for (let i = 0; i < vec1.length; i++) {
|
| 467 |
+
dotProduct += vec1[i] * vec2[i];
|
| 468 |
+
magnitude1 += vec1[i] * vec1[i];
|
| 469 |
+
magnitude2 += vec2[i] * vec2[i];
|
| 470 |
+
}
|
| 471 |
+
magnitude1 = Math.sqrt(magnitude1);
|
| 472 |
+
magnitude2 = Math.sqrt(magnitude2);
|
| 473 |
+
if (magnitude1 === 0 || magnitude2 === 0) {
|
| 474 |
+
return 0;
|
| 475 |
+
}
|
| 476 |
+
return dotProduct / (magnitude1 * magnitude2);
|
| 477 |
+
}
|
| 478 |
+
|
| 479 |
+
// --- RAG Lookup Logic ---
|
| 480 |
+
async function performRagLookup(query) {
|
| 481 |
+
if (skipRagCheckbox.checked) {
|
| 482 |
+
appendDiagnostic('RAG skipped by user preference.');
|
| 483 |
+
return null;
|
| 484 |
+
}
|
| 485 |
+
if (!embedder || miniTableIndexEmbeddings.length === 0 || detailedSchemaEmbeddings.length === 0) {
|
| 486 |
+
console.warn("Embedding model or knowledge base not ready for RAG lookup.");
|
| 487 |
+
appendDiagnostic("Embedding model or knowledge base not ready for RAG lookup.");
|
| 488 |
+
return null;
|
| 489 |
+
}
|
| 490 |
+
appendDiagnostic('RAG start for query: ' + query);
|
| 491 |
+
|
| 492 |
+
try {
|
| 493 |
+
// Stage 1: Embed user query and identify relevant tables from mini-index
|
| 494 |
+
const queryEmbeddingOutput = await embedder(query, { pooling: 'mean', normalize: true });
|
| 495 |
+
const queryEmbedding = queryEmbeddingOutput.data;
|
| 496 |
+
appendDiagnostic('RAG: query embedded dim=' + queryEmbedding.length);
|
| 497 |
+
|
| 498 |
+
let tableSimilarities = [];
|
| 499 |
+
for (const tableIndex of miniTableIndexEmbeddings) {
|
| 500 |
+
const score = cosineSimilarity(queryEmbedding, tableIndex.embedding);
|
| 501 |
+
tableSimilarities.push({ tableId: tableIndex.tableId, score: score });
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
tableSimilarities.sort((a, b) => b.score - a.score);
|
| 505 |
+
const topRelevantTableIds = tableSimilarities.filter(s => s.score > 0.5).slice(0, 3).map(s => s.tableId); // Top 3 tables with a minimum score
|
| 506 |
+
|
| 507 |
+
if (topRelevantTableIds.length === 0) {
|
| 508 |
+
console.log("No highly relevant tables identified for query:", query);
|
| 509 |
+
appendDiagnostic("RAG: No table above threshold.");
|
| 510 |
+
return null;
|
| 511 |
+
}
|
| 512 |
+
appendDiagnostic("RAG: tables -> " + topRelevantTableIds.join(','));
|
| 513 |
+
console.log("Identified relevant tables for RAG:", topRelevantTableIds);
|
| 514 |
+
|
| 515 |
+
// Stage 2: Filter detailed chunks by relevant tables and re-rank
|
| 516 |
+
let relevantDetailedChunks = [];
|
| 517 |
+
const filteredDetailedChunks = detailedSchemaEmbeddings.filter(chunk =>
|
| 518 |
+
topRelevantTableIds.includes(chunk.tableId)
|
| 519 |
+
);
|
| 520 |
+
|
| 521 |
+
let chunkSimilarities = [];
|
| 522 |
+
for (const chunk of filteredDetailedChunks) {
|
| 523 |
+
const score = cosineSimilarity(queryEmbedding, chunk.embedding);
|
| 524 |
+
chunkSimilarities.push({ chunk: chunk.text, score: score });
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
chunkSimilarities.sort((a, b) => b.score - a.score);
|
| 528 |
+
|
| 529 |
+
// Consolidate context: take top N most relevant detailed chunks
|
| 530 |
+
const maxChunksToInclude = 5; // Limit the number of chunks to manage context window
|
| 531 |
+
const contextChunks = chunkSimilarities.filter(s => s.score > 0.4).slice(0, maxChunksToInclude).map(s => s.chunk); // Filter by score again
|
| 532 |
+
|
| 533 |
+
if (contextChunks.length > 0) {
|
| 534 |
+
appendDiagnostic('RAG: selected ' + contextChunks.length + ' chunks.');
|
| 535 |
+
return contextChunks.join("\n\n---\n\n");
|
| 536 |
+
} else {
|
| 537 |
+
appendDiagnostic('RAG: No chunk passed score filter.');
|
| 538 |
+
return null; // No relevant chunks found after filtering
|
| 539 |
+
}
|
| 540 |
+
|
| 541 |
+
} catch (error) {
|
| 542 |
+
console.error("Error during RAG lookup:", error);
|
| 543 |
+
return null;
|
| 544 |
+
}
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
// --- Model Initialization ---
|
| 548 |
+
|
| 549 |
+
async function initializeModels() {
|
| 550 |
+
downloadStatus.classList.remove('hidden');
|
| 551 |
+
downloadStatus.textContent = 'Detecting acceleration backends...';
|
| 552 |
+
|
| 553 |
+
const hasWebGPU = !!navigator.gpu;
|
| 554 |
+
const hasWebGL2 = (() => { try { const c=document.createElement('canvas'); return !!c.getContext('webgl2'); } catch(_) { return false; } })();
|
| 555 |
+
console.log('Backend availability:', { hasWebGPU, hasWebGL2 });
|
| 556 |
+
|
| 557 |
+
// Attempt order: transformers webgpu -> transformers webgl -> webllm -> transformers wasm
|
| 558 |
+
const modelLoadErrors = [];
|
| 559 |
+
let validatedModelCandidates = null;
|
| 560 |
+
async function preflightModels() {
|
| 561 |
+
if (validatedModelCandidates) return validatedModelCandidates;
|
| 562 |
+
validatedModelCandidates = [];
|
| 563 |
+
appendDiagnostic('Preflight HEAD validation for models...');
|
| 564 |
+
for (const modelId of TRANSFORMERS_MODEL_CANDIDATES) {
|
| 565 |
+
const cfgUrl = `${env.remoteURL}/${modelId}/resolve/main/config.json`;
|
| 566 |
+
try {
|
| 567 |
+
let resp = await fetch(cfgUrl, { method: 'HEAD' });
|
| 568 |
+
if (resp.status === 405) { // Method not allowed, try GET minimal
|
| 569 |
+
resp = await fetch(cfgUrl, { method: 'GET' });
|
| 570 |
+
}
|
| 571 |
+
if (resp.ok) {
|
| 572 |
+
validatedModelCandidates.push(modelId);
|
| 573 |
+
appendDiagnostic(`OK ${modelId}`);
|
| 574 |
+
} else {
|
| 575 |
+
appendDiagnostic(`Skip ${modelId} (${resp.status})`);
|
| 576 |
+
}
|
| 577 |
+
} catch (e) {
|
| 578 |
+
appendDiagnostic(`Skip ${modelId} (error: ${e.message})`);
|
| 579 |
+
}
|
| 580 |
+
}
|
| 581 |
+
if (validatedModelCandidates.length === 0) {
|
| 582 |
+
appendDiagnostic('No valid models after preflight.');
|
| 583 |
+
}
|
| 584 |
+
return validatedModelCandidates;
|
| 585 |
+
}
|
| 586 |
+
async function tryTransformers(deviceTag) {
|
| 587 |
+
const candidates = await preflightModels();
|
| 588 |
+
for (const modelId of candidates) {
|
| 589 |
+
try {
|
| 590 |
+
downloadStatus.textContent = `Loading ${modelId} (${deviceTag})...`;
|
| 591 |
+
const opts = { quantized: true };
|
| 592 |
+
opts.device = deviceTag.startsWith('web') ? 'gpu' : (deviceTag === 'wasm' ? 'cpu' : 'cpu');
|
| 593 |
+
textGenPipeline = await pipeline('text-generation', modelId, opts);
|
| 594 |
+
chatBackend = `transformers-${deviceTag}`;
|
| 595 |
+
chosenTransformersModel = modelId;
|
| 596 |
+
console.log(`Loaded transformers model '${modelId}' on ${deviceTag}`);
|
| 597 |
+
return true;
|
| 598 |
+
} catch (e) {
|
| 599 |
+
const msg = (e?.message || '').toLowerCase();
|
| 600 |
+
let short = e.message;
|
| 601 |
+
if (msg.includes('unauthorized')) {
|
| 602 |
+
short += ' (Likely gated model; set window.HF_TOKEN before loading or choose an open model)';
|
| 603 |
+
} else if (msg.includes('404')) {
|
| 604 |
+
short += ' (Resource not found; if self-hosting assets, ensure files exist)';
|
| 605 |
+
}
|
| 606 |
+
modelLoadErrors.push({ device: deviceTag, model: modelId, error: short });
|
| 607 |
+
appendDiagnostic(`FAIL ${deviceTag} ${modelId}: ${short}`);
|
| 608 |
+
console.warn(`Transformers load failed for ${modelId} on ${deviceTag}:`, e);
|
| 609 |
+
// Try next model candidate
|
| 610 |
+
}
|
| 611 |
+
}
|
| 612 |
+
return false; // none loaded
|
| 613 |
+
}
|
| 614 |
+
|
| 615 |
+
let initialized = false;
|
| 616 |
+
const userPref = backendSelect.value; // may guide attempt ordering
|
| 617 |
+
const attemptOrder = (() => {
|
| 618 |
+
const base = ['transformers-webgpu','transformers-webgl','webllm','transformers-wasm'];
|
| 619 |
+
if (base.includes(userPref)) {
|
| 620 |
+
return [userPref, ...base.filter(b=>b!==userPref)];
|
| 621 |
+
}
|
| 622 |
+
return base;
|
| 623 |
+
})();
|
| 624 |
+
appendDiagnostic('Attempt order: ' + attemptOrder.join(' -> '));
|
| 625 |
+
for (const step of attemptOrder) {
|
| 626 |
+
if (initialized) break;
|
| 627 |
+
if (step === 'transformers-webgpu' && hasWebGPU) initialized = await tryTransformers('webgpu');
|
| 628 |
+
else if (step === 'transformers-webgl' && hasWebGL2) initialized = await tryTransformers('webgl');
|
| 629 |
+
else if (step === 'webllm' && hasWebGPU && !initialized) {
|
| 630 |
+
try {
|
| 631 |
+
appendDiagnostic('Trying WebLLM...');
|
| 632 |
+
downloadStatus.textContent = 'Loading WebLLM model (WebGPU)...';
|
| 633 |
+
engine = new webllm.MLCEngine();
|
| 634 |
+
engine.setInitProgressCallback(updateEngineInitProgressCallback);
|
| 635 |
+
let selectedModel = null;
|
| 636 |
+
const preferredModelPattern = 'TinyLlama';
|
| 637 |
+
const availableModels = webllm.prebuiltAppConfig.model_list;
|
| 638 |
+
const suitableModels = availableModels.filter(m => m.model_id.toLowerCase().includes(preferredModelPattern.toLowerCase()) && (m.model_id.includes('q4f16_1-MLC') || m.model_id.includes('q4f32_1-MLC')) && m.model_id.includes('Instruct'));
|
| 639 |
+
if (suitableModels.length > 0) { selectedModel = suitableModels[0].model_id; } else {
|
| 640 |
+
const fb = ['TinyLlama-1.1B-Chat-v1.0-q4f16_1-MLC','Qwen2.5-0.5B-Instruct-q4f16_1-MLC','gemma-2b-it-q4f16_1-MLC','Phi-3.5-mini-instruct-q4f16_1-MLC'];
|
| 641 |
+
for (const id of fb) { if (availableModels.find(m => m.model_id === id)) { selectedModel = id; break; } }
|
| 642 |
+
}
|
| 643 |
+
if (!selectedModel) throw new Error('No WebLLM model found');
|
| 644 |
+
await engine.reload(selectedModel, { temperature: 0.7, top_p: 0.9 });
|
| 645 |
+
chatBackend = 'webllm';
|
| 646 |
+
initialized = true;
|
| 647 |
+
appendDiagnostic('WebLLM loaded: ' + selectedModel);
|
| 648 |
+
} catch (e) {
|
| 649 |
+
appendDiagnostic('WebLLM failed: ' + e.message);
|
| 650 |
+
console.warn('WebLLM load failed:', e);
|
| 651 |
+
}
|
| 652 |
+
} else if (step === 'transformers-wasm' && !initialized) {
|
| 653 |
+
initialized = await tryTransformers('wasm');
|
| 654 |
+
}
|
| 655 |
+
}
|
| 656 |
+
|
| 657 |
+
// WebLLM attempt (only if not already have transformers GPU/WebGL and WebGPU present)
|
| 658 |
+
if (!initialized && hasWebGPU) {
|
| 659 |
+
try {
|
| 660 |
+
downloadStatus.textContent = 'Loading WebLLM model (WebGPU)...';
|
| 661 |
+
engine = new webllm.MLCEngine();
|
| 662 |
+
engine.setInitProgressCallback(updateEngineInitProgressCallback);
|
| 663 |
+
let selectedModel = null;
|
| 664 |
+
const preferredModelPattern = 'TinyLlama';
|
| 665 |
+
const availableModels = webllm.prebuiltAppConfig.model_list;
|
| 666 |
+
const suitableModels = availableModels.filter(m => m.model_id.toLowerCase().includes(preferredModelPattern.toLowerCase()) && (m.model_id.includes('q4f16_1-MLC') || m.model_id.includes('q4f32_1-MLC')) && m.model_id.includes('Instruct'));
|
| 667 |
+
if (suitableModels.length > 0) { selectedModel = suitableModels[0].model_id; } else {
|
| 668 |
+
const fb = ['TinyLlama-1.1B-Chat-v1.0-q4f16_1-MLC','Qwen2.5-0.5B-Instruct-q4f16_1-MLC','gemma-2b-it-q4f16_1-MLC','Phi-3.5-mini-instruct-q4f16_1-MLC'];
|
| 669 |
+
for (const id of fb) { if (availableModels.find(m => m.model_id === id)) { selectedModel = id; break; } }
|
| 670 |
+
}
|
| 671 |
+
if (!selectedModel) throw new Error('No WebLLM model found');
|
| 672 |
+
await engine.reload(selectedModel, { temperature: 0.7, top_p: 0.9 });
|
| 673 |
+
chatBackend = 'webllm';
|
| 674 |
+
initialized = true;
|
| 675 |
+
console.log('Loaded WebLLM model:', selectedModel);
|
| 676 |
+
} catch (e) {
|
| 677 |
+
console.warn('WebLLM load failed:', e);
|
| 678 |
+
}
|
| 679 |
+
}
|
| 680 |
+
|
| 681 |
+
// Final fallback: transformers wasm (CPU)
|
| 682 |
+
if (!initialized) {
|
| 683 |
+
downloadStatus.textContent = 'All model backend attempts failed. See diagnostics.';
|
| 684 |
+
activeBackendLabel.textContent = 'backend: failed';
|
| 685 |
+
diagnosticsEl.classList.add('show');
|
| 686 |
+
appendDiagnostic('FINAL: All attempts failed. Provide HF token if 401, or pick smaller model.');
|
| 687 |
+
return;
|
| 688 |
+
}
|
| 689 |
+
|
| 690 |
+
// Embeddings (shared)
|
| 691 |
+
try {
|
| 692 |
+
downloadStatus.textContent = 'Loading embedding model...';
|
| 693 |
+
embedder = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
|
| 694 |
+
for (const table of rawSqlSchema) {
|
| 695 |
+
const summaryOutput = await embedder(table.summary, { pooling: 'mean', normalize: true });
|
| 696 |
+
miniTableIndexEmbeddings.push({ tableId: table.name, text: table.summary, embedding: summaryOutput.data });
|
| 697 |
+
for (let i = 0; i < table.details.length; i++) {
|
| 698 |
+
const chunkText = table.details[i];
|
| 699 |
+
const chunkOutput = await embedder(chunkText, { pooling: 'mean', normalize: true });
|
| 700 |
+
detailedSchemaEmbeddings.push({ tableId: table.name, chunkId: `${table.name}_chunk_${i}`, text: chunkText, embedding: chunkOutput.data });
|
| 701 |
+
}
|
| 702 |
+
}
|
| 703 |
+
} catch (e) {
|
| 704 |
+
downloadStatus.textContent = 'Embedding init failed: ' + e.message;
|
| 705 |
+
console.error('Embedding init error:', e);
|
| 706 |
+
return;
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
// Ready UI
|
| 710 |
+
const backendLabel = chatBackend || 'unknown';
|
| 711 |
+
const slow = backendLabel.includes('wasm');
|
| 712 |
+
sendButton.disabled = false;
|
| 713 |
+
userInput.disabled = false;
|
| 714 |
+
userInput.setAttribute('placeholder', slow ? 'Type (CPU fallback, slower)...' : 'Type a message...');
|
| 715 |
+
if (chosenTransformersModel) {
|
| 716 |
+
appendMessage({ role: 'system', content: `AI (${backendLabel}/${chosenTransformersModel}): Ready. Ask about the SQL schema. ${slow ? 'Consider smaller model ('+SMALLER_MODEL_HINT+') for speed.' : ''}` });
|
| 717 |
+
downloadStatus.textContent = 'Models loaded (' + backendLabel + ').';
|
| 718 |
+
activeBackendLabel.textContent = `backend: ${backendLabel}`;
|
| 719 |
+
} else if (backendLabel === 'webllm') {
|
| 720 |
+
appendMessage({ role: 'system', content: `AI (${backendLabel}): Ready. Ask about the SQL schema.` });
|
| 721 |
+
downloadStatus.textContent = 'Models loaded (' + backendLabel + ').';
|
| 722 |
+
activeBackendLabel.textContent = `backend: ${backendLabel}`;
|
| 723 |
+
}
|
| 724 |
+
}
|
| 725 |
+
|
| 726 |
+
|
| 727 |
+
// Function to handle sending a message - MODIFIED FOR LLM-DRIVEN RAG
|
| 728 |
+
async function onMessageSend() {
|
| 729 |
+
const input = userInput.value.trim();
|
| 730 |
+
if (input.length === 0) {
|
| 731 |
+
return;
|
| 732 |
+
}
|
| 733 |
+
|
| 734 |
+
// Add user message to UI
|
| 735 |
+
const userMessage = { content: input, role: "user" };
|
| 736 |
+
messages.push(userMessage); // Add to conversation history
|
| 737 |
+
appendMessage(userMessage);
|
| 738 |
+
|
| 739 |
+
userInput.value = "";
|
| 740 |
+
sendButton.disabled = true;
|
| 741 |
+
userInput.setAttribute("placeholder", "Thinking and possibly looking up schema...");
|
| 742 |
+
|
| 743 |
+
// Temporarily append a placeholder for AI response
|
| 744 |
+
const aiMessagePlaceholder = { content: "typing...", role: "assistant" };
|
| 745 |
+
appendMessage(aiMessagePlaceholder, true); // Mark as streaming message for potential update
|
| 746 |
+
|
| 747 |
+
let fullAssistantResponse = "";
|
| 748 |
+
chatStats.classList.add("hidden");
|
| 749 |
+
|
| 750 |
+
console.log('Messages ', messages);
|
| 751 |
+
|
| 752 |
+
try {
|
| 753 |
+
if (chatBackend === 'webllm') {
|
| 754 |
+
// Original WebLLM two-pass tool invocation logic
|
| 755 |
+
const initialCompletion = await engine.chat.completions.create({
|
| 756 |
+
messages: messages,
|
| 757 |
+
stream: false,
|
| 758 |
+
temperature: 0.7,
|
| 759 |
+
top_p: 0.9,
|
| 760 |
+
});
|
| 761 |
+
let llmFirstResponseContent = initialCompletion.choices?.[0]?.message?.content || "";
|
| 762 |
+
let finalResponseContent = "";
|
| 763 |
+
if (skipRagCheckbox.checked) {
|
| 764 |
+
appendDiagnostic('Skip RAG mode: using first LLM response directly.');
|
| 765 |
+
finalResponseContent = llmFirstResponseContent;
|
| 766 |
+
updateLastAssistantMessage(finalResponseContent);
|
| 767 |
+
} else {
|
| 768 |
+
let parsedAction = null;
|
| 769 |
+
try { parsedAction = JSON.parse(llmFirstResponseContent); } catch (_) {}
|
| 770 |
+
if (parsedAction && parsedAction.action === "lookup_schema_info" && parsedAction.query) {
|
| 771 |
+
appendDiagnostic("RAG lookup requested by model: " + parsedAction.query);
|
| 772 |
+
updateLastAssistantMessage("π Searching schema for: " + parsedAction.query);
|
| 773 |
+
messages.push({ role: "assistant", content: llmFirstResponseContent });
|
| 774 |
+
const retrievedContext = await performRagLookup(parsedAction.query);
|
| 775 |
+
if (retrievedContext) {
|
| 776 |
+
const toolOutputMessage = `Here is the requested schema information:\n\`\`\`\n${retrievedContext}\n\`\`\`\nPlease use this information to answer the user's original question: "${input}"`;
|
| 777 |
+
messages.push({ role: "user", content: toolOutputMessage });
|
| 778 |
+
updateLastAssistantMessage("π§ Processing with retrieved info...");
|
| 779 |
+
const finalCompletion = await engine.chat.completions.create({
|
| 780 |
+
messages: messages,
|
| 781 |
+
stream: true,
|
| 782 |
+
temperature: 0.7,
|
| 783 |
+
top_p: 0.9,
|
| 784 |
+
});
|
| 785 |
+
for await (const chunk of finalCompletion) {
|
| 786 |
+
const curDelta = chunk.choices?.[0]?.delta.content;
|
| 787 |
+
if (curDelta) {
|
| 788 |
+
fullAssistantResponse += curDelta;
|
| 789 |
+
updateLastAssistantMessage(fullAssistantResponse);
|
| 790 |
+
}
|
| 791 |
+
}
|
| 792 |
+
finalResponseContent = fullAssistantResponse;
|
| 793 |
+
} else {
|
| 794 |
+
finalResponseContent = "No relevant context.";
|
| 795 |
+
updateLastAssistantMessage(finalResponseContent);
|
| 796 |
+
}
|
| 797 |
+
} else {
|
| 798 |
+
finalResponseContent = llmFirstResponseContent;
|
| 799 |
+
updateLastAssistantMessage(finalResponseContent);
|
| 800 |
+
}
|
| 801 |
+
}
|
| 802 |
+
messages.push({ content: finalResponseContent, role: 'assistant' });
|
| 803 |
+
const usageText = await engine.runtimeStatsText();
|
| 804 |
+
chatStats.classList.remove('hidden');
|
| 805 |
+
chatStats.textContent = usageText;
|
| 806 |
+
} else if (chatBackend && chatBackend.startsWith('transformers')) {
|
| 807 |
+
// Fallback CPU flow: single pass with RAG context (no tool JSON handshake to save latency)
|
| 808 |
+
updateLastAssistantMessage('π§ Gathering relevant schema context...');
|
| 809 |
+
let ragContext = null;
|
| 810 |
+
if (!skipRagCheckbox.checked) ragContext = await performRagLookup(input);
|
| 811 |
+
const prompt = skipRagCheckbox.checked
|
| 812 |
+
? `${systemMessageContent}\n\nUser question: ${input}\n\nAnswer:`
|
| 813 |
+
: `${systemMessageContent}\n\nUser question: ${input}\n\nRelevant schema context:\n${ragContext || 'No relevant context.'}\n\nAnswer:`;
|
| 814 |
+
updateLastAssistantMessage(`βοΈ Generating answer (${chatBackend}${chosenTransformersModel? '/' + chosenTransformersModel: ''})...`);
|
| 815 |
+
let streamedAnswer = '';
|
| 816 |
+
try {
|
| 817 |
+
const result = await textGenPipeline(prompt, {
|
| 818 |
+
max_new_tokens: 220,
|
| 819 |
+
temperature: 0.7,
|
| 820 |
+
top_p: 0.9,
|
| 821 |
+
repetition_penalty: 1.05,
|
| 822 |
+
callback_function: (data) => {
|
| 823 |
+
if (data?.token?.text) {
|
| 824 |
+
streamedAnswer += data.token.text;
|
| 825 |
+
// Avoid dumping the entire prompt back (strip if echo)
|
| 826 |
+
const splitIdx = streamedAnswer.lastIndexOf('Answer:');
|
| 827 |
+
const display = splitIdx !== -1 ? streamedAnswer.slice(splitIdx + 7).trimStart() : streamedAnswer;
|
| 828 |
+
updateLastAssistantMessage(display);
|
| 829 |
+
}
|
| 830 |
+
}
|
| 831 |
+
});
|
| 832 |
+
// Final extraction (if callback incomplete)
|
| 833 |
+
let finalText;
|
| 834 |
+
if (Array.isArray(result)) {
|
| 835 |
+
finalText = result[0]?.generated_text || streamedAnswer;
|
| 836 |
+
} else {
|
| 837 |
+
finalText = result.generated_text || streamedAnswer;
|
| 838 |
+
}
|
| 839 |
+
const answer = (() => {
|
| 840 |
+
const parts = finalText.split('Answer:');
|
| 841 |
+
if (parts.length > 1) return parts.slice(1).join('Answer:').trim();
|
| 842 |
+
return finalText.replace(prompt,'').trim();
|
| 843 |
+
})();
|
| 844 |
+
updateLastAssistantMessage(answer);
|
| 845 |
+
messages.push({ content: answer, role: 'assistant' });
|
| 846 |
+
} catch(genErr) {
|
| 847 |
+
updateLastAssistantMessage('Generation error: ' + genErr.message);
|
| 848 |
+
appendDiagnostic('Generation error: ' + genErr.stack);
|
| 849 |
+
}
|
| 850 |
+
chatStats.classList.add('hidden');
|
| 851 |
+
} else {
|
| 852 |
+
updateLastAssistantMessage('No active backend. Initialization error.');
|
| 853 |
+
}
|
| 854 |
+
} catch (error) {
|
| 855 |
+
updateLastAssistantMessage(`Error: ${error.message}`);
|
| 856 |
+
console.error('Error during chat handling:', error);
|
| 857 |
+
appendDiagnostic('Chat error: ' + error.stack);
|
| 858 |
+
} finally {
|
| 859 |
+
sendButton.disabled = false;
|
| 860 |
+
userInput.disabled = false;
|
| 861 |
+
const slow = chatBackend && chatBackend.endsWith('wasm');
|
| 862 |
+
userInput.setAttribute('placeholder', slow ? 'Type (CPU fallback, slower)...' : 'Type a message...');
|
| 863 |
+
currentAssistantMessageElement = null;
|
| 864 |
+
}
|
| 865 |
+
}
|
| 866 |
+
|
| 867 |
+
// Diagnostics helper
|
| 868 |
+
function appendDiagnostic(line) {
|
| 869 |
+
const ts = new Date().toISOString().split('T')[1].replace('Z','');
|
| 870 |
+
diagnosticsEl.textContent += `[${ts}] ${line}\n`;
|
| 871 |
+
diagnosticsEl.scrollTop = diagnosticsEl.scrollHeight;
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
// Control events
|
| 875 |
+
applyTokenBtn.addEventListener('click', () => {
|
| 876 |
+
const raw = prompt('Enter HF token (starts with hf_). This will be stored locally (clearable).');
|
| 877 |
+
if (raw && raw.startsWith('hf_')) {
|
| 878 |
+
localStorage.setItem('HF_TOKEN', raw);
|
| 879 |
+
window.location.reload();
|
| 880 |
+
}
|
| 881 |
+
});
|
| 882 |
+
applyModelsBtn.addEventListener('click', () => {
|
| 883 |
+
const raw = modelCandidatesInput.value.trim();
|
| 884 |
+
if (!raw) return;
|
| 885 |
+
localStorage.setItem('MODEL_CANDIDATES', raw);
|
| 886 |
+
window.location.reload();
|
| 887 |
+
});
|
| 888 |
+
forceReloadBtn.addEventListener('click', () => window.location.reload());
|
| 889 |
+
toggleDiagBtn.addEventListener('click', () => diagnosticsEl.classList.toggle('show'));
|
| 890 |
+
|
| 891 |
+
// --- Dynamic Trial Models Discovery (tokenless) ---
|
| 892 |
+
async function discoverOpenSmallModels(maxModels = 6) {
|
| 893 |
+
// Curated base list of realistically loadable tokenless models published with ONNX/TFJS weights.
|
| 894 |
+
const CURATED = [
|
| 895 |
+
'Xenova/gpt2',
|
| 896 |
+
'Xenova/distilgpt2',
|
| 897 |
+
'Xenova/phi-2',
|
| 898 |
+
'Xenova/TinyLlama-1.1B-Chat-v1.0'
|
| 899 |
+
];
|
| 900 |
+
const archWhitelist = [
|
| 901 |
+
'GPT2LMHeadModel',
|
| 902 |
+
'PhiForCausalLM',
|
| 903 |
+
'LlamaForCausalLM',
|
| 904 |
+
'MistralForCausalLM',
|
| 905 |
+
'TinyLlamaForCausalLM'
|
| 906 |
+
];
|
| 907 |
+
const accepted = [];
|
| 908 |
+
async function fetchConfig(modelId) {
|
| 909 |
+
const url = `${env.remoteURL}/${modelId}/resolve/main/config.json`;
|
| 910 |
+
try {
|
| 911 |
+
const resp = await fetch(url, { headers:{ 'Accept':'application/json' } });
|
| 912 |
+
if (!resp.ok) throw new Error(resp.status+ ' ' + resp.statusText);
|
| 913 |
+
return await resp.json();
|
| 914 |
+
} catch (e) {
|
| 915 |
+
appendDiagnostic('Config fail '+modelId+': '+e.message);
|
| 916 |
+
return null;
|
| 917 |
+
}
|
| 918 |
+
}
|
| 919 |
+
for (const m of CURATED) {
|
| 920 |
+
if (accepted.length >= maxModels) break;
|
| 921 |
+
const cfg = await fetchConfig(m);
|
| 922 |
+
if (!cfg) continue;
|
| 923 |
+
const archs = cfg.architectures || [];
|
| 924 |
+
const ok = archs.some(a => archWhitelist.includes(a));
|
| 925 |
+
if (!ok) {
|
| 926 |
+
appendDiagnostic('Skip '+m+' (arch '+archs.join('/')+' not whitelisted)');
|
| 927 |
+
continue;
|
| 928 |
+
}
|
| 929 |
+
// Rough size gating: reject if hidden_size * n_layer heuristic too large (> ~4B tokens weight proxy)
|
| 930 |
+
const hs = cfg.hidden_size || cfg.n_embd || 0;
|
| 931 |
+
const nl = cfg.num_hidden_layers || cfg.n_layer || 0;
|
| 932 |
+
if (hs && nl && hs * nl > 20000) { // heuristic threshold
|
| 933 |
+
appendDiagnostic('Skip '+m+' (heuristic size too large hs*nl='+hs*nl+')');
|
| 934 |
+
continue;
|
| 935 |
+
}
|
| 936 |
+
accepted.push(m);
|
| 937 |
+
}
|
| 938 |
+
if (accepted.length === 0) {
|
| 939 |
+
appendDiagnostic('Discovery empty; using minimal fallback list.');
|
| 940 |
+
accepted.push('Xenova/gpt2','Xenova/distilgpt2');
|
| 941 |
+
}
|
| 942 |
+
return accepted.slice(0, maxModels);
|
| 943 |
+
}
|
| 944 |
+
|
| 945 |
+
trialModelsBtn.addEventListener('click', async () => {
|
| 946 |
+
trialModelsBtn.disabled = true;
|
| 947 |
+
const TRIAL_PROMPT = 'Do planes fly higher than bees?';
|
| 948 |
+
// Create a live-updating system message
|
| 949 |
+
const liveHeader = '### Model Trials (live, no token)';
|
| 950 |
+
appendMessage({ role: 'system', content: liveHeader + '\nStarting discovery...' });
|
| 951 |
+
const liveEl = chatBox.lastElementChild; // system container
|
| 952 |
+
const lines = [liveHeader, 'Starting discovery...'];
|
| 953 |
+
const flush = () => { liveEl.textContent = lines.join('\n'); };
|
| 954 |
+
const addLine = (l) => { lines.push(l); flush(); };
|
| 955 |
+
const yieldUI = async () => new Promise(r=>requestAnimationFrame(r));
|
| 956 |
+
function withTimeout(promise, ms, label) {
|
| 957 |
+
return Promise.race([
|
| 958 |
+
promise,
|
| 959 |
+
new Promise((_, rej) => setTimeout(()=>rej(new Error(label + ' timeout after '+ms+'ms')), ms))
|
| 960 |
+
]);
|
| 961 |
+
}
|
| 962 |
+
appendDiagnostic('Trial: starting discovery...');
|
| 963 |
+
let discovered = [];
|
| 964 |
+
try {
|
| 965 |
+
discovered = await discoverOpenSmallModels(10);
|
| 966 |
+
} catch(e) {
|
| 967 |
+
appendDiagnostic('Discovery error: ' + e.message);
|
| 968 |
+
addLine('Discovery error: ' + e.message);
|
| 969 |
+
}
|
| 970 |
+
if (!discovered.length) {
|
| 971 |
+
addLine('No models discovered dynamically. Using static fallbacks.');
|
| 972 |
+
discovered = ['Xenova/gpt2','Xenova/distilgpt2'];
|
| 973 |
+
}
|
| 974 |
+
const baseline = ['Xenova/gpt2','Xenova/distilgpt2'];
|
| 975 |
+
const ordered = baseline.concat(discovered.filter(m=>!baseline.includes(m)));
|
| 976 |
+
const MODELS = ordered.slice(0,6);
|
| 977 |
+
addLine('Models to try: ' + MODELS.join(', '));
|
| 978 |
+
appendDiagnostic('Trial: Models -> ' + discovered.join(', '));
|
| 979 |
+
const collected = [];
|
| 980 |
+
try {
|
| 981 |
+
for (const modelId of MODELS) {
|
| 982 |
+
let loadTime='-', genTime='-', snippet='', error=null;
|
| 983 |
+
const t0 = performance.now();
|
| 984 |
+
addLine(`Loading ${modelId} ...`);
|
| 985 |
+
flush();
|
| 986 |
+
try {
|
| 987 |
+
const pipe = await withTimeout(pipeline('text-generation', modelId, { quantized: true }), 20000, 'load');
|
| 988 |
+
const t1 = performance.now();
|
| 989 |
+
const out = await withTimeout(pipe(TRIAL_PROMPT, { max_new_tokens: 30, temperature: 0.7 }), 12000, 'gen');
|
| 990 |
+
const t2 = performance.now();
|
| 991 |
+
loadTime = ((t1-t0)/1000).toFixed(2)+'s';
|
| 992 |
+
genTime = ((t2-t1)/1000).toFixed(2)+'s';
|
| 993 |
+
const full = Array.isArray(out) ? (out[0]?.generated_text||'') : (out.generated_text||'');
|
| 994 |
+
snippet = full.trim().slice(0,200).replace(/\n+/g,' ') || '(empty)';
|
| 995 |
+
addLine(`${modelId} β load ${loadTime} gen ${genTime}`);
|
| 996 |
+
addLine(` β ${snippet}`);
|
| 997 |
+
} catch(e) {
|
| 998 |
+
error = e?.message || String(e);
|
| 999 |
+
addLine(`${modelId} β ${error}`);
|
| 1000 |
+
appendDiagnostic('Trial error '+modelId+': '+error);
|
| 1001 |
+
}
|
| 1002 |
+
collected.push({ model:modelId, loadTime, genTime, snippet, error });
|
| 1003 |
+
await yieldUI();
|
| 1004 |
+
}
|
| 1005 |
+
} finally {
|
| 1006 |
+
trialModelsBtn.disabled = false;
|
| 1007 |
+
}
|
| 1008 |
+
addLine('');
|
| 1009 |
+
addLine('### Trial Summary');
|
| 1010 |
+
for (const r of collected) {
|
| 1011 |
+
if (r.error) {
|
| 1012 |
+
addLine(`- ${r.model}: ERROR ${r.error}`);
|
| 1013 |
+
} else {
|
| 1014 |
+
addLine(`- ${r.model} (Load ${r.loadTime} / Gen ${r.genTime})`);
|
| 1015 |
+
}
|
| 1016 |
+
}
|
| 1017 |
+
appendDiagnostic('Trial: progress & summary streamed into chat message.');
|
| 1018 |
+
});
|
| 1019 |
+
|
| 1020 |
+
// Event Listeners
|
| 1021 |
+
sendButton.addEventListener("click", onMessageSend);
|
| 1022 |
+
userInput.addEventListener("keypress", (event) => {
|
| 1023 |
+
if (event.key === "Enter" && !sendButton.disabled) {
|
| 1024 |
+
onMessageSend();
|
| 1025 |
+
}
|
| 1026 |
+
});
|
| 1027 |
+
|
| 1028 |
+
// Attempt to reduce ONNX Runtime verbosity (if backend loads onnxruntime-web)
|
| 1029 |
+
async function quietOnnxLogs() {
|
| 1030 |
+
try {
|
| 1031 |
+
const ort = await import('https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js');
|
| 1032 |
+
// ort.env.logLevel values: 'verbose'|'info'|'warning'|'error' (or numeric severity)
|
| 1033 |
+
ort.env.logLevel = 'info';
|
| 1034 |
+
} catch (e) {
|
| 1035 |
+
appendDiagnostic('ORT log level not set: ' + e.message);
|
| 1036 |
+
}
|
| 1037 |
+
}
|
| 1038 |
+
|
| 1039 |
+
// Initialize all models (WebLLM and Embedding model) when the page loads
|
| 1040 |
+
document.addEventListener("DOMContentLoaded", () => { quietOnnxLogs(); initializeModels(); });
|
| 1041 |
+
</script>
|
| 1042 |
+
</body>
|
| 1043 |
+
</html>
|
index.html
CHANGED
|
@@ -1,1043 +1,12 @@
|
|
| 1 |
<!DOCTYPE html>
|
| 2 |
<html lang="en">
|
| 3 |
<head>
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
body {
|
| 9 |
-
font-family: Arial, sans-serif;
|
| 10 |
-
margin: 0;
|
| 11 |
-
padding: 0;
|
| 12 |
-
background-color: #f0f2f5;
|
| 13 |
-
display: flex;
|
| 14 |
-
justify-content: center;
|
| 15 |
-
align-items: center;
|
| 16 |
-
min-height: 100vh;
|
| 17 |
-
color: #333;
|
| 18 |
-
}
|
| 19 |
-
|
| 20 |
-
#chat-container {
|
| 21 |
-
background-color: #fff;
|
| 22 |
-
border-radius: 10px;
|
| 23 |
-
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
|
| 24 |
-
width: 100vw;
|
| 25 |
-
max-width: none;
|
| 26 |
-
display: flex;
|
| 27 |
-
flex-direction: column;
|
| 28 |
-
overflow: hidden;
|
| 29 |
-
min-height: 80vh;
|
| 30 |
-
max-height: 95vh;
|
| 31 |
-
position: relative;
|
| 32 |
-
}
|
| 33 |
-
|
| 34 |
-
h1 {
|
| 35 |
-
text-align: center;
|
| 36 |
-
color: #4a4a4a;
|
| 37 |
-
padding: 15px;
|
| 38 |
-
margin: 0;
|
| 39 |
-
border-bottom: 1px solid #eee;
|
| 40 |
-
font-size: 1.5em;
|
| 41 |
-
}
|
| 42 |
-
|
| 43 |
-
.status-message {
|
| 44 |
-
text-align: center;
|
| 45 |
-
padding: 10px;
|
| 46 |
-
background-color: #e0f7fa;
|
| 47 |
-
color: #00796b;
|
| 48 |
-
font-weight: bold;
|
| 49 |
-
border-bottom: 1px solid #b2ebf2;
|
| 50 |
-
}
|
| 51 |
-
|
| 52 |
-
#chat-box {
|
| 53 |
-
flex-grow: 1;
|
| 54 |
-
padding: 20px;
|
| 55 |
-
overflow-y: auto;
|
| 56 |
-
display: flex;
|
| 57 |
-
flex-direction: column;
|
| 58 |
-
gap: 10px;
|
| 59 |
-
}
|
| 60 |
-
|
| 61 |
-
.message-container {
|
| 62 |
-
display: flex;
|
| 63 |
-
flex-direction: column;
|
| 64 |
-
max-width: 80%;
|
| 65 |
-
}
|
| 66 |
-
|
| 67 |
-
.message-container.user {
|
| 68 |
-
align-self: flex-end;
|
| 69 |
-
align-items: flex-end;
|
| 70 |
-
}
|
| 71 |
-
|
| 72 |
-
.message-container.assistant {
|
| 73 |
-
align-self: flex-start;
|
| 74 |
-
align-items: flex-start;
|
| 75 |
-
}
|
| 76 |
-
|
| 77 |
-
.message-container.system {
|
| 78 |
-
align-self: center; /* Center system messages */
|
| 79 |
-
align-items: center;
|
| 80 |
-
font-size: 0.85em;
|
| 81 |
-
color: #666;
|
| 82 |
-
text-align: left;
|
| 83 |
-
padding: 5px 10px;
|
| 84 |
-
border-radius: 10px;
|
| 85 |
-
background-color: #f0f0f0;
|
| 86 |
-
margin: 5px 0;
|
| 87 |
-
white-space: pre-wrap; /* preserve markdown line breaks */
|
| 88 |
-
}
|
| 89 |
-
|
| 90 |
-
.message-bubble {
|
| 91 |
-
padding: 10px 15px;
|
| 92 |
-
border-radius: 20px;
|
| 93 |
-
line-height: 1.4;
|
| 94 |
-
word-wrap: break-word;
|
| 95 |
-
white-space: pre-wrap; /* Preserve whitespace and line breaks */
|
| 96 |
-
}
|
| 97 |
-
|
| 98 |
-
.message-container.user .message-bubble {
|
| 99 |
-
background-color: #007bff;
|
| 100 |
-
color: white;
|
| 101 |
-
border-bottom-right-radius: 5px;
|
| 102 |
-
}
|
| 103 |
-
|
| 104 |
-
.message-container.assistant .message-bubble {
|
| 105 |
-
background-color: #e9e9eb;
|
| 106 |
-
color: #333;
|
| 107 |
-
border-bottom-left-radius: 5px;
|
| 108 |
-
}
|
| 109 |
-
|
| 110 |
-
.chat-input-container {
|
| 111 |
-
display: flex;
|
| 112 |
-
padding: 15px;
|
| 113 |
-
border-top: 1px solid #eee;
|
| 114 |
-
background-color: #fff;
|
| 115 |
-
gap: 10px;
|
| 116 |
-
}
|
| 117 |
-
|
| 118 |
-
#user-input {
|
| 119 |
-
flex-grow: 1;
|
| 120 |
-
padding: 10px 15px;
|
| 121 |
-
border: 1px solid #ddd;
|
| 122 |
-
border-radius: 20px;
|
| 123 |
-
font-size: 1em;
|
| 124 |
-
outline: none;
|
| 125 |
-
}
|
| 126 |
-
|
| 127 |
-
#user-input:focus {
|
| 128 |
-
border-color: #007bff;
|
| 129 |
-
}
|
| 130 |
-
|
| 131 |
-
#send {
|
| 132 |
-
padding: 10px 20px;
|
| 133 |
-
background-color: #007bff;
|
| 134 |
-
color: white;
|
| 135 |
-
border: none;
|
| 136 |
-
border-radius: 20px;
|
| 137 |
-
cursor: pointer;
|
| 138 |
-
font-size: 1em;
|
| 139 |
-
transition: background-color 0.2s;
|
| 140 |
-
}
|
| 141 |
-
|
| 142 |
-
#send:hover:not(:disabled) {
|
| 143 |
-
background-color: #0056b3;
|
| 144 |
-
}
|
| 145 |
-
|
| 146 |
-
#send:disabled {
|
| 147 |
-
background-color: #a0c9ff;
|
| 148 |
-
cursor: not-allowed;
|
| 149 |
-
}
|
| 150 |
-
|
| 151 |
-
.chat-stats {
|
| 152 |
-
font-size: 0.8em;
|
| 153 |
-
color: #666;
|
| 154 |
-
text-align: right;
|
| 155 |
-
padding: 5px 20px;
|
| 156 |
-
background-color: #f9f9f9;
|
| 157 |
-
border-top: 1px solid #eee;
|
| 158 |
-
}
|
| 159 |
-
|
| 160 |
-
.hidden {
|
| 161 |
-
display: none!important;
|
| 162 |
-
}
|
| 163 |
-
|
| 164 |
-
.controls {
|
| 165 |
-
padding: 8px 12px;
|
| 166 |
-
background:#fafafa;
|
| 167 |
-
border-bottom:1px solid #eee;
|
| 168 |
-
display:flex;
|
| 169 |
-
flex-wrap:wrap;
|
| 170 |
-
gap:8px;
|
| 171 |
-
align-items:center;
|
| 172 |
-
font-size:0.75rem;
|
| 173 |
-
}
|
| 174 |
-
.controls input[type=text] {
|
| 175 |
-
padding:4px 8px;
|
| 176 |
-
border:1px solid #ccc;
|
| 177 |
-
border-radius:6px;
|
| 178 |
-
font-size:0.75rem;
|
| 179 |
-
}
|
| 180 |
-
.controls button, .controls select {
|
| 181 |
-
padding:4px 10px;
|
| 182 |
-
font-size:0.7rem;
|
| 183 |
-
border:1px solid #ccc;
|
| 184 |
-
border-radius:6px;
|
| 185 |
-
background:#fff;
|
| 186 |
-
cursor:pointer;
|
| 187 |
-
}
|
| 188 |
-
.controls button:hover { background:#f0f0f0; }
|
| 189 |
-
#diagnostics {
|
| 190 |
-
max-height:120px;
|
| 191 |
-
overflow:auto;
|
| 192 |
-
font-family:monospace;
|
| 193 |
-
background:#1e1e1e;
|
| 194 |
-
color:#c9d1d9;
|
| 195 |
-
padding:6px 8px;
|
| 196 |
-
font-size:0.65rem;
|
| 197 |
-
border-top:1px solid #333;
|
| 198 |
-
display:none;
|
| 199 |
-
white-space:pre-wrap;
|
| 200 |
-
}
|
| 201 |
-
#diagnostics.show { display:block; }
|
| 202 |
-
</style>
|
| 203 |
</head>
|
| 204 |
<body>
|
| 205 |
-
|
| 206 |
-
<h1>In-Browser LLM Chat with RAG</h1>
|
| 207 |
-
<div class="controls">
|
| 208 |
-
<label>HF Token:
|
| 209 |
-
<input type="text" id="hf-token" placeholder="hf_... (optional)" size="18" autocomplete="off" />
|
| 210 |
-
</label>
|
| 211 |
-
<button id="apply-token" title="Store token (localStorage) & reload">Apply Token + Reload</button>
|
| 212 |
-
<label style="display:flex;align-items:center;gap:4px;">Models:
|
| 213 |
-
<input type="text" id="model-candidates" placeholder="comma-separated model ids" size="26" />
|
| 214 |
-
</label>
|
| 215 |
-
<button id="apply-models" title="Store custom model list & reload">Apply Models</button>
|
| 216 |
-
<label style="display:flex;align-items:center;gap:4px;">Skip RAG:
|
| 217 |
-
<input type="checkbox" id="skip-rag" title="If checked, no retrieval augmented context will be gathered." />
|
| 218 |
-
</label>
|
| 219 |
-
|
| 220 |
-
<select id="preferred-backend" title="Preferred first backend">
|
| 221 |
-
<option value="transformers-webgpu">TF WebGPU</option>
|
| 222 |
-
<option value="transformers-webgl">TF WebGL</option>
|
| 223 |
-
<option value="webllm">WebLLM</option>
|
| 224 |
-
<option value="transformers-wasm">TF WASM</option>
|
| 225 |
-
</select>
|
| 226 |
-
<button id="force-reload" title="Reinitialize models">Reload Models</button>
|
| 227 |
-
<button id="trial-models" title="Try/test multiple small models">Trial Models</button>
|
| 228 |
-
<button id="toggle-diagnostics" title="Show/Hide diagnostics">Diagnostics</button>
|
| 229 |
-
<span id="active-backend" style="margin-left:auto;font-weight:bold;">backend: -</span>
|
| 230 |
-
</div>
|
| 231 |
-
<div id="download-status" class="status-message">Loading model...</div>
|
| 232 |
-
<div id="chat-box">
|
| 233 |
-
</div>
|
| 234 |
-
<div id="chat-stats" class="chat-stats hidden"></div>
|
| 235 |
-
<div id="diagnostics"></div>
|
| 236 |
-
<div id="trial-results" style="display:none;padding:12px;"></div>
|
| 237 |
-
<div class="chat-input-container">
|
| 238 |
-
<input type="text" id="user-input" placeholder="Loading models for RAG..." disabled>
|
| 239 |
-
<button id="send" disabled>Send</button>
|
| 240 |
-
</div>
|
| 241 |
-
</div>
|
| 242 |
-
|
| 243 |
-
<script type="module">
|
| 244 |
-
import * as webllm from "https://esm.run/@mlc-ai/web-llm";
|
| 245 |
-
import { pipeline, env } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.14.0';
|
| 246 |
-
|
| 247 |
-
// ---- Console Log Filtering (suppress noisy ONNX optimizer warnings) ----
|
| 248 |
-
const LOG_FILTER_PATTERNS = [
|
| 249 |
-
/CleanUnusedInitializersAndNodeArgs/i,
|
| 250 |
-
/graph\.cc:\d+ CleanUnusedInitializersAndNodeArgs/i,
|
| 251 |
-
/Removing initializer '\/transformer\//i
|
| 252 |
-
];
|
| 253 |
-
const originalConsole = { log: console.log, warn: console.warn };
|
| 254 |
-
function shouldSuppress(args) {
|
| 255 |
-
return args.some(a => typeof a === 'string' && LOG_FILTER_PATTERNS.some(p => p.test(a)));
|
| 256 |
-
}
|
| 257 |
-
console.warn = (...args) => {
|
| 258 |
-
if (shouldSuppress(args)) { return; }
|
| 259 |
-
originalConsole.warn(...args);
|
| 260 |
-
};
|
| 261 |
-
console.log = (...args) => {
|
| 262 |
-
if (shouldSuppress(args)) { return; }
|
| 263 |
-
originalConsole.log(...args);
|
| 264 |
-
};
|
| 265 |
-
|
| 266 |
-
/*************** WebLLM Logic & RAG Components ***************/
|
| 267 |
-
|
| 268 |
-
// System message for the LLM to understand its role and tool use
|
| 269 |
-
const systemMessageContent = `
|
| 270 |
-
You are an intelligent person with honesty and broad knowledge.
|
| 271 |
-
|
| 272 |
-
Although you also know about SQL queries.
|
| 273 |
-
|
| 274 |
-
You have access to a special "lookup" tool. If you need more specific details about tables or concepts to answer a user's question, you MUST respond with a JSON object in this exact format:
|
| 275 |
-
|
| 276 |
-
\`\`\`json
|
| 277 |
-
{
|
| 278 |
-
"action": "lookup_schema_info",
|
| 279 |
-
"query": "concise natural language phrase describing what schema information you need"
|
| 280 |
-
}
|
| 281 |
-
\`\`\`
|
| 282 |
-
|
| 283 |
-
Examples of "query" for the lookup_schema_info action:
|
| 284 |
-
- "details about the Users and Products tables"
|
| 285 |
-
- "columns in the Orders table and its related tables"
|
| 286 |
-
- "how Categories table relates to Products"
|
| 287 |
-
|
| 288 |
-
If you can answer the question directly with your existing knowledge or after using the tool, provide the natural language answer or SQL query. Do NOT use the lookup tool if you already have enough information.
|
| 289 |
-
`.trim(); // Trim to remove leading/trailing whitespace
|
| 290 |
-
|
| 291 |
-
const messages = [{ role: "system", content: systemMessageContent }];
|
| 292 |
-
|
| 293 |
-
const chatBox = document.getElementById("chat-box");
|
| 294 |
-
const userInput = document.getElementById("user-input");
|
| 295 |
-
const sendButton = document.getElementById("send");
|
| 296 |
-
const downloadStatus = document.getElementById("download-status");
|
| 297 |
-
const chatStats = document.getElementById("chat-stats");
|
| 298 |
-
const diagnosticsEl = document.getElementById('diagnostics');
|
| 299 |
-
const tokenInput = document.getElementById('hf-token');
|
| 300 |
-
const applyTokenBtn = document.getElementById('apply-token');
|
| 301 |
-
const forceReloadBtn = document.getElementById('force-reload');
|
| 302 |
-
const toggleDiagBtn = document.getElementById('toggle-diagnostics');
|
| 303 |
-
const backendSelect = document.getElementById('preferred-backend');
|
| 304 |
-
const activeBackendLabel = document.getElementById('active-backend');
|
| 305 |
-
const trialModelsBtn = document.getElementById('trial-models');
|
| 306 |
-
const skipRagCheckbox = document.getElementById('skip-rag');
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
let currentAssistantMessageElement = null; // To update the streaming message
|
| 310 |
-
let embedder = null; // In-browser embedding model
|
| 311 |
-
|
| 312 |
-
// Fix: Declare engine as 'let' at module scope. It will be instantiated inside initializeModels.
|
| 313 |
-
let engine;
|
| 314 |
-
// Backend selection flow (priority):
|
| 315 |
-
// 1. transformers:webgpu 2. transformers:webgl 3. webllm:webgpu 4. transformers:wasm
|
| 316 |
-
let chatBackend = null;
|
| 317 |
-
let textGenPipeline = null; // transformers.js pipeline instance
|
| 318 |
-
// Candidate models (ordered). We rotate until one loads. Prefer fully open, ungated models first.
|
| 319 |
-
let TRANSFORMERS_MODEL_CANDIDATES = [];
|
| 320 |
-
const DEFAULT_TRANSFORMERS_MODEL_CANDIDATES = [
|
| 321 |
-
// Force GPT2 first as requested, with a tiny fallback.
|
| 322 |
-
'Xenova/gpt2', // preferred primary model for chat
|
| 323 |
-
'Xenova/distilgpt2' // tiny fallback
|
| 324 |
-
// (Removed larger models to avoid long downloads / gated issues without token)
|
| 325 |
-
];
|
| 326 |
-
const SMALLER_MODEL_HINT = 'Xenova/distilgpt2';
|
| 327 |
-
const modelCandidatesInput = document.getElementById('model-candidates');
|
| 328 |
-
const applyModelsBtn = document.getElementById('apply-models');
|
| 329 |
-
const storedModels = localStorage.getItem('MODEL_CANDIDATES');
|
| 330 |
-
if (storedModels) {
|
| 331 |
-
TRANSFORMERS_MODEL_CANDIDATES = storedModels.split(',').map(s=>s.trim()).filter(Boolean);
|
| 332 |
-
modelCandidatesInput.value = TRANSFORMERS_MODEL_CANDIDATES.join(',');
|
| 333 |
-
} else {
|
| 334 |
-
TRANSFORMERS_MODEL_CANDIDATES = [...DEFAULT_TRANSFORMERS_MODEL_CANDIDATES];
|
| 335 |
-
modelCandidatesInput.value = TRANSFORMERS_MODEL_CANDIDATES.join(',');
|
| 336 |
-
}
|
| 337 |
-
let chosenTransformersModel = null;
|
| 338 |
-
// Load skip RAG preference
|
| 339 |
-
const storedSkipRag = localStorage.getItem('SKIP_RAG') === '1';
|
| 340 |
-
skipRagCheckbox.checked = storedSkipRag;
|
| 341 |
-
skipRagCheckbox.addEventListener('change', () => {
|
| 342 |
-
localStorage.setItem('SKIP_RAG', skipRagCheckbox.checked ? '1' : '0');
|
| 343 |
-
appendDiagnostic('Skip RAG set to ' + skipRagCheckbox.checked);
|
| 344 |
-
});
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
// Allow user to inject HF token before loading (e.g., window.HF_TOKEN = 'hf_xxx'; before this script)
|
| 348 |
-
if (window.HF_TOKEN) {
|
| 349 |
-
env.HF_ACCESS_TOKEN = window.HF_TOKEN;
|
| 350 |
-
}
|
| 351 |
-
// Load token from localStorage if present
|
| 352 |
-
const savedToken = localStorage.getItem('HF_TOKEN');
|
| 353 |
-
if (savedToken && !env.HF_ACCESS_TOKEN) {
|
| 354 |
-
env.HF_ACCESS_TOKEN = savedToken;
|
| 355 |
-
tokenInput.value = savedToken.slice(0,12) + 'β¦';
|
| 356 |
-
}
|
| 357 |
-
// Ensure remote huggingface URL (avoid accidental local mirror attempts). Can be customized.
|
| 358 |
-
env.remoteURL = 'https://huggingface.co';
|
| 359 |
-
// Disable local model resolution attempts to avoid 404 on /models/* when self-hosting without copies.
|
| 360 |
-
env.allowLocalModels = false;
|
| 361 |
-
|
| 362 |
-
let miniTableIndexEmbeddings = []; // Stores { tableId: "users", text: "...", embedding: [...] }
|
| 363 |
-
let detailedSchemaEmbeddings = []; // Stores { tableId: "users", chunkId: "col_details", text: "...", embedding: [...] }
|
| 364 |
-
|
| 365 |
-
// --- Your SQL Table Data ---
|
| 366 |
-
// This static data represents your knowledge base. In a real app, this might come from a file.
|
| 367 |
-
const rawSqlSchema = [
|
| 368 |
-
{
|
| 369 |
-
name: "Users",
|
| 370 |
-
summary: "Stores user account details including authentication and profile information.",
|
| 371 |
-
details: [
|
| 372 |
-
"Table `Users` has columns: UserID (PRIMARY KEY, INTEGER), Username (TEXT UNIQUE), Email (TEXT UNIQUE), PasswordHash (TEXT), RegistrationDate (DATETIME).",
|
| 373 |
-
"Purpose of `Users` table: Manages user login, identifies individuals, and stores core contact info.",
|
| 374 |
-
"Relationships of `Users`: One-to-many with `Orders` (UserID in `Orders` references UserID in `Users`)."
|
| 375 |
-
]
|
| 376 |
-
},
|
| 377 |
-
{
|
| 378 |
-
name: "Products",
|
| 379 |
-
summary: "Lists all available products with descriptions, pricing, and stock.",
|
| 380 |
-
details: [
|
| 381 |
-
"Table `Products` has columns: ProductID (PRIMARY KEY, INTEGER), ProductName (TEXT), Description (TEXT), CategoryID (FOREIGN KEY to Categories.CategoryID, INTEGER).",
|
| 382 |
-
"Table `Products` also has columns: Price (DECIMAL), StockQuantity (INTEGER), CreatedDate (DATETIME), LastUpdatedDate (DATETIME).",
|
| 383 |
-
"Table `Products` also has columns: ImageURL (TEXT), Weight (DECIMAL), Dimensions (TEXT), ProductStatus (TEXT).",
|
| 384 |
-
"Relationships of `Products`: One-to-many with `OrderItems` (ProductID in `OrderItems` references ProductID in `Products`)."
|
| 385 |
-
]
|
| 386 |
-
},
|
| 387 |
-
{
|
| 388 |
-
name: "Orders",
|
| 389 |
-
summary: "Records customer purchase transactions.",
|
| 390 |
-
details: [
|
| 391 |
-
"Table `Orders` has columns: OrderID (PRIMARY KEY, INTEGER), UserID (FOREIGN KEY to Users.UserID, INTEGER), OrderDate (DATETIME), TotalAmount (DECIMAL).",
|
| 392 |
-
"Purpose of `Orders` table: Tracks individual customer purchases and their aggregated cost.",
|
| 393 |
-
"Relationships of `Orders`: One-to-many with `OrderItems` (OrderID in `OrderItems` references OrderID in `Orders`)."
|
| 394 |
-
]
|
| 395 |
-
},
|
| 396 |
-
{
|
| 397 |
-
name: "OrderItems",
|
| 398 |
-
summary: "Details each item within a specific customer order.",
|
| 399 |
-
details: [
|
| 400 |
-
"Table `OrderItems` has columns: OrderItemID (PRIMARY KEY, INTEGER), OrderID (FOREIGN KEY to Orders.OrderID, INTEGER), ProductID (FOREIGN KEY to Products.ProductID, INTEGER).",
|
| 401 |
-
"Table `OrderItems` also has columns: Quantity (INTEGER), UnitPriceAtPurchase (DECIMAL), SubtotalItemAmount (DECIMAL).",
|
| 402 |
-
"Purpose of `OrderItems` table: Breaks down an order into its constituent products and quantities."
|
| 403 |
-
]
|
| 404 |
-
},
|
| 405 |
-
{
|
| 406 |
-
name: "Categories",
|
| 407 |
-
summary: "Classifies products into various categories.",
|
| 408 |
-
details: [
|
| 409 |
-
"Table `Categories` has columns: CategoryID (PRIMARY KEY, INTEGER), CategoryName (TEXT UNIQUE), CategoryDescription (TEXT).",
|
| 410 |
-
"Purpose of `Categories` table: Helps organize products for easier browsing and filtering.",
|
| 411 |
-
"Relationships of `Categories`: One-to-many with `Products` (CategoryID in `Products` references CategoryID in `Categories`)."
|
| 412 |
-
]
|
| 413 |
-
}
|
| 414 |
-
];
|
| 415 |
-
|
| 416 |
-
appendDiagnostic(messages[0].content);
|
| 417 |
-
|
| 418 |
-
// --- Helper Functions ---
|
| 419 |
-
|
| 420 |
-
// Callback function for initializing WebLLM progress.
|
| 421 |
-
function updateEngineInitProgressCallback(report) {
|
| 422 |
-
console.log("WebLLM Init:", report.progress, report.text);
|
| 423 |
-
downloadStatus.textContent = report.text;
|
| 424 |
-
}
|
| 425 |
-
|
| 426 |
-
// Helper function to append messages to the chat box
|
| 427 |
-
function appendMessage(message, isStreaming = false) {
|
| 428 |
-
const messageContainer = document.createElement("div");
|
| 429 |
-
messageContainer.classList.add("message-container", message.role);
|
| 430 |
-
|
| 431 |
-
// Only create a message bubble for user and assistant messages
|
| 432 |
-
if (message.role === "user" || message.role === "assistant") {
|
| 433 |
-
const messageBubble = document.createElement("div");
|
| 434 |
-
messageBubble.classList.add("message-bubble");
|
| 435 |
-
messageBubble.textContent = message.content;
|
| 436 |
-
messageContainer.appendChild(messageBubble);
|
| 437 |
-
} else {
|
| 438 |
-
// For system messages, just set the text content directly on the container
|
| 439 |
-
messageContainer.textContent = message.content;
|
| 440 |
-
}
|
| 441 |
-
|
| 442 |
-
chatBox.appendChild(messageContainer);
|
| 443 |
-
chatBox.scrollTop = chatBox.scrollHeight; // Scroll to bottom
|
| 444 |
-
|
| 445 |
-
if (isStreaming && message.role === "assistant") {
|
| 446 |
-
currentAssistantMessageElement = messageContainer.querySelector(".message-bubble");
|
| 447 |
-
}
|
| 448 |
-
}
|
| 449 |
-
|
| 450 |
-
// Helper function to update the content of the last assistant message (for streaming)
|
| 451 |
-
function updateLastAssistantMessage(newContent) {
|
| 452 |
-
if (currentAssistantMessageElement) {
|
| 453 |
-
currentAssistantMessageElement.textContent = newContent;
|
| 454 |
-
chatBox.scrollTop = chatBox.scrollHeight; // Scroll to bottom
|
| 455 |
-
}
|
| 456 |
-
}
|
| 457 |
-
|
| 458 |
-
// Cosine Similarity Function for RAG lookup
|
| 459 |
-
function cosineSimilarity(vec1, vec2) {
|
| 460 |
-
if (vec1.length !== vec2.length) {
|
| 461 |
-
return 0;
|
| 462 |
-
}
|
| 463 |
-
let dotProduct = 0;
|
| 464 |
-
let magnitude1 = 0;
|
| 465 |
-
let magnitude2 = 0;
|
| 466 |
-
for (let i = 0; i < vec1.length; i++) {
|
| 467 |
-
dotProduct += vec1[i] * vec2[i];
|
| 468 |
-
magnitude1 += vec1[i] * vec1[i];
|
| 469 |
-
magnitude2 += vec2[i] * vec2[i];
|
| 470 |
-
}
|
| 471 |
-
magnitude1 = Math.sqrt(magnitude1);
|
| 472 |
-
magnitude2 = Math.sqrt(magnitude2);
|
| 473 |
-
if (magnitude1 === 0 || magnitude2 === 0) {
|
| 474 |
-
return 0;
|
| 475 |
-
}
|
| 476 |
-
return dotProduct / (magnitude1 * magnitude2);
|
| 477 |
-
}
|
| 478 |
-
|
| 479 |
-
// --- RAG Lookup Logic ---
|
| 480 |
-
async function performRagLookup(query) {
|
| 481 |
-
if (skipRagCheckbox.checked) {
|
| 482 |
-
appendDiagnostic('RAG skipped by user preference.');
|
| 483 |
-
return null;
|
| 484 |
-
}
|
| 485 |
-
if (!embedder || miniTableIndexEmbeddings.length === 0 || detailedSchemaEmbeddings.length === 0) {
|
| 486 |
-
console.warn("Embedding model or knowledge base not ready for RAG lookup.");
|
| 487 |
-
appendDiagnostic("Embedding model or knowledge base not ready for RAG lookup.");
|
| 488 |
-
return null;
|
| 489 |
-
}
|
| 490 |
-
appendDiagnostic('RAG start for query: ' + query);
|
| 491 |
-
|
| 492 |
-
try {
|
| 493 |
-
// Stage 1: Embed user query and identify relevant tables from mini-index
|
| 494 |
-
const queryEmbeddingOutput = await embedder(query, { pooling: 'mean', normalize: true });
|
| 495 |
-
const queryEmbedding = queryEmbeddingOutput.data;
|
| 496 |
-
appendDiagnostic('RAG: query embedded dim=' + queryEmbedding.length);
|
| 497 |
-
|
| 498 |
-
let tableSimilarities = [];
|
| 499 |
-
for (const tableIndex of miniTableIndexEmbeddings) {
|
| 500 |
-
const score = cosineSimilarity(queryEmbedding, tableIndex.embedding);
|
| 501 |
-
tableSimilarities.push({ tableId: tableIndex.tableId, score: score });
|
| 502 |
-
}
|
| 503 |
-
|
| 504 |
-
tableSimilarities.sort((a, b) => b.score - a.score);
|
| 505 |
-
const topRelevantTableIds = tableSimilarities.filter(s => s.score > 0.5).slice(0, 3).map(s => s.tableId); // Top 3 tables with a minimum score
|
| 506 |
-
|
| 507 |
-
if (topRelevantTableIds.length === 0) {
|
| 508 |
-
console.log("No highly relevant tables identified for query:", query);
|
| 509 |
-
appendDiagnostic("RAG: No table above threshold.");
|
| 510 |
-
return null;
|
| 511 |
-
}
|
| 512 |
-
appendDiagnostic("RAG: tables -> " + topRelevantTableIds.join(','));
|
| 513 |
-
console.log("Identified relevant tables for RAG:", topRelevantTableIds);
|
| 514 |
-
|
| 515 |
-
// Stage 2: Filter detailed chunks by relevant tables and re-rank
|
| 516 |
-
let relevantDetailedChunks = [];
|
| 517 |
-
const filteredDetailedChunks = detailedSchemaEmbeddings.filter(chunk =>
|
| 518 |
-
topRelevantTableIds.includes(chunk.tableId)
|
| 519 |
-
);
|
| 520 |
-
|
| 521 |
-
let chunkSimilarities = [];
|
| 522 |
-
for (const chunk of filteredDetailedChunks) {
|
| 523 |
-
const score = cosineSimilarity(queryEmbedding, chunk.embedding);
|
| 524 |
-
chunkSimilarities.push({ chunk: chunk.text, score: score });
|
| 525 |
-
}
|
| 526 |
-
|
| 527 |
-
chunkSimilarities.sort((a, b) => b.score - a.score);
|
| 528 |
-
|
| 529 |
-
// Consolidate context: take top N most relevant detailed chunks
|
| 530 |
-
const maxChunksToInclude = 5; // Limit the number of chunks to manage context window
|
| 531 |
-
const contextChunks = chunkSimilarities.filter(s => s.score > 0.4).slice(0, maxChunksToInclude).map(s => s.chunk); // Filter by score again
|
| 532 |
-
|
| 533 |
-
if (contextChunks.length > 0) {
|
| 534 |
-
appendDiagnostic('RAG: selected ' + contextChunks.length + ' chunks.');
|
| 535 |
-
return contextChunks.join("\n\n---\n\n");
|
| 536 |
-
} else {
|
| 537 |
-
appendDiagnostic('RAG: No chunk passed score filter.');
|
| 538 |
-
return null; // No relevant chunks found after filtering
|
| 539 |
-
}
|
| 540 |
-
|
| 541 |
-
} catch (error) {
|
| 542 |
-
console.error("Error during RAG lookup:", error);
|
| 543 |
-
return null;
|
| 544 |
-
}
|
| 545 |
-
}
|
| 546 |
-
|
| 547 |
-
// --- Model Initialization ---
|
| 548 |
-
|
| 549 |
-
async function initializeModels() {
|
| 550 |
-
downloadStatus.classList.remove('hidden');
|
| 551 |
-
downloadStatus.textContent = 'Detecting acceleration backends...';
|
| 552 |
-
|
| 553 |
-
const hasWebGPU = !!navigator.gpu;
|
| 554 |
-
const hasWebGL2 = (() => { try { const c=document.createElement('canvas'); return !!c.getContext('webgl2'); } catch(_) { return false; } })();
|
| 555 |
-
console.log('Backend availability:', { hasWebGPU, hasWebGL2 });
|
| 556 |
-
|
| 557 |
-
// Attempt order: transformers webgpu -> transformers webgl -> webllm -> transformers wasm
|
| 558 |
-
const modelLoadErrors = [];
|
| 559 |
-
let validatedModelCandidates = null;
|
| 560 |
-
async function preflightModels() {
|
| 561 |
-
if (validatedModelCandidates) return validatedModelCandidates;
|
| 562 |
-
validatedModelCandidates = [];
|
| 563 |
-
appendDiagnostic('Preflight HEAD validation for models...');
|
| 564 |
-
for (const modelId of TRANSFORMERS_MODEL_CANDIDATES) {
|
| 565 |
-
const cfgUrl = `${env.remoteURL}/${modelId}/resolve/main/config.json`;
|
| 566 |
-
try {
|
| 567 |
-
let resp = await fetch(cfgUrl, { method: 'HEAD' });
|
| 568 |
-
if (resp.status === 405) { // Method not allowed, try GET minimal
|
| 569 |
-
resp = await fetch(cfgUrl, { method: 'GET' });
|
| 570 |
-
}
|
| 571 |
-
if (resp.ok) {
|
| 572 |
-
validatedModelCandidates.push(modelId);
|
| 573 |
-
appendDiagnostic(`OK ${modelId}`);
|
| 574 |
-
} else {
|
| 575 |
-
appendDiagnostic(`Skip ${modelId} (${resp.status})`);
|
| 576 |
-
}
|
| 577 |
-
} catch (e) {
|
| 578 |
-
appendDiagnostic(`Skip ${modelId} (error: ${e.message})`);
|
| 579 |
-
}
|
| 580 |
-
}
|
| 581 |
-
if (validatedModelCandidates.length === 0) {
|
| 582 |
-
appendDiagnostic('No valid models after preflight.');
|
| 583 |
-
}
|
| 584 |
-
return validatedModelCandidates;
|
| 585 |
-
}
|
| 586 |
-
async function tryTransformers(deviceTag) {
|
| 587 |
-
const candidates = await preflightModels();
|
| 588 |
-
for (const modelId of candidates) {
|
| 589 |
-
try {
|
| 590 |
-
downloadStatus.textContent = `Loading ${modelId} (${deviceTag})...`;
|
| 591 |
-
const opts = { quantized: true };
|
| 592 |
-
opts.device = deviceTag.startsWith('web') ? 'gpu' : (deviceTag === 'wasm' ? 'cpu' : 'cpu');
|
| 593 |
-
textGenPipeline = await pipeline('text-generation', modelId, opts);
|
| 594 |
-
chatBackend = `transformers-${deviceTag}`;
|
| 595 |
-
chosenTransformersModel = modelId;
|
| 596 |
-
console.log(`Loaded transformers model '${modelId}' on ${deviceTag}`);
|
| 597 |
-
return true;
|
| 598 |
-
} catch (e) {
|
| 599 |
-
const msg = (e?.message || '').toLowerCase();
|
| 600 |
-
let short = e.message;
|
| 601 |
-
if (msg.includes('unauthorized')) {
|
| 602 |
-
short += ' (Likely gated model; set window.HF_TOKEN before loading or choose an open model)';
|
| 603 |
-
} else if (msg.includes('404')) {
|
| 604 |
-
short += ' (Resource not found; if self-hosting assets, ensure files exist)';
|
| 605 |
-
}
|
| 606 |
-
modelLoadErrors.push({ device: deviceTag, model: modelId, error: short });
|
| 607 |
-
appendDiagnostic(`FAIL ${deviceTag} ${modelId}: ${short}`);
|
| 608 |
-
console.warn(`Transformers load failed for ${modelId} on ${deviceTag}:`, e);
|
| 609 |
-
// Try next model candidate
|
| 610 |
-
}
|
| 611 |
-
}
|
| 612 |
-
return false; // none loaded
|
| 613 |
-
}
|
| 614 |
-
|
| 615 |
-
let initialized = false;
|
| 616 |
-
const userPref = backendSelect.value; // may guide attempt ordering
|
| 617 |
-
const attemptOrder = (() => {
|
| 618 |
-
const base = ['transformers-webgpu','transformers-webgl','webllm','transformers-wasm'];
|
| 619 |
-
if (base.includes(userPref)) {
|
| 620 |
-
return [userPref, ...base.filter(b=>b!==userPref)];
|
| 621 |
-
}
|
| 622 |
-
return base;
|
| 623 |
-
})();
|
| 624 |
-
appendDiagnostic('Attempt order: ' + attemptOrder.join(' -> '));
|
| 625 |
-
for (const step of attemptOrder) {
|
| 626 |
-
if (initialized) break;
|
| 627 |
-
if (step === 'transformers-webgpu' && hasWebGPU) initialized = await tryTransformers('webgpu');
|
| 628 |
-
else if (step === 'transformers-webgl' && hasWebGL2) initialized = await tryTransformers('webgl');
|
| 629 |
-
else if (step === 'webllm' && hasWebGPU && !initialized) {
|
| 630 |
-
try {
|
| 631 |
-
appendDiagnostic('Trying WebLLM...');
|
| 632 |
-
downloadStatus.textContent = 'Loading WebLLM model (WebGPU)...';
|
| 633 |
-
engine = new webllm.MLCEngine();
|
| 634 |
-
engine.setInitProgressCallback(updateEngineInitProgressCallback);
|
| 635 |
-
let selectedModel = null;
|
| 636 |
-
const preferredModelPattern = 'TinyLlama';
|
| 637 |
-
const availableModels = webllm.prebuiltAppConfig.model_list;
|
| 638 |
-
const suitableModels = availableModels.filter(m => m.model_id.toLowerCase().includes(preferredModelPattern.toLowerCase()) && (m.model_id.includes('q4f16_1-MLC') || m.model_id.includes('q4f32_1-MLC')) && m.model_id.includes('Instruct'));
|
| 639 |
-
if (suitableModels.length > 0) { selectedModel = suitableModels[0].model_id; } else {
|
| 640 |
-
const fb = ['TinyLlama-1.1B-Chat-v1.0-q4f16_1-MLC','Qwen2.5-0.5B-Instruct-q4f16_1-MLC','gemma-2b-it-q4f16_1-MLC','Phi-3.5-mini-instruct-q4f16_1-MLC'];
|
| 641 |
-
for (const id of fb) { if (availableModels.find(m => m.model_id === id)) { selectedModel = id; break; } }
|
| 642 |
-
}
|
| 643 |
-
if (!selectedModel) throw new Error('No WebLLM model found');
|
| 644 |
-
await engine.reload(selectedModel, { temperature: 0.7, top_p: 0.9 });
|
| 645 |
-
chatBackend = 'webllm';
|
| 646 |
-
initialized = true;
|
| 647 |
-
appendDiagnostic('WebLLM loaded: ' + selectedModel);
|
| 648 |
-
} catch (e) {
|
| 649 |
-
appendDiagnostic('WebLLM failed: ' + e.message);
|
| 650 |
-
console.warn('WebLLM load failed:', e);
|
| 651 |
-
}
|
| 652 |
-
} else if (step === 'transformers-wasm' && !initialized) {
|
| 653 |
-
initialized = await tryTransformers('wasm');
|
| 654 |
-
}
|
| 655 |
-
}
|
| 656 |
-
|
| 657 |
-
// WebLLM attempt (only if not already have transformers GPU/WebGL and WebGPU present)
|
| 658 |
-
if (!initialized && hasWebGPU) {
|
| 659 |
-
try {
|
| 660 |
-
downloadStatus.textContent = 'Loading WebLLM model (WebGPU)...';
|
| 661 |
-
engine = new webllm.MLCEngine();
|
| 662 |
-
engine.setInitProgressCallback(updateEngineInitProgressCallback);
|
| 663 |
-
let selectedModel = null;
|
| 664 |
-
const preferredModelPattern = 'TinyLlama';
|
| 665 |
-
const availableModels = webllm.prebuiltAppConfig.model_list;
|
| 666 |
-
const suitableModels = availableModels.filter(m => m.model_id.toLowerCase().includes(preferredModelPattern.toLowerCase()) && (m.model_id.includes('q4f16_1-MLC') || m.model_id.includes('q4f32_1-MLC')) && m.model_id.includes('Instruct'));
|
| 667 |
-
if (suitableModels.length > 0) { selectedModel = suitableModels[0].model_id; } else {
|
| 668 |
-
const fb = ['TinyLlama-1.1B-Chat-v1.0-q4f16_1-MLC','Qwen2.5-0.5B-Instruct-q4f16_1-MLC','gemma-2b-it-q4f16_1-MLC','Phi-3.5-mini-instruct-q4f16_1-MLC'];
|
| 669 |
-
for (const id of fb) { if (availableModels.find(m => m.model_id === id)) { selectedModel = id; break; } }
|
| 670 |
-
}
|
| 671 |
-
if (!selectedModel) throw new Error('No WebLLM model found');
|
| 672 |
-
await engine.reload(selectedModel, { temperature: 0.7, top_p: 0.9 });
|
| 673 |
-
chatBackend = 'webllm';
|
| 674 |
-
initialized = true;
|
| 675 |
-
console.log('Loaded WebLLM model:', selectedModel);
|
| 676 |
-
} catch (e) {
|
| 677 |
-
console.warn('WebLLM load failed:', e);
|
| 678 |
-
}
|
| 679 |
-
}
|
| 680 |
-
|
| 681 |
-
// Final fallback: transformers wasm (CPU)
|
| 682 |
-
if (!initialized) {
|
| 683 |
-
downloadStatus.textContent = 'All model backend attempts failed. See diagnostics.';
|
| 684 |
-
activeBackendLabel.textContent = 'backend: failed';
|
| 685 |
-
diagnosticsEl.classList.add('show');
|
| 686 |
-
appendDiagnostic('FINAL: All attempts failed. Provide HF token if 401, or pick smaller model.');
|
| 687 |
-
return;
|
| 688 |
-
}
|
| 689 |
-
|
| 690 |
-
// Embeddings (shared)
|
| 691 |
-
try {
|
| 692 |
-
downloadStatus.textContent = 'Loading embedding model...';
|
| 693 |
-
embedder = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
|
| 694 |
-
for (const table of rawSqlSchema) {
|
| 695 |
-
const summaryOutput = await embedder(table.summary, { pooling: 'mean', normalize: true });
|
| 696 |
-
miniTableIndexEmbeddings.push({ tableId: table.name, text: table.summary, embedding: summaryOutput.data });
|
| 697 |
-
for (let i = 0; i < table.details.length; i++) {
|
| 698 |
-
const chunkText = table.details[i];
|
| 699 |
-
const chunkOutput = await embedder(chunkText, { pooling: 'mean', normalize: true });
|
| 700 |
-
detailedSchemaEmbeddings.push({ tableId: table.name, chunkId: `${table.name}_chunk_${i}`, text: chunkText, embedding: chunkOutput.data });
|
| 701 |
-
}
|
| 702 |
-
}
|
| 703 |
-
} catch (e) {
|
| 704 |
-
downloadStatus.textContent = 'Embedding init failed: ' + e.message;
|
| 705 |
-
console.error('Embedding init error:', e);
|
| 706 |
-
return;
|
| 707 |
-
}
|
| 708 |
-
|
| 709 |
-
// Ready UI
|
| 710 |
-
const backendLabel = chatBackend || 'unknown';
|
| 711 |
-
const slow = backendLabel.includes('wasm');
|
| 712 |
-
sendButton.disabled = false;
|
| 713 |
-
userInput.disabled = false;
|
| 714 |
-
userInput.setAttribute('placeholder', slow ? 'Type (CPU fallback, slower)...' : 'Type a message...');
|
| 715 |
-
if (chosenTransformersModel) {
|
| 716 |
-
appendMessage({ role: 'system', content: `AI (${backendLabel}/${chosenTransformersModel}): Ready. Ask about the SQL schema. ${slow ? 'Consider smaller model ('+SMALLER_MODEL_HINT+') for speed.' : ''}` });
|
| 717 |
-
downloadStatus.textContent = 'Models loaded (' + backendLabel + ').';
|
| 718 |
-
activeBackendLabel.textContent = `backend: ${backendLabel}`;
|
| 719 |
-
} else if (backendLabel === 'webllm') {
|
| 720 |
-
appendMessage({ role: 'system', content: `AI (${backendLabel}): Ready. Ask about the SQL schema.` });
|
| 721 |
-
downloadStatus.textContent = 'Models loaded (' + backendLabel + ').';
|
| 722 |
-
activeBackendLabel.textContent = `backend: ${backendLabel}`;
|
| 723 |
-
}
|
| 724 |
-
}
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
// Function to handle sending a message - MODIFIED FOR LLM-DRIVEN RAG
|
| 728 |
-
async function onMessageSend() {
|
| 729 |
-
const input = userInput.value.trim();
|
| 730 |
-
if (input.length === 0) {
|
| 731 |
-
return;
|
| 732 |
-
}
|
| 733 |
-
|
| 734 |
-
// Add user message to UI
|
| 735 |
-
const userMessage = { content: input, role: "user" };
|
| 736 |
-
messages.push(userMessage); // Add to conversation history
|
| 737 |
-
appendMessage(userMessage);
|
| 738 |
-
|
| 739 |
-
userInput.value = "";
|
| 740 |
-
sendButton.disabled = true;
|
| 741 |
-
userInput.setAttribute("placeholder", "Thinking and possibly looking up schema...");
|
| 742 |
-
|
| 743 |
-
// Temporarily append a placeholder for AI response
|
| 744 |
-
const aiMessagePlaceholder = { content: "typing...", role: "assistant" };
|
| 745 |
-
appendMessage(aiMessagePlaceholder, true); // Mark as streaming message for potential update
|
| 746 |
-
|
| 747 |
-
let fullAssistantResponse = "";
|
| 748 |
-
chatStats.classList.add("hidden");
|
| 749 |
-
|
| 750 |
-
console.log('Messages ', messages);
|
| 751 |
-
|
| 752 |
-
try {
|
| 753 |
-
if (chatBackend === 'webllm') {
|
| 754 |
-
// Original WebLLM two-pass tool invocation logic
|
| 755 |
-
const initialCompletion = await engine.chat.completions.create({
|
| 756 |
-
messages: messages,
|
| 757 |
-
stream: false,
|
| 758 |
-
temperature: 0.7,
|
| 759 |
-
top_p: 0.9,
|
| 760 |
-
});
|
| 761 |
-
let llmFirstResponseContent = initialCompletion.choices?.[0]?.message?.content || "";
|
| 762 |
-
let finalResponseContent = "";
|
| 763 |
-
if (skipRagCheckbox.checked) {
|
| 764 |
-
appendDiagnostic('Skip RAG mode: using first LLM response directly.');
|
| 765 |
-
finalResponseContent = llmFirstResponseContent;
|
| 766 |
-
updateLastAssistantMessage(finalResponseContent);
|
| 767 |
-
} else {
|
| 768 |
-
let parsedAction = null;
|
| 769 |
-
try { parsedAction = JSON.parse(llmFirstResponseContent); } catch (_) {}
|
| 770 |
-
if (parsedAction && parsedAction.action === "lookup_schema_info" && parsedAction.query) {
|
| 771 |
-
appendDiagnostic("RAG lookup requested by model: " + parsedAction.query);
|
| 772 |
-
updateLastAssistantMessage("π Searching schema for: " + parsedAction.query);
|
| 773 |
-
messages.push({ role: "assistant", content: llmFirstResponseContent });
|
| 774 |
-
const retrievedContext = await performRagLookup(parsedAction.query);
|
| 775 |
-
if (retrievedContext) {
|
| 776 |
-
const toolOutputMessage = `Here is the requested schema information:\n\`\`\`\n${retrievedContext}\n\`\`\`\nPlease use this information to answer the user's original question: "${input}"`;
|
| 777 |
-
messages.push({ role: "user", content: toolOutputMessage });
|
| 778 |
-
updateLastAssistantMessage("π§ Processing with retrieved info...");
|
| 779 |
-
const finalCompletion = await engine.chat.completions.create({
|
| 780 |
-
messages: messages,
|
| 781 |
-
stream: true,
|
| 782 |
-
temperature: 0.7,
|
| 783 |
-
top_p: 0.9,
|
| 784 |
-
});
|
| 785 |
-
for await (const chunk of finalCompletion) {
|
| 786 |
-
const curDelta = chunk.choices?.[0]?.delta.content;
|
| 787 |
-
if (curDelta) {
|
| 788 |
-
fullAssistantResponse += curDelta;
|
| 789 |
-
updateLastAssistantMessage(fullAssistantResponse);
|
| 790 |
-
}
|
| 791 |
-
}
|
| 792 |
-
finalResponseContent = fullAssistantResponse;
|
| 793 |
-
} else {
|
| 794 |
-
finalResponseContent = "No relevant context.";
|
| 795 |
-
updateLastAssistantMessage(finalResponseContent);
|
| 796 |
-
}
|
| 797 |
-
} else {
|
| 798 |
-
finalResponseContent = llmFirstResponseContent;
|
| 799 |
-
updateLastAssistantMessage(finalResponseContent);
|
| 800 |
-
}
|
| 801 |
-
}
|
| 802 |
-
messages.push({ content: finalResponseContent, role: 'assistant' });
|
| 803 |
-
const usageText = await engine.runtimeStatsText();
|
| 804 |
-
chatStats.classList.remove('hidden');
|
| 805 |
-
chatStats.textContent = usageText;
|
| 806 |
-
} else if (chatBackend && chatBackend.startsWith('transformers')) {
|
| 807 |
-
// Fallback CPU flow: single pass with RAG context (no tool JSON handshake to save latency)
|
| 808 |
-
updateLastAssistantMessage('π§ Gathering relevant schema context...');
|
| 809 |
-
let ragContext = null;
|
| 810 |
-
if (!skipRagCheckbox.checked) ragContext = await performRagLookup(input);
|
| 811 |
-
const prompt = skipRagCheckbox.checked
|
| 812 |
-
? `${systemMessageContent}\n\nUser question: ${input}\n\nAnswer:`
|
| 813 |
-
: `${systemMessageContent}\n\nUser question: ${input}\n\nRelevant schema context:\n${ragContext || 'No relevant context.'}\n\nAnswer:`;
|
| 814 |
-
updateLastAssistantMessage(`βοΈ Generating answer (${chatBackend}${chosenTransformersModel? '/' + chosenTransformersModel: ''})...`);
|
| 815 |
-
let streamedAnswer = '';
|
| 816 |
-
try {
|
| 817 |
-
const result = await textGenPipeline(prompt, {
|
| 818 |
-
max_new_tokens: 220,
|
| 819 |
-
temperature: 0.7,
|
| 820 |
-
top_p: 0.9,
|
| 821 |
-
repetition_penalty: 1.05,
|
| 822 |
-
callback_function: (data) => {
|
| 823 |
-
if (data?.token?.text) {
|
| 824 |
-
streamedAnswer += data.token.text;
|
| 825 |
-
// Avoid dumping the entire prompt back (strip if echo)
|
| 826 |
-
const splitIdx = streamedAnswer.lastIndexOf('Answer:');
|
| 827 |
-
const display = splitIdx !== -1 ? streamedAnswer.slice(splitIdx + 7).trimStart() : streamedAnswer;
|
| 828 |
-
updateLastAssistantMessage(display);
|
| 829 |
-
}
|
| 830 |
-
}
|
| 831 |
-
});
|
| 832 |
-
// Final extraction (if callback incomplete)
|
| 833 |
-
let finalText;
|
| 834 |
-
if (Array.isArray(result)) {
|
| 835 |
-
finalText = result[0]?.generated_text || streamedAnswer;
|
| 836 |
-
} else {
|
| 837 |
-
finalText = result.generated_text || streamedAnswer;
|
| 838 |
-
}
|
| 839 |
-
const answer = (() => {
|
| 840 |
-
const parts = finalText.split('Answer:');
|
| 841 |
-
if (parts.length > 1) return parts.slice(1).join('Answer:').trim();
|
| 842 |
-
return finalText.replace(prompt,'').trim();
|
| 843 |
-
})();
|
| 844 |
-
updateLastAssistantMessage(answer);
|
| 845 |
-
messages.push({ content: answer, role: 'assistant' });
|
| 846 |
-
} catch(genErr) {
|
| 847 |
-
updateLastAssistantMessage('Generation error: ' + genErr.message);
|
| 848 |
-
appendDiagnostic('Generation error: ' + genErr.stack);
|
| 849 |
-
}
|
| 850 |
-
chatStats.classList.add('hidden');
|
| 851 |
-
} else {
|
| 852 |
-
updateLastAssistantMessage('No active backend. Initialization error.');
|
| 853 |
-
}
|
| 854 |
-
} catch (error) {
|
| 855 |
-
updateLastAssistantMessage(`Error: ${error.message}`);
|
| 856 |
-
console.error('Error during chat handling:', error);
|
| 857 |
-
appendDiagnostic('Chat error: ' + error.stack);
|
| 858 |
-
} finally {
|
| 859 |
-
sendButton.disabled = false;
|
| 860 |
-
userInput.disabled = false;
|
| 861 |
-
const slow = chatBackend && chatBackend.endsWith('wasm');
|
| 862 |
-
userInput.setAttribute('placeholder', slow ? 'Type (CPU fallback, slower)...' : 'Type a message...');
|
| 863 |
-
currentAssistantMessageElement = null;
|
| 864 |
-
}
|
| 865 |
-
}
|
| 866 |
-
|
| 867 |
-
// Diagnostics helper
|
| 868 |
-
function appendDiagnostic(line) {
|
| 869 |
-
const ts = new Date().toISOString().split('T')[1].replace('Z','');
|
| 870 |
-
diagnosticsEl.textContent += `[${ts}] ${line}\n`;
|
| 871 |
-
diagnosticsEl.scrollTop = diagnosticsEl.scrollHeight;
|
| 872 |
-
}
|
| 873 |
-
|
| 874 |
-
// Control events
|
| 875 |
-
applyTokenBtn.addEventListener('click', () => {
|
| 876 |
-
const raw = prompt('Enter HF token (starts with hf_). This will be stored locally (clearable).');
|
| 877 |
-
if (raw && raw.startsWith('hf_')) {
|
| 878 |
-
localStorage.setItem('HF_TOKEN', raw);
|
| 879 |
-
window.location.reload();
|
| 880 |
-
}
|
| 881 |
-
});
|
| 882 |
-
applyModelsBtn.addEventListener('click', () => {
|
| 883 |
-
const raw = modelCandidatesInput.value.trim();
|
| 884 |
-
if (!raw) return;
|
| 885 |
-
localStorage.setItem('MODEL_CANDIDATES', raw);
|
| 886 |
-
window.location.reload();
|
| 887 |
-
});
|
| 888 |
-
forceReloadBtn.addEventListener('click', () => window.location.reload());
|
| 889 |
-
toggleDiagBtn.addEventListener('click', () => diagnosticsEl.classList.toggle('show'));
|
| 890 |
-
|
| 891 |
-
// --- Dynamic Trial Models Discovery (tokenless) ---
|
| 892 |
-
async function discoverOpenSmallModels(maxModels = 6) {
|
| 893 |
-
// Curated base list of realistically loadable tokenless models published with ONNX/TFJS weights.
|
| 894 |
-
const CURATED = [
|
| 895 |
-
'Xenova/gpt2',
|
| 896 |
-
'Xenova/distilgpt2',
|
| 897 |
-
'Xenova/phi-2',
|
| 898 |
-
'Xenova/TinyLlama-1.1B-Chat-v1.0'
|
| 899 |
-
];
|
| 900 |
-
const archWhitelist = [
|
| 901 |
-
'GPT2LMHeadModel',
|
| 902 |
-
'PhiForCausalLM',
|
| 903 |
-
'LlamaForCausalLM',
|
| 904 |
-
'MistralForCausalLM',
|
| 905 |
-
'TinyLlamaForCausalLM'
|
| 906 |
-
];
|
| 907 |
-
const accepted = [];
|
| 908 |
-
async function fetchConfig(modelId) {
|
| 909 |
-
const url = `${env.remoteURL}/${modelId}/resolve/main/config.json`;
|
| 910 |
-
try {
|
| 911 |
-
const resp = await fetch(url, { headers:{ 'Accept':'application/json' } });
|
| 912 |
-
if (!resp.ok) throw new Error(resp.status+ ' ' + resp.statusText);
|
| 913 |
-
return await resp.json();
|
| 914 |
-
} catch (e) {
|
| 915 |
-
appendDiagnostic('Config fail '+modelId+': '+e.message);
|
| 916 |
-
return null;
|
| 917 |
-
}
|
| 918 |
-
}
|
| 919 |
-
for (const m of CURATED) {
|
| 920 |
-
if (accepted.length >= maxModels) break;
|
| 921 |
-
const cfg = await fetchConfig(m);
|
| 922 |
-
if (!cfg) continue;
|
| 923 |
-
const archs = cfg.architectures || [];
|
| 924 |
-
const ok = archs.some(a => archWhitelist.includes(a));
|
| 925 |
-
if (!ok) {
|
| 926 |
-
appendDiagnostic('Skip '+m+' (arch '+archs.join('/')+' not whitelisted)');
|
| 927 |
-
continue;
|
| 928 |
-
}
|
| 929 |
-
// Rough size gating: reject if hidden_size * n_layer heuristic too large (> ~4B tokens weight proxy)
|
| 930 |
-
const hs = cfg.hidden_size || cfg.n_embd || 0;
|
| 931 |
-
const nl = cfg.num_hidden_layers || cfg.n_layer || 0;
|
| 932 |
-
if (hs && nl && hs * nl > 20000) { // heuristic threshold
|
| 933 |
-
appendDiagnostic('Skip '+m+' (heuristic size too large hs*nl='+hs*nl+')');
|
| 934 |
-
continue;
|
| 935 |
-
}
|
| 936 |
-
accepted.push(m);
|
| 937 |
-
}
|
| 938 |
-
if (accepted.length === 0) {
|
| 939 |
-
appendDiagnostic('Discovery empty; using minimal fallback list.');
|
| 940 |
-
accepted.push('Xenova/gpt2','Xenova/distilgpt2');
|
| 941 |
-
}
|
| 942 |
-
return accepted.slice(0, maxModels);
|
| 943 |
-
}
|
| 944 |
-
|
| 945 |
-
trialModelsBtn.addEventListener('click', async () => {
|
| 946 |
-
trialModelsBtn.disabled = true;
|
| 947 |
-
const TRIAL_PROMPT = 'Do planes fly higher than bees?';
|
| 948 |
-
// Create a live-updating system message
|
| 949 |
-
const liveHeader = '### Model Trials (live, no token)';
|
| 950 |
-
appendMessage({ role: 'system', content: liveHeader + '\nStarting discovery...' });
|
| 951 |
-
const liveEl = chatBox.lastElementChild; // system container
|
| 952 |
-
const lines = [liveHeader, 'Starting discovery...'];
|
| 953 |
-
const flush = () => { liveEl.textContent = lines.join('\n'); };
|
| 954 |
-
const addLine = (l) => { lines.push(l); flush(); };
|
| 955 |
-
const yieldUI = async () => new Promise(r=>requestAnimationFrame(r));
|
| 956 |
-
function withTimeout(promise, ms, label) {
|
| 957 |
-
return Promise.race([
|
| 958 |
-
promise,
|
| 959 |
-
new Promise((_, rej) => setTimeout(()=>rej(new Error(label + ' timeout after '+ms+'ms')), ms))
|
| 960 |
-
]);
|
| 961 |
-
}
|
| 962 |
-
appendDiagnostic('Trial: starting discovery...');
|
| 963 |
-
let discovered = [];
|
| 964 |
-
try {
|
| 965 |
-
discovered = await discoverOpenSmallModels(10);
|
| 966 |
-
} catch(e) {
|
| 967 |
-
appendDiagnostic('Discovery error: ' + e.message);
|
| 968 |
-
addLine('Discovery error: ' + e.message);
|
| 969 |
-
}
|
| 970 |
-
if (!discovered.length) {
|
| 971 |
-
addLine('No models discovered dynamically. Using static fallbacks.');
|
| 972 |
-
discovered = ['Xenova/gpt2','Xenova/distilgpt2'];
|
| 973 |
-
}
|
| 974 |
-
const baseline = ['Xenova/gpt2','Xenova/distilgpt2'];
|
| 975 |
-
const ordered = baseline.concat(discovered.filter(m=>!baseline.includes(m)));
|
| 976 |
-
const MODELS = ordered.slice(0,6);
|
| 977 |
-
addLine('Models to try: ' + MODELS.join(', '));
|
| 978 |
-
appendDiagnostic('Trial: Models -> ' + discovered.join(', '));
|
| 979 |
-
const collected = [];
|
| 980 |
-
try {
|
| 981 |
-
for (const modelId of MODELS) {
|
| 982 |
-
let loadTime='-', genTime='-', snippet='', error=null;
|
| 983 |
-
const t0 = performance.now();
|
| 984 |
-
addLine(`Loading ${modelId} ...`);
|
| 985 |
-
flush();
|
| 986 |
-
try {
|
| 987 |
-
const pipe = await withTimeout(pipeline('text-generation', modelId, { quantized: true }), 20000, 'load');
|
| 988 |
-
const t1 = performance.now();
|
| 989 |
-
const out = await withTimeout(pipe(TRIAL_PROMPT, { max_new_tokens: 30, temperature: 0.7 }), 12000, 'gen');
|
| 990 |
-
const t2 = performance.now();
|
| 991 |
-
loadTime = ((t1-t0)/1000).toFixed(2)+'s';
|
| 992 |
-
genTime = ((t2-t1)/1000).toFixed(2)+'s';
|
| 993 |
-
const full = Array.isArray(out) ? (out[0]?.generated_text||'') : (out.generated_text||'');
|
| 994 |
-
snippet = full.trim().slice(0,200).replace(/\n+/g,' ') || '(empty)';
|
| 995 |
-
addLine(`${modelId} β load ${loadTime} gen ${genTime}`);
|
| 996 |
-
addLine(` β ${snippet}`);
|
| 997 |
-
} catch(e) {
|
| 998 |
-
error = e?.message || String(e);
|
| 999 |
-
addLine(`${modelId} β ${error}`);
|
| 1000 |
-
appendDiagnostic('Trial error '+modelId+': '+error);
|
| 1001 |
-
}
|
| 1002 |
-
collected.push({ model:modelId, loadTime, genTime, snippet, error });
|
| 1003 |
-
await yieldUI();
|
| 1004 |
-
}
|
| 1005 |
-
} finally {
|
| 1006 |
-
trialModelsBtn.disabled = false;
|
| 1007 |
-
}
|
| 1008 |
-
addLine('');
|
| 1009 |
-
addLine('### Trial Summary');
|
| 1010 |
-
for (const r of collected) {
|
| 1011 |
-
if (r.error) {
|
| 1012 |
-
addLine(`- ${r.model}: ERROR ${r.error}`);
|
| 1013 |
-
} else {
|
| 1014 |
-
addLine(`- ${r.model} (Load ${r.loadTime} / Gen ${r.genTime})`);
|
| 1015 |
-
}
|
| 1016 |
-
}
|
| 1017 |
-
appendDiagnostic('Trial: progress & summary streamed into chat message.');
|
| 1018 |
-
});
|
| 1019 |
-
|
| 1020 |
-
// Event Listeners
|
| 1021 |
-
sendButton.addEventListener("click", onMessageSend);
|
| 1022 |
-
userInput.addEventListener("keypress", (event) => {
|
| 1023 |
-
if (event.key === "Enter" && !sendButton.disabled) {
|
| 1024 |
-
onMessageSend();
|
| 1025 |
-
}
|
| 1026 |
-
});
|
| 1027 |
-
|
| 1028 |
-
// Attempt to reduce ONNX Runtime verbosity (if backend loads onnxruntime-web)
|
| 1029 |
-
async function quietOnnxLogs() {
|
| 1030 |
-
try {
|
| 1031 |
-
const ort = await import('https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js');
|
| 1032 |
-
// ort.env.logLevel values: 'verbose'|'info'|'warning'|'error' (or numeric severity)
|
| 1033 |
-
ort.env.logLevel = 'info';
|
| 1034 |
-
} catch (e) {
|
| 1035 |
-
appendDiagnostic('ORT log level not set: ' + e.message);
|
| 1036 |
-
}
|
| 1037 |
-
}
|
| 1038 |
-
|
| 1039 |
-
// Initialize all models (WebLLM and Embedding model) when the page loads
|
| 1040 |
-
document.addEventListener("DOMContentLoaded", () => { quietOnnxLogs(); initializeModels(); });
|
| 1041 |
-
</script>
|
| 1042 |
</body>
|
| 1043 |
-
</html>
|
|
|
|
| 1 |
<!DOCTYPE html>
|
| 2 |
<html lang="en">
|
| 3 |
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>App...</title>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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
</body>
|
| 12 |
+
</html>
|
package-lock.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
package.json
CHANGED
|
@@ -1,10 +1,11 @@
|
|
| 1 |
{
|
| 2 |
"name": "localm",
|
| 3 |
-
"version": "1.0.
|
| 4 |
"description": "",
|
| 5 |
"main": "chat-full.js",
|
| 6 |
"scripts": {
|
| 7 |
-
"
|
|
|
|
| 8 |
"test": "echo \"Error: no test specified\" && exit 1"
|
| 9 |
},
|
| 10 |
"repository": {
|
|
@@ -18,5 +19,9 @@
|
|
| 18 |
"bugs": {
|
| 19 |
"url": "https://github.com/oyin-bo/localm/issues"
|
| 20 |
},
|
| 21 |
-
"homepage": "https://github.com/oyin-bo/localm#readme"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"name": "localm",
|
| 3 |
+
"version": "1.0.2",
|
| 4 |
"description": "",
|
| 5 |
"main": "chat-full.js",
|
| 6 |
"scripts": {
|
| 7 |
+
"build": "esbuild src/index.js --target=es6 --bundle --sourcemap --outfile=./index.js --format=iife --external:fs --external:path --external:child_process --external:ws",
|
| 8 |
+
"start": "npm run build -- --watch --serve=0.0.0.0:8460 --servedir=. --serve-fallback=index.html",
|
| 9 |
"test": "echo \"Error: no test specified\" && exit 1"
|
| 10 |
},
|
| 11 |
"repository": {
|
|
|
|
| 19 |
"bugs": {
|
| 20 |
"url": "https://github.com/oyin-bo/localm/issues"
|
| 21 |
},
|
| 22 |
+
"homepage": "https://github.com/oyin-bo/localm#readme",
|
| 23 |
+
"dependencies": {
|
| 24 |
+
"@milkdown/crepe": "^7.15.3",
|
| 25 |
+
"esbuild": "^0.25.9"
|
| 26 |
+
}
|
| 27 |
}
|
src/app/app.css
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
body {
|
| 2 |
+
position: absolute;
|
| 3 |
+
left: 0;
|
| 4 |
+
top: 0;
|
| 5 |
+
width: 100%;
|
| 6 |
+
height: 100%;
|
| 7 |
+
margin: 0;
|
| 8 |
+
padding: 0;
|
| 9 |
+
border: none;
|
| 10 |
+
display: grid;
|
| 11 |
+
grid-template: 1fr auto / 1fr;
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
.chat-log {
|
| 15 |
+
display: grid;
|
| 16 |
+
grid-template: 1fr / 1fr;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
.chat-input {
|
| 20 |
+
border-top: solid 1px black;
|
| 21 |
+
display: grid;
|
| 22 |
+
grid-template: 1fr auto / 1fr;
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
.prose-mirror {
|
| 26 |
+
overflow-y: auto;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
.milkdown {
|
| 30 |
+
display: grid;
|
| 31 |
+
grid-template: 1fr / 1fr;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
.milkdown .ProseMirror {
|
| 35 |
+
padding: 0.6em 1em;
|
| 36 |
+
font-family: inherit;
|
| 37 |
+
white-space: pre-wrap;
|
| 38 |
+
outline: none;
|
| 39 |
+
}
|
src/app/boot-app.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// @ts-check
|
| 2 |
+
|
| 3 |
+
import { initHTML } from './init-html';
|
| 4 |
+
import { initMilkdown } from './init-milkdown';
|
| 5 |
+
import { outputMessage } from './output-message';
|
| 6 |
+
|
| 7 |
+
/** @type {import('@milkdown/core').Editor | undefined} */
|
| 8 |
+
export var chatLogEditor;
|
| 9 |
+
|
| 10 |
+
/** @type {import('@milkdown/core').Editor | undefined} */
|
| 11 |
+
export var chatInputEditor;
|
| 12 |
+
|
| 13 |
+
export async function bootApp() {
|
| 14 |
+
const { chatLog, chatInput } = initHTML();
|
| 15 |
+
const { chatLogEditor: chatLogEditorInstance, chatInputEditor: chatInputEditorInstance } = await initMilkdown({ chatLog, chatInput });
|
| 16 |
+
chatLogEditor = chatLogEditorInstance;
|
| 17 |
+
chatInputEditor = chatInputEditorInstance;
|
| 18 |
+
|
| 19 |
+
outputMessage('Editor loaded OK.');
|
| 20 |
+
|
| 21 |
+
}
|
src/app/clean-body.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// @ts-check
|
| 2 |
+
|
| 3 |
+
export function cleanBody() {
|
| 4 |
+
for (const elem of [...document.body.childNodes]) {
|
| 5 |
+
if ((/** @type {HTMLElement} */ (elem).tagName || '').toLowerCase() === 'script') continue;
|
| 6 |
+
elem.remove();
|
| 7 |
+
}
|
| 8 |
+
}
|
src/app/init-html.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// @ts-check
|
| 2 |
+
|
| 3 |
+
import './app.css';
|
| 4 |
+
|
| 5 |
+
import { cleanBody } from './clean-body';
|
| 6 |
+
|
| 7 |
+
export function initHTML() {
|
| 8 |
+
const ui = document.createElement('div');
|
| 9 |
+
ui.innerHTML = `
|
| 10 |
+
<div class=chat-log>Loading...</div>
|
| 11 |
+
<div class=chat-input>[Input]</div>
|
| 12 |
+
`;
|
| 13 |
+
|
| 14 |
+
if (!document.body) {
|
| 15 |
+
document.documentElement.appendChild(document.createElement('body'));
|
| 16 |
+
} else {
|
| 17 |
+
cleanBody();
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
for (const elem of [...ui.children]) {
|
| 21 |
+
document.body.appendChild(elem);
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
const chatLog = /** @type {HTMLElement|null} */ (document.querySelector('.chat-log'));
|
| 25 |
+
const chatInput = /** @type {HTMLElement|null} */ (document.querySelector('.chat-input'));
|
| 26 |
+
|
| 27 |
+
return { chatLog, chatInput };
|
| 28 |
+
}
|
src/app/init-milkdown.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// @ts-check
|
| 2 |
+
|
| 3 |
+
import { defaultValueCtx, Editor, editorViewOptionsCtx, rootCtx } from '@milkdown/core';
|
| 4 |
+
import { commonmark } from '@milkdown/kit/preset/commonmark';
|
| 5 |
+
|
| 6 |
+
export async function initMilkdown({ chatLog, chatInput }) {
|
| 7 |
+
if (chatLog) chatLog.textContent = 'Loading Milkdown...';
|
| 8 |
+
|
| 9 |
+
if (chatLog) chatLog.innerHTML = '';
|
| 10 |
+
if (chatInput) chatInput.innerHTML = '';
|
| 11 |
+
|
| 12 |
+
// Create read-only editor in .chat-log
|
| 13 |
+
const chatLogEditor = await Editor.make()
|
| 14 |
+
.config((ctx) => {
|
| 15 |
+
ctx.set(rootCtx, chatLog);
|
| 16 |
+
ctx.set(defaultValueCtx, 'Loaded.');
|
| 17 |
+
ctx.set(editorViewOptionsCtx, { editable: () => false });
|
| 18 |
+
})
|
| 19 |
+
.use(commonmark)
|
| 20 |
+
.create();
|
| 21 |
+
|
| 22 |
+
// Create editable editor in .chat-input, no placeholder, starts empty
|
| 23 |
+
const chatInputEditor = await Editor.make()
|
| 24 |
+
.config((ctx) => {
|
| 25 |
+
ctx.set(rootCtx, chatInput);
|
| 26 |
+
ctx.set(defaultValueCtx, '');
|
| 27 |
+
})
|
| 28 |
+
.use(commonmark)
|
| 29 |
+
.create();
|
| 30 |
+
|
| 31 |
+
return {
|
| 32 |
+
chatLogEditor,
|
| 33 |
+
chatInputEditor
|
| 34 |
+
};
|
| 35 |
+
}
|
src/app/output-message.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// @ts-check
|
| 2 |
+
|
| 3 |
+
import { defaultValueCtx, Editor, editorViewCtx, editorViewOptionsCtx, parserCtx, rootCtx, serializerCtx } from '@milkdown/core';
|
| 4 |
+
|
| 5 |
+
import { chatLogEditor } from './boot-app';
|
| 6 |
+
|
| 7 |
+
export function outputMessage(msg) {
|
| 8 |
+
if (!chatLogEditor) {
|
| 9 |
+
const elem = document.createElement('pre');
|
| 10 |
+
elem.textContent = msg;
|
| 11 |
+
elem.style.whiteSpace = 'pre-wrap';
|
| 12 |
+
document.body.appendChild(elem);
|
| 13 |
+
return;
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
chatLogEditor.action((ctx) => {
|
| 17 |
+
const view = ctx.get(editorViewCtx);
|
| 18 |
+
const parser = ctx.get(parserCtx);
|
| 19 |
+
const serializer = ctx.get(serializerCtx);
|
| 20 |
+
const state = view.state;
|
| 21 |
+
// Get current markdown, append new message, and parse
|
| 22 |
+
const currentMarkdown = serializer(state.doc);
|
| 23 |
+
const newMarkdown = currentMarkdown ? (currentMarkdown + '\n' + msg) : msg;
|
| 24 |
+
const doc = parser(newMarkdown);
|
| 25 |
+
// Use replaceWith and doc.content to avoid TransformError
|
| 26 |
+
const tr = state.tr.replaceWith(0, state.doc.content.size, doc.content);
|
| 27 |
+
view.dispatch(tr);
|
| 28 |
+
});
|
| 29 |
+
// Scroll chat log to bottom (smooth if possible)
|
| 30 |
+
const chatLogElem = document.querySelector('.chat-log');
|
| 31 |
+
if (chatLogElem) {
|
| 32 |
+
if (typeof chatLogElem.scrollTo === 'function') {
|
| 33 |
+
chatLogElem.scrollTo({ top: chatLogElem.scrollHeight, behavior: 'smooth' });
|
| 34 |
+
} else {
|
| 35 |
+
chatLogElem.scrollTop = chatLogElem.scrollHeight;
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
+
}
|
src/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// @ts-check
|
| 2 |
+
|
| 3 |
+
import { bootApp } from './app/boot-app';
|
| 4 |
+
|
| 5 |
+
if (typeof window !== 'undefined' && typeof window?.alert === 'function'
|
| 6 |
+
&& typeof document !== 'undefined' && typeof document?.createElement === 'function') {
|
| 7 |
+
bootApp();
|
| 8 |
+
}
|