Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
4e16b54
1
Parent(s): cf95cd1
backend stabilization
Browse filesFiles changed (3)
170 unmodified lines17117217317417517686 unmodified lines2632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962971 unmodified line2993003013023033043051 unmodified line30730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334498 unmodified lines443444445446447448449450170 unmodified lineslogger.error(f"Query expansion failed: {e}")return []async def execute_multimodal_search(db: AsyncSession,q: str,86 unmodified linesif project_id: keyword_stmt = keyword_stmt.where(KBArticle.project_id == project_id)keyword_stmt = keyword_stmt.order_by(desc("kw_score")).limit(15)# --- Parallel Execution (ISOLATED SESSIONS) ---async def run_query(stmt):async with async_session_factory() as session:res = await session.execute(stmt)return res.all()# Launch 3-Branch Retrievalsem_task = run_query(semantic_stmt)vis_task = run_query(visual_stmt)kw_task = run_query(keyword_stmt)hits, v_hits, kw_hits = await asyncio.gather(sem_task, vis_task, kw_task)await record_workflow_step(db, search_id, current_user.workspace_id, "SEARCH","RETRIEVAL_COMPLETE",output_data={"semantic_hits": len(hits), "visual_hits": len(v_hits), "keyword_hits": len(kw_hits)},duration_ms=(time.perf_counter() - sem_start) * 1000)# 4. Hybrid Fusion (Weighted Reciprocal Rank Fusion)fusion_start = time.perf_counter()results_map = {}def apply_fusion(list_hits, weight, score_attr):for rank, row in enumerate(list_hits):art = row[0]chunk_txt = row[1] if len(row) > 2 else None # Only semantic hits have this# RRF formula with weightsrrf_score = weight * (1.0 / (60 + rank + 1))if art.id not in results_map:1 unmodified lineelse:results_map[art.id]["score"] += rrf_scoreresults_map[art.id]["types"].add(score_attr)# Keep the best chunk if we hit it again via keywordif not results_map[art.id]["chunk"] and chunk_txt:results_map[art.id]["chunk"] = chunk_txt1 unmodified lineapply_fusion(kw_hits, 0.3, "kw_score")apply_fusion(v_hits, 0.2, "vis_score")# Sort & Normalize to 100%sorted_results = sorted(results_map.values(), key=lambda x: x["score"], reverse=True)[:10]final_output = {}for r in sorted_results:art = r["obj"]# Normalize RRF to 100% (Theoretical max = 1.0/61 = 0.01639344)norm_score = min(((r["score"] / 0.01639344) * 100), 100.0)# Determine match type stringm_types = list(r["types"])m_type = "hybrid" if len(m_types) > 1 else m_types[0].replace("_score", "")final_output[art.id] = {"obj": art,"score": round(norm_score, 1),"type": m_type,"snippet": r["chunk"],"search_id": str(search_id)}await record_workflow_step(db, search_id, current_user.workspace_id, "SEARCH","HYBRID_FUSION_COMPLETE",output_data={"final_result_count": len(final_output)},duration_ms=(time.perf_counter() - fusion_start) * 1000,current_stage="RESULTS_DELIVERED")# Commit search workflowawait db.commit()return final_output@router.get("/search/", response_model=KBSearchResponse)98 unmodified linesarticle_obj = data["obj"]res_dict = KBArticleResponse.model_validate(article_obj).model_dump()res_dict["score"] = scoreres_dict["match_type"] = data.get("type", "semantic") # Safe access to avoid KeyErrorres_dict["snippet"] = data.get("snippet")final_results.append(res_dict)final_results.sort(key=lambda x: float(x.get("score") or 0.0), reverse=True)170 unmodified lines17117217317417517617717817918018118218318418518618718818919086 unmodified lines2772782792802812822832842852862872882892902912922932942952962972982993003011 unmodified line3033043053063073081 unmodified line31031131231331431531631731831932032132232332432532632732832933033133233398 unmodified lines432433434435436437438439440441170 unmodified lineslogger.error(f"Query expansion failed: {e}")return []def strip_markdown(text: str | None) -> str:"""Removes code blocks, bold, italics, and headers for a clean search snippet."""if not text: return ""import re# Remove code blockstext = re.sub(r'```[\s\S]*?```', '', text)# Remove inline codetext = re.sub(r'`.*?`', '', text)# Remove headings, bold, italicstext = re.sub(r'[#*>]', '', text)# Normalize whitespacetext = re.sub(r'\s+', ' ', text).strip()return textasync def execute_multimodal_search(db: AsyncSession,q: str,86 unmodified linesif project_id: keyword_stmt = keyword_stmt.where(KBArticle.project_id == project_id)keyword_stmt = keyword_stmt.order_by(desc("kw_score")).limit(15)# --- Parallel Execution ---async def run_query(stmt):async with async_session_factory() as session:res = await session.execute(stmt)return res.all()hits, v_hits, kw_hits = await asyncio.gather(run_query(semantic_stmt),run_query(visual_stmt),run_query(keyword_stmt))# 4. Hybrid Fusion (Weighted Reciprocal Rank Fusion)results_map = {}def apply_fusion(list_hits, weight, score_attr):for rank, row in enumerate(list_hits):art = row[0]chunk_txt = row[1] if len(row) > 1 and isinstance(row[1], str) else Nonerrf_score = weight * (1.0 / (60 + rank + 1))if art.id not in results_map:1 unmodified lineelse:results_map[art.id]["score"] += rrf_scoreresults_map[art.id]["types"].add(score_attr)if not results_map[art.id]["chunk"] and chunk_txt:results_map[art.id]["chunk"] = chunk_txt1 unmodified lineapply_fusion(kw_hits, 0.3, "kw_score")apply_fusion(v_hits, 0.2, "vis_score")sorted_results = sorted(results_map.values(), key=lambda x: x["score"], reverse=True)[:10]final_output = {}# MAX_POSSIBLE_SCORE = sum(weights) * (1/61) = 1.0 * (1/61) = 0.0163934426MAX_RRF = 0.0163934426for r in sorted_results:art = r["obj"]norm_score = min(((r["score"] / MAX_RRF) * 100), 100.0)final_output[art.id] = {"obj": art,"score": round(norm_score, 1),"type": "hybrid" if len(r["types"]) > 1 else list(r["types"])[0].replace("_score", ""),"snippet": strip_markdown(r["chunk"]),"search_id": str(search_id)}await db.commit()return final_output@router.get("/search/", response_model=KBSearchResponse)98 unmodified linesarticle_obj = data["obj"]res_dict = KBArticleResponse.model_validate(article_obj).model_dump()res_dict["score"] = scoreres_dict["match_type"] = data.get("type", "semantic")res_dict["snippet"] = data.get("snippet")# Defensive Cleanup: Strip markdown from historical summariesres_dict["summary"] = strip_markdown(article_obj.summary)final_results.append(res_dict)final_results.sort(key=lambda x: float(x.get("score") or 0.0), reverse=True)
305 unmodified lines306307308309310311312305 unmodified linestry:content_blocks = [{"type": "text", "text": content_txt}]if article_imgs: content_blocks.extend(article_imgs)prompt = [SystemMessage(content="Summarize this technical KB article in 2-3 sentences. Focus on clarity."), HumanMessage(content=content_blocks)]resp = await llm.ainvoke(prompt)article.summary = resp.contentexcept Exception as vision_err:305 unmodified lines306307308309310311312313314315305 unmodified linestry:content_blocks = [{"type": "text", "text": content_txt}]if article_imgs: content_blocks.extend(article_imgs)prompt = [SystemMessage(content="Summarize this technical KB article in 2-3 sentences. Focus on clarity. IMPORTANT: DO NOT include any code blocks, backticks, or raw technical snippets in the summary. Keep it plain text."),HumanMessage(content=content_blocks)]resp = await llm.ainvoke(prompt)article.summary = resp.contentexcept Exception as vision_err:
212 unmodified lines213214215216217218219212 unmodified linesconst isDownload = href?.includes('/download/');let decoratedHref = href;if (isDownload) {const token = localStorage.getItem('token') || localStorage.getItem('access_token');if (token) {const connector = href.includes('?') ? '&' : '?';212 unmodified lines213214215216217218219212 unmodified linesconst isDownload = href?.includes('/download/');let decoratedHref = href;if (isDownload && href) {const token = localStorage.getItem('token') || localStorage.getItem('access_token');if (token) {const connector = href.includes('?') ? '&' : '?';
api/v1/kb.py+30-39
core/tasks.py+4-1
frontend/packages/shared/src/components/NexusMarkdown.tsx+1-1