Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
4e16b54
1
Parent(s): cf95cd1
backend stabilization
Browse filesFiles changed (3)
170 unmodified lines17117217317417517617717817918018118218318418518618718818919086 unmodified lines2772782792662802812822832842852722732742752762772782792802812822832862872882892902852912922872932942952962972932942982993003011 unmodified line3033043053023063073081 unmodified line31031131231031331431531631731831932031631732131831932032132232232332432632732532632732832933133233333433533633733833933034133133233398 unmodified lines432433434446435436437438439440441170 unmodified lines logger.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 blocks text = re.sub(r'```[\s\S]*?```', '', text) # Remove inline code text = re.sub(r'`.*?`', '', text) # Remove headings, bold, italics text = re.sub(r'[#*>]', '', text) # Normalize whitespace text = re.sub(r'\s+', ' ', text).strip() return text
async def execute_multimodal_search( db: AsyncSession, q: str, 86 unmodified lines if 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) --- # --- Parallel Execution --- async def run_query(stmt): async with async_session_factory() as session: res = await session.execute(stmt) return res.all()
# Launch 3-Branch Retrieval sem_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 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) 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 weights chunk_txt = row[1] if len(row) > 1 and isinstance(row[1], str) else None rrf_score = weight * (1.0 / (60 + rank + 1)) if art.id not in results_map:1 unmodified line else: results_map[art.id]["score"] += rrf_score results_map[art.id]["types"].add(score_attr) # Keep the best chunk if we hit it again via keyword if not results_map[art.id]["chunk"] and chunk_txt: results_map[art.id]["chunk"] = chunk_txt
1 unmodified line apply_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 = {} # MAX_POSSIBLE_SCORE = sum(weights) * (1/61) = 1.0 * (1/61) = 0.0163934426 MAX_RRF = 0.0163934426 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) norm_score = min(((r["score"] / MAX_RRF) * 100), 100.0) # Determine match type string m_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"], "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 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 workflow await db.commit()
return final_output
@router.get("/search/", response_model=KBSearchResponse)98 unmodified lines article_obj = data["obj"] res_dict = KBArticleResponse.model_validate(article_obj).model_dump() res_dict["score"] = score res_dict["match_type"] = data.get("type", "semantic") # Safe access to avoid KeyError res_dict["match_type"] = data.get("type", "semantic") res_dict["snippet"] = data.get("snippet") # Defensive Cleanup: Strip markdown from historical summaries res_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 lines306307308309309310311312313314315305 unmodified lines try: 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)] 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.content except Exception as vision_err:212 unmodified lines213214215216216217218219212 unmodified lines const isDownload = href?.includes('/download/'); let decoratedHref = href;
if (isDownload) { 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