Spaces:
Paused

dushyantsingh0 commited on
Commit
2d0e9e3
·
1 Parent(s): 837cc5f

backend stabilization

Browse files
Files changed (4) hide show
  1. api/v1/kb.py +49 -63
  2. core/cache.py +7 -12
  3. core/tasks.py +29 -6
  4. reindex_kb_v2.py +24 -0
api/v1/kb.py CHANGED
@@ -251,7 +251,7 @@ async def execute_multimodal_search(
251
  KBArticle.is_published == True,
252
  # Broaden: Match if either the keywords hit OR similarity is decent
253
  (
254
- Attachment.search_vector.op("@@")(func.plainto_tsquery('english', q)) |
255
  (func.similarity(Attachment.ai_caption, q) > 0.3)
256
  ),
257
  KBArticle.workspace_id == workspace_id
@@ -273,7 +273,7 @@ async def execute_multimodal_search(
273
  .where(
274
  KBArticle.deleted_at.is_(None),
275
  KBArticle.is_published == True,
276
- KBArticle.search_vector.op("@@")(func.plainto_tsquery('english', q)),
277
  KBArticle.workspace_id == workspace_id
278
  )
279
  )
@@ -371,24 +371,20 @@ async def search_kb_articles(
371
  logger.info(f"⚡ Search Cache HIT [KB]: {q}")
372
  return cached_res
373
 
374
- # 0.5 Semantic Cache Check for pin-point Answer (if meaningful query)
375
- is_question = (
376
- q.strip().endswith('?') or
377
- any(q.lower().startswith(w) for w in ["how", "what", "where", "why", "who", "tell", "explain", "describe"]) or
378
- len(q.strip().split()) >= 5 # Broaden to multi-word technical queries like "Data models"
379
- )
380
- if is_question:
381
- sem_answer = await SemanticCacheManager.check_cache(
382
- str(target_ws), q,
383
- is_agent=(current_user.role in ALL_SC_ROLES),
384
- user_role=current_user.role.value if hasattr(current_user.role, 'value') else str(current_user.role),
385
- user_id=str(current_user.id)
386
- )
387
- if sem_answer:
388
- logger.info(f"🧠 Semantic Cache HIT [KB]: {q}")
389
- # Still need the document results, but we'll return the answer from cache
390
- # For speed, if we have a semantic answer, we might still want to refresh the docs
391
- pass # We'll check again after doc retrieval
392
 
393
  # 1. Start Original Search Branch IMMEDIATELY (Don't wait for LLM)
394
  original_search_task = execute_multimodal_search(db, q, current_user, category, project_id, workspace_id=target_ws)
@@ -453,60 +449,50 @@ async def search_kb_articles(
453
  direct_answer = None
454
  is_ai_synthetic = False
455
 
456
- if is_question and top_results:
457
- # Check semantic cache first (redundant but safe)
458
- direct_answer = await SemanticCacheManager.check_cache(
459
- str(current_user.workspace_id), q,
460
- is_agent=(current_user.role in ALL_SC_ROLES),
461
- user_role=current_user.role.value if hasattr(current_user.role, 'value') else str(current_user.role),
462
- user_id=str(current_user.id)
463
- )
464
-
465
- if not direct_answer:
466
- # Construct context from TOP RAW CHUNKS (High Fidelity)
467
- # We use the raw chunks to ensure mermaid/technical diagrams are visible to the LLM
468
  context_txt = "\n\n".join([
469
  f"DOC {i+1} [{r['title']}]:\n---\n{r.get('raw_chunk') or r.get('snippet') or r['content'][:500]}\n---"
470
  for i, r in enumerate(top_results)
471
  ])
472
- try:
473
- llm = get_llm()
474
- prompt = [
475
- SystemMessage(content=(
476
- "You are a technical support architect. Provide a high-precision direct answer based ONLY on the provided documentation context. "
477
- "The context may contain Mermaid diagrams or code blocks; interpret them to explain flows or logic. "
478
- "Structure your answer with clear bullet points if describing a sequence. "
479
- "If the answer isn't firmly supported by the context, admit you don't know."
480
- )),
481
- HumanMessage(content=f"Context:\n{context_txt}\n\nQuestion: {q}")
482
- ]
483
- synth_resp = await llm.ainvoke(prompt)
484
- direct_answer = synth_resp.content
485
- is_ai_synthetic = True
486
-
487
- # Persist to Semantic Cache
488
- asyncio.create_task(SemanticCacheManager.set_cache(
489
- str(target_ws), str(current_user.id), q, direct_answer,
490
- is_agent=(current_user.role in ALL_SC_ROLES),
491
- user_role=current_user.role.value if hasattr(current_user.role, 'value') else str(current_user.role)
492
- ))
493
- except Exception as e:
494
- logger.error(f"Synthesis failed: {e}")
495
- else:
496
  is_ai_synthetic = True
 
 
 
 
 
497
 
498
- # 5. Suggestion for UI if results are still thin
499
- suggestion = expanded_queries[0] if expanded_queries and expanded_queries[0].lower() != q.lower() else None
500
-
501
  end_time = time.perf_counter()
502
  search_time_s = end_time - start_time
503
 
504
  res_data = {
505
  "results": top_results,
506
- "answer": direct_answer,
507
- "is_ai_synthetic": is_ai_synthetic,
508
- "suggestion": suggestion if not top_results else None,
509
- "expanded_queries": expanded_queries,
510
  "search_time_s": round(search_time_s, 3)
511
  }
512
 
 
251
  KBArticle.is_published == True,
252
  # Broaden: Match if either the keywords hit OR similarity is decent
253
  (
254
+ Attachment.search_vector.op("@@")(func.websearch_to_tsquery('english', q)) |
255
  (func.similarity(Attachment.ai_caption, q) > 0.3)
256
  ),
257
  KBArticle.workspace_id == workspace_id
 
273
  .where(
274
  KBArticle.deleted_at.is_(None),
275
  KBArticle.is_published == True,
276
+ KBArticle.search_vector.op("@@")(func.websearch_to_tsquery('english', q)),
277
  KBArticle.workspace_id == workspace_id
278
  )
279
  )
 
371
  logger.info(f"⚡ Search Cache HIT [KB]: {q}")
372
  return cached_res
373
 
374
+ # 0.5 Semantic Cache Check (Unified Workspace Knowledge)
375
+ sem_answer = await SemanticCacheManager.check_cache(str(target_ws), q)
376
+ if sem_answer:
377
+ logger.info(f"🧠 Semantic Cache HIT [KB]: {q}")
378
+ # Process and return immediately with cache marker
379
+ # We still run a minimal doc retrieval in background if needed (skipped for now for speed)
380
+ return {
381
+ "aiAnswer": sem_answer,
382
+ "results": [], # Or could fetch top docs if UI requires
383
+ "isSynthetic": True,
384
+ "cacheHit": True,
385
+ "confidence": 1.0,
386
+ "durationMs": (time.perf_counter() - start_time) * 1000
387
+ }
 
 
 
 
388
 
389
  # 1. Start Original Search Branch IMMEDIATELY (Don't wait for LLM)
390
  original_search_task = execute_multimodal_search(db, q, current_user, category, project_id, workspace_id=target_ws)
 
449
  direct_answer = None
450
  is_ai_synthetic = False
451
 
452
+ # 4.5 Synthesis Branch (The "Full RAG" Pathway)
453
+ direct_answer = None
454
+ is_ai_synthetic = False
455
+
456
+ # Trigger synthesis if any hit is high confidence (>0.6) or it's a multi-word query
457
+ high_confidence = any(r.get("score", 0.0) > 0.6 for r in top_results)
458
+ should_synthesize = high_confidence or len(q.split()) >= 3
459
+
460
+ if should_synthesize and top_results:
461
+ try:
462
+ # Construct context from TOP RAW CHUNKS (Fidelity + Enrichment)
 
463
  context_txt = "\n\n".join([
464
  f"DOC {i+1} [{r['title']}]:\n---\n{r.get('raw_chunk') or r.get('snippet') or r['content'][:500]}\n---"
465
  for i, r in enumerate(top_results)
466
  ])
467
+
468
+ llm = get_llm()
469
+ prompt = [
470
+ SystemMessage(content=(
471
+ "You are a technical support architect. Provide a high-precision direct answer based ONLY on the provided documentation context. "
472
+ "Look for [TEK_NAV] tags for navigational context in diagrams. "
473
+ "Structure your answer with clear bullet points. If unsure, say you don't know."
474
+ )),
475
+ HumanMessage(content=f"Context:\n{context_txt}\n\nQuestion: {q}")
476
+ ]
477
+ synth_resp = await llm.ainvoke(prompt)
478
+ direct_answer = synth_resp.content
 
 
 
 
 
 
 
 
 
 
 
 
479
  is_ai_synthetic = True
480
+
481
+ # Persist to Semantic Cache (Workspace-Unified)
482
+ await SemanticCacheManager.set_cache(str(target_ws), str(current_user.id), q, direct_answer)
483
+ except Exception as e:
484
+ logger.error(f"Synthesis failed: {e}")
485
 
486
+ # 5. Final Response Payload
 
 
487
  end_time = time.perf_counter()
488
  search_time_s = end_time - start_time
489
 
490
  res_data = {
491
  "results": top_results,
492
+ "aiAnswer": direct_answer,
493
+ "isSynthetic": is_ai_synthetic,
494
+ "confidence": top_results[0].get("score") if top_results else 0.0,
495
+ "suggestion": expanded_queries[0] if expanded_queries and expanded_queries[0].lower() != q.lower() and not top_results else None,
496
  "search_time_s": round(search_time_s, 3)
497
  }
498
 
core/cache.py CHANGED
@@ -64,7 +64,7 @@ class SemanticCacheManager:
64
  """
65
 
66
  @staticmethod
67
- async def check_cache(workspace_id: str, query: str, is_agent: bool, user_role: str, user_id: str) -> Optional[str]:
68
  from core.llm import get_embeddings
69
  from core.database import async_session_factory
70
  from models.nexus_semantic_cache import NexusSemanticCache
@@ -88,10 +88,7 @@ class SemanticCacheManager:
88
  NexusSemanticCache.query_embedding.cosine_distance(query_vector).label("distance")
89
  )
90
  .where(
91
- NexusSemanticCache.workspace_id == workspace_id,
92
- NexusSemanticCache.is_agent == is_agent,
93
- NexusSemanticCache.user_role == user_role,
94
- NexusSemanticCache.user_id == user_id # Strict Identity Partitioning
95
  )
96
  .order_by("distance")
97
  .limit(1)
@@ -99,8 +96,8 @@ class SemanticCacheManager:
99
  res = await db.execute(stmt)
100
  row = res.first()
101
 
102
- # Check for > 0.95 similarity (distance < 0.05)
103
- if row and row.distance < 0.05:
104
  cache_hit = row[0]
105
 
106
  # Update hit count
@@ -117,7 +114,7 @@ class SemanticCacheManager:
117
  return None
118
 
119
  @staticmethod
120
- async def set_cache(workspace_id: str, user_id: str, query: str, response_text: str, is_agent: bool, user_role: str):
121
  from core.llm import get_embeddings
122
  from core.database import async_session_factory
123
  from models.nexus_semantic_cache import NexusSemanticCache
@@ -136,12 +133,10 @@ class SemanticCacheManager:
136
  async with async_session_factory() as db:
137
  cache_entry = NexusSemanticCache(
138
  workspace_id=workspace_id,
139
- user_id=user_id,
140
  query_text=query,
141
  query_embedding=query_vector,
142
- response_text=response_text,
143
- is_agent=is_agent,
144
- user_role=user_role
145
  )
146
  db.add(cache_entry)
147
  await db.commit()
 
64
  """
65
 
66
  @staticmethod
67
+ async def check_cache(workspace_id: str, query: str) -> Optional[str]:
68
  from core.llm import get_embeddings
69
  from core.database import async_session_factory
70
  from models.nexus_semantic_cache import NexusSemanticCache
 
88
  NexusSemanticCache.query_embedding.cosine_distance(query_vector).label("distance")
89
  )
90
  .where(
91
+ NexusSemanticCache.workspace_id == workspace_id
 
 
 
92
  )
93
  .order_by("distance")
94
  .limit(1)
 
96
  res = await db.execute(stmt)
97
  row = res.first()
98
 
99
+ # Check for > 0.90 similarity (distance < 0.10) - slightly more permissive
100
+ if row and row.distance < 0.10:
101
  cache_hit = row[0]
102
 
103
  # Update hit count
 
114
  return None
115
 
116
  @staticmethod
117
+ async def set_cache(workspace_id: str, user_id: str, query: str, response_text: str):
118
  from core.llm import get_embeddings
119
  from core.database import async_session_factory
120
  from models.nexus_semantic_cache import NexusSemanticCache
 
133
  async with async_session_factory() as db:
134
  cache_entry = NexusSemanticCache(
135
  workspace_id=workspace_id,
136
+ user_id=user_id, # Keep user_id in record for audit, but not lookup
137
  query_text=query,
138
  query_embedding=query_vector,
139
+ response_text=response_text
 
 
140
  )
141
  db.add(cache_entry)
142
  await db.commit()
core/tasks.py CHANGED
@@ -197,18 +197,41 @@ async def index_kb_article(ctx, article_id: UUID):
197
  except Exception as e:
198
  logger.error(f"PHASE 2 [Embeddings] Failed for {article_id} (Length: {len(text_to_embed)}): {str(e)}")
199
 
200
- # --- PHASE 3: Chunking & Search Vector Persistence ---
201
  try:
202
  await db.execute(delete(KBArticleChunk).where(KBArticleChunk.article_id == article_id))
203
- chunks = chunk_text(article.content, chunk_size=1200, chunk_overlap=100)
204
- for i, text in enumerate(chunks):
205
- chunk_vector = await text_model.aembed_query(f"{article.title}: {text}")
206
- new_chunk = KBArticleChunk(article_id=article.id, content=text, chunk_index=i, embedding=chunk_vector)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  db.add(new_chunk)
 
208
  if await _abort_if_deleted(): return
209
  await db.commit()
210
  await db.refresh(article)
211
- logger.info(f"PHASE 3 [Chunking] Complete for {article_id} ({len(chunks)} chunks)")
212
  except Exception as e:
213
  logger.error(f"PHASE 3 [Chunking] Failed for {article_id}: {e}")
214
  await db.rollback()
 
197
  except Exception as e:
198
  logger.error(f"PHASE 2 [Embeddings] Failed for {article_id} (Length: {len(text_to_embed)}): {str(e)}")
199
 
200
+ # --- PHASE 3: Chunking & Architecture Enrichment ---
201
  try:
202
  await db.execute(delete(KBArticleChunk).where(KBArticleChunk.article_id == article_id))
203
+ raw_chunks = chunk_text(article.content, chunk_size=1200, chunk_overlap=100)
204
+
205
+ for i, text_content in enumerate(raw_chunks):
206
+ # Architecture Enrichment Step
207
+ processed_text = text_content
208
+ if "```mermaid" in text_content.lower() or "```json" in text_content.lower() or "graph " in text_content[:50].lower():
209
+ try:
210
+ logger.info(f"Technical block detected in chunk {i} of {article_id}. Generating TEK_NAV...")
211
+ enrich_prompt = (
212
+ f"Explain this technical block in ONE concise sentence for search indexing. "
213
+ f"Identify what the flow/data represents.\n\nBLOCK:\n{text_content[:2000]}"
214
+ )
215
+ enrich_res = await llm.ainvoke(enrich_prompt)
216
+ if enrich_res and enrich_res.content:
217
+ nav_tag = f"[TEK_NAV: {enrich_res.content.strip()}]\n"
218
+ processed_text = nav_tag + text_content
219
+ except Exception as enrich_err:
220
+ logger.warning(f"Architecture Enrichment failed for chunk {i}: {enrich_err}")
221
+
222
+ chunk_vector = await text_model.aembed_query(f"{article.title}: {processed_text}")
223
+ new_chunk = KBArticleChunk(
224
+ article_id=article.id,
225
+ content=processed_text,
226
+ chunk_index=i,
227
+ embedding=chunk_vector
228
+ )
229
  db.add(new_chunk)
230
+
231
  if await _abort_if_deleted(): return
232
  await db.commit()
233
  await db.refresh(article)
234
+ logger.info(f"PHASE 3 [Enrichment] Complete for {article_id} ({len(raw_chunks)} chunks)")
235
  except Exception as e:
236
  logger.error(f"PHASE 3 [Chunking] Failed for {article_id}: {e}")
237
  await db.rollback()
reindex_kb_v2.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from arq import create_pool
3
+ from core.config import get_redis_settings
4
+ from core.database import async_session_factory
5
+ from sqlalchemy import select
6
+ from models.kb_article import KBArticle
7
+
8
+ async def run():
9
+ print("Connecting to Redis...")
10
+ try:
11
+ pool = await create_pool(get_redis_settings())
12
+ async with async_session_factory() as db:
13
+ print("Finding articles...")
14
+ res = await db.execute(select(KBArticle))
15
+ arts = res.scalars().all()
16
+ for a in arts:
17
+ print(f"Queueing: {a.title} ({a.id})")
18
+ await pool.enqueue_job('index_kb_article', a.id)
19
+ print("Done. All articles queued for re-indexing.")
20
+ except Exception as e:
21
+ print(f"Error: {e}")
22
+
23
+ if __name__ == "__main__":
24
+ asyncio.run(run())