Spaces:
Runtime error
Runtime error
ui/ux fix; response error inspection & fix
Browse filesFiles changed (5)
- config.py+1-1
- graph.py+32-8
- requirements.txt-1
- static/app.js+84-43
- static/style.css+48-37
30 unmodified lines3132333430 unmodified lines# --- Defaults ---DEFAULT_PERSONA = "nerd"RETRIEVAL_TOP_K = 5LLM_TIMEOUT = 60 # seconds — prevents indefinite hangs on slow models30 unmodified lines3132333430 unmodified lines# --- Defaults ---DEFAULT_PERSONA = "nerd"RETRIEVAL_TOP_K = 5LLM_TIMEOUT = 180 # seconds — free models are slow, needs generous timeout
23 unmodified lines242526272829253 unmodified lines2832842852862872882896 unmodified lines29629729829930030130230330430530630742 unmodified lines35035135235335435535635735835936036136236336436536636736836937037123 unmodified linesimport urllib.requestimport threadingimport tracebackfrom langgraph.checkpoint.sqlite import SqliteSaverfrom config import OPENROUTER_API_KEY, DB_PATH, LLM_TIMEOUTimport prompts253 unmodified linesreturn out# ── LLM factory ───────────────────────────────────────────────def _make_llm(api_key: str, model_id: str):key = api_key or OPENROUTER_API_KEY6 unmodified linesopenrouter_api_key=key,temperature=0.5,max_tokens=4096,max_retries=1,timeout=LLM_TIMEOUT,streaming=True,)# ── LangGraph state & node ────────────────────────────────────class ChatState(TypedDict):42 unmodified linessys = SystemMessage(content=base_prompt)print(f"[ROUTER] category={category} model={model_id} vision={actual == 'vision'}")# 5) Invoke with model rotation on failuremax_attempts = 3last_error = Nonefor attempt in range(max_attempts):try:llm = _make_llm(api_key, model_id)resp = llm.invoke([sys] + messages)return {"messages": [resp]}except Exception as e:last_error = eprint(f"[ROUTER] Model {model_id} failed (attempt {attempt+1}/{max_attempts}):")print(f"[ROUTER] {type(e).__name__}: {str(e)[:200]}")traceback.print_exc()if attempt < max_attempts - 1:model_id, actual = _pick(category, has_image=has_image)print(f"[ROUTER] Rotating to model: {model_id}")# All attempts failed — raise so app.py SSE handler can show the errorprint(f"[ROUTER] All {max_attempts} attempts failed. Raising last error.")23 unmodified lines24252627282930253 unmodified lines2842852862872882892902912922932942952962972982993003013023036 unmodified lines31031131231331431531631731831932032132232332432532642 unmodified lines36937037137237337437537637737837938038138238338438538638738838939039139239339439523 unmodified linesimport urllib.requestimport threadingimport tracebackimport concurrent.futuresfrom langgraph.checkpoint.sqlite import SqliteSaverfrom config import OPENROUTER_API_KEY, DB_PATH, LLM_TIMEOUTimport prompts253 unmodified linesreturn out# ── LLM factory & thread-timeout wrapper ─────────────────────## ChatOpenRouter wraps the `openrouter` Python SDK which creates its# own httpx.Client internally. That client does NOT inherit the# `timeout` kwarg passed to ChatOpenRouter at the LangChain level.## Fix: run llm.invoke() in a daemon thread and enforce a hard# Python-level deadline with future.result(timeout=LLM_TIMEOUT).# This kills the blocked thread from Python's perspective and raises# TimeoutError which our retry loop handles like any other error.# Thread pool — reused across calls to avoid spawn overhead_executor = concurrent.futures.ThreadPoolExecutor(max_workers=4)def _make_llm(api_key: str, model_id: str):key = api_key or OPENROUTER_API_KEY6 unmodified linesopenrouter_api_key=key,temperature=0.5,max_tokens=4096,max_retries=0, # disable SDK retries — our loop handles rotationstreaming=True,)def _invoke_with_timeout(llm, messages: list, timeout: float):"""Run llm.invoke in a thread; raise TimeoutError after `timeout` seconds."""future = _executor.submit(llm.invoke, messages)return future.result(timeout=timeout)# ── LangGraph state & node ────────────────────────────────────class ChatState(TypedDict):42 unmodified linessys = SystemMessage(content=base_prompt)print(f"[ROUTER] category={category} model={model_id} vision={actual == 'vision'}")# 5) Invoke with model rotation + hard Python timeoutmax_attempts = 3last_error = Nonefor attempt in range(max_attempts):try:llm = _make_llm(api_key, model_id)resp = _invoke_with_timeout(llm, [sys] + messages, timeout=LLM_TIMEOUT)return {"messages": [resp]}except concurrent.futures.TimeoutError:last_error = TimeoutError(f"Model {model_id} timed out after {LLM_TIMEOUT}s")print(f"[ROUTER] TIMEOUT {model_id} after {LLM_TIMEOUT}s (attempt {attempt+1}/{max_attempts})")if attempt < max_attempts - 1:model_id, actual = _pick(category, has_image=has_image)print(f"[ROUTER] Rotating to: {model_id}")except Exception as e:last_error = eprint(f"[ROUTER] FAIL {model_id} (attempt {attempt+1}/{max_attempts}): {type(e).__name__}: {str(e)[:200]}")traceback.print_exc()if attempt < max_attempts - 1:model_id, actual = _pick(category, has_image=has_image)print(f"[ROUTER] Rotating to: {model_id}")# All attempts failed — raise so app.py SSE handler can show the errorprint(f"[ROUTER] All {max_attempts} attempts failed. Raising last error.")
2 unmodified lines34567892 unmodified linespython-multipartlanggraphlangchain-corelangchain-google-genailangchain-openrouterlanggraph-checkpoint-sqlitepinecone2 unmodified lines3456782 unmodified linespython-multipartlanggraphlangchain-corelangchain-openrouterlanggraph-checkpoint-sqlitepinecone
203 unmodified lines20420520620720820921021121252 unmodified lines26526626726826927027127227327427527627727856 unmodified lines3353363373383393403414 unmodified lines346347348349350351352185 unmodified lines53853954054154254354434 unmodified lines57958058158258358458558658726 unmodified lines61461561661761861962062162262362467 unmodified lines692693694695696697698174 unmodified lines8738748758768778788798808818828838848858868878888894 unmodified lines8948958968978988999009019029039049059069079089099109112 unmodified lines91491591691791891992092192292392492517 unmodified lines943944945946947948949131 unmodified lines1081108210831084108510861087118 unmodified lines120612071208120912101211121220 unmodified lines1233123412351236123712381239203 unmodified linescategory: cat, message: msg})}).then(r => { if (!r.ok) throw new Error(); return r.json(); }).then(() => { settingsOverlay.classList.remove('show'); document.getElementById('feedbackMessage').value = ''; showToast('Feedback submitted. Thank you!', 'success'); }).catch(() => showToast('Could not submit feedback.', 'error')).finally(() => { btn.disabled = false; btn.textContent = 'Submit Securely'; });});}52 unmodified linesmethod: 'POST', headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ token: response.credential }),}).then(r => { if (!r.ok) throw new Error('Auth failed'); return r.json(); }).then(data => {if (data.error) { showToast('Login failed: ' + data.error, 'error'); return; }currentUser = data.user;localStorage.setItem('stemcopilot_user', JSON.stringify(currentUser));currentUsername = currentUser.name;localStorage.setItem('stemcopilot_username', currentUsername);if (!data.has_api_key) showByok(); else showApp();}).catch(() => showToast('Login failed. Check your connection.', 'error'));}function checkExistingSession() {56 unmodified linesif (data.user.student_profile && profileInput) profileInput.value = data.user.student_profile;if (data.user.openrouter_key && settingsApiKeyInput) settingsApiKeyInput.value = '••••••••••••';}}).catch(() => {});}if (usernameInput) usernameInput.value = currentUsername;4 unmodified linesfetch('/threads?user_id=' + encodeURIComponent(userId)).then(r => r.json()).then(data => { data.threads.forEach(t => threads.push({ id: t.id, title: t.title })); renderHistory(); }).catch(() => {});if (window.innerWidth <= 768) closeSidebar();enterHeroMode();185 unmodified lines<svg viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9" /></svg></button><div class="style-dropdown" id="heroStyleDropdownDynamic">${['vidyut','nerd','noob','thoughtful','panic'].map(p => `<div class="style-option ${currentPersona === p ? 'active' : ''}" data-persona="${p}"><div class="style-option-name">${_PERSONA_LABELS[p]}</div><div class="style-option-desc">${_personaDesc(p)}</div>34 unmodified linesdynUpload.addEventListener('click', () => dynFileInput.click());dynFileInput.addEventListener('change', () => {if (dynFileInput.files[0]) { handleImageFile(dynFileInput.files[0]); _showHeroImagePreview(dynImgPreview, dynImgThumb); }});dynImgRemove.addEventListener('click', () => { _clearImage(); dynImgPreview.classList.remove('visible'); });// Style selectorif (dynStyleBtn) {26 unmodified linesreturn descs[p] || '';}function _showHeroImagePreview(previewEl, thumbEl) {if (pendingImageDataUrl && previewEl && thumbEl) {thumbEl.style.backgroundImage = `url(${pendingImageDataUrl})`;previewEl.classList.add('visible');}}67 unmodified linesdocument.querySelectorAll('.options-menu.show').forEach(m => m.classList.remove('show'));document.querySelectorAll('.options-btn.menu-open').forEach(b => b.classList.remove('menu-open'));if (userMenu) userMenu.classList.remove('show');if (styleDropdown) { styleDropdown.classList.remove('show'); styleSelectorBtn?.classList.remove('open'); }}function deleteChat(e, optionEl) {174 unmodified lines/* ── Image Upload ───────────────────────────────────────────── */if (uploadBtn) uploadBtn.addEventListener('click', () => imageInput.click());if (imageInput) imageInput.addEventListener('change', () => { if (imageInput.files[0]) handleImageFile(imageInput.files[0]); });if (heroUploadBtn) heroUploadBtn.addEventListener('click', () => heroImageInput.click());if (heroImageInput) heroImageInput.addEventListener('change', () => {if (heroImageInput.files[0]) {handleImageFile(heroImageInput.files[0]);if (heroImagePreview && heroImagePreviewThumb && pendingImageDataUrl) {heroImagePreviewThumb.style.backgroundImage = `url(${pendingImageDataUrl})`;heroImagePreview.classList.add('visible');}}});document.addEventListener('paste', (e) => {4 unmodified lines}});function handleImageFile(file) {const reader = new FileReader();reader.onload = (e) => {const dataUrl = e.target.result;pendingImage = dataUrl.split(',')[1];pendingImageDataUrl = dataUrl;if (imagePreviewThumb) imagePreviewThumb.style.backgroundImage = `url(${dataUrl})`;if (imagePreviewBar) imagePreviewBar.style.display = 'flex';if (isHeroMode) {const hp = document.getElementById('heroImagePreviewDynamic') || heroImagePreview;const ht = document.getElementById('heroImagePreviewThumbDynamic') || heroImagePreviewThumb;if (hp && ht) { ht.style.backgroundImage = `url(${dataUrl})`; hp.classList.add('visible'); }}};reader.readAsDataURL(file);2 unmodified linesfunction _clearImage() {pendingImage = null;pendingImageDataUrl = null;if (imagePreviewBar) imagePreviewBar.style.display = 'none';if (imageInput) imageInput.value = '';}if (imagePreviewRemove) imagePreviewRemove.addEventListener('click', _clearImage);if (heroImagePreviewRemove) heroImagePreviewRemove.addEventListener('click', () => { _clearImage(); if (heroImagePreview) heroImagePreview.classList.remove('visible'); });/* ── Chat & Streaming ───────────────────────────────────────── */17 unmodified linesstopBtn.addEventListener('click', () => {currentStreamStopped = true;if (currentRenderTimer) { clearTimeout(currentRenderTimer); currentRenderTimer = null; }if (currentStreamReader) { try { currentStreamReader.cancel(); } catch (_) {} currentStreamReader = null; }if (currentAbortController) { currentAbortController.abort(); currentAbortController = null; }isSending = false;_showAdaptiveBtn();131 unmodified linesrawText += data.token;scheduleRender();}} catch (_) {}}if (!currentStreamStopped) read();}).catch(err => {118 unmodified lines/* ── PWA ────────────────────────────────────────────────────── */if ('serviceWorker' in navigator) navigator.serviceWorker.register('/sw.js').catch(() => {});let deferredPrompt = null;20 unmodified linesif (sidebar) sidebar.classList.add('collapsed');try { if (screen.orientation && screen.orientation.lock) screen.orientation.lock('portrait').catch(() => {}); } catch (_) {}window.addEventListener('load', () => {checkExistingSession();203 unmodified lines20420520620720820921021121252 unmodified lines26526626726826927027127227327427527627727856 unmodified lines3353363373383393403414 unmodified lines346347348349350351352185 unmodified lines53853954054154254354434 unmodified lines57958058158258358458558658758858959059159259326 unmodified lines62062162262362462562662762867 unmodified lines696697698699700701702703704174 unmodified lines8798808818828838848858868878888898908918928938948958968978988999009019029039049054 unmodified lines9109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449452 unmodified lines94894995095195295395495595695795895996096196296396496596617 unmodified lines984985986987988989990131 unmodified lines1122112311241125112611271128118 unmodified lines124712481249125012511252125320 unmodified lines1274127512761277127812791280203 unmodified linescategory: cat, message: msg})}).then(r => { if (!r.ok) throw new Error(); return r.json(); }).then(() => { settingsOverlay.classList.remove('show'); document.getElementById('feedbackMessage').value = ''; showToast('Feedback submitted. Thank you!', 'success'); }).catch(() => showToast('Could not submit feedback.', 'error')).finally(() => { btn.disabled = false; btn.textContent = 'Submit Securely'; });});}52 unmodified linesmethod: 'POST', headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ token: response.credential }),}).then(r => { if (!r.ok) throw new Error('Auth failed'); return r.json(); }).then(data => {if (data.error) { showToast('Login failed: ' + data.error, 'error'); return; }currentUser = data.user;localStorage.setItem('stemcopilot_user', JSON.stringify(currentUser));currentUsername = currentUser.name;localStorage.setItem('stemcopilot_username', currentUsername);if (!data.has_api_key) showByok(); else showApp();}).catch(() => showToast('Login failed. Check your connection.', 'error'));}function checkExistingSession() {56 unmodified linesif (data.user.student_profile && profileInput) profileInput.value = data.user.student_profile;if (data.user.openrouter_key && settingsApiKeyInput) settingsApiKeyInput.value = '••••••••••••';}}).catch(() => { });}if (usernameInput) usernameInput.value = currentUsername;4 unmodified linesfetch('/threads?user_id=' + encodeURIComponent(userId)).then(r => r.json()).then(data => { data.threads.forEach(t => threads.push({ id: t.id, title: t.title })); renderHistory(); }).catch(() => { });if (window.innerWidth <= 768) closeSidebar();enterHeroMode();185 unmodified lines<svg viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9" /></svg></button><div class="style-dropdown" id="heroStyleDropdownDynamic">${['vidyut', 'nerd', 'noob', 'thoughtful', 'panic'].map(p => `<div class="style-option ${currentPersona === p ? 'active' : ''}" data-persona="${p}"><div class="style-option-name">${_PERSONA_LABELS[p]}</div><div class="style-option-desc">${_personaDesc(p)}</div>34 unmodified linesdynUpload.addEventListener('click', () => dynFileInput.click());dynFileInput.addEventListener('change', () => {if (dynFileInput.files[0]) handleImageFile(dynFileInput.files[0], dynImgPreview);});dynImgPreview.addEventListener('click', (e) => {if (e.target.closest('.image-chip-remove')) {_clearImage();dynImgPreview.classList.remove('visible');dynImgPreview.innerHTML = '';}});// Style selectorif (dynStyleBtn) {26 unmodified linesreturn descs[p] || '';}function _showHeroImagePreview(previewEl) {// kept for compatibility — chip rendering is handled in handleImageFileif (previewEl) previewEl.classList.add('visible');}67 unmodified linesdocument.querySelectorAll('.options-menu.show').forEach(m => m.classList.remove('show'));document.querySelectorAll('.options-btn.menu-open').forEach(b => b.classList.remove('menu-open'));if (userMenu) userMenu.classList.remove('show');// Close ALL style dropdowns — static and dynamic hero onesdocument.querySelectorAll('.style-dropdown.show').forEach(d => d.classList.remove('show'));document.querySelectorAll('.style-selector-btn.open').forEach(b => b.classList.remove('open'));}function deleteChat(e, optionEl) {174 unmodified lines/* ── Image Upload ───────────────────────────────────────────── */function _makeChip(dataUrl, filename, onRemove) {const chip = document.createElement('div');chip.className = 'image-chip';chip.innerHTML = `<div class="image-chip-thumb" style="background-image:url(${dataUrl})"></div><span class="image-chip-name">${escapeHtml(filename)}</span><button class="image-chip-remove" title="Remove"><svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>`;chip.querySelector('.image-chip-remove').addEventListener('click', (e) => {e.stopPropagation(); onRemove();});return chip;}if (uploadBtn) uploadBtn.addEventListener('click', () => imageInput.click());if (imageInput) imageInput.addEventListener('change', () => { if (imageInput.files[0]) handleImageFile(imageInput.files[0]); });if (heroUploadBtn) heroUploadBtn.addEventListener('click', () => heroImageInput.click());if (heroImageInput) heroImageInput.addEventListener('change', () => {if (heroImageInput.files[0]) handleImageFile(heroImageInput.files[0]);});document.addEventListener('paste', (e) => {4 unmodified lines}});function handleImageFile(file, targetPreviewEl) {const reader = new FileReader();reader.onload = (e) => {const dataUrl = e.target.result;pendingImage = dataUrl.split(',')[1];pendingImageDataUrl = dataUrl;const filename = file.name || 'image';// Bottom input chipif (imagePreviewBar) {imagePreviewBar.innerHTML = '';imagePreviewBar.appendChild(_makeChip(dataUrl, filename, () => {_clearImage();imagePreviewBar.innerHTML = '';imagePreviewBar.style.display = 'none';}));imagePreviewBar.style.display = 'flex';}// Hero input chipconst heroPreview = targetPreviewEl ||(isHeroMode ? (document.getElementById('heroImagePreviewDynamic') || heroImagePreview) : null);if (heroPreview) {heroPreview.innerHTML = '';heroPreview.appendChild(_makeChip(dataUrl, filename, () => {_clearImage();heroPreview.innerHTML = '';heroPreview.classList.remove('visible');}));heroPreview.classList.add('visible');}};reader.readAsDataURL(file);2 unmodified linesfunction _clearImage() {pendingImage = null;pendingImageDataUrl = null;if (imageInput) imageInput.value = '';if (heroImageInput) heroImageInput.value = '';}// Legacy remove buttons (static HTML fallbacks)if (imagePreviewRemove) imagePreviewRemove.addEventListener('click', () => {_clearImage();if (imagePreviewBar) { imagePreviewBar.innerHTML = ''; imagePreviewBar.style.display = 'none'; }});if (heroImagePreviewRemove) heroImagePreviewRemove.addEventListener('click', () => {_clearImage();if (heroImagePreview) { heroImagePreview.innerHTML = ''; heroImagePreview.classList.remove('visible'); }});/* ── Chat & Streaming ───────────────────────────────────────── */17 unmodified linesstopBtn.addEventListener('click', () => {currentStreamStopped = true;if (currentRenderTimer) { clearTimeout(currentRenderTimer); currentRenderTimer = null; }if (currentStreamReader) { try { currentStreamReader.cancel(); } catch (_) { } currentStreamReader = null; }if (currentAbortController) { currentAbortController.abort(); currentAbortController = null; }isSending = false;_showAdaptiveBtn();131 unmodified linesrawText += data.token;scheduleRender();}} catch (_) { }}if (!currentStreamStopped) read();}).catch(err => {118 unmodified lines/* ── PWA ────────────────────────────────────────────────────── */if ('serviceWorker' in navigator) navigator.serviceWorker.register('/sw.js').catch(() => { });let deferredPrompt = null;20 unmodified linesif (sidebar) sidebar.classList.add('collapsed');try { if (screen.orientation && screen.orientation.lock) screen.orientation.lock('portrait').catch(() => { }); } catch (_) { }window.addEventListener('load', () => {checkExistingSession();
1039 unmodified lines10401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080212 unmodified lines12931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261039 unmodified linesmax-width: 640px;}/* Image preview inside hero */.hero-image-preview {display: none;align-items: center;gap: 8px;margin-bottom: 8px;padding: 6px 10px;background: var(--bg-card);border: 1px solid var(--border-color);border-radius: var(--radius);}.hero-image-preview.visible { display: flex; }.hero-image-preview-thumb {width: 48px;height: 48px;border-radius: 6px;background-size: cover;background-position: center;}.hero-image-preview-remove {margin-left: auto;background: none;border: none;color: var(--text-secondary);font-size: 20px;cursor: pointer;padding: 4px 8px;transition: color 0.2s;}.hero-image-preview-remove:hover { color: #ff4a4a; }.hero-input-box {display: flex;align-items: flex-end;212 unmodified lineswidth: 100%;display: flex;align-items: center;gap: 8px;margin-bottom: 8px;padding: 6px 10px;background: var(--bg-card);border: 1px solid var(--border-color);border-radius: var(--radius);}.image-preview-thumb {width: 48px;height: 48px;border-radius: 6px;background-size: cover;background-position: center;}.image-preview-remove {margin-left: auto;background: none;border: none;color: var(--text-secondary);font-size: 20px;cursor: pointer;padding: 4px 8px;transition: color 0.2s;}.image-preview-remove:hover { color: #ff4a4a; }.input-box {width: 100%;1039 unmodified lines1040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064212 unmodified lines12771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371039 unmodified linesmax-width: 640px;}/* Image chip preview inside hero */.hero-image-preview {display: none;gap: 6px;margin-bottom: 4px;flex-wrap: wrap;padding: 0 2px;}.hero-image-preview.visible { display: flex; }.hero-image-preview-thumb {display: none; /* replaced by .image-chip-thumb inside */}.hero-image-preview-remove {display: none; /* replaced by .image-chip-remove inside */}.hero-input-box {display: flex;align-items: flex-end;212 unmodified lineswidth: 100%;display: flex;align-items: center;gap: 6px;margin-bottom: 4px;flex-wrap: wrap;padding: 0 4px;}.image-chip {display: inline-flex;align-items: center;gap: 6px;background: var(--bg-card);border: 1px solid var(--border-color);border-radius: 8px;padding: 4px 8px 4px 4px;max-width: 200px;transition: border-color 0.2s;}.image-chip:hover {border-color: var(--brand);}.image-chip-thumb {width: 32px;height: 32px;border-radius: 5px;background-size: cover;background-position: center;flex-shrink: 0;}.image-chip-name {font-size: 11px;color: var(--text-secondary);white-space: nowrap;overflow: hidden;text-overflow: ellipsis;max-width: 100px;}.image-chip-remove {background: none;border: none;color: var(--text-muted);font-size: 14px;line-height: 1;cursor: pointer;padding: 0 2px;flex-shrink: 0;transition: color 0.2s;display: flex;align-items: center;}.image-chip-remove:hover { color: #ff4a4a; }.input-box {width: 100%;
config.py+1-1
graph.py+32-8
requirements.txt-1
static/app.js+84-43
static/style.css+48-37