Spaces:
Running
Running
Commit
·
283515f
1
Parent(s):
83c32ef
Upd namer and namer session js
Browse files- helpers/namer.py +32 -5
- routes/chats.py +22 -5
- static/script.js +6 -0
- static/sessions.js +18 -1
helpers/namer.py
CHANGED
|
@@ -35,6 +35,12 @@ async def auto_name_session(
|
|
| 35 |
Generated session name or None if failed
|
| 36 |
"""
|
| 37 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
if not nvidia_rotator:
|
| 39 |
logger.warning("[NAMER] NVIDIA rotator not available")
|
| 40 |
return None
|
|
@@ -64,6 +70,10 @@ Return only the session name, nothing else."""
|
|
| 64 |
from utils.api.router import generate_answer_with_model
|
| 65 |
selection = {"provider": "nvidia", "model": "meta/llama-3.1-8b-instruct"}
|
| 66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
response = await generate_answer_with_model(
|
| 68 |
selection=selection,
|
| 69 |
system_prompt=sys_prompt,
|
|
@@ -72,41 +82,58 @@ Return only the session name, nothing else."""
|
|
| 72 |
nvidia_rotator=nvidia_rotator
|
| 73 |
)
|
| 74 |
|
|
|
|
|
|
|
| 75 |
# Clean up the response
|
| 76 |
session_name = response.strip()
|
|
|
|
|
|
|
| 77 |
# Remove quotes if present
|
| 78 |
if session_name.startswith('"') and session_name.endswith('"'):
|
| 79 |
session_name = session_name[1:-1]
|
|
|
|
| 80 |
if session_name.startswith("'") and session_name.endswith("'"):
|
| 81 |
session_name = session_name[1:-1]
|
|
|
|
| 82 |
|
| 83 |
# Truncate if too long (safety measure)
|
| 84 |
if len(session_name) > 50:
|
| 85 |
session_name = session_name[:47] + "..."
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
# Update the session with the auto-generated name in database
|
| 88 |
if rag_db:
|
|
|
|
|
|
|
|
|
|
| 89 |
result = rag_db["chat_sessions"].update_many(
|
| 90 |
{"user_id": user_id, "project_id": project_id, "session_id": session_id},
|
| 91 |
{"$set": {"session_name": session_name, "is_auto_named": True}}
|
| 92 |
)
|
| 93 |
|
|
|
|
|
|
|
| 94 |
if result.modified_count > 0:
|
| 95 |
-
logger.info(f"[NAMER]
|
| 96 |
return session_name
|
| 97 |
else:
|
| 98 |
-
logger.warning(f"[NAMER] Session not found for auto-naming: {session_id}")
|
|
|
|
| 99 |
return None
|
| 100 |
else:
|
| 101 |
-
logger.warning("[NAMER] Database connection not provided")
|
| 102 |
return session_name
|
| 103 |
|
| 104 |
except Exception as e:
|
| 105 |
-
logger.
|
|
|
|
| 106 |
return None
|
| 107 |
|
| 108 |
except Exception as e:
|
| 109 |
-
logger.error(f"[NAMER] Failed to auto-name session: {e}")
|
|
|
|
| 110 |
return None
|
| 111 |
|
| 112 |
|
|
|
|
| 35 |
Generated session name or None if failed
|
| 36 |
"""
|
| 37 |
try:
|
| 38 |
+
logger.info(f"[NAMER] Starting auto-naming for session {session_id}")
|
| 39 |
+
logger.info(f"[NAMER] User: {user_id}, Project: {project_id}")
|
| 40 |
+
logger.info(f"[NAMER] First query: {first_query[:100]}...")
|
| 41 |
+
logger.info(f"[NAMER] NVIDIA rotator available: {nvidia_rotator is not None}")
|
| 42 |
+
logger.info(f"[NAMER] Database available: {rag_db is not None}")
|
| 43 |
+
|
| 44 |
if not nvidia_rotator:
|
| 45 |
logger.warning("[NAMER] NVIDIA rotator not available")
|
| 46 |
return None
|
|
|
|
| 70 |
from utils.api.router import generate_answer_with_model
|
| 71 |
selection = {"provider": "nvidia", "model": "meta/llama-3.1-8b-instruct"}
|
| 72 |
|
| 73 |
+
logger.info(f"[NAMER] Calling NVIDIA API with model: {selection['model']}")
|
| 74 |
+
logger.info(f"[NAMER] System prompt length: {len(sys_prompt)}")
|
| 75 |
+
logger.info(f"[NAMER] User prompt: {user_prompt}")
|
| 76 |
+
|
| 77 |
response = await generate_answer_with_model(
|
| 78 |
selection=selection,
|
| 79 |
system_prompt=sys_prompt,
|
|
|
|
| 82 |
nvidia_rotator=nvidia_rotator
|
| 83 |
)
|
| 84 |
|
| 85 |
+
logger.info(f"[NAMER] Raw API response: {response}")
|
| 86 |
+
|
| 87 |
# Clean up the response
|
| 88 |
session_name = response.strip()
|
| 89 |
+
logger.info(f"[NAMER] Initial session name: '{session_name}'")
|
| 90 |
+
|
| 91 |
# Remove quotes if present
|
| 92 |
if session_name.startswith('"') and session_name.endswith('"'):
|
| 93 |
session_name = session_name[1:-1]
|
| 94 |
+
logger.info(f"[NAMER] Removed double quotes: '{session_name}'")
|
| 95 |
if session_name.startswith("'") and session_name.endswith("'"):
|
| 96 |
session_name = session_name[1:-1]
|
| 97 |
+
logger.info(f"[NAMER] Removed single quotes: '{session_name}'")
|
| 98 |
|
| 99 |
# Truncate if too long (safety measure)
|
| 100 |
if len(session_name) > 50:
|
| 101 |
session_name = session_name[:47] + "..."
|
| 102 |
+
logger.info(f"[NAMER] Truncated long name: '{session_name}'")
|
| 103 |
+
|
| 104 |
+
logger.info(f"[NAMER] Final session name: '{session_name}'")
|
| 105 |
|
| 106 |
# Update the session with the auto-generated name in database
|
| 107 |
if rag_db:
|
| 108 |
+
logger.info(f"[NAMER] Updating database for session {session_id}")
|
| 109 |
+
logger.info(f"[NAMER] Query: user_id={user_id}, project_id={project_id}, session_id={session_id}")
|
| 110 |
+
|
| 111 |
result = rag_db["chat_sessions"].update_many(
|
| 112 |
{"user_id": user_id, "project_id": project_id, "session_id": session_id},
|
| 113 |
{"$set": {"session_name": session_name, "is_auto_named": True}}
|
| 114 |
)
|
| 115 |
|
| 116 |
+
logger.info(f"[NAMER] Database update result: matched={result.matched_count}, modified={result.modified_count}")
|
| 117 |
+
|
| 118 |
if result.modified_count > 0:
|
| 119 |
+
logger.info(f"[NAMER] ✅ Successfully auto-named session '{session_id}' to '{session_name}'")
|
| 120 |
return session_name
|
| 121 |
else:
|
| 122 |
+
logger.warning(f"[NAMER] ❌ Session not found for auto-naming: {session_id}")
|
| 123 |
+
logger.warning(f"[NAMER] This might mean the session doesn't exist in the database yet")
|
| 124 |
return None
|
| 125 |
else:
|
| 126 |
+
logger.warning("[NAMER] ❌ Database connection not provided")
|
| 127 |
return session_name
|
| 128 |
|
| 129 |
except Exception as e:
|
| 130 |
+
logger.error(f"[NAMER] ❌ Auto-naming API call failed: {e}")
|
| 131 |
+
logger.error(f"[NAMER] Exception type: {type(e).__name__}")
|
| 132 |
return None
|
| 133 |
|
| 134 |
except Exception as e:
|
| 135 |
+
logger.error(f"[NAMER] ❌ Failed to auto-name session: {e}")
|
| 136 |
+
logger.error(f"[NAMER] Exception type: {type(e).__name__}")
|
| 137 |
return None
|
| 138 |
|
| 139 |
|
routes/chats.py
CHANGED
|
@@ -321,6 +321,10 @@ async def chat(
|
|
| 321 |
# Check if this is the first message in the session for auto-naming
|
| 322 |
session_name = None
|
| 323 |
if session_id:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
# Check if session record exists (not just messages)
|
| 325 |
existing_session = rag.db["chat_sessions"].find_one({
|
| 326 |
"user_id": user_id,
|
|
@@ -337,8 +341,11 @@ async def chat(
|
|
| 337 |
"role": "user" # Only count user messages
|
| 338 |
})
|
| 339 |
|
|
|
|
|
|
|
| 340 |
# If session doesn't exist, create it
|
| 341 |
if not existing_session:
|
|
|
|
| 342 |
session_data = {
|
| 343 |
"user_id": user_id,
|
| 344 |
"project_id": project_id,
|
|
@@ -349,14 +356,16 @@ async def chat(
|
|
| 349 |
"timestamp": time.time()
|
| 350 |
}
|
| 351 |
rag.db["chat_sessions"].insert_one(session_data)
|
| 352 |
-
logger.info(f"[CHAT] Created session record for {session_id}")
|
| 353 |
|
| 354 |
# If this is the first user message, trigger auto-naming with short timeout, then fall back to background
|
| 355 |
if existing_messages == 0:
|
|
|
|
| 356 |
try:
|
| 357 |
from helpers.namer import auto_name_session_immediate
|
| 358 |
import asyncio as _asyncio_name
|
| 359 |
try:
|
|
|
|
| 360 |
session_name = await _asyncio_name.wait_for(
|
| 361 |
auto_name_session_immediate(
|
| 362 |
user_id, project_id, session_id, question, nvidia_rotator, rag.db
|
|
@@ -364,20 +373,28 @@ async def chat(
|
|
| 364 |
timeout=2.0
|
| 365 |
)
|
| 366 |
if session_name:
|
| 367 |
-
logger.info(f"[CHAT] Auto-named session {session_id} to '{session_name}' (inline)")
|
|
|
|
|
|
|
| 368 |
except _asyncio_name.TimeoutError:
|
|
|
|
| 369 |
async def _do_name():
|
| 370 |
try:
|
|
|
|
| 371 |
_name = await auto_name_session_immediate(
|
| 372 |
user_id, project_id, session_id, question, nvidia_rotator, rag.db
|
| 373 |
)
|
| 374 |
if _name:
|
| 375 |
-
logger.info(f"[CHAT] Auto-named session {session_id} to '{_name}' (background)")
|
|
|
|
|
|
|
| 376 |
except Exception as _e:
|
| 377 |
-
logger.
|
| 378 |
_asyncio_name.create_task(_do_name())
|
| 379 |
except Exception as e:
|
| 380 |
-
logger.
|
|
|
|
|
|
|
| 381 |
|
| 382 |
# Get the chat response
|
| 383 |
chat_response = await asyncio.wait_for(_chat_impl(user_id, project_id, question, k, use_web=use_web, max_web=max_web, session_id=session_id), timeout=120.0)
|
|
|
|
| 321 |
# Check if this is the first message in the session for auto-naming
|
| 322 |
session_name = None
|
| 323 |
if session_id:
|
| 324 |
+
logger.info(f"[CHAT] 🔍 Checking auto-naming for session {session_id}")
|
| 325 |
+
logger.info(f"[CHAT] User: {user_id}, Project: {project_id}")
|
| 326 |
+
logger.info(f"[CHAT] Question: {question[:100]}...")
|
| 327 |
+
|
| 328 |
# Check if session record exists (not just messages)
|
| 329 |
existing_session = rag.db["chat_sessions"].find_one({
|
| 330 |
"user_id": user_id,
|
|
|
|
| 341 |
"role": "user" # Only count user messages
|
| 342 |
})
|
| 343 |
|
| 344 |
+
logger.info(f"[CHAT] Session {session_id}: existing_session={existing_session is not None}, existing_messages={existing_messages}")
|
| 345 |
+
|
| 346 |
# If session doesn't exist, create it
|
| 347 |
if not existing_session:
|
| 348 |
+
logger.info(f"[CHAT] Creating new session record for {session_id}")
|
| 349 |
session_data = {
|
| 350 |
"user_id": user_id,
|
| 351 |
"project_id": project_id,
|
|
|
|
| 356 |
"timestamp": time.time()
|
| 357 |
}
|
| 358 |
rag.db["chat_sessions"].insert_one(session_data)
|
| 359 |
+
logger.info(f"[CHAT] ✅ Created session record for {session_id}")
|
| 360 |
|
| 361 |
# If this is the first user message, trigger auto-naming with short timeout, then fall back to background
|
| 362 |
if existing_messages == 0:
|
| 363 |
+
logger.info(f"[CHAT] 🚀 First message detected - triggering auto-naming for session {session_id}")
|
| 364 |
try:
|
| 365 |
from helpers.namer import auto_name_session_immediate
|
| 366 |
import asyncio as _asyncio_name
|
| 367 |
try:
|
| 368 |
+
logger.info(f"[CHAT] Attempting immediate auto-naming with 2s timeout...")
|
| 369 |
session_name = await _asyncio_name.wait_for(
|
| 370 |
auto_name_session_immediate(
|
| 371 |
user_id, project_id, session_id, question, nvidia_rotator, rag.db
|
|
|
|
| 373 |
timeout=2.0
|
| 374 |
)
|
| 375 |
if session_name:
|
| 376 |
+
logger.info(f"[CHAT] ✅ Auto-named session {session_id} to '{session_name}' (inline)")
|
| 377 |
+
else:
|
| 378 |
+
logger.warning(f"[CHAT] ❌ Auto-naming returned None (inline)")
|
| 379 |
except _asyncio_name.TimeoutError:
|
| 380 |
+
logger.info(f"[CHAT] ⏰ Auto-naming timed out, running in background...")
|
| 381 |
async def _do_name():
|
| 382 |
try:
|
| 383 |
+
logger.info(f"[CHAT] Background auto-naming starting...")
|
| 384 |
_name = await auto_name_session_immediate(
|
| 385 |
user_id, project_id, session_id, question, nvidia_rotator, rag.db
|
| 386 |
)
|
| 387 |
if _name:
|
| 388 |
+
logger.info(f"[CHAT] ✅ Auto-named session {session_id} to '{_name}' (background)")
|
| 389 |
+
else:
|
| 390 |
+
logger.warning(f"[CHAT] ❌ Auto-naming returned None (background)")
|
| 391 |
except Exception as _e:
|
| 392 |
+
logger.error(f"[CHAT] ❌ Background auto-naming failed: {_e}")
|
| 393 |
_asyncio_name.create_task(_do_name())
|
| 394 |
except Exception as e:
|
| 395 |
+
logger.error(f"[CHAT] ❌ Auto-naming scheduling failed: {e}")
|
| 396 |
+
else:
|
| 397 |
+
logger.info(f"[CHAT] Not first message (count={existing_messages}), skipping auto-naming")
|
| 398 |
|
| 399 |
# Get the chat response
|
| 400 |
chat_response = await asyncio.wait_for(_chat_impl(user_id, project_id, question, k, use_web=use_web, max_web=max_web, session_id=session_id), timeout=120.0)
|
static/script.js
CHANGED
|
@@ -586,10 +586,16 @@
|
|
| 586 |
|
| 587 |
// Handle session auto-naming if returned
|
| 588 |
if (data.session_name && data.session_id) {
|
|
|
|
| 589 |
// Update the session name in the UI immediately
|
| 590 |
if (window.__sb_update_session_name) {
|
|
|
|
| 591 |
window.__sb_update_session_name(data.session_id, data.session_name);
|
|
|
|
|
|
|
| 592 |
}
|
|
|
|
|
|
|
| 593 |
}
|
| 594 |
|
| 595 |
await saveChatMessage(
|
|
|
|
| 586 |
|
| 587 |
// Handle session auto-naming if returned
|
| 588 |
if (data.session_name && data.session_id) {
|
| 589 |
+
console.log(`[FRONTEND] 🎯 Auto-naming received: session_id=${data.session_id}, name='${data.session_name}'`);
|
| 590 |
// Update the session name in the UI immediately
|
| 591 |
if (window.__sb_update_session_name) {
|
| 592 |
+
console.log(`[FRONTEND] 🔄 Calling updateSessionName function...`);
|
| 593 |
window.__sb_update_session_name(data.session_id, data.session_name);
|
| 594 |
+
} else {
|
| 595 |
+
console.warn(`[FRONTEND] ❌ updateSessionName function not available`);
|
| 596 |
}
|
| 597 |
+
} else {
|
| 598 |
+
console.log(`[FRONTEND] ℹ️ No auto-naming data received:`, { session_name: data.session_name, session_id: data.session_id });
|
| 599 |
}
|
| 600 |
|
| 601 |
await saveChatMessage(
|
static/sessions.js
CHANGED
|
@@ -98,6 +98,9 @@
|
|
| 98 |
}
|
| 99 |
|
| 100 |
function updateSessionDropdown() {
|
|
|
|
|
|
|
|
|
|
| 101 |
sessionDropdown.innerHTML = '<option value="">Select Session</option>';
|
| 102 |
|
| 103 |
sessions.forEach(session => {
|
|
@@ -108,6 +111,7 @@
|
|
| 108 |
option.textContent += ' (Auto)';
|
| 109 |
}
|
| 110 |
sessionDropdown.appendChild(option);
|
|
|
|
| 111 |
});
|
| 112 |
|
| 113 |
// Add create new session option
|
|
@@ -118,6 +122,8 @@
|
|
| 118 |
|
| 119 |
// Update session actions visibility
|
| 120 |
updateSessionActions();
|
|
|
|
|
|
|
| 121 |
}
|
| 122 |
|
| 123 |
function updateSessionActions() {
|
|
@@ -361,21 +367,32 @@
|
|
| 361 |
|
| 362 |
// Function to update session name in UI immediately
|
| 363 |
function updateSessionName(sessionId, newName) {
|
|
|
|
|
|
|
|
|
|
| 364 |
// Update the session in our local sessions array
|
| 365 |
const sessionIndex = sessions.findIndex(s => s.session_id === sessionId);
|
|
|
|
|
|
|
| 366 |
if (sessionIndex !== -1) {
|
|
|
|
| 367 |
sessions[sessionIndex].name = newName;
|
| 368 |
sessions[sessionIndex].is_auto_named = false;
|
| 369 |
|
| 370 |
// Update the dropdown to reflect the new name
|
|
|
|
| 371 |
updateSessionDropdown();
|
| 372 |
|
| 373 |
// If this is the currently selected session, update the dropdown value
|
| 374 |
if (currentSessionId === sessionId) {
|
|
|
|
| 375 |
sessionDropdown.value = sessionId;
|
| 376 |
}
|
| 377 |
|
| 378 |
-
console.log(`[SESSIONS] Updated session name to: ${newName}`);
|
|
|
|
|
|
|
|
|
|
| 379 |
}
|
| 380 |
}
|
| 381 |
|
|
|
|
| 98 |
}
|
| 99 |
|
| 100 |
function updateSessionDropdown() {
|
| 101 |
+
console.log(`[SESSIONS] 🔄 updateSessionDropdown called with ${sessions.length} sessions`);
|
| 102 |
+
console.log(`[SESSIONS] Sessions:`, sessions.map(s => ({ id: s.session_id, name: s.name, auto: s.is_auto_named })));
|
| 103 |
+
|
| 104 |
sessionDropdown.innerHTML = '<option value="">Select Session</option>';
|
| 105 |
|
| 106 |
sessions.forEach(session => {
|
|
|
|
| 111 |
option.textContent += ' (Auto)';
|
| 112 |
}
|
| 113 |
sessionDropdown.appendChild(option);
|
| 114 |
+
console.log(`[SESSIONS] Added option: ${option.value} = ${option.textContent}`);
|
| 115 |
});
|
| 116 |
|
| 117 |
// Add create new session option
|
|
|
|
| 122 |
|
| 123 |
// Update session actions visibility
|
| 124 |
updateSessionActions();
|
| 125 |
+
|
| 126 |
+
console.log(`[SESSIONS] ✅ Dropdown updated with ${sessionDropdown.children.length} options`);
|
| 127 |
}
|
| 128 |
|
| 129 |
function updateSessionActions() {
|
|
|
|
| 367 |
|
| 368 |
// Function to update session name in UI immediately
|
| 369 |
function updateSessionName(sessionId, newName) {
|
| 370 |
+
console.log(`[SESSIONS] 🔄 updateSessionName called: sessionId=${sessionId}, newName='${newName}'`);
|
| 371 |
+
console.log(`[SESSIONS] Current sessions:`, sessions.map(s => ({ id: s.session_id, name: s.name })));
|
| 372 |
+
|
| 373 |
// Update the session in our local sessions array
|
| 374 |
const sessionIndex = sessions.findIndex(s => s.session_id === sessionId);
|
| 375 |
+
console.log(`[SESSIONS] Session index found: ${sessionIndex}`);
|
| 376 |
+
|
| 377 |
if (sessionIndex !== -1) {
|
| 378 |
+
console.log(`[SESSIONS] 📝 Updating session at index ${sessionIndex}: '${sessions[sessionIndex].name}' -> '${newName}'`);
|
| 379 |
sessions[sessionIndex].name = newName;
|
| 380 |
sessions[sessionIndex].is_auto_named = false;
|
| 381 |
|
| 382 |
// Update the dropdown to reflect the new name
|
| 383 |
+
console.log(`[SESSIONS] 🔄 Updating dropdown...`);
|
| 384 |
updateSessionDropdown();
|
| 385 |
|
| 386 |
// If this is the currently selected session, update the dropdown value
|
| 387 |
if (currentSessionId === sessionId) {
|
| 388 |
+
console.log(`[SESSIONS] 🎯 This is the current session, updating dropdown selection`);
|
| 389 |
sessionDropdown.value = sessionId;
|
| 390 |
}
|
| 391 |
|
| 392 |
+
console.log(`[SESSIONS] ✅ Updated session name to: ${newName}`);
|
| 393 |
+
} else {
|
| 394 |
+
console.warn(`[SESSIONS] ❌ Session not found in local array: ${sessionId}`);
|
| 395 |
+
console.warn(`[SESSIONS] Available sessions:`, sessions.map(s => s.session_id));
|
| 396 |
}
|
| 397 |
}
|
| 398 |
|