Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
2d0e9e3
1
Parent(s): 837cc5f
backend stabilization
Browse filesFiles changed (4)
- api/v1/kb.py+49-63
- core/cache.py+7-12
- core/tasks.py+29-6
- reindex_kb_v2.pyAdded+24
250 unmodified lines25125225325425425525625715 unmodified lines27327427527627627727827991 unmodified lines37137237337437537637737837938038138238338438538638738838939039137437537637737837938038138238338438538638738838939058 unmodified lines449450451456457458459460461462463464465466467452453454455456457458459460461462463464465466472473474475476477478479480481482483484485486487488489490491492493494495467468469470471472473474475476477478479480481482483484485498499500486487488489490491506507508509492493494495496497498250 unmodified lines KBArticle.is_published == True, # Broaden: Match if either the keywords hit OR similarity is decent ( Attachment.search_vector.op("@@")(func.plainto_tsquery('english', q)) | Attachment.search_vector.op("@@")(func.websearch_to_tsquery('english', q)) | (func.similarity(Attachment.ai_caption, q) > 0.3) ), KBArticle.workspace_id == workspace_id15 unmodified lines .where( KBArticle.deleted_at.is_(None), KBArticle.is_published == True, KBArticle.search_vector.op("@@")(func.plainto_tsquery('english', q)), KBArticle.search_vector.op("@@")(func.websearch_to_tsquery('english', q)), KBArticle.workspace_id == workspace_id ) )91 unmodified lines logger.info(f"⚡ Search Cache HIT [KB]: {q}") return cached_res # 0.5 Semantic Cache Check for pin-point Answer (if meaningful query) is_question = ( q.strip().endswith('?') or any(q.lower().startswith(w) for w in ["how", "what", "where", "why", "who", "tell", "explain", "describe"]) or len(q.strip().split()) >= 5 # Broaden to multi-word technical queries like "Data models" ) if is_question: sem_answer = await SemanticCacheManager.check_cache( str(target_ws), q, is_agent=(current_user.role in ALL_SC_ROLES), user_role=current_user.role.value if hasattr(current_user.role, 'value') else str(current_user.role), user_id=str(current_user.id) ) if sem_answer: logger.info(f"🧠 Semantic Cache HIT [KB]: {q}") # Still need the document results, but we'll return the answer from cache # For speed, if we have a semantic answer, we might still want to refresh the docs pass # We'll check again after doc retrieval # 0.5 Semantic Cache Check (Unified Workspace Knowledge) sem_answer = await SemanticCacheManager.check_cache(str(target_ws), q) if sem_answer: logger.info(f"🧠 Semantic Cache HIT [KB]: {q}") # Process and return immediately with cache marker # We still run a minimal doc retrieval in background if needed (skipped for now for speed) return { "aiAnswer": sem_answer, "results": [], # Or could fetch top docs if UI requires "isSynthetic": True, "cacheHit": True, "confidence": 1.0, "durationMs": (time.perf_counter() - start_time) * 1000 } # 1. Start Original Search Branch IMMEDIATELY (Don't wait for LLM) original_search_task = execute_multimodal_search(db, q, current_user, category, project_id, workspace_id=target_ws)58 unmodified lines direct_answer = None is_ai_synthetic = False
if is_question and top_results: # Check semantic cache first (redundant but safe) direct_answer = await SemanticCacheManager.check_cache( str(current_user.workspace_id), q, is_agent=(current_user.role in ALL_SC_ROLES), user_role=current_user.role.value if hasattr(current_user.role, 'value') else str(current_user.role), user_id=str(current_user.id) ) if not direct_answer: # Construct context from TOP RAW CHUNKS (High Fidelity) # We use the raw chunks to ensure mermaid/technical diagrams are visible to the LLM # 4.5 Synthesis Branch (The "Full RAG" Pathway) direct_answer = None is_ai_synthetic = False
# Trigger synthesis if any hit is high confidence (>0.6) or it's a multi-word query high_confidence = any(r.get("score", 0.0) > 0.6 for r in top_results) should_synthesize = high_confidence or len(q.split()) >= 3
if should_synthesize and top_results: try: # Construct context from TOP RAW CHUNKS (Fidelity + Enrichment) context_txt = "\n\n".join([ f"DOC {i+1} [{r['title']}]:\n---\n{r.get('raw_chunk') or r.get('snippet') or r['content'][:500]}\n---" for i, r in enumerate(top_results) ]) try: llm = get_llm() prompt = [ SystemMessage(content=( "You are a technical support architect. Provide a high-precision direct answer based ONLY on the provided documentation context. " "The context may contain Mermaid diagrams or code blocks; interpret them to explain flows or logic. " "Structure your answer with clear bullet points if describing a sequence. " "If the answer isn't firmly supported by the context, admit you don't know." )), HumanMessage(content=f"Context:\n{context_txt}\n\nQuestion: {q}") ] synth_resp = await llm.ainvoke(prompt) direct_answer = synth_resp.content is_ai_synthetic = True # Persist to Semantic Cache asyncio.create_task(SemanticCacheManager.set_cache( str(target_ws), str(current_user.id), q, direct_answer, is_agent=(current_user.role in ALL_SC_ROLES), user_role=current_user.role.value if hasattr(current_user.role, 'value') else str(current_user.role) )) except Exception as e: logger.error(f"Synthesis failed: {e}") else: llm = get_llm() prompt = [ SystemMessage(content=( "You are a technical support architect. Provide a high-precision direct answer based ONLY on the provided documentation context. " "Look for [TEK_NAV] tags for navigational context in diagrams. " "Structure your answer with clear bullet points. If unsure, say you don't know." )), HumanMessage(content=f"Context:\n{context_txt}\n\nQuestion: {q}") ] synth_resp = await llm.ainvoke(prompt) direct_answer = synth_resp.content is_ai_synthetic = True # Persist to Semantic Cache (Workspace-Unified) await SemanticCacheManager.set_cache(str(target_ws), str(current_user.id), q, direct_answer) except Exception as e: logger.error(f"Synthesis failed: {e}")
# 5. Suggestion for UI if results are still thin suggestion = expanded_queries[0] if expanded_queries and expanded_queries[0].lower() != q.lower() else None # 5. Final Response Payload end_time = time.perf_counter() search_time_s = end_time - start_time
res_data = { "results": top_results, "answer": direct_answer, "is_ai_synthetic": is_ai_synthetic, "suggestion": suggestion if not top_results else None, "expanded_queries": expanded_queries, "aiAnswer": direct_answer, "isSynthetic": is_ai_synthetic, "confidence": top_results[0].get("score") if top_results else 0.0, "suggestion": expanded_queries[0] if expanded_queries and expanded_queries[0].lower() != q.lower() and not top_results else None, "search_time_s": round(search_time_s, 3) } 63 unmodified lines646566676768697017 unmodified lines88899091929394919293941 unmodified line9697981021039910010110210310 unmodified lines11411511612011711811912012 unmodified lines13313413513913613713814214314413914014114263 unmodified lines """ @staticmethod async def check_cache(workspace_id: str, query: str, is_agent: bool, user_role: str, user_id: str) -> Optional[str]: async def check_cache(workspace_id: str, query: str) -> Optional[str]: from core.llm import get_embeddings from core.database import async_session_factory from models.nexus_semantic_cache import NexusSemanticCache17 unmodified lines NexusSemanticCache.query_embedding.cosine_distance(query_vector).label("distance") ) .where( NexusSemanticCache.workspace_id == workspace_id, NexusSemanticCache.is_agent == is_agent, NexusSemanticCache.user_role == user_role, NexusSemanticCache.user_id == user_id # Strict Identity Partitioning NexusSemanticCache.workspace_id == workspace_id ) .order_by("distance") .limit(1)1 unmodified line res = await db.execute(stmt) row = res.first() # Check for > 0.95 similarity (distance < 0.05) if row and row.distance < 0.05: # Check for > 0.90 similarity (distance < 0.10) - slightly more permissive if row and row.distance < 0.10: cache_hit = row[0] # Update hit count10 unmodified lines return None
@staticmethod async def set_cache(workspace_id: str, user_id: str, query: str, response_text: str, is_agent: bool, user_role: str): async def set_cache(workspace_id: str, user_id: str, query: str, response_text: str): from core.llm import get_embeddings from core.database import async_session_factory from models.nexus_semantic_cache import NexusSemanticCache12 unmodified lines async with async_session_factory() as db: cache_entry = NexusSemanticCache( workspace_id=workspace_id, user_id=user_id, user_id=user_id, # Keep user_id in record for audit, but not lookup query_text=query, query_embedding=query_vector, response_text=response_text, is_agent=is_agent, user_role=user_role response_text=response_text ) db.add(cache_entry) await db.commit()196 unmodified lines197198199200200201202203204205206203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233211234235236237196 unmodified lines except Exception as e: logger.error(f"PHASE 2 [Embeddings] Failed for {article_id} (Length: {len(text_to_embed)}): {str(e)}")
# --- PHASE 3: Chunking & Search Vector Persistence --- # --- PHASE 3: Chunking & Architecture Enrichment --- try: await db.execute(delete(KBArticleChunk).where(KBArticleChunk.article_id == article_id)) chunks = chunk_text(article.content, chunk_size=1200, chunk_overlap=100) for i, text in enumerate(chunks): chunk_vector = await text_model.aembed_query(f"{article.title}: {text}") new_chunk = KBArticleChunk(article_id=article.id, content=text, chunk_index=i, embedding=chunk_vector) raw_chunks = chunk_text(article.content, chunk_size=1200, chunk_overlap=100) for i, text_content in enumerate(raw_chunks): # Architecture Enrichment Step processed_text = text_content if "```mermaid" in text_content.lower() or "```json" in text_content.lower() or "graph " in text_content[:50].lower(): try: logger.info(f"Technical block detected in chunk {i} of {article_id}. Generating TEK_NAV...") enrich_prompt = ( f"Explain this technical block in ONE concise sentence for search indexing. " f"Identify what the flow/data represents.\n\nBLOCK:\n{text_content[:2000]}" ) enrich_res = await llm.ainvoke(enrich_prompt) if enrich_res and enrich_res.content: nav_tag = f"[TEK_NAV: {enrich_res.content.strip()}]\n" processed_text = nav_tag + text_content except Exception as enrich_err: logger.warning(f"Architecture Enrichment failed for chunk {i}: {enrich_err}") chunk_vector = await text_model.aembed_query(f"{article.title}: {processed_text}") new_chunk = KBArticleChunk( article_id=article.id, content=processed_text, chunk_index=i, embedding=chunk_vector ) db.add(new_chunk) if await _abort_if_deleted(): return await db.commit() await db.refresh(article) logger.info(f"PHASE 3 [Chunking] Complete for {article_id} ({len(chunks)} chunks)") logger.info(f"PHASE 3 [Enrichment] Complete for {article_id} ({len(raw_chunks)} chunks)") except Exception as e: logger.error(f"PHASE 3 [Chunking] Failed for {article_id}: {e}") await db.rollback()123456789101112131415161718192021222324import asynciofrom arq import create_poolfrom core.config import get_redis_settingsfrom core.database import async_session_factoryfrom sqlalchemy import selectfrom models.kb_article import KBArticle
async def run(): print("Connecting to Redis...") try: pool = await create_pool(get_redis_settings()) async with async_session_factory() as db: print("Finding articles...") res = await db.execute(select(KBArticle)) arts = res.scalars().all() for a in arts: print(f"Queueing: {a.title} ({a.id})") await pool.enqueue_job('index_kb_article', a.id) print("Done. All articles queued for re-indexing.") except Exception as e: print(f"Error: {e}")
if __name__ == "__main__": asyncio.run(run())api/v1/kb.py+49-63
core/cache.py+7-12
core/tasks.py+29-6
reindex_kb_v2.pyAdded+24