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 lines25125225325425525625715 unmodified lines27327427527627727827991 unmodified lines37137237337437537637737837938038138238338438538638738838939039139239339458 unmodified lines453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512250 unmodified linesKBArticle.is_published == True,# Broaden: Match if either the keywords hit OR similarity is decent(Attachment.search_vector.op("@@")(func.plainto_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.workspace_id == workspace_id))91 unmodified lineslogger.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('?') orany(q.lower().startswith(w) for w in ["how", "what", "where", "why", "who", "tell", "explain", "describe"]) orlen(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 docspass # We'll check again after doc retrieval# 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 linesdirect_answer = Noneis_ai_synthetic = Falseif 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 LLMcontext_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.contentis_ai_synthetic = True# Persist to Semantic Cacheasyncio.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:is_ai_synthetic = True# 5. Suggestion for UI if results are still thinsuggestion = expanded_queries[0] if expanded_queries and expanded_queries[0].lower() != q.lower() else Noneend_time = time.perf_counter()search_time_s = end_time - start_timeres_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,"search_time_s": round(search_time_s, 3)}250 unmodified lines25125225325425525625715 unmodified lines27327427527627727827991 unmodified lines37137237337437537637737837938038138238338438538638738838939058 unmodified lines449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498250 unmodified linesKBArticle.is_published == True,# Broaden: Match if either the keywords hit OR similarity is decent(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.websearch_to_tsquery('english', q)),KBArticle.workspace_id == workspace_id))91 unmodified lineslogger.info(f"⚡ Search Cache HIT [KB]: {q}")return cached_res# 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 linesdirect_answer = Noneis_ai_synthetic = False# 4.5 Synthesis Branch (The "Full RAG" Pathway)direct_answer = Noneis_ai_synthetic = False# Trigger synthesis if any hit is high confidence (>0.6) or it's a multi-word queryhigh_confidence = any(r.get("score", 0.0) > 0.6 for r in top_results)should_synthesize = high_confidence or len(q.split()) >= 3if 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)])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.contentis_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. Final Response Payloadend_time = time.perf_counter()search_time_s = end_time - start_timeres_data = {"results": top_results,"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 lines6465666768697017 unmodified lines888990919293949596971 unmodified line9910010110210310410510610 unmodified lines11711811912012112212312 unmodified lines13613713813914014114214314414514614763 unmodified lines"""@staticmethodasync def check_cache(workspace_id: str, query: str, is_agent: bool, user_role: str, user_id: str) -> Optional[str]:from core.llm import get_embeddingsfrom core.database import async_session_factoryfrom models.nexus_semantic_cache import NexusSemanticCache17 unmodified linesNexusSemanticCache.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).order_by("distance").limit(1)1 unmodified lineres = await db.execute(stmt)row = res.first()# Check for > 0.95 similarity (distance < 0.05)if row and row.distance < 0.05:cache_hit = row[0]# Update hit count10 unmodified linesreturn None@staticmethodasync def set_cache(workspace_id: str, user_id: str, query: str, response_text: str, is_agent: bool, user_role: str):from core.llm import get_embeddingsfrom core.database import async_session_factoryfrom models.nexus_semantic_cache import NexusSemanticCache12 unmodified linesasync with async_session_factory() as db:cache_entry = NexusSemanticCache(workspace_id=workspace_id,user_id=user_id,query_text=query,query_embedding=query_vector,response_text=response_text,is_agent=is_agent,user_role=user_role)db.add(cache_entry)await db.commit()63 unmodified lines6465666768697017 unmodified lines888990919293941 unmodified line9697989910010110210310 unmodified lines11411511611711811912012 unmodified lines13313413513613713813914014114263 unmodified lines"""@staticmethodasync def check_cache(workspace_id: str, query: str) -> Optional[str]:from core.llm import get_embeddingsfrom core.database import async_session_factoryfrom models.nexus_semantic_cache import NexusSemanticCache17 unmodified linesNexusSemanticCache.query_embedding.cosine_distance(query_vector).label("distance")).where(NexusSemanticCache.workspace_id == workspace_id).order_by("distance").limit(1)1 unmodified lineres = await db.execute(stmt)row = res.first()# Check for > 0.90 similarity (distance < 0.10) - slightly more permissiveif row and row.distance < 0.10:cache_hit = row[0]# Update hit count10 unmodified linesreturn None@staticmethodasync def set_cache(workspace_id: str, user_id: str, query: str, response_text: str):from core.llm import get_embeddingsfrom core.database import async_session_factoryfrom models.nexus_semantic_cache import NexusSemanticCache12 unmodified linesasync with async_session_factory() as db:cache_entry = NexusSemanticCache(workspace_id=workspace_id,user_id=user_id, # Keep user_id in record for audit, but not lookupquery_text=query,query_embedding=query_vector,response_text=response_text)db.add(cache_entry)await db.commit()
196 unmodified lines197198199200201202203204205206207208209210211212213214196 unmodified linesexcept 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 ---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)db.add(new_chunk)if await _abort_if_deleted(): returnawait db.commit()await db.refresh(article)logger.info(f"PHASE 3 [Chunking] Complete for {article_id} ({len(chunks)} chunks)")except Exception as e:logger.error(f"PHASE 3 [Chunking] Failed for {article_id}: {e}")await db.rollback()196 unmodified lines197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237196 unmodified linesexcept Exception as e:logger.error(f"PHASE 2 [Embeddings] Failed for {article_id} (Length: {len(text_to_embed)}): {str(e)}")# --- PHASE 3: Chunking & Architecture Enrichment ---try:await db.execute(delete(KBArticleChunk).where(KBArticleChunk.article_id == article_id))raw_chunks = chunk_text(article.content, chunk_size=1200, chunk_overlap=100)for i, text_content in enumerate(raw_chunks):# Architecture Enrichment Stepprocessed_text = text_contentif "```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_contentexcept 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(): returnawait db.commit()await db.refresh(article)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