Spaces:
Paused
Paused
Download api/v1/kb.py from TeamError404/nexus: direct link, hf CLI and curl.
- Browser
- Download file 30.3 kB
-
https://huggingface.co/spaces/TeamError404/nexus/resolve/main/api/v1/kb.py
- Command line
-
hf download hf://spaces/TeamError404/nexus/api/v1/kb.py
-
curl -L -o kb.py https://huggingface.co/spaces/TeamError404/nexus/resolve/main/api/v1/kb.py
30.3 kB
| import asyncio | |
| import time | |
| from datetime import datetime | |
| from typing import Any, List, Optional | |
| from uuid import UUID | |
| from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy import select, func, text, desc, update | |
| from core.database import async_session_factory | |
| from core.deps import get_db, get_current_user, get_arq_pool | |
| from core.permissions import require_roles, ALL_SC_ROLES | |
| from core.logging import get_logger | |
| from models.user import User, UserRole | |
| from models.kb_article import KBArticle | |
| from models.kb_article_chunk import KBArticleChunk | |
| from models.project import Project | |
| from core.llm import get_embeddings, get_llm, get_text_embeddings | |
| from core.vision import resolve_image | |
| from langchain.schema import HumanMessage, SystemMessage | |
| from models.attachment import Attachment | |
| from core.search import chunk_text | |
| from core.vision import extract_visual_context | |
| from core.sync import sync_markdown_images | |
| from models.user_workspace import UserWorkspace | |
| from core.cache import generate_cache_key, get_cached_search, set_cached_search, SemanticCacheManager | |
| from schemas.kb import KBArticleCreate, KBArticleResponse, KBArticleUpdate, KBSearchResponse, KBBulkActionRequest, KBBulkSyncRequest | |
| router = APIRouter() | |
| logger = get_logger(__name__) | |
| # AI Lifecycle is now handled by arq worker task: index_kb_article | |
| async def create_kb_article( | |
| payload: KBArticleCreate, | |
| background_tasks: BackgroundTasks, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db), | |
| arq_pool: Any = Depends(get_arq_pool) | |
| ) -> Any: | |
| """Agents/Admin only: create a KB article.""" | |
| # 1. Validate project_id if provided | |
| if payload.project_id: | |
| proj_stmt = select(Project).where( | |
| Project.id == payload.project_id, | |
| Project.workspace_id == current_user.workspace_id, | |
| Project.deleted_at.is_(None) | |
| ) | |
| proj_res = (await db.execute(proj_stmt)).scalar_one_or_none() | |
| if not proj_res: | |
| raise HTTPException( | |
| status_code=400, | |
| detail=f"Project {payload.project_id} not found in your workspace" | |
| ) | |
| new_article = KBArticle( | |
| title=payload.title, | |
| content=payload.content, | |
| category=payload.category, | |
| project_id=payload.project_id, | |
| workspace_id=current_user.workspace_id, | |
| author_id=current_user.id | |
| ) | |
| db.add(new_article) | |
| await db.commit() | |
| await db.refresh(new_article) | |
| # Unified ARQ Indexing Lifecycle (Categorization, Embedding, Chunking, Summary) | |
| await arq_pool.enqueue_job("index_kb_article", new_article.id) | |
| logger.info(f"KB Article created and enqueued: {new_article.id} by user {current_user.id}") | |
| return new_article | |
| async def list_kb_articles( | |
| category: str = None, | |
| workspace_id: Optional[str] = None, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| """List KB articles (Many-to-Many).""" | |
| # 1. Global Visibility for Super Admin | |
| is_global = (workspace_id == "all" and current_user.role == UserRole.SC_ADMIN) | |
| stmt = select(KBArticle).where( | |
| KBArticle.deleted_at.is_(None), | |
| KBArticle.duplicate_of_id.is_(None) | |
| ) | |
| if not is_global: | |
| target_ws = current_user.workspace_id | |
| if workspace_id and current_user.role in ALL_SC_ROLES: | |
| if current_user.role == UserRole.SC_ADMIN: | |
| target_ws = workspace_id | |
| else: | |
| ws_check = await db.execute( | |
| select(UserWorkspace).where( | |
| UserWorkspace.user_id == current_user.id, | |
| UserWorkspace.workspace_id == workspace_id | |
| ) | |
| ) | |
| if ws_check.scalar_one_or_none(): | |
| target_ws = workspace_id | |
| stmt = stmt.where(KBArticle.workspace_id == target_ws) | |
| if category: | |
| if category == "N/A": | |
| stmt = stmt.where(KBArticle.category.is_(None)) | |
| else: | |
| stmt = stmt.where(KBArticle.category == category) | |
| result = await db.execute(stmt) | |
| return result.scalars().all() | |
| async def list_kb_categories( | |
| workspace_id: Optional[str] = None, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| """Retrieve all unique categories in use (Many-to-Many).""" | |
| # 1. Global Visibility for Super Admin | |
| is_global = (workspace_id == "all" and current_user.role == UserRole.SC_ADMIN) | |
| stmt = select(func.distinct(KBArticle.category)).where( | |
| KBArticle.deleted_at.is_(None) | |
| ) | |
| if not is_global: | |
| target_ws = current_user.workspace_id | |
| if workspace_id and current_user.role in ALL_SC_ROLES: | |
| if current_user.role == UserRole.SC_ADMIN: | |
| target_ws = workspace_id | |
| else: | |
| ws_check = await db.execute( | |
| select(UserWorkspace).where( | |
| UserWorkspace.user_id == current_user.id, | |
| UserWorkspace.workspace_id == workspace_id | |
| ) | |
| ) | |
| if ws_check.scalar_one_or_none(): | |
| target_ws = workspace_id | |
| stmt = stmt.where(KBArticle.workspace_id == target_ws) | |
| result = await db.execute(stmt) | |
| categories = [c for c in result.scalars().all()] | |
| # Normalize nulls to "N/A" | |
| normalized = sorted([c if c else "N/A" for c in categories]) | |
| return normalized | |
| async def generate_query_variations(query: str) -> List[str]: | |
| """Uses LLM to generate variations of the search query for better hit coverage.""" | |
| # Fast-path for extremely short queries | |
| if len(query.strip()) < 3: | |
| return [] | |
| try: | |
| llm = get_llm() | |
| # Slimmed prompt for faster Ollama generation | |
| prompt = ( | |
| f"Generate 3 short search variations for: '{query}'. " | |
| f"Return ONLY the variations, one per line, no numbering." | |
| ) | |
| resp = await llm.ainvoke(prompt) | |
| text = resp.content if hasattr(resp, "content") else str(resp) | |
| vars = [v.strip() for v in text.split("\n") if v.strip() and v.strip() != query] | |
| return vars[:3] | |
| except Exception as e: | |
| logger.error(f"Query expansion failed: {e}") | |
| return [] | |
| def strip_markdown(text: str | None) -> str: | |
| """Removes code blocks, bold, italics, tables, 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 markdown table structure (pipes and continuous dashes) | |
| text = re.sub(r'\|', ' ', text) | |
| text = re.sub(r'^-{3,}$', ' ', text, flags=re.MULTILINE) | |
| text = re.sub(r'^\s*[-:]{3,}\s*$', ' ', text, flags=re.MULTILINE) | |
| # 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, | |
| current_user: User, | |
| category: Optional[str], | |
| project_id: Optional[UUID], | |
| workspace_id: UUID | |
| ): | |
| """Internal helper to execute factual hybrid search + visual attachment search.""" | |
| import uuid | |
| import time | |
| from core.observability import record_workflow_step | |
| search_id = uuid.uuid4() | |
| start_time = time.perf_counter() | |
| # 1. Get Text Embedding for the query (Nomic-768) | |
| embed_start = time.perf_counter() | |
| query_vector = await get_text_embeddings().aembed_query(q) | |
| await record_workflow_step( | |
| db, search_id, current_user.workspace_id, "SEARCH", | |
| "QUERY_EMBEDDING", | |
| input_data={"q": q}, | |
| duration_ms=(time.perf_counter() - embed_start) * 1000 | |
| ) | |
| # 2. SEACH A: Text Semantic Match (Articles) | |
| sem_start = time.perf_counter() | |
| semantic_stmt = ( | |
| select( | |
| KBArticle, | |
| KBArticleChunk.content, | |
| (1 - KBArticleChunk.embedding.cosine_distance(query_vector)).label("sim_score") | |
| ) | |
| .join(KBArticleChunk, KBArticle.id == KBArticleChunk.article_id) | |
| .where( | |
| KBArticle.deleted_at.is_(None), | |
| KBArticle.is_published == True, | |
| KBArticle.duplicate_of_id.is_(None), | |
| KBArticle.workspace_id == workspace_id | |
| ) | |
| ) | |
| if category: semantic_stmt = semantic_stmt.where(KBArticle.category == category) | |
| if project_id: semantic_stmt = semantic_stmt.where(KBArticle.project_id == project_id) | |
| semantic_stmt = semantic_stmt.order_by(desc("sim_score")).limit(20) | |
| # 3. SEARCH B: Visual Caption Match (Attachments) | |
| # Uses pg_trgm for fuzzy similarity + search_vector for keyword relevance | |
| vis_start = time.perf_counter() | |
| visual_stmt = ( | |
| select( | |
| KBArticle, | |
| ( | |
| func.ts_rank(Attachment.search_vector, func.plainto_tsquery('english', q)) + | |
| func.similarity(Attachment.ai_caption, q) | |
| ).label("vis_score") | |
| ) | |
| .join(Attachment, KBArticle.id == Attachment.article_id) | |
| .where( | |
| KBArticle.deleted_at.is_(None), | |
| KBArticle.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_id | |
| ) | |
| ) | |
| visual_stmt = visual_stmt.order_by(desc("vis_score")).limit(10) | |
| # 4. SEARCH C: Keyword Match (FTS with Title Boost) | |
| # Optimized for short queries: Uses ts_rank_cd + Head-of-Document boost | |
| from sqlalchemy import case | |
| kw_start = time.perf_counter() | |
| keyword_stmt = ( | |
| select( | |
| KBArticle, | |
| ( | |
| func.ts_rank_cd(KBArticle.search_vector, func.websearch_to_tsquery('english', q)) + | |
| case((KBArticle.title.ilike(f"%{q}%"), 0.5), else_=0.0) | |
| ).label("kw_score") | |
| ) | |
| .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 | |
| ) | |
| ) | |
| if category: keyword_stmt = keyword_stmt.where(KBArticle.category == category) | |
| 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 --- | |
| 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): | |
| # Best-Hit Deduplication: Ensure an article only scores once per search branch | |
| seen_in_branch = set() | |
| for rank, row in enumerate(list_hits): | |
| art = row[0] | |
| if art.id in seen_in_branch: | |
| continue | |
| seen_in_branch.add(art.id) | |
| 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: | |
| results_map[art.id] = {"obj": art, "score": rrf_score, "types": {score_attr}, "chunk": chunk_txt, "raw_chunk": chunk_txt} | |
| else: | |
| results_map[art.id]["score"] += rrf_score | |
| results_map[art.id]["types"].add(score_attr) | |
| if not results_map[art.id]["raw_chunk"] and chunk_txt: | |
| results_map[art.id]["raw_chunk"] = chunk_txt | |
| if not results_map[art.id]["chunk"] and chunk_txt: | |
| results_map[art.id]["chunk"] = chunk_txt | |
| apply_fusion(hits, 0.5, "sim_score") | |
| apply_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.0163934426 | |
| MAX_RRF = 0.0163934426 | |
| for 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"]), | |
| "raw_chunk": r.get("raw_chunk"), | |
| "search_id": str(search_id) | |
| } | |
| await db.commit() | |
| return final_output | |
| async def search_kb_articles( | |
| q: str, | |
| category: Optional[str] = None, | |
| project_id: Optional[UUID] = None, | |
| workspace_id: Optional[UUID] = None, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| """Advanced Search with LLM Multi-Query Expansion for maximum reliability.""" | |
| start_time = time.perf_counter() | |
| target_ws = current_user.workspace_id | |
| if workspace_id and current_user.role in ALL_SC_ROLES: | |
| if current_user.role == UserRole.SC_ADMIN: | |
| target_ws = workspace_id | |
| else: | |
| ws_check = await db.execute( | |
| select(UserWorkspace).where( | |
| UserWorkspace.user_id == current_user.id, | |
| UserWorkspace.workspace_id == workspace_id | |
| ) | |
| ) | |
| if ws_check.scalar_one_or_none(): | |
| target_ws = workspace_id | |
| # 0. Local Search Cache Lookup (Dual-Redis Architecture) | |
| cache_filters = {"category": category, "project_id": str(project_id) if project_id else None} | |
| cache_key = generate_cache_key("kb", str(target_ws), q, cache_filters) | |
| cached_res = await get_cached_search(cache_key) | |
| if cached_res: | |
| logger.info(f"⚡ Search Cache HIT [KB]: {q}") | |
| return cached_res | |
| # 0.5 Semantic Cache Check (Unified Workspace Knowledge) | |
| sem_answer = await SemanticCacheManager.check_cache( | |
| workspace_id=str(target_ws), | |
| query=q, | |
| is_agent=current_user.role in ALL_SC_ROLES, | |
| user_role=str(current_user.role), | |
| user_id=str(current_user.id) | |
| ) | |
| 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. Execute Original Search | |
| orig_res = await execute_multimodal_search( | |
| db, q, current_user, category, project_id, target_ws | |
| ) | |
| all_local_results = [orig_res] | |
| expanded_queries = [] | |
| # 2. Performance Optimization: High Confidence Early Exit | |
| # If original search has a near-perfect match (>80%), skip expensive LLM variations | |
| max_orig_score = max([r["score"] for r in orig_res.values()]) if orig_res else 0.0 | |
| is_high_confidence = max_orig_score > 80.0 | |
| # Check if query is complex enough to warrant expansion (e.g., >3 words or technical) | |
| is_complex = len(q.split()) >= 3 or any(w in q.lower() for w in ["how", "why", "steps", "explain"]) | |
| if not is_high_confidence and is_complex and len(q.strip()) >= 5: | |
| # Launch AI expansion task | |
| expanded_queries = await generate_query_variations(q) | |
| if expanded_queries: | |
| # Launch searches for variations in parallel | |
| async def run_variation_search(v): | |
| async with async_session_factory() as session: | |
| return await execute_multimodal_search(session, v, current_user, category, project_id, workspace_id=target_ws) | |
| var_tasks = [run_variation_search(v) for v in expanded_queries if v != q] | |
| if var_tasks: | |
| var_results = await asyncio.gather(*var_tasks) | |
| all_local_results.extend(var_results) | |
| # 3. Global Fusion (RRF across all branches and variations) | |
| global_merged = {} | |
| for local_res in all_local_results: | |
| for art_id, data in local_res.items(): | |
| score = float(data.get("score") or 0.0) | |
| if art_id not in global_merged: | |
| global_merged[art_id] = data | |
| global_merged[art_id]["score"] = score # ensure it exists | |
| else: | |
| global_merged[art_id]["score"] = max(float(global_merged[art_id].get("score") or 0.0), score) | |
| # 4. Final Scoring & Thresholding | |
| THRESHOLD = 0.2 | |
| final_results = [] | |
| for art_id, data in global_merged.items(): | |
| score = float(data.get("score") or 0.0) | |
| if score >= THRESHOLD: | |
| 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") | |
| res_dict["snippet"] = data.get("snippet") | |
| res_dict["raw_chunk"] = data.get("raw_chunk") | |
| # 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) | |
| top_results = final_results[:5] | |
| # 4.5 Synthesis Branch (The "Direct Answer" Engine) | |
| direct_answer = None | |
| is_ai_synthetic = False | |
| # Trigger synthesis if it's a complex query or we have high confidence hits | |
| # This provides a quick "Direct Answer" summary of the top documentation | |
| if is_complex and top_results: | |
| try: | |
| from core.llm import get_llm | |
| from langchain_core.messages import SystemMessage, HumanMessage | |
| # Construct context from TOP CHUNKS | |
| 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 expert. Provide a concise, highly structured direct answer. " | |
| "Use MARKDOWN for the following:\n" | |
| "- Use **Bold** for key facts and product names.\n" | |
| "- Use `inline code` for technical terms, database names, or variables.\n" | |
| "- Use bulleted lists to cite evidence from provided documentation.\n" | |
| "If the answer is not in the context, be honest. Keep it under 150 words." | |
| )), | |
| HumanMessage(content=f"Question: {q}\n\nDocumentation Context:\n{context_txt}") | |
| ] | |
| synth_resp = await llm.ainvoke(prompt) | |
| direct_answer = synth_resp.content | |
| is_ai_synthetic = True | |
| # Asynchronously Cache to Semantic Cache | |
| await SemanticCacheManager.set_cache( | |
| workspace_id=str(target_ws), | |
| user_id=str(current_user.id), | |
| query=q, | |
| response_text=direct_answer, | |
| is_agent=current_user.role in ALL_SC_ROLES, | |
| user_role=str(current_user.role) | |
| ) | |
| except Exception as e: | |
| logger.error(f"Synthesis failed: {e}") | |
| # 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, | |
| "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, | |
| "expanded_queries": expanded_queries if expanded_queries else [], | |
| "search_time_s": round(search_time_s, 3) | |
| } | |
| # Save to Local Search Cache before returning (1 hour TTL) | |
| await set_cached_search(cache_key, res_data) | |
| return res_data | |
| async def get_kb_article( | |
| article_id: UUID, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| """Get a specific KB article.""" | |
| stmt = select(KBArticle).where( | |
| KBArticle.id == article_id, | |
| KBArticle.workspace_id == current_user.workspace_id, | |
| KBArticle.deleted_at.is_(None) | |
| ) | |
| result = await db.execute(stmt) | |
| article = result.scalar_one_or_none() | |
| if not article: | |
| raise HTTPException(status_code=404, detail="Article not found") | |
| return article | |
| async def update_kb_article( | |
| article_id: UUID, | |
| payload: KBArticleUpdate, | |
| background_tasks: BackgroundTasks, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db), | |
| arq_pool: Any = Depends(get_arq_pool) | |
| ) -> Any: | |
| """Agents/Admin only: update KB article details.""" | |
| stmt = select(KBArticle).where( | |
| KBArticle.id == article_id, | |
| KBArticle.workspace_id == current_user.workspace_id, | |
| KBArticle.deleted_at.is_(None) | |
| ) | |
| result = await db.execute(stmt) | |
| article = result.scalar_one_or_none() | |
| if not article: | |
| raise HTTPException(status_code=404, detail="Article not found") | |
| update_data = payload.model_dump(exclude_unset=True) | |
| # Validate project_id if it's being updated | |
| if "project_id" in update_data and update_data["project_id"] is not None: | |
| proj_stmt = select(Project).where( | |
| Project.id == update_data["project_id"], | |
| Project.deleted_at.is_(None) | |
| ) | |
| if current_user.role != UserRole.SC_ADMIN: | |
| proj_stmt = proj_stmt.where(Project.workspace_id == current_user.workspace_id) | |
| proj_res = (await db.execute(proj_stmt)).scalar_one_or_none() | |
| if not proj_res: | |
| raise HTTPException( | |
| status_code=400, | |
| detail=f"Project {update_data['project_id']} not found in your workspace" | |
| ) | |
| # Sync images if content is updated | |
| if "content" in update_data: | |
| # Corrected signature: (db, entity_id, workspace_id, content, entity_type, uploader_id) | |
| await sync_markdown_images(db, article.id, article.workspace_id, update_data["content"], entity_type="article", uploader_id=current_user.id) | |
| for field, value in update_data.items(): | |
| setattr(article, field, value) | |
| db.add(article) | |
| await db.commit() | |
| await db.refresh(article) | |
| # Unified ARQ Indexing Lifecycle (Re-index if content/title changed) | |
| if "content" in update_data or "title" in update_data: | |
| await arq_pool.enqueue_job("index_kb_article", article.id) | |
| logger.info(f"KB Article {article_id} updated, re-indexing enqueued...") | |
| return article | |
| async def delete_kb_article( | |
| article_id: UUID, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| """Agents/Admin only: Soft Delete a KB article.""" | |
| # Redundant Role Hardening: Capture any leakage from require_roles decorator | |
| if current_user.role not in ALL_SC_ROLES: | |
| raise HTTPException(status_code=403, detail="Only SC staff can manage the knowledge base") | |
| stmt = select(KBArticle).where( | |
| KBArticle.id == article_id, | |
| KBArticle.workspace_id == current_user.workspace_id, | |
| KBArticle.deleted_at.is_(None) | |
| ) | |
| result = await db.execute(stmt) | |
| article = result.scalar_one_or_none() | |
| if not article: | |
| raise HTTPException(status_code=404, detail="Article not found") | |
| from sqlalchemy import delete | |
| article.deleted_at = datetime.utcnow() | |
| article.deleted_by_id = current_user.id | |
| article.is_published = False | |
| # Cascade inactivation to attachments | |
| att_stmt = ( | |
| update(Attachment) | |
| .where(Attachment.article_id == article_id) | |
| .values(deleted_at=article.deleted_at) | |
| ) | |
| await db.execute(att_stmt) | |
| # Purge chunks | |
| await db.execute(delete(KBArticleChunk).where(KBArticleChunk.article_id == article_id)) | |
| db.add(article) | |
| await db.commit() | |
| logger.info(f"KB Article and children inactivated: {article_id} by user {current_user.id}") | |
| return {"status": "deleted"} | |
| async def bulk_publish_articles( | |
| payload: KBBulkSyncRequest, | |
| background_tasks: BackgroundTasks, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db), | |
| arq_pool: Any = Depends(get_arq_pool) | |
| ) -> Any: | |
| """Agents/Admin only: Bulk process (Create/Update) and Publish KB articles.""" | |
| results = {"created": 0, "updated": 0, "ids": []} | |
| processed_article_ids = set() | |
| for art_def in payload.articles: | |
| # Check for existing by title in this workspace, excluding what we've already processed in this batch | |
| stmt = select(KBArticle).where( | |
| KBArticle.title == art_def.title, | |
| KBArticle.workspace_id == current_user.workspace_id, | |
| KBArticle.deleted_at.is_(None) | |
| ) | |
| if processed_article_ids: | |
| # Cast to list for SQLAlchemy 2.0 cache-key compatibility | |
| stmt = stmt.where(KBArticle.id.not_in(list(processed_article_ids))) | |
| res = await db.execute(stmt) | |
| article = res.scalar_one_or_none() | |
| # Optimization: Only re-index if content/title actually changed OR it's a new article | |
| should_index = False | |
| if article: | |
| # Check if content-related fields changed | |
| if article.content != art_def.content or article.title != art_def.title: | |
| should_index = True | |
| article.content = art_def.content | |
| article.category = art_def.category | |
| article.project_id = art_def.project_id | |
| article.is_published = True | |
| results["updated"] += 1 | |
| else: | |
| article = KBArticle( | |
| title=art_def.title, | |
| content=art_def.content, | |
| category=art_def.category, | |
| project_id=art_def.project_id, | |
| workspace_id=current_user.workspace_id, | |
| author_id=current_user.id, | |
| is_published=True | |
| ) | |
| db.add(article) | |
| results["created"] += 1 | |
| should_index = True | |
| await db.flush() # ensure ID is available | |
| processed_article_ids.add(article.id) | |
| results["ids"].append(str(article.id)) | |
| # Trigger Unified ARQ Indexing Lifecycle ONLY if needed | |
| if should_index: | |
| await arq_pool.enqueue_job("index_kb_article", article.id) | |
| logger.info(f"KB Bulk: Indexing enqueued for {article.id}") | |
| else: | |
| logger.info(f"KB Bulk: Indexing skipped for {article.id} (no content changes)") | |
| await db.commit() | |
| logger.info(f"Bulk Sync & Publish (Isolated): {results['created']} created, {results['updated']} updated for workspace {current_user.workspace_id}") | |
| return {"status": "success", "summary": results} | |
| async def bulk_unpublish_articles( | |
| payload: KBBulkActionRequest, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| """Agents/Admin only: Bulk inactivate (Soft Delete) KB articles and their chunks.""" | |
| from sqlalchemy import delete | |
| ids = payload.article_ids | |
| # 1. Soft Delete the Articles | |
| stmt = ( | |
| update(KBArticle) | |
| .where( | |
| KBArticle.id.in_(ids), | |
| KBArticle.workspace_id == current_user.workspace_id, | |
| KBArticle.deleted_at.is_(None) | |
| ) | |
| .values( | |
| deleted_at=datetime.utcnow(), | |
| deleted_by_id=current_user.id, | |
| is_published=False | |
| ) | |
| ) | |
| res = await db.execute(stmt) | |
| count = res.rowcount | |
| # 2. Hard Delete the Chunks (to deactivate search) | |
| chunk_del = delete(KBArticleChunk).where(KBArticleChunk.article_id.in_(ids)) | |
| await db.execute(chunk_del) | |
| # 3. Soft Delete the Attachments | |
| att_del = ( | |
| update(Attachment) | |
| .where(Attachment.article_id.in_(ids)) | |
| .values(deleted_at=datetime.utcnow()) | |
| ) | |
| await db.execute(att_del) | |
| await db.commit() | |
| logger.info(f"Bulk Inactivation: {count} articles and their children deactivated by user {current_user.id}") | |
| return {"status": "success", "inactivated_count": count} | |