Spaces:
Paused
Paused
Download api/v1/kb.py from 3SCError404/miracle: direct link, hf CLI and curl.
- Browser
- Download file 53.8 kB
-
https://huggingface.co/spaces/3SCError404/miracle/resolve/main/api/v1/kb.py
- Command line
-
hf download hf://spaces/3SCError404/miracle/api/v1/kb.py
-
curl -L -o kb.py https://huggingface.co/spaces/3SCError404/miracle/resolve/main/api/v1/kb.py
53.8 kB
import asyncio
import hashlib
import time
from datetime import datetime, timezone
from typing import Any, List, Optional
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks, UploadFile, File
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func, desc, update, or_, case
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, get_effective_context
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.kb_article_version import KBArticleVersion
from models.project import Project
from core.llm import get_llm, get_text_embeddings
from models.attachment import Attachment
from core.sync import sync_markdown_images, link_internal_attachments
from core.cache import (
generate_cache_key, get_cached_search, set_cached_search,
SemanticCacheManager, invalidate_cache, delete_by_pattern,
invalidate_workspace_semantic_cache, get_cached_object, set_cached_object
)
from core.search_utils import refine_search_query, get_relaxed_tsquery
from schemas.kb import (
KBArticleCreate, KBArticleResponse, KBArticleUpdate, KBSearchResponse,
KBBulkActionRequest, KBBulkSyncRequest, KBAutoDraftRequest, KBAutoDraftResponse
)
router = APIRouter()
logger = get_logger(__name__)
@router.post("/autodraft/", response_model=KBAutoDraftResponse, dependencies=[Depends(require_roles(ALL_SC_ROLES))])
async def autodraft_kb_article(
payload: KBAutoDraftRequest,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
) -> Any:
"""AI-powered markdown formatter for KB articles."""
try:
from core.llm import get_llm
from langchain_core.messages import SystemMessage, HumanMessage
llm = get_llm(timeout=120)
prompt = [
SystemMessage(content=(
"You are a technical documentation expert. Your task is to REFORMAT the provided markdown content "
"to ensure it follows best practices for technical documentation.\n\n"
"Rules:\n"
"1. DO NOT change the technical meaning or remove any information.\n"
"2. Ensure consistent heading levels (H1 for title, H2 for main sections, H3 for sub-sections).\n"
"3. Fix inconsistent lists and ensure they are properly indented.\n"
"4. Ensure code blocks have appropriate language tags if they can be inferred.\n"
"5. Correct common markdown syntax errors.\n"
"6. Make the documentation more readable by adding logical breaks if necessary.\n"
"7. Keep the tone professional and technical.\n"
"8. Return ONLY the reformatted markdown content."
)),
HumanMessage(content=f"Reformat this markdown content:\n\n{payload.content}")
]
resp = await llm.ainvoke(prompt)
formatted_content = resp.content.strip()
return KBAutoDraftResponse(formatted_content=formatted_content)
except Exception as e:
logger.error(f"Auto-drafting failed: {e}")
raise HTTPException(status_code=500, detail=f"Neural formatting failed: {str(e)}")
# AI Lifecycle is now handled by arq worker task: index_kb_article
@router.post("/", response_model=KBArticleResponse, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_roles(ALL_SC_ROLES))])
async def create_kb_article(
payload: KBArticleCreate,
background_tasks: BackgroundTasks,
workspace_id: Optional[str] = None,
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."""
# BOLA: Enforce strict workspace isolation
target_ws, effective_role = await get_effective_context(db, current_user, workspace_id)
# Verify staff permissions for the TARGET workspace
if effective_role not in ALL_SC_ROLES and not current_user.is_platform_admin:
raise HTTPException(status_code=403, detail="Creation denied: Staff privilege required for this workspace.")
# 1. Validate project_id if provided
if payload.project_id:
proj_stmt = select(Project).where(
Project.id == payload.project_id,
Project.workspace_id == target_ws,
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=target_ws,
author_id=current_user.id,
is_published=payload.is_published if hasattr(payload, 'is_published') and payload.is_published is not None else True,
version=1
)
db.add(new_article)
await db.flush() # Secure ID assignment for the version record
# Store initial version (Atomic with article creation)
v1 = KBArticleVersion(
article_id=new_article.id,
version_number=1,
author_id=current_user.id,
title=new_article.title,
content=new_article.content,
category=new_article.category
)
db.add(v1)
# Atomic Commit: Article + Version must exist together or not at all
await db.commit()
await db.refresh(new_article)
# Unified ARQ Indexing Lifecycle
from core.tasks import enqueue_task
await enqueue_task(arq_pool, "index_kb_article", new_article.id)
logger.info(f"KB Article created and enqueued: {new_article.id} by user {current_user.id}")
# Atomic Invalidation: Clear all KB-related caches for this workspace
await delete_by_pattern(f"kb:list:{target_ws}:*")
await invalidate_cache(f"kb:categories:{target_ws}")
await delete_by_pattern(f"cache:search:kb:{target_ws}*")
await invalidate_workspace_semantic_cache(str(target_ws))
# Invalidate Dashboard AI Insights as they may depend on KB context
await delete_by_pattern(f"dashboard:insights:{target_ws}:*")
return new_article
@router.get("/", response_model=List[KBArticleResponse])
async def list_kb_articles(
category: Optional[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 Platform Super Admin
is_global = (workspace_id == "all" and current_user.is_platform_admin)
stmt = select(KBArticle).where(
KBArticle.deleted_at.is_(None),
KBArticle.duplicate_of_id.is_(None)
)
if is_global:
target_ws = "all"
else:
# Strictly enforce workspace isolation
target_ws, effective_role = await get_effective_context(db, current_user, 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)
# 0. Cache lookup (10m TTL)
target_ws = target_ws if not is_global else "global"
cache_key = f"kb:list:{target_ws}:{category or 'all'}"
if not current_user.is_platform_admin:
cached_res = await get_cached_object(cache_key)
if cached_res:
logger.info(f"⚡ Cache HIT [KB List]: {target_ws}")
return cached_res
result = await db.execute(stmt)
articles_orm = result.scalars().all()
from schemas.kb import KBArticleResponse
articles = [KBArticleResponse.model_validate(a).model_dump(mode='json') for a in articles_orm]
# Store in Cache (10m TTL as requested)
if not current_user.is_platform_admin:
await set_cached_object(cache_key, articles, ttl=600)
return articles
@router.get("/categories/", response_model=List[str])
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 (Cached 1h)."""
# BOLA: Enforce strict workspace isolation
target_ws, effective_role = await get_effective_context(db, current_user, workspace_id)
is_global = (workspace_id == "all" and current_user.is_platform_admin)
cache_key = f"kb:categories:{'global' if is_global else target_ws}"
cached = await get_cached_object(cache_key)
if cached:
return cached
stmt = select(func.distinct(KBArticle.category)).where(
KBArticle.deleted_at.is_(None)
)
if not is_global:
stmt = stmt.where(KBArticle.workspace_id == target_ws)
# Security: Customers only see categories that contain AT LEAST one published article
is_staff = effective_role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT, UserRole.SUPERADMIN]
if not is_staff and not current_user.is_platform_admin:
stmt = stmt.where(KBArticle.is_published)
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])
# Save to Cache
await set_cached_object(cache_key, normalized, ttl=3600)
return normalized
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,
skip_vector: bool = False
):
"""Internal helper to execute factual hybrid search + visual attachment search."""
import uuid
from core.observability import record_workflow_step
search_id = uuid.uuid4()
# 0. Query Refinement for Natural Language
clean_q = refine_search_query(q)
relaxed_q = get_relaxed_tsquery(clean_q)
# 1. Get Text Embedding for the query (Nomic-768)
query_vector = None
if not skip_vector:
try:
embed_start = time.perf_counter()
query_vector = await get_text_embeddings().aembed_query(clean_q)
if workspace_id:
await record_workflow_step(
db, search_id, workspace_id, "SEARCH",
"QUERY_EMBEDDING",
input_data={"q": clean_q},
duration_ms=(time.perf_counter() - embed_start) * 1000
)
except Exception as e:
logger.warning(f"[NEXUS_RESILIENCE] Embedding failed, falling back to pure FTS: {e}")
query_vector = None
# 2. SEACH A: Text Semantic Match (Articles) - Gated by vector success
hits = []
if query_vector:
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,
KBArticle.duplicate_of_id.is_(None),
)
)
if workspace_id:
semantic_stmt = semantic_stmt.where(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)
else:
# Dummy if no vector
semantic_stmt = None
# 3. SEARCH B: Visual Caption Match (Attachments)
# Uses pg_trgm for fuzzy similarity + search_vector for keyword relevance
visual_stmt = (
select(
KBArticle,
(
func.ts_rank(Attachment.search_vector, func.plainto_tsquery('english', clean_q)) +
func.similarity(Attachment.ai_caption, clean_q)
).label("vis_score")
)
.join(Attachment, KBArticle.id == Attachment.article_id)
.where(
KBArticle.deleted_at.is_(None),
KBArticle.is_published,
# Broaden: Match if either the keywords hit OR similarity is decent
(
Attachment.search_vector.op("@@")(func.websearch_to_tsquery('english', clean_q)) |
Attachment.search_vector.op("@@")(func.to_tsquery('english', relaxed_q)) |
(func.similarity(Attachment.ai_caption, clean_q) > 0.3)
)
)
)
if workspace_id:
visual_stmt = visual_stmt.where(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
keyword_stmt = (
select(
KBArticle,
(
# TS Rank CD with combined strict and relaxed queries
func.ts_rank_cd(KBArticle.search_vector, func.websearch_to_tsquery('english', clean_q)) * 2.0 +
func.ts_rank_cd(KBArticle.search_vector, func.to_tsquery('english', relaxed_q)) * 0.5 +
case((KBArticle.title.ilike(f"%{clean_q}%"), 1.0), else_=0.0)
).label("kw_score")
)
.where(
KBArticle.deleted_at.is_(None),
KBArticle.is_published,
or_(
KBArticle.search_vector.op("@@")(func.websearch_to_tsquery('english', clean_q)),
KBArticle.search_vector.op("@@")(func.to_tsquery('english', relaxed_q)),
KBArticle.title.ilike(f"%{clean_q}%")
)
)
)
if workspace_id:
keyword_stmt = keyword_stmt.where(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):
if stmt is None:
return []
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
@router.get("/search/", response_model=KBSearchResponse)
async def search_kb_articles(
q: str,
category: Optional[str] = None,
project_id: Optional[UUID] = None,
workspace_id: Optional[str] = None,
skip_ai: bool = False, # Express-route for automated processing
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
) -> Any:
"""Advanced Search with optional AI expansion. Use skip_ai=true for high-speed background processing."""
start_time = time.perf_counter()
# Strictly enforce workspace isolation using the central permissions engine
target_ws, effective_role = await get_effective_context(db, current_user, workspace_id)
if not target_ws:
# Should not happen with current get_effective_context logic, but defensive
raise HTTPException(status_code=400, detail="A valid workspace context is required.")
# 0. Local Search Cache Lookup (Dual-Redis Architecture)
cache_filters = {"category": category, "project_id": str(project_id) if project_id else None, "skip_ai": skip_ai}
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)
if not skip_ai and target_ws:
sem_answer = await SemanticCacheManager.check_cache(
workspace_id=target_ws,
query=q,
is_agent=False, # Universal KB visibility
user_role="universal",
user_id=str(current_user.id)
)
if sem_answer:
logger.info(f"🧠 Semantic Cache HIT [KB]: {q}")
# Ensure each result has a score field even in cache hits
results = sem_answer["results"]
for r in results:
if "score" not in r:
r["score"] = 99.0
return {
"answer": sem_answer["answer"],
"results": results,
"is_ai_synthetic": True,
"cacheHit": True,
"confidence": 0.99, # Represent high semantic match
"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, skip_vector=skip_ai
)
all_local_results = [orig_res]
expanded_queries = []
# 2. OPTIMIZATION: Intelligent AI Routing
# Removed query expansion based on user feedback to prioritize speed and reduce visual clutter.
# We maintain high accuracy through the hybrid search executed above.
is_complex = len(q.split()) >= 3 or any(w in q.lower() for w in ["how", "why", "steps", "explain"])
# 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.001 # Corrected for RRF scale (Max RRF ~0.016)
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(mode='json')
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 and NOT explicitly skipping AI
# This provides a quick "Direct Answer" summary of the top documentation for human users
if not skip_ai and 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)
])
# Increased to 120s for complex document synthesis
llm = get_llm(timeout=120)
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
if target_ws:
await SemanticCacheManager.set_cache(
workspace_id=target_ws,
user_id=current_user.id,
query=q,
response_text=direct_answer,
results=top_results,
is_agent=False,
user_role="universal"
)
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
# --- Telemetry: Increment View Counts for Top Results (Asynchronous) ---
if top_results:
async def increment_views(article_ids: List[str]):
async with async_session_factory() as db_session:
try:
await db_session.execute(
update(KBArticle)
.where(KBArticle.id.in_(article_ids))
.values(view_count=KBArticle.view_count + 1)
)
await db_session.commit()
logger.debug(f"Telemetry: Incremented view counts for {len(article_ids)} articles.")
except Exception as tel_err:
logger.warning(f"Background Search Telemetry failed: {tel_err}")
# We use the BackgroundTasks object if provided in search_kb_articles,
# but since we're in a helper, we can't easily access it without changing signature.
# Fixed: Use safe_create_task for fire-and-forget telemetry.
from core.logging import safe_create_task
top_ids = [r["id"] for r in top_results]
safe_create_task(increment_views(top_ids), name=f"kb_view_telemetry_{q[:10]}")
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
@router.get("/{article_id}/", response_model=KBArticleResponse)
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. Redis cached."""
cache_key = f"kb:article:{article_id}"
cached_art = await get_cached_object(cache_key)
if cached_art:
# Security: ownership / association check for cache
try:
from core.permissions import get_effective_context
await get_effective_context(db, current_user, cached_art.get("workspace_id"))
logger.info(f"⚡ Cache HIT [KB Article]: {article_id}")
return cached_art
except Exception:
pass
stmt = select(KBArticle).where(
KBArticle.id == article_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")
# BOLA: Enforce strict workspace isolation
from core.permissions import get_effective_context
await get_effective_context(db, current_user, article.workspace_id)
# Store in Cache (1 hour TTL for articles)
# Explicit Pydantic serialization for single article
from schemas.kb import KBArticleResponse
res_data = KBArticleResponse.model_validate(article).model_dump(mode='json')
await set_cached_object(cache_key, res_data, ttl=600)
return res_data
@router.patch("/{article_id}/", response_model=KBArticleResponse, dependencies=[Depends(require_roles(ALL_SC_ROLES))])
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.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")
# BOLA: Enforce strict workspace isolation
from core.permissions import get_effective_context
target_ws, effective_role = await get_effective_context(db, current_user, article.workspace_id)
update_data = payload.model_dump(exclude_unset=True, mode='json')
# 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.workspace_id == target_ws,
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 {update_data['project_id']} not found in the target workspace"
)
# Sync images if content is updated
if "content" in update_data:
# Link internal attachments first
await link_internal_attachments(db, article.id, update_data["content"], entity_type="article")
# Then sync external images
# 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)
if "content" in update_data or "title" in update_data or "category" in update_data:
article.version = article.version + 1
db.add(article)
await db.commit()
await db.refresh(article)
# Create version snapshot
new_version = KBArticleVersion(
article_id=article.id,
version_number=article.version,
author_id=current_user.id,
title=article.title,
content=article.content,
category=article.category
)
db.add(new_version)
await db.commit()
else:
db.add(article)
await db.commit()
await db.refresh(article)
# Proactive Cache Invalidation
await invalidate_cache(f"kb:article:{article_id}")
await delete_by_pattern(f"kb:list:{target_ws}:*")
await invalidate_cache(f"kb:categories:{target_ws}")
await delete_by_pattern(f"cache:search:kb:{target_ws}*")
await invalidate_workspace_semantic_cache(str(target_ws))
# Invalidate Dashboard AI Insights as they may depend on KB context
await delete_by_pattern(f"dashboard:insights:{target_ws}:*")
# Unified ARQ Indexing Lifecycle (Re-index if content/title changed)
if "content" in update_data or "title" in update_data:
from core.tasks import enqueue_task
await enqueue_task(arq_pool, "index_kb_article", article.id)
logger.info(f"KB Article {article_id} updated, re-indexing enqueued...")
return article
@router.delete("/{article_id}/", status_code=status.HTTP_200_OK, dependencies=[Depends(require_roles(ALL_SC_ROLES))])
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.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")
# BOLA: Enforce strict workspace isolation
from core.permissions import get_effective_context
target_ws, effective_role = await get_effective_context(db, current_user, article.workspace_id)
from sqlalchemy import delete
article.deleted_at = datetime.now(timezone.utc)
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()
# Proactive Cache Invalidation
from core.cache import invalidate_cache, delete_by_pattern
await invalidate_cache(f"kb:article:{article_id}")
await delete_by_pattern(f"kb:list:{target_ws}:*")
await invalidate_cache(f"kb:categories:{target_ws}")
await delete_by_pattern(f"cache:search:kb:{target_ws}*")
# Invalidate Dashboard AI Insights as they may depend on KB context
await delete_by_pattern(f"dashboard:insights:{target_ws}:*")
logger.info(f"KB Article and children inactivated: {article_id} by user {current_user.id}")
return {"status": "deleted"}
@router.get("/{article_id}/versions/", dependencies=[Depends(require_roles(ALL_SC_ROLES))])
async def list_article_versions(
article_id: UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
) -> Any:
"""Agents/Admin only: Get chronological list of previous article versions."""
from sqlalchemy.orm import selectinload
# Ensure article exists
stmt = select(KBArticle).where(
KBArticle.id == article_id,
KBArticle.deleted_at.is_(None)
)
article = (await db.execute(stmt)).scalar_one_or_none()
if not article:
raise HTTPException(status_code=404, detail="Article not found")
# BOLA: Enforce strict workspace isolation
from core.permissions import get_effective_context
await get_effective_context(db, current_user, article.workspace_id)
versions_stmt = (
select(KBArticleVersion)
.options(selectinload(KBArticleVersion.author))
.where(KBArticleVersion.article_id == article_id)
.order_by(desc(KBArticleVersion.version_number))
)
result = await db.execute(versions_stmt)
versions = result.scalars().all()
res = []
for v in versions:
author_name = v.author.full_name if v.author else "System"
res.append({
"id": str(v.id),
"version_number": v.version_number,
"title": v.title,
"content": v.content,
"category": v.category,
"created_at": v.created_at.isoformat(),
"author_id": str(v.author_id),
"author_name": author_name
})
return res
@router.post("/{article_id}/restore/{version_id}/", response_model=KBArticleResponse, dependencies=[Depends(require_roles(ALL_SC_ROLES))])
async def restore_article_version(
article_id: UUID,
version_id: UUID,
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: Restore article to a previous version."""
# Ensure article exists
stmt = select(KBArticle).where(
KBArticle.id == article_id,
KBArticle.deleted_at.is_(None)
)
article = (await db.execute(stmt)).scalar_one_or_none()
if not article:
raise HTTPException(status_code=404, detail="Article not found")
# BOLA: Enforce strict workspace isolation
from core.permissions import get_effective_context
target_ws, effective_role = await get_effective_context(db, current_user, article.workspace_id)
# Get the version snapshot
v_stmt = select(KBArticleVersion).where(
KBArticleVersion.id == version_id,
KBArticleVersion.article_id == article_id
)
version = (await db.execute(v_stmt)).scalar_one_or_none()
if not version:
raise HTTPException(status_code=404, detail="Version not found")
# Overwrite article content and increment version
article.title = version.title
article.content = version.content
article.category = version.category
article.version = article.version + 1
db.add(article)
await db.commit()
await db.refresh(article)
# Store the restored version as a new snapshot for auditability
restored_v = KBArticleVersion(
article_id=article.id,
version_number=article.version,
author_id=current_user.id,
title=article.title,
content=article.content,
category=article.category
)
db.add(restored_v)
await db.commit()
from core.cache import invalidate_cache, delete_by_pattern, invalidate_workspace_semantic_cache
await invalidate_cache(f"kb:article:{article_id}")
await invalidate_cache(f"kb:list:{target_ws}:all")
await invalidate_cache(f"kb:categories:{target_ws}")
await delete_by_pattern(f"cache:search:kb:{target_ws}*")
await invalidate_workspace_semantic_cache(str(target_ws))
from core.tasks import enqueue_task
await enqueue_task(arq_pool, "index_kb_article", article.id)
logger.info(f"Article {article_id} restored to version {version.version_number}")
return article
@router.post("/parse-file/", dependencies=[Depends(require_roles(ALL_SC_ROLES))])
async def parse_kb_file(
file: UploadFile = File(...),
current_user: User = Depends(get_current_user)
) -> Any:
"""Agents/Admin only: Parse an uploaded file into structured Markdown using LLM."""
if not file.filename.endswith(('.txt', '.md')):
raise HTTPException(status_code=400, detail="Only .txt and .md files are supported for AI parsing.")
contents = await file.read()
# 10 KB limit for synchronous parsing to prevent 502/524 Cloudflare chunk timeouts
max_size = 10 * 1024
if len(contents) > max_size:
raise HTTPException(status_code=400, detail="File too large for synchronous direct-edit parsing. Please upload a file smaller than 10KB.")
try:
text = contents.decode('utf-8')
except UnicodeDecodeError:
raise HTTPException(status_code=400, detail="File must be valid UTF-8 text.")
from langchain_core.messages import SystemMessage, HumanMessage
llm = get_llm(timeout=300) # 90s to stay within Cloudflare 100s limit
logger.info(f"AI Parse: Commencing transformation for {file.filename} ({len(contents)} bytes)")
prompt = [
SystemMessage(content=(
"You are an expert technical writer. Convert the following unstructured text "
"into a high-quality Markdown knowledge base article.\n\n"
"REQUIREMENTS:\n"
"1. Output ONLY the raw markdown content without any summary or conversational preamble.\n"
"2. Add a clear # Title at the top.\n"
"3. Use structured headings (##, ###).\n"
"4. Add bolding for emphasis, code blocks for technical parameters, and tables for comparative data.\n"
"5. If describing a process or system architecture, explicitly generate a Mermaid.js diagram (` ```mermaid `)."
)),
HumanMessage(content=f"UNSTRUCTURED CONTENT:\n\n{text}")
]
import asyncio
max_retries = 3
for attempt in range(max_retries):
try:
resp = await llm.ainvoke(prompt)
ai_content = resp.content.strip()
# Strip potential markdown formatting block if LLM wraps the whole response
if ai_content.startswith("```markdown") and ai_content.endswith("```"):
ai_content = ai_content[11:-3].strip()
# Try to extract a title (first h1)
import re
title_match = re.search(r'^#\s+(.+)$', ai_content, re.MULTILINE)
title = title_match.group(1).strip() if title_match else "AI Generated Article"
return {
"title": title,
"content": ai_content,
"category": "General"
}
except Exception as e:
error_str = str(e)
is_transient = "502" in error_str or "504" in error_str or "timeout" in error_str.lower()
if is_transient and attempt < max_retries - 1:
logger.warning(f"AI Parse transient error (attempt {attempt+1}/{max_retries}): {e}. Retrying in 2 seconds...")
await asyncio.sleep(2)
continue
logger.error(f"AI Parse Failed after {attempt+1} attempts: {e}")
detail = f"AI transformation failed: {str(e)}"
if "502" in error_str:
detail = "AI Service Unavailable (502 Bad Gateway). The Ollama backend might be down."
elif "504" in error_str or "timeout" in error_str.lower():
detail = "AI Service Timeout (504). The file might be too complex for the current model."
raise HTTPException(status_code=500, detail=detail)
@router.post("/ingest/", dependencies=[Depends(require_roles(ALL_SC_ROLES))])
async def ingest_kb_files(
files: List[UploadFile] = File(...),
workspace_id: Optional[str] = None,
current_user: User = Depends(get_current_user),
arq_pool: Any = Depends(get_arq_pool)
) -> Any:
"""Agents/Admin only: Bulk ingest files into KB via background AI workers."""
# BOLA: Enforce strict workspace isolation
async with async_session_factory() as setup_db:
target_ws, effective_role = await get_effective_context(setup_db, current_user, workspace_id)
if effective_role not in ALL_SC_ROLES and not current_user.is_platform_admin:
raise HTTPException(status_code=403, detail="Ingestion denied: Staff privilege required for this workspace.")
if not files:
raise HTTPException(status_code=400, detail="No files provided for ingestion.")
queued_count = 0
created_drafts = []
from core.tasks import enqueue_task
from core.cache import invalidate_cache
async with async_session_factory() as db:
for file in files:
filename_lower = file.filename.lower()
# Support basic text-based formats for immediate parsing
if not filename_lower.endswith(('.txt', '.md', '.pdf', '.docx')):
logger.warning(f"Ingest skip: {file.filename} (Unsupported extension)")
continue
contents = await file.read()
# 1MB Hard limit for background ingestion
max_size = 1024 * 1024
if len(contents) > max_size:
logger.warning(f"Ingest skip: {file.filename} (Too large: {len(contents)} bytes)")
continue
try:
# OPTIMIZATION: Immediate Draft for small text/md files (< 20KB)
if len(contents) < 20 * 1024 and filename_lower.endswith(('.txt', '.md')):
text = contents.decode('utf-8', errors='ignore')
# Extract title from first line or filename
lines = [line.strip() for line in text.split('\n') if line.strip()]
title = lines[0].lstrip('# ').strip() if lines else file.filename
if len(title) > 100:
title = title[:97] + "..."
# Deduplication via Content Hash (GAP FIX)
payload_str = f"{title.strip()}|{text.strip()}"
c_hash = hashlib.sha256(payload_str.encode('utf-8')).hexdigest()
dup_stmt = select(KBArticle).where(
KBArticle.workspace_id == target_ws,
KBArticle.content_hash == c_hash,
KBArticle.deleted_at.is_(None)
)
dup_res = await db.execute(dup_stmt)
existing_dup = dup_res.scalar_one_or_none()
if existing_dup:
logger.info(f"Ingest DUPLICATE (Hash): Skipping {file.filename}, already exists as {existing_dup.id}")
created_drafts.append({
"id": str(existing_dup.id),
"title": existing_dup.title,
"content": existing_dup.content,
"category": existing_dup.category,
"is_published": existing_dup.is_published,
"updated_at": existing_dup.updated_at.isoformat(),
"view_count": existing_dup.view_count,
"citation_count": existing_dup.citation_count,
"status": "LIVE" if existing_dup.is_published else "DRAFT",
"immediate": True,
"duplicate": True
})
continue
new_article = KBArticle(
workspace_id=target_ws,
author_id=current_user.id,
title=title,
content=text,
category="Imported",
is_published=False, # Always Draft
content_hash=c_hash
)
db.add(new_article)
await db.flush() # Get ID
# Trigger indexing immediately (Heavy worker handles embedding/chunking)
await enqueue_task(arq_pool, "index_kb_article", new_article.id)
created_drafts.append({
"id": str(new_article.id),
"title": new_article.title,
"content": new_article.content,
"category": new_article.category,
"is_published": False,
"updated_at": datetime.now(timezone.utc).isoformat(),
"view_count": 0,
"citation_count": 0,
"status": "DRAFT",
"immediate": True
})
logger.info(f"Ingest IMMEDIATE: {file.filename} -> {new_article.id}")
else:
# HEAVY PATH: Enqueue for AI transformation (LLM structures the doc)
text = contents.decode('utf-8', errors='ignore')
await enqueue_task(
arq_pool,
"process_kb_import_task",
target_ws,
current_user.id,
text,
file.filename
)
queued_count += 1
logger.info(f"Ingest enqueued: {file.filename} (Workspace: {target_ws})")
except Exception as e:
logger.error(f"Ingest processing error for {file.filename}: {e}")
continue
await db.commit()
# Invalidate KB list cache for this workspace to show new drafts
await invalidate_cache(f"kb:list:{target_ws}*")
# Invalidate caches (GAP FIX: ensure immediate visibility)
await invalidate_workspace_semantic_cache(str(target_ws))
await delete_by_pattern(f"kb:search:{target_ws}:*")
return {
"status": "success",
"queued": queued_count,
"immediate_count": len(created_drafts),
"created_drafts": created_drafts,
"message": f"Successfully processed {len(created_drafts) + queued_count} files. {len(created_drafts)} drafts created immediately."
}
@router.post("/bulk-publish/", status_code=status.HTTP_200_OK, dependencies=[Depends(require_roles(ALL_SC_ROLES))])
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": []}
# Record keeping for post-commit job enqueueing
to_index = []
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:
stmt = stmt.where(KBArticle.id.not_in(list(processed_article_ids)))
res = await db.execute(stmt)
article = res.scalar_one_or_none()
should_index = False
if article:
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
article.version += 1 # Auto-increment version on bulk update
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,
version=1
)
db.add(article)
results["created"] += 1
should_index = True
await db.flush()
processed_article_ids.add(article.id)
results["ids"].append(str(article.id))
# Consistent Versioning: Store snapshot for bulk operations
v = KBArticleVersion(
article_id=article.id,
version_number=article.version,
author_id=current_user.id,
title=article.title,
content=article.content,
category=article.category
)
db.add(v)
if should_index:
to_index.append(article.id)
await db.commit() # COMMIT FIRST: Ensure worker can find the articles
# Unified ARQ Indexing Lifecycle (ENQUEUE AFTER COMMIT)
from core.tasks import enqueue_task
for a_id in to_index:
await enqueue_task(arq_pool, "index_kb_article", a_id)
logger.info(f"KB Bulk: Indexing enqueued for {a_id}")
# Proactive Cache Invalidation
await invalidate_cache(f"kb:list:{current_user.workspace_id}:all")
for a_id in results["ids"]:
await invalidate_cache(f"kb:article:{a_id}")
await invalidate_workspace_semantic_cache(str(current_user.workspace_id))
logger.info(f"Bulk Sync & Publish: {results['created']} created, {results['updated']} updated for workspace {current_user.workspace_id}")
return {"status": "success", "summary": results}
@router.post("/bulk-unpublish/", status_code=status.HTTP_200_OK, dependencies=[Depends(require_roles(ALL_SC_ROLES))])
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.now(timezone.utc),
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.now(timezone.utc))
)
await db.execute(att_del)
await db.commit()
# Proactive Cache Invalidation
from core.cache import invalidate_cache
await invalidate_cache(f"kb:list:{current_user.workspace_id}:all")
for a_id in ids:
await invalidate_cache(f"kb:article:{a_id}")
logger.info(f"Bulk Inactivation: {count} articles and their children deactivated by user {current_user.id}")
return {"status": "success", "inactivated_count": count}
import asyncio
import hashlib
import time
from datetime import datetime, timezone
from typing import Any, List, Optional
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks, UploadFile, File
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func, desc, update, or_, case
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, get_effective_context
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.kb_article_version import KBArticleVersion
from models.project import Project
from core.llm import get_llm, get_text_embeddings
from models.attachment import Attachment
from core.sync import sync_markdown_images, link_internal_attachments
from core.cache import (
generate_cache_key, get_cached_search, set_cached_search,
SemanticCacheManager, invalidate_cache, delete_by_pattern,
invalidate_workspace_semantic_cache, get_cached_object, set_cached_object
)
from core.search_utils import refine_search_query, get_relaxed_tsquery
from schemas.kb import (
KBArticleCreate, KBArticleResponse, KBArticleUpdate, KBSearchResponse,
KBBulkActionRequest, KBBulkSyncRequest, KBAutoDraftRequest, KBAutoDraftResponse
)
router = APIRouter()
logger = get_logger(__name__)
async def autodraft_kb_article(
payload: KBAutoDraftRequest,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
) -> Any:
"""AI-powered markdown formatter for KB articles."""
try:
from core.llm import get_llm
from langchain_core.messages import SystemMessage, HumanMessage
llm = get_llm(timeout=120)
prompt = [
SystemMessage(content=(
"You are a technical documentation expert. Your task is to REFORMAT the provided markdown content "
"to ensure it follows best practices for technical documentation.\n\n"
"Rules:\n"
"1. DO NOT change the technical meaning or remove any information.\n"
"2. Ensure consistent heading levels (H1 for title, H2 for main sections, H3 for sub-sections).\n"
"3. Fix inconsistent lists and ensure they are properly indented.\n"
"4. Ensure code blocks have appropriate language tags if they can be inferred.\n"
"5. Correct common markdown syntax errors.\n"
"6. Make the documentation more readable by adding logical breaks if necessary.\n"
"7. Keep the tone professional and technical.\n"
"8. Return ONLY the reformatted markdown content."
)),
HumanMessage(content=f"Reformat this markdown content:\n\n{payload.content}")
]
resp = await llm.ainvoke(prompt)
formatted_content = resp.content.strip()
return KBAutoDraftResponse(formatted_content=formatted_content)
except Exception as e:
logger.error(f"Auto-drafting failed: {e}")
raise HTTPException(status_code=500, detail=f"Neural formatting failed: {str(e)}")
# AI Lifecycle is now handled by arq worker task: index_kb_article
async def create_kb_article(
payload: KBArticleCreate,
background_tasks: BackgroundTasks,
workspace_id: Optional[str] = None,
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."""
# BOLA: Enforce strict workspace isolation
target_ws, effective_role = await get_effective_context(db, current_user, workspace_id)
# Verify staff permissions for the TARGET workspace
if effective_role not in ALL_SC_ROLES and not current_user.is_platform_admin:
raise HTTPException(status_code=403, detail="Creation denied: Staff privilege required for this workspace.")
# 1. Validate project_id if provided
if payload.project_id:
proj_stmt = select(Project).where(
Project.id == payload.project_id,
Project.workspace_id == target_ws,
Project.deleted_at.is_(None)
)
proj_res = (await db.execute(proj_stmt)).scalar_one_or_none()