Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
d8744fd
1
Parent(s): 17923f1
Initial commit
Browse files- api/v1/kb.py +53 -54
- core/cache.py +7 -7
- core/search_utils.py +60 -0
- scratch/test_nl_search.py +28 -0
- services/ticket_service.py +27 -17
- tasks/ai.py +46 -34
- tasks/analytics.py +13 -9
- tasks/notifications.py +3 -3
- tasks/remediation.py +6 -3
- tasks/stories.py +15 -15
- tasks/system.py +19 -14
api/v1/kb.py
CHANGED
|
@@ -1,12 +1,12 @@
|
|
| 1 |
import asyncio
|
| 2 |
import hashlib
|
| 3 |
import time
|
| 4 |
-
from datetime import datetime
|
| 5 |
from typing import Any, List, Optional
|
| 6 |
from uuid import UUID
|
| 7 |
-
from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks
|
| 8 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 9 |
-
from sqlalchemy import select, func, desc, update
|
| 10 |
from core.database import async_session_factory
|
| 11 |
|
| 12 |
from core.deps import get_db, get_current_user, get_arq_pool
|
|
@@ -21,10 +21,11 @@ from core.llm import get_llm, get_text_embeddings
|
|
| 21 |
from models.attachment import Attachment
|
| 22 |
from core.sync import sync_markdown_images, link_internal_attachments
|
| 23 |
from core.cache import (
|
| 24 |
-
generate_cache_key, get_cached_search, set_cached_search,
|
| 25 |
SemanticCacheManager, invalidate_cache, delete_by_pattern,
|
| 26 |
invalidate_workspace_semantic_cache, get_cached_object, set_cached_object
|
| 27 |
)
|
|
|
|
| 28 |
from schemas.kb import (
|
| 29 |
KBArticleCreate, KBArticleResponse, KBArticleUpdate, KBSearchResponse,
|
| 30 |
KBBulkActionRequest, KBBulkSyncRequest, KBAutoDraftRequest, KBAutoDraftResponse
|
|
@@ -150,7 +151,7 @@ async def create_kb_article(
|
|
| 150 |
|
| 151 |
@router.get("/", response_model=List[KBArticleResponse])
|
| 152 |
async def list_kb_articles(
|
| 153 |
-
category: str = None,
|
| 154 |
workspace_id: Optional[str] = None,
|
| 155 |
current_user: User = Depends(get_current_user),
|
| 156 |
db: AsyncSession = Depends(get_db)
|
|
@@ -224,7 +225,7 @@ async def list_kb_categories(
|
|
| 224 |
# Security: Customers only see categories that contain AT LEAST one published article
|
| 225 |
is_staff = effective_role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT, UserRole.SUPERADMIN]
|
| 226 |
if not is_staff and not current_user.is_platform_admin:
|
| 227 |
-
stmt = stmt.where(KBArticle.is_published
|
| 228 |
|
| 229 |
|
| 230 |
result = await db.execute(stmt)
|
|
@@ -239,7 +240,8 @@ async def list_kb_categories(
|
|
| 239 |
|
| 240 |
def strip_markdown(text: str | None) -> str:
|
| 241 |
"""Removes code blocks, bold, italics, tables, and headers for a clean search snippet."""
|
| 242 |
-
if not text:
|
|
|
|
| 243 |
import re
|
| 244 |
# Remove code blocks
|
| 245 |
text = re.sub(r'```[\s\S]*?```', '', text)
|
|
@@ -266,22 +268,23 @@ async def execute_multimodal_search(
|
|
| 266 |
):
|
| 267 |
"""Internal helper to execute factual hybrid search + visual attachment search."""
|
| 268 |
import uuid
|
| 269 |
-
import time
|
| 270 |
from core.observability import record_workflow_step
|
| 271 |
search_id = uuid.uuid4()
|
| 272 |
-
|
|
|
|
|
|
|
| 273 |
|
| 274 |
# 1. Get Text Embedding for the query (Nomic-768)
|
| 275 |
query_vector = None
|
| 276 |
if not skip_vector:
|
| 277 |
try:
|
| 278 |
embed_start = time.perf_counter()
|
| 279 |
-
query_vector = await get_text_embeddings().aembed_query(
|
| 280 |
if workspace_id:
|
| 281 |
await record_workflow_step(
|
| 282 |
db, search_id, workspace_id, "SEARCH",
|
| 283 |
"QUERY_EMBEDDING",
|
| 284 |
-
input_data={"q":
|
| 285 |
duration_ms=(time.perf_counter() - embed_start) * 1000
|
| 286 |
)
|
| 287 |
except Exception as e:
|
|
@@ -291,7 +294,6 @@ async def execute_multimodal_search(
|
|
| 291 |
# 2. SEACH A: Text Semantic Match (Articles) - Gated by vector success
|
| 292 |
hits = []
|
| 293 |
if query_vector:
|
| 294 |
-
sem_start = time.perf_counter()
|
| 295 |
semantic_stmt = (
|
| 296 |
select(
|
| 297 |
KBArticle,
|
|
@@ -301,14 +303,16 @@ async def execute_multimodal_search(
|
|
| 301 |
.join(KBArticleChunk, KBArticle.id == KBArticleChunk.article_id)
|
| 302 |
.where(
|
| 303 |
KBArticle.deleted_at.is_(None),
|
| 304 |
-
KBArticle.is_published
|
| 305 |
KBArticle.duplicate_of_id.is_(None),
|
| 306 |
)
|
| 307 |
)
|
| 308 |
if workspace_id:
|
| 309 |
semantic_stmt = semantic_stmt.where(KBArticle.workspace_id == workspace_id)
|
| 310 |
-
if category:
|
| 311 |
-
|
|
|
|
|
|
|
| 312 |
semantic_stmt = semantic_stmt.order_by(desc("sim_score")).limit(20)
|
| 313 |
else:
|
| 314 |
# Dummy if no vector
|
|
@@ -316,23 +320,23 @@ async def execute_multimodal_search(
|
|
| 316 |
|
| 317 |
# 3. SEARCH B: Visual Caption Match (Attachments)
|
| 318 |
# Uses pg_trgm for fuzzy similarity + search_vector for keyword relevance
|
| 319 |
-
vis_start = time.perf_counter()
|
| 320 |
visual_stmt = (
|
| 321 |
select(
|
| 322 |
KBArticle,
|
| 323 |
(
|
| 324 |
-
func.ts_rank(Attachment.search_vector, func.plainto_tsquery('english',
|
| 325 |
-
func.similarity(Attachment.ai_caption,
|
| 326 |
).label("vis_score")
|
| 327 |
)
|
| 328 |
.join(Attachment, KBArticle.id == Attachment.article_id)
|
| 329 |
.where(
|
| 330 |
KBArticle.deleted_at.is_(None),
|
| 331 |
-
KBArticle.is_published
|
| 332 |
# Broaden: Match if either the keywords hit OR similarity is decent
|
| 333 |
(
|
| 334 |
-
Attachment.search_vector.op("@@")(func.websearch_to_tsquery('english',
|
| 335 |
-
(func.
|
|
|
|
| 336 |
)
|
| 337 |
)
|
| 338 |
)
|
|
@@ -342,31 +346,38 @@ async def execute_multimodal_search(
|
|
| 342 |
|
| 343 |
# 4. SEARCH C: Keyword Match (FTS with Title Boost)
|
| 344 |
# Optimized for short queries: Uses ts_rank_cd + Head-of-Document boost
|
| 345 |
-
from sqlalchemy import case
|
| 346 |
-
kw_start = time.perf_counter()
|
| 347 |
keyword_stmt = (
|
| 348 |
select(
|
| 349 |
KBArticle,
|
| 350 |
(
|
| 351 |
-
|
| 352 |
-
|
|
|
|
|
|
|
| 353 |
).label("kw_score")
|
| 354 |
)
|
| 355 |
.where(
|
| 356 |
KBArticle.deleted_at.is_(None),
|
| 357 |
-
KBArticle.is_published
|
| 358 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
)
|
| 360 |
)
|
| 361 |
if workspace_id:
|
| 362 |
keyword_stmt = keyword_stmt.where(KBArticle.workspace_id == workspace_id)
|
| 363 |
-
if category:
|
| 364 |
-
|
|
|
|
|
|
|
| 365 |
keyword_stmt = keyword_stmt.order_by(desc("kw_score")).limit(15)
|
| 366 |
|
| 367 |
# --- Parallel Execution ---
|
| 368 |
async def run_query(stmt):
|
| 369 |
-
if stmt is None:
|
|
|
|
| 370 |
async with async_session_factory() as session:
|
| 371 |
res = await session.execute(stmt)
|
| 372 |
return res.all()
|
|
@@ -439,20 +450,12 @@ async def search_kb_articles(
|
|
| 439 |
) -> Any:
|
| 440 |
"""Advanced Search with optional AI expansion. Use skip_ai=true for high-speed background processing."""
|
| 441 |
start_time = time.perf_counter()
|
|
|
|
|
|
|
| 442 |
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
target_ws = UUID(str(workspace_id))
|
| 447 |
-
except ValueError:
|
| 448 |
-
target_ws = current_user.workspace_id
|
| 449 |
-
elif workspace_id and str(workspace_id).lower() == "all" and current_user.is_platform_admin:
|
| 450 |
-
target_ws = None # Global search for platform admins
|
| 451 |
-
|
| 452 |
-
# Ensure target_ws is either a UUID or None, NOT a string "None"
|
| 453 |
-
if target_ws and str(target_ws) == "None":
|
| 454 |
-
target_ws = None
|
| 455 |
-
|
| 456 |
|
| 457 |
# 0. Local Search Cache Lookup (Dual-Redis Architecture)
|
| 458 |
cache_filters = {"category": category, "project_id": str(project_id) if project_id else None, "skip_ai": skip_ai}
|
|
@@ -498,7 +501,6 @@ async def search_kb_articles(
|
|
| 498 |
# 2. OPTIMIZATION: Intelligent AI Routing
|
| 499 |
# Removed query expansion based on user feedback to prioritize speed and reduce visual clutter.
|
| 500 |
# We maintain high accuracy through the hybrid search executed above.
|
| 501 |
-
max_orig_score = max([r["score"] for r in orig_res.values()]) if orig_res else 0.0
|
| 502 |
is_complex = len(q.split()) >= 3 or any(w in q.lower() for w in ["how", "why", "steps", "explain"])
|
| 503 |
|
| 504 |
# 3. Global Fusion (RRF across all branches and variations)
|
|
@@ -598,7 +600,6 @@ async def search_kb_articles(
|
|
| 598 |
except Exception as tel_err:
|
| 599 |
logger.warning(f"Background Search Telemetry failed: {tel_err}")
|
| 600 |
|
| 601 |
-
from fastapi import BackgroundTasks
|
| 602 |
# We use the BackgroundTasks object if provided in search_kb_articles,
|
| 603 |
# but since we're in a helper, we can't easily access it without changing signature.
|
| 604 |
# Fixed: Use safe_create_task for fire-and-forget telemetry.
|
|
@@ -765,7 +766,7 @@ async def delete_kb_article(
|
|
| 765 |
raise HTTPException(status_code=404, detail="Article not found")
|
| 766 |
|
| 767 |
from sqlalchemy import delete
|
| 768 |
-
article.deleted_at = datetime.
|
| 769 |
article.deleted_by_id = current_user.id
|
| 770 |
article.is_published = False
|
| 771 |
|
|
@@ -901,8 +902,6 @@ async def restore_article_version(
|
|
| 901 |
logger.info(f"Article {article_id} restored to version {version.version_number}")
|
| 902 |
return article
|
| 903 |
|
| 904 |
-
from fastapi import UploadFile, File
|
| 905 |
-
|
| 906 |
@router.post("/parse-file/", dependencies=[Depends(require_roles(ALL_SC_ROLES))])
|
| 907 |
async def parse_kb_file(
|
| 908 |
file: UploadFile = File(...),
|
|
@@ -923,7 +922,6 @@ async def parse_kb_file(
|
|
| 923 |
except UnicodeDecodeError:
|
| 924 |
raise HTTPException(status_code=400, detail="File must be valid UTF-8 text.")
|
| 925 |
|
| 926 |
-
from core.llm import get_llm
|
| 927 |
from langchain_core.messages import SystemMessage, HumanMessage
|
| 928 |
|
| 929 |
llm = get_llm(timeout=300) # 90s to stay within Cloudflare 100s limit
|
|
@@ -1025,9 +1023,10 @@ async def ingest_kb_files(
|
|
| 1025 |
text = contents.decode('utf-8', errors='ignore')
|
| 1026 |
|
| 1027 |
# Extract title from first line or filename
|
| 1028 |
-
lines = [
|
| 1029 |
title = lines[0].lstrip('# ').strip() if lines else file.filename
|
| 1030 |
-
if len(title) > 100:
|
|
|
|
| 1031 |
|
| 1032 |
# Deduplication via Content Hash (GAP FIX)
|
| 1033 |
payload_str = f"{title.strip()}|{text.strip()}"
|
|
@@ -1079,7 +1078,7 @@ async def ingest_kb_files(
|
|
| 1079 |
"content": new_article.content,
|
| 1080 |
"category": new_article.category,
|
| 1081 |
"is_published": False,
|
| 1082 |
-
"updated_at": datetime.
|
| 1083 |
"view_count": 0,
|
| 1084 |
"citation_count": 0,
|
| 1085 |
"status": "DRAFT",
|
|
@@ -1231,7 +1230,7 @@ async def bulk_unpublish_articles(
|
|
| 1231 |
KBArticle.deleted_at.is_(None)
|
| 1232 |
)
|
| 1233 |
.values(
|
| 1234 |
-
deleted_at=datetime.
|
| 1235 |
deleted_by_id=current_user.id,
|
| 1236 |
is_published=False
|
| 1237 |
)
|
|
@@ -1247,7 +1246,7 @@ async def bulk_unpublish_articles(
|
|
| 1247 |
att_del = (
|
| 1248 |
update(Attachment)
|
| 1249 |
.where(Attachment.article_id.in_(ids))
|
| 1250 |
-
.values(deleted_at=datetime.
|
| 1251 |
)
|
| 1252 |
await db.execute(att_del)
|
| 1253 |
|
|
|
|
| 1 |
import asyncio
|
| 2 |
import hashlib
|
| 3 |
import time
|
| 4 |
+
from datetime import datetime, timezone
|
| 5 |
from typing import Any, List, Optional
|
| 6 |
from uuid import UUID
|
| 7 |
+
from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks, UploadFile, File
|
| 8 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 9 |
+
from sqlalchemy import select, func, desc, update, or_, case
|
| 10 |
from core.database import async_session_factory
|
| 11 |
|
| 12 |
from core.deps import get_db, get_current_user, get_arq_pool
|
|
|
|
| 21 |
from models.attachment import Attachment
|
| 22 |
from core.sync import sync_markdown_images, link_internal_attachments
|
| 23 |
from core.cache import (
|
| 24 |
+
generate_cache_key, get_cached_search, set_cached_search,
|
| 25 |
SemanticCacheManager, invalidate_cache, delete_by_pattern,
|
| 26 |
invalidate_workspace_semantic_cache, get_cached_object, set_cached_object
|
| 27 |
)
|
| 28 |
+
from core.search_utils import refine_search_query, get_relaxed_tsquery
|
| 29 |
from schemas.kb import (
|
| 30 |
KBArticleCreate, KBArticleResponse, KBArticleUpdate, KBSearchResponse,
|
| 31 |
KBBulkActionRequest, KBBulkSyncRequest, KBAutoDraftRequest, KBAutoDraftResponse
|
|
|
|
| 151 |
|
| 152 |
@router.get("/", response_model=List[KBArticleResponse])
|
| 153 |
async def list_kb_articles(
|
| 154 |
+
category: Optional[str] = None,
|
| 155 |
workspace_id: Optional[str] = None,
|
| 156 |
current_user: User = Depends(get_current_user),
|
| 157 |
db: AsyncSession = Depends(get_db)
|
|
|
|
| 225 |
# Security: Customers only see categories that contain AT LEAST one published article
|
| 226 |
is_staff = effective_role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT, UserRole.SUPERADMIN]
|
| 227 |
if not is_staff and not current_user.is_platform_admin:
|
| 228 |
+
stmt = stmt.where(KBArticle.is_published)
|
| 229 |
|
| 230 |
|
| 231 |
result = await db.execute(stmt)
|
|
|
|
| 240 |
|
| 241 |
def strip_markdown(text: str | None) -> str:
|
| 242 |
"""Removes code blocks, bold, italics, tables, and headers for a clean search snippet."""
|
| 243 |
+
if not text:
|
| 244 |
+
return ""
|
| 245 |
import re
|
| 246 |
# Remove code blocks
|
| 247 |
text = re.sub(r'```[\s\S]*?```', '', text)
|
|
|
|
| 268 |
):
|
| 269 |
"""Internal helper to execute factual hybrid search + visual attachment search."""
|
| 270 |
import uuid
|
|
|
|
| 271 |
from core.observability import record_workflow_step
|
| 272 |
search_id = uuid.uuid4()
|
| 273 |
+
# 0. Query Refinement for Natural Language
|
| 274 |
+
clean_q = refine_search_query(q)
|
| 275 |
+
relaxed_q = get_relaxed_tsquery(clean_q)
|
| 276 |
|
| 277 |
# 1. Get Text Embedding for the query (Nomic-768)
|
| 278 |
query_vector = None
|
| 279 |
if not skip_vector:
|
| 280 |
try:
|
| 281 |
embed_start = time.perf_counter()
|
| 282 |
+
query_vector = await get_text_embeddings().aembed_query(clean_q)
|
| 283 |
if workspace_id:
|
| 284 |
await record_workflow_step(
|
| 285 |
db, search_id, workspace_id, "SEARCH",
|
| 286 |
"QUERY_EMBEDDING",
|
| 287 |
+
input_data={"q": clean_q},
|
| 288 |
duration_ms=(time.perf_counter() - embed_start) * 1000
|
| 289 |
)
|
| 290 |
except Exception as e:
|
|
|
|
| 294 |
# 2. SEACH A: Text Semantic Match (Articles) - Gated by vector success
|
| 295 |
hits = []
|
| 296 |
if query_vector:
|
|
|
|
| 297 |
semantic_stmt = (
|
| 298 |
select(
|
| 299 |
KBArticle,
|
|
|
|
| 303 |
.join(KBArticleChunk, KBArticle.id == KBArticleChunk.article_id)
|
| 304 |
.where(
|
| 305 |
KBArticle.deleted_at.is_(None),
|
| 306 |
+
KBArticle.is_published,
|
| 307 |
KBArticle.duplicate_of_id.is_(None),
|
| 308 |
)
|
| 309 |
)
|
| 310 |
if workspace_id:
|
| 311 |
semantic_stmt = semantic_stmt.where(KBArticle.workspace_id == workspace_id)
|
| 312 |
+
if category:
|
| 313 |
+
semantic_stmt = semantic_stmt.where(KBArticle.category == category)
|
| 314 |
+
if project_id:
|
| 315 |
+
semantic_stmt = semantic_stmt.where(KBArticle.project_id == project_id)
|
| 316 |
semantic_stmt = semantic_stmt.order_by(desc("sim_score")).limit(20)
|
| 317 |
else:
|
| 318 |
# Dummy if no vector
|
|
|
|
| 320 |
|
| 321 |
# 3. SEARCH B: Visual Caption Match (Attachments)
|
| 322 |
# Uses pg_trgm for fuzzy similarity + search_vector for keyword relevance
|
|
|
|
| 323 |
visual_stmt = (
|
| 324 |
select(
|
| 325 |
KBArticle,
|
| 326 |
(
|
| 327 |
+
func.ts_rank(Attachment.search_vector, func.plainto_tsquery('english', clean_q)) +
|
| 328 |
+
func.similarity(Attachment.ai_caption, clean_q)
|
| 329 |
).label("vis_score")
|
| 330 |
)
|
| 331 |
.join(Attachment, KBArticle.id == Attachment.article_id)
|
| 332 |
.where(
|
| 333 |
KBArticle.deleted_at.is_(None),
|
| 334 |
+
KBArticle.is_published,
|
| 335 |
# Broaden: Match if either the keywords hit OR similarity is decent
|
| 336 |
(
|
| 337 |
+
Attachment.search_vector.op("@@")(func.websearch_to_tsquery('english', clean_q)) |
|
| 338 |
+
Attachment.search_vector.op("@@")(func.to_tsquery('english', relaxed_q)) |
|
| 339 |
+
(func.similarity(Attachment.ai_caption, clean_q) > 0.3)
|
| 340 |
)
|
| 341 |
)
|
| 342 |
)
|
|
|
|
| 346 |
|
| 347 |
# 4. SEARCH C: Keyword Match (FTS with Title Boost)
|
| 348 |
# Optimized for short queries: Uses ts_rank_cd + Head-of-Document boost
|
|
|
|
|
|
|
| 349 |
keyword_stmt = (
|
| 350 |
select(
|
| 351 |
KBArticle,
|
| 352 |
(
|
| 353 |
+
# TS Rank CD with combined strict and relaxed queries
|
| 354 |
+
func.ts_rank_cd(KBArticle.search_vector, func.websearch_to_tsquery('english', clean_q)) * 2.0 +
|
| 355 |
+
func.ts_rank_cd(KBArticle.search_vector, func.to_tsquery('english', relaxed_q)) * 0.5 +
|
| 356 |
+
case((KBArticle.title.ilike(f"%{clean_q}%"), 1.0), else_=0.0)
|
| 357 |
).label("kw_score")
|
| 358 |
)
|
| 359 |
.where(
|
| 360 |
KBArticle.deleted_at.is_(None),
|
| 361 |
+
KBArticle.is_published,
|
| 362 |
+
or_(
|
| 363 |
+
KBArticle.search_vector.op("@@")(func.websearch_to_tsquery('english', clean_q)),
|
| 364 |
+
KBArticle.search_vector.op("@@")(func.to_tsquery('english', relaxed_q)),
|
| 365 |
+
KBArticle.title.ilike(f"%{clean_q}%")
|
| 366 |
+
)
|
| 367 |
)
|
| 368 |
)
|
| 369 |
if workspace_id:
|
| 370 |
keyword_stmt = keyword_stmt.where(KBArticle.workspace_id == workspace_id)
|
| 371 |
+
if category:
|
| 372 |
+
keyword_stmt = keyword_stmt.where(KBArticle.category == category)
|
| 373 |
+
if project_id:
|
| 374 |
+
keyword_stmt = keyword_stmt.where(KBArticle.project_id == project_id)
|
| 375 |
keyword_stmt = keyword_stmt.order_by(desc("kw_score")).limit(15)
|
| 376 |
|
| 377 |
# --- Parallel Execution ---
|
| 378 |
async def run_query(stmt):
|
| 379 |
+
if stmt is None:
|
| 380 |
+
return []
|
| 381 |
async with async_session_factory() as session:
|
| 382 |
res = await session.execute(stmt)
|
| 383 |
return res.all()
|
|
|
|
| 450 |
) -> Any:
|
| 451 |
"""Advanced Search with optional AI expansion. Use skip_ai=true for high-speed background processing."""
|
| 452 |
start_time = time.perf_counter()
|
| 453 |
+
# Strictly enforce workspace isolation using the central permissions engine
|
| 454 |
+
target_ws, effective_role = await get_effective_context(db, current_user, workspace_id)
|
| 455 |
|
| 456 |
+
if not target_ws:
|
| 457 |
+
# Should not happen with current get_effective_context logic, but defensive
|
| 458 |
+
raise HTTPException(status_code=400, detail="A valid workspace context is required.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 459 |
|
| 460 |
# 0. Local Search Cache Lookup (Dual-Redis Architecture)
|
| 461 |
cache_filters = {"category": category, "project_id": str(project_id) if project_id else None, "skip_ai": skip_ai}
|
|
|
|
| 501 |
# 2. OPTIMIZATION: Intelligent AI Routing
|
| 502 |
# Removed query expansion based on user feedback to prioritize speed and reduce visual clutter.
|
| 503 |
# We maintain high accuracy through the hybrid search executed above.
|
|
|
|
| 504 |
is_complex = len(q.split()) >= 3 or any(w in q.lower() for w in ["how", "why", "steps", "explain"])
|
| 505 |
|
| 506 |
# 3. Global Fusion (RRF across all branches and variations)
|
|
|
|
| 600 |
except Exception as tel_err:
|
| 601 |
logger.warning(f"Background Search Telemetry failed: {tel_err}")
|
| 602 |
|
|
|
|
| 603 |
# We use the BackgroundTasks object if provided in search_kb_articles,
|
| 604 |
# but since we're in a helper, we can't easily access it without changing signature.
|
| 605 |
# Fixed: Use safe_create_task for fire-and-forget telemetry.
|
|
|
|
| 766 |
raise HTTPException(status_code=404, detail="Article not found")
|
| 767 |
|
| 768 |
from sqlalchemy import delete
|
| 769 |
+
article.deleted_at = datetime.now(timezone.utc)
|
| 770 |
article.deleted_by_id = current_user.id
|
| 771 |
article.is_published = False
|
| 772 |
|
|
|
|
| 902 |
logger.info(f"Article {article_id} restored to version {version.version_number}")
|
| 903 |
return article
|
| 904 |
|
|
|
|
|
|
|
| 905 |
@router.post("/parse-file/", dependencies=[Depends(require_roles(ALL_SC_ROLES))])
|
| 906 |
async def parse_kb_file(
|
| 907 |
file: UploadFile = File(...),
|
|
|
|
| 922 |
except UnicodeDecodeError:
|
| 923 |
raise HTTPException(status_code=400, detail="File must be valid UTF-8 text.")
|
| 924 |
|
|
|
|
| 925 |
from langchain_core.messages import SystemMessage, HumanMessage
|
| 926 |
|
| 927 |
llm = get_llm(timeout=300) # 90s to stay within Cloudflare 100s limit
|
|
|
|
| 1023 |
text = contents.decode('utf-8', errors='ignore')
|
| 1024 |
|
| 1025 |
# Extract title from first line or filename
|
| 1026 |
+
lines = [line.strip() for line in text.split('\n') if line.strip()]
|
| 1027 |
title = lines[0].lstrip('# ').strip() if lines else file.filename
|
| 1028 |
+
if len(title) > 100:
|
| 1029 |
+
title = title[:97] + "..."
|
| 1030 |
|
| 1031 |
# Deduplication via Content Hash (GAP FIX)
|
| 1032 |
payload_str = f"{title.strip()}|{text.strip()}"
|
|
|
|
| 1078 |
"content": new_article.content,
|
| 1079 |
"category": new_article.category,
|
| 1080 |
"is_published": False,
|
| 1081 |
+
"updated_at": datetime.now(timezone.utc).isoformat(),
|
| 1082 |
"view_count": 0,
|
| 1083 |
"citation_count": 0,
|
| 1084 |
"status": "DRAFT",
|
|
|
|
| 1230 |
KBArticle.deleted_at.is_(None)
|
| 1231 |
)
|
| 1232 |
.values(
|
| 1233 |
+
deleted_at=datetime.now(timezone.utc),
|
| 1234 |
deleted_by_id=current_user.id,
|
| 1235 |
is_published=False
|
| 1236 |
)
|
|
|
|
| 1246 |
att_del = (
|
| 1247 |
update(Attachment)
|
| 1248 |
.where(Attachment.article_id.in_(ids))
|
| 1249 |
+
.values(deleted_at=datetime.now(timezone.utc))
|
| 1250 |
)
|
| 1251 |
await db.execute(att_del)
|
| 1252 |
|
core/cache.py
CHANGED
|
@@ -1,6 +1,8 @@
|
|
| 1 |
import json
|
| 2 |
import hashlib
|
| 3 |
import logging
|
|
|
|
|
|
|
| 4 |
from typing import Any, Optional, List
|
| 5 |
import redis.asyncio as redis
|
| 6 |
from core.config import get_settings
|
|
@@ -14,7 +16,6 @@ settings = get_settings()
|
|
| 14 |
_redis_client: Optional[redis.Redis] = None
|
| 15 |
|
| 16 |
# --- L1 MEMORY CACHE (Zero-Latency Layer) ---
|
| 17 |
-
import time
|
| 18 |
_l1_cache: dict[str, tuple[Any, float]] = {}
|
| 19 |
MAX_L1_SIZE = 2048
|
| 20 |
|
|
@@ -72,7 +73,7 @@ def get_redis_client() -> redis.Redis:
|
|
| 72 |
}
|
| 73 |
|
| 74 |
if is_rediss:
|
| 75 |
-
redis_kwargs["ssl_cert_reqs"] =
|
| 76 |
|
| 77 |
_redis_client = redis.from_url(target_url, **redis_kwargs)
|
| 78 |
return _redis_client
|
|
@@ -101,12 +102,12 @@ def get_worker_redis_client() -> redis.Redis:
|
|
| 101 |
}
|
| 102 |
|
| 103 |
if is_rediss:
|
| 104 |
-
redis_kwargs["ssl_cert_reqs"] =
|
| 105 |
|
| 106 |
_worker_redis_client = redis.from_url(target_url, **redis_kwargs)
|
| 107 |
return _worker_redis_client
|
| 108 |
|
| 109 |
-
def generate_cache_key(prefix: str, workspace_id: str, query: str, filters: dict = None) -> str:
|
| 110 |
"""Generates a deterministic cache key based on query parameters."""
|
| 111 |
filter_str = json.dumps(filters, sort_keys=True) if filters else "{}"
|
| 112 |
payload = f"{workspace_id}:{query}:{filter_str}".lower().strip()
|
|
@@ -206,9 +207,8 @@ async def invalidate_workspace_semantic_cache(workspace_id: str) -> None:
|
|
| 206 |
Entries created before this timestamp will be ignored.
|
| 207 |
"""
|
| 208 |
try:
|
| 209 |
-
from datetime import datetime
|
| 210 |
client = get_redis_client()
|
| 211 |
-
now = datetime.
|
| 212 |
await client.set(f"semantic_cache:invalidation:{workspace_id}", str(now), ex=86400)
|
| 213 |
except Exception:
|
| 214 |
pass
|
|
@@ -251,7 +251,7 @@ class SemanticCacheManager:
|
|
| 251 |
@staticmethod
|
| 252 |
def _normalize_role_class(user_role: str = "", is_agent: bool = False) -> str:
|
| 253 |
"""Normalize any role string to a strict partition class."""
|
| 254 |
-
role_lower =
|
| 255 |
if is_agent or "3sc" in role_lower or "agent" in role_lower or "lead" in role_lower or role_lower == "admin":
|
| 256 |
return "staff"
|
| 257 |
return "customer"
|
|
|
|
| 1 |
import json
|
| 2 |
import hashlib
|
| 3 |
import logging
|
| 4 |
+
import time
|
| 5 |
+
from datetime import datetime, timezone
|
| 6 |
from typing import Any, Optional, List
|
| 7 |
import redis.asyncio as redis
|
| 8 |
from core.config import get_settings
|
|
|
|
| 16 |
_redis_client: Optional[redis.Redis] = None
|
| 17 |
|
| 18 |
# --- L1 MEMORY CACHE (Zero-Latency Layer) ---
|
|
|
|
| 19 |
_l1_cache: dict[str, tuple[Any, float]] = {}
|
| 20 |
MAX_L1_SIZE = 2048
|
| 21 |
|
|
|
|
| 73 |
}
|
| 74 |
|
| 75 |
if is_rediss:
|
| 76 |
+
redis_kwargs["ssl_cert_reqs"] = "none"
|
| 77 |
|
| 78 |
_redis_client = redis.from_url(target_url, **redis_kwargs)
|
| 79 |
return _redis_client
|
|
|
|
| 102 |
}
|
| 103 |
|
| 104 |
if is_rediss:
|
| 105 |
+
redis_kwargs["ssl_cert_reqs"] = "none"
|
| 106 |
|
| 107 |
_worker_redis_client = redis.from_url(target_url, **redis_kwargs)
|
| 108 |
return _worker_redis_client
|
| 109 |
|
| 110 |
+
def generate_cache_key(prefix: str, workspace_id: str, query: str, filters: Optional[dict] = None) -> str:
|
| 111 |
"""Generates a deterministic cache key based on query parameters."""
|
| 112 |
filter_str = json.dumps(filters, sort_keys=True) if filters else "{}"
|
| 113 |
payload = f"{workspace_id}:{query}:{filter_str}".lower().strip()
|
|
|
|
| 207 |
Entries created before this timestamp will be ignored.
|
| 208 |
"""
|
| 209 |
try:
|
|
|
|
| 210 |
client = get_redis_client()
|
| 211 |
+
now = datetime.now(timezone.utc).timestamp()
|
| 212 |
await client.set(f"semantic_cache:invalidation:{workspace_id}", str(now), ex=86400)
|
| 213 |
except Exception:
|
| 214 |
pass
|
|
|
|
| 251 |
@staticmethod
|
| 252 |
def _normalize_role_class(user_role: str = "", is_agent: bool = False) -> str:
|
| 253 |
"""Normalize any role string to a strict partition class."""
|
| 254 |
+
role_lower = user_role.lower()
|
| 255 |
if is_agent or "3sc" in role_lower or "agent" in role_lower or "lead" in role_lower or role_lower == "admin":
|
| 256 |
return "staff"
|
| 257 |
return "customer"
|
core/search_utils.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from typing import List
|
| 3 |
+
|
| 4 |
+
FILLER_PHRASES = [
|
| 5 |
+
r"\btickets?\s+related\s+to\s+",
|
| 6 |
+
r"\btickets?\s+about\s+",
|
| 7 |
+
r"\btickets?\s+for\s+",
|
| 8 |
+
r"\btickets?\s+regarding\s+",
|
| 9 |
+
r"\bfind\s+(me\s+)?tickets?\s*(for|about|related\s+to|regarding)?\b",
|
| 10 |
+
r"\bshow\s+(me\s+)?tickets?\s*(for|about|related\s+to|regarding)?\b",
|
| 11 |
+
r"\blist\s+tickets?\s*(for|about|related\s+to|regarding)?\b",
|
| 12 |
+
r"\bsearch\s+(for\s+)?tickets?\b",
|
| 13 |
+
r"\bhow\s+(do\s+i|to|can\s+i)\s+",
|
| 14 |
+
r"\bwhat\s+(is|are)\s+",
|
| 15 |
+
r"\b(is\s+there|are\s+there)\s+any\b",
|
| 16 |
+
r"\brelated\s+to\b",
|
| 17 |
+
r"\brelated\s+tickets?\b",
|
| 18 |
+
r"\btickets?\b",
|
| 19 |
+
r"\bshow\s+me\b",
|
| 20 |
+
r"\bfind\b",
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
def refine_search_query(q: str) -> str:
|
| 24 |
+
"""
|
| 25 |
+
Cleans natural language queries to extract core keywords.
|
| 26 |
+
Removes common filler phrases like 'tickets related to' or 'how to find'.
|
| 27 |
+
"""
|
| 28 |
+
if not q:
|
| 29 |
+
return ""
|
| 30 |
+
|
| 31 |
+
# Preserve original for short or specific queries (e.g. "Ticket #123")
|
| 32 |
+
if len(q.split()) <= 1 or re.search(r'#\d+', q):
|
| 33 |
+
return q.strip()
|
| 34 |
+
|
| 35 |
+
clean_q = q.lower().strip()
|
| 36 |
+
|
| 37 |
+
# 1. Strip common NL filler phrases
|
| 38 |
+
for phrase in FILLER_PHRASES:
|
| 39 |
+
# We replace with a space to avoid joining words accidentally
|
| 40 |
+
clean_q = re.sub(phrase, " ", clean_q, flags=re.IGNORECASE)
|
| 41 |
+
|
| 42 |
+
# 2. Normalize whitespace
|
| 43 |
+
clean_q = re.sub(r'\s+', ' ', clean_q).strip()
|
| 44 |
+
|
| 45 |
+
# Fallback to original if we stripped everything or query became too short
|
| 46 |
+
if not clean_q or len(clean_q) < 2:
|
| 47 |
+
return q.strip()
|
| 48 |
+
|
| 49 |
+
return clean_q
|
| 50 |
+
|
| 51 |
+
def get_relaxed_tsquery(q: str) -> str:
|
| 52 |
+
"""
|
| 53 |
+
Converts a space-separated query into a Postgres OR-based tsquery.
|
| 54 |
+
Example: 'dashboard issue' -> 'dashboard | issue'
|
| 55 |
+
"""
|
| 56 |
+
# Filter out very short words from the relaxed query
|
| 57 |
+
words = [w for w in re.split(r'[^\w]+', q) if len(w) > 2]
|
| 58 |
+
if not words:
|
| 59 |
+
return q
|
| 60 |
+
return " | ".join(words)
|
scratch/test_nl_search.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import os
|
| 3 |
+
import asyncio
|
| 4 |
+
from uuid import UUID
|
| 5 |
+
|
| 6 |
+
# Mock dependencies
|
| 7 |
+
sys.path.append(os.getcwd())
|
| 8 |
+
from core.search_utils import refine_search_query, get_relaxed_tsquery
|
| 9 |
+
|
| 10 |
+
def test_refinement():
|
| 11 |
+
test_cases = [
|
| 12 |
+
"dashboard",
|
| 13 |
+
"dashboard related tickets",
|
| 14 |
+
"show me tickets about password reset",
|
| 15 |
+
"find tickets regarding dashboard customization",
|
| 16 |
+
"how to reset password",
|
| 17 |
+
"Ticket #12345"
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
print(f"{'Original Query':<50} | {'Refined Query':<30} | {'Relaxed TSQuery'}")
|
| 21 |
+
print("-" * 110)
|
| 22 |
+
for q in test_cases:
|
| 23 |
+
refined = refine_search_query(q)
|
| 24 |
+
relaxed = get_relaxed_tsquery(refined)
|
| 25 |
+
print(f"{q:<50} | {refined:<30} | {relaxed}")
|
| 26 |
+
|
| 27 |
+
if __name__ == "__main__":
|
| 28 |
+
test_refinement()
|
services/ticket_service.py
CHANGED
|
@@ -5,15 +5,16 @@ Ticket Service: Handles core business logic for tickets.
|
|
| 5 |
import asyncio
|
| 6 |
import uuid
|
| 7 |
import hashlib
|
| 8 |
-
from datetime import datetime, timedelta
|
| 9 |
from typing import Any, Optional, Dict
|
| 10 |
from uuid import UUID
|
| 11 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 12 |
-
from sqlalchemy import select, update, cast, String, or_, func,
|
| 13 |
from sqlalchemy.orm import joinedload
|
| 14 |
from fastapi import HTTPException
|
| 15 |
|
| 16 |
from core.llm import get_text_embeddings
|
|
|
|
| 17 |
|
| 18 |
from core.permissions import get_effective_context
|
| 19 |
|
|
@@ -53,7 +54,7 @@ class TicketService:
|
|
| 53 |
# 1. Resolve context
|
| 54 |
target_ws, effective_role = await get_effective_context(db, current_user, workspace_id)
|
| 55 |
|
| 56 |
-
now = datetime.
|
| 57 |
since = now - timedelta(days=days)
|
| 58 |
|
| 59 |
# 2. Optimized Unified Query
|
|
@@ -303,7 +304,7 @@ class TicketService:
|
|
| 303 |
EscalationRule.priority_level == cast(payload.priority or TicketPriority.P2, String)
|
| 304 |
)
|
| 305 |
rule = (await db.execute(rule_stmt)).scalar_one_or_none()
|
| 306 |
-
sla_deadline = datetime.
|
| 307 |
|
| 308 |
new_ticket = Ticket(
|
| 309 |
id=uuid.uuid4(),
|
|
@@ -329,9 +330,8 @@ class TicketService:
|
|
| 329 |
# Handle Mentions in description
|
| 330 |
mentions = await parse_mentions(payload.description, current_user.workspace_id, db)
|
| 331 |
if mentions:
|
| 332 |
-
from arq import create_pool
|
| 333 |
from core.config import get_settings
|
| 334 |
-
|
| 335 |
# Note: We usually have arq_pool passed in, but in some contexts we might need to get it.
|
| 336 |
# In TicketService, it's passed into create_ticket.
|
| 337 |
await enqueue_task(arq_pool, "notify_mentions", str(current_user.workspace_id), new_ticket.title, mentions, ticket_id=str(new_ticket.id))
|
|
@@ -404,7 +404,7 @@ class TicketService:
|
|
| 404 |
if current_user.role not in [UserRole.SC_LEAD, UserRole.SC_ADMIN, UserRole.SUPERADMIN] and update_data["status"] not in ALLOWED_TRANSITIONS.get(ticket.status, []):
|
| 405 |
raise HTTPException(status_code=400, detail="Invalid status transition")
|
| 406 |
if update_data["status"] in [TicketStatus.RESOLVED, TicketStatus.CLOSED]:
|
| 407 |
-
ticket.resolved_at = datetime.
|
| 408 |
ticket.resolved_by = current_user.id
|
| 409 |
# TRIGGER: AI Summarization on Resolution
|
| 410 |
await enqueue_task(arq_pool, "auto_summarize_ticket", ticket.id, manual=True)
|
|
@@ -576,7 +576,7 @@ class TicketService:
|
|
| 576 |
if ticket.is_escalated:
|
| 577 |
return await TicketService.sanitize_ticket_response(ticket, current_user, db)
|
| 578 |
|
| 579 |
-
ticket.is_escalated = datetime.
|
| 580 |
ticket.priority = TicketPriority.P0 # Force to P0 on manual escalation
|
| 581 |
|
| 582 |
db.add(AuditLog(
|
|
@@ -751,25 +751,33 @@ class TicketService:
|
|
| 751 |
|
| 752 |
is_staff = effective_role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT, UserRole.SUPERADMIN]
|
| 753 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 754 |
# 1. Start External Embedding API call in background (Latent step)
|
| 755 |
-
|
|
|
|
| 756 |
|
| 757 |
# 2. Branch A: Keyword (FTS + ID Match) - Run while embedding is generating
|
| 758 |
keyword_stmt = select(
|
| 759 |
Ticket.id.label("id"),
|
| 760 |
(
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
|
|
|
|
|
|
|
| 764 |
).label("branch_score"),
|
| 765 |
literal_column("'keyword'").label("match_type")
|
| 766 |
).where(
|
| 767 |
Ticket.deleted_at.is_(None),
|
| 768 |
Ticket.workspace_id == target_ws,
|
| 769 |
or_(
|
| 770 |
-
Ticket.search_vector.op("@@")(func.websearch_to_tsquery('english',
|
| 771 |
-
Ticket.
|
| 772 |
-
|
|
|
|
| 773 |
)
|
| 774 |
)
|
| 775 |
|
|
@@ -829,11 +837,13 @@ class TicketService:
|
|
| 829 |
results = []
|
| 830 |
for tid in top_ids:
|
| 831 |
t = tickets.get(tid)
|
| 832 |
-
if not t:
|
|
|
|
| 833 |
|
| 834 |
raw_fused = merged_scores[tid]
|
| 835 |
norm_score = min(round((raw_fused / 0.45) * 100, 1), 100.0)
|
| 836 |
-
if norm_score < 10:
|
|
|
|
| 837 |
|
| 838 |
# Restore High-Quality AI Summary Selection
|
| 839 |
summaries = (t.ai_metadata or {}).get("summaries", {})
|
|
|
|
| 5 |
import asyncio
|
| 6 |
import uuid
|
| 7 |
import hashlib
|
| 8 |
+
from datetime import datetime, timedelta, timezone
|
| 9 |
from typing import Any, Optional, Dict
|
| 10 |
from uuid import UUID
|
| 11 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 12 |
+
from sqlalchemy import select, update, cast, String, or_, func, case, Float, literal_column
|
| 13 |
from sqlalchemy.orm import joinedload
|
| 14 |
from fastapi import HTTPException
|
| 15 |
|
| 16 |
from core.llm import get_text_embeddings
|
| 17 |
+
from core.search_utils import refine_search_query, get_relaxed_tsquery
|
| 18 |
|
| 19 |
from core.permissions import get_effective_context
|
| 20 |
|
|
|
|
| 54 |
# 1. Resolve context
|
| 55 |
target_ws, effective_role = await get_effective_context(db, current_user, workspace_id)
|
| 56 |
|
| 57 |
+
now = datetime.now(timezone.utc)
|
| 58 |
since = now - timedelta(days=days)
|
| 59 |
|
| 60 |
# 2. Optimized Unified Query
|
|
|
|
| 304 |
EscalationRule.priority_level == cast(payload.priority or TicketPriority.P2, String)
|
| 305 |
)
|
| 306 |
rule = (await db.execute(rule_stmt)).scalar_one_or_none()
|
| 307 |
+
sla_deadline = datetime.now(timezone.utc) + timedelta(minutes=rule.threshold_minutes if rule else 2880)
|
| 308 |
|
| 309 |
new_ticket = Ticket(
|
| 310 |
id=uuid.uuid4(),
|
|
|
|
| 330 |
# Handle Mentions in description
|
| 331 |
mentions = await parse_mentions(payload.description, current_user.workspace_id, db)
|
| 332 |
if mentions:
|
|
|
|
| 333 |
from core.config import get_settings
|
| 334 |
+
get_settings()
|
| 335 |
# Note: We usually have arq_pool passed in, but in some contexts we might need to get it.
|
| 336 |
# In TicketService, it's passed into create_ticket.
|
| 337 |
await enqueue_task(arq_pool, "notify_mentions", str(current_user.workspace_id), new_ticket.title, mentions, ticket_id=str(new_ticket.id))
|
|
|
|
| 404 |
if current_user.role not in [UserRole.SC_LEAD, UserRole.SC_ADMIN, UserRole.SUPERADMIN] and update_data["status"] not in ALLOWED_TRANSITIONS.get(ticket.status, []):
|
| 405 |
raise HTTPException(status_code=400, detail="Invalid status transition")
|
| 406 |
if update_data["status"] in [TicketStatus.RESOLVED, TicketStatus.CLOSED]:
|
| 407 |
+
ticket.resolved_at = datetime.now(timezone.utc)
|
| 408 |
ticket.resolved_by = current_user.id
|
| 409 |
# TRIGGER: AI Summarization on Resolution
|
| 410 |
await enqueue_task(arq_pool, "auto_summarize_ticket", ticket.id, manual=True)
|
|
|
|
| 576 |
if ticket.is_escalated:
|
| 577 |
return await TicketService.sanitize_ticket_response(ticket, current_user, db)
|
| 578 |
|
| 579 |
+
ticket.is_escalated = datetime.now(timezone.utc)
|
| 580 |
ticket.priority = TicketPriority.P0 # Force to P0 on manual escalation
|
| 581 |
|
| 582 |
db.add(AuditLog(
|
|
|
|
| 751 |
|
| 752 |
is_staff = effective_role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT, UserRole.SUPERADMIN]
|
| 753 |
|
| 754 |
+
# 0. Query Refinement for Natural Language
|
| 755 |
+
clean_q = refine_search_query(q)
|
| 756 |
+
relaxed_q = get_relaxed_tsquery(clean_q)
|
| 757 |
+
|
| 758 |
# 1. Start External Embedding API call in background (Latent step)
|
| 759 |
+
# We embed the CLEAN query to remove noise for the vector search
|
| 760 |
+
embed_task = asyncio.create_task(get_text_embeddings().aembed_query(clean_q))
|
| 761 |
|
| 762 |
# 2. Branch A: Keyword (FTS + ID Match) - Run while embedding is generating
|
| 763 |
keyword_stmt = select(
|
| 764 |
Ticket.id.label("id"),
|
| 765 |
(
|
| 766 |
+
# Use ts_rank_cd on both strict and relaxed queries
|
| 767 |
+
func.ts_rank_cd(Ticket.search_vector, func.websearch_to_tsquery('english', clean_q)) * 2.0 +
|
| 768 |
+
func.ts_rank_cd(Ticket.search_vector, func.to_tsquery('english', relaxed_q)) * 0.5 +
|
| 769 |
+
case((cast(Ticket.id, String).ilike(f"{clean_q}%"), 5.0), else_=0.0) +
|
| 770 |
+
case((Ticket.title.ilike(f"%{clean_q}%"), 1.0), else_=0.0)
|
| 771 |
).label("branch_score"),
|
| 772 |
literal_column("'keyword'").label("match_type")
|
| 773 |
).where(
|
| 774 |
Ticket.deleted_at.is_(None),
|
| 775 |
Ticket.workspace_id == target_ws,
|
| 776 |
or_(
|
| 777 |
+
Ticket.search_vector.op("@@")(func.websearch_to_tsquery('english', clean_q)),
|
| 778 |
+
Ticket.search_vector.op("@@")(func.to_tsquery('english', relaxed_q)),
|
| 779 |
+
Ticket.title.ilike(f"%{clean_q}%"),
|
| 780 |
+
cast(Ticket.id, String).ilike(f"{clean_q}%")
|
| 781 |
)
|
| 782 |
)
|
| 783 |
|
|
|
|
| 837 |
results = []
|
| 838 |
for tid in top_ids:
|
| 839 |
t = tickets.get(tid)
|
| 840 |
+
if not t:
|
| 841 |
+
continue
|
| 842 |
|
| 843 |
raw_fused = merged_scores[tid]
|
| 844 |
norm_score = min(round((raw_fused / 0.45) * 100, 1), 100.0)
|
| 845 |
+
if norm_score < 10:
|
| 846 |
+
norm_score = 10.0
|
| 847 |
|
| 848 |
# Restore High-Quality AI Summary Selection
|
| 849 |
summaries = (t.ai_metadata or {}).get("summaries", {})
|
tasks/ai.py
CHANGED
|
@@ -6,15 +6,15 @@ import json
|
|
| 6 |
import asyncio
|
| 7 |
from typing import Any, Dict, Optional
|
| 8 |
from uuid import UUID
|
| 9 |
-
from datetime import datetime, timedelta
|
| 10 |
-
from sqlalchemy import select, desc, cast, String,
|
| 11 |
|
| 12 |
from core.database import async_session_factory
|
| 13 |
from core.logging import get_logger
|
| 14 |
from core.config import get_settings
|
| 15 |
-
from core.llm import get_llm, get_text_embeddings
|
| 16 |
from core.websockets import manager
|
| 17 |
-
from core.vision import extract_visual_context
|
| 18 |
from core.cache import invalidate_cache
|
| 19 |
from core.search import chunk_text
|
| 20 |
from core.sync import sync_markdown_images
|
|
@@ -24,9 +24,6 @@ from models.message import Message
|
|
| 24 |
from models.kb_article import KBArticle
|
| 25 |
from models.kb_article_chunk import KBArticleChunk
|
| 26 |
from models.nexus_memory import NexusMemory
|
| 27 |
-
from models.attachment import Attachment
|
| 28 |
-
from models.ai_interaction import AIInteraction
|
| 29 |
-
from models.audit_log import AuditLog
|
| 30 |
from langchain.schema import HumanMessage, SystemMessage
|
| 31 |
from langchain_core.prompts import ChatPromptTemplate
|
| 32 |
from tasks.system import check_job_latch
|
|
@@ -35,20 +32,24 @@ logger = get_logger(__name__)
|
|
| 35 |
settings = get_settings()
|
| 36 |
|
| 37 |
def truncate_content(text_content: str, max_chars: int = 15000) -> str:
|
| 38 |
-
if not text_content:
|
| 39 |
-
|
|
|
|
|
|
|
| 40 |
return text_content[:max_chars] + "\n\n... [Content Truncated] ..."
|
| 41 |
|
| 42 |
async def auto_summarize_ticket(ctx, ticket_id: UUID, **kwargs):
|
| 43 |
"""Background task to generate dual summaries."""
|
| 44 |
-
if not await check_job_latch(ctx, ticket_id, "auto_summarize_ticket"):
|
|
|
|
| 45 |
|
| 46 |
for attempt in range(1, 4):
|
| 47 |
try:
|
| 48 |
async with async_session_factory() as db:
|
| 49 |
stmt = select(Ticket).where(Ticket.id == ticket_id, Ticket.deleted_at.is_(None))
|
| 50 |
ticket = (await db.execute(stmt)).scalar_one_or_none()
|
| 51 |
-
if not ticket:
|
|
|
|
| 52 |
|
| 53 |
limit = 50 if kwargs.get('manual') else 15
|
| 54 |
msg_stmt = select(Message).where(Message.ticket_id == ticket_id, Message.deleted_at.is_(None)).order_by(Message.created_at.desc()).limit(limit)
|
|
@@ -71,7 +72,7 @@ async def auto_summarize_ticket(ctx, ticket_id: UUID, **kwargs):
|
|
| 71 |
def format_convo(msg_list):
|
| 72 |
return "\n".join([f"{'['+'INTERNAL'+'] ' if m.is_internal else ''}{m.sender_id}: {m.content}" for m in msg_list])
|
| 73 |
|
| 74 |
-
|
| 75 |
|
| 76 |
cust_prompt = [
|
| 77 |
SystemMessage(content="Summarize for a CUSTOMER. Focus on the core issue and final resolution. Max 3 sentences."),
|
|
@@ -113,7 +114,8 @@ async def auto_summarize_ticket(ctx, ticket_id: UUID, **kwargs):
|
|
| 113 |
await invalidate_cache(f"ticket:detail:{ticket_id}")
|
| 114 |
break
|
| 115 |
except Exception as e:
|
| 116 |
-
if attempt == 3:
|
|
|
|
| 117 |
await asyncio.sleep(attempt * 5)
|
| 118 |
|
| 119 |
async def crystallize_memory(ctx, user_id: UUID, workspace_id: UUID, thread_id: Optional[UUID], history_str: str, old_summary: str, old_gist: Dict[str, Any], **kwargs):
|
|
@@ -133,9 +135,11 @@ async def crystallize_memory(ctx, user_id: UUID, workspace_id: UUID, thread_id:
|
|
| 133 |
from schemas.ai import UserIdentityGist
|
| 134 |
gist_llm = get_llm(is_heavy_task=True).with_structured_output(UserIdentityGist)
|
| 135 |
gist_prompt = ChatPromptTemplate.from_template(get_prompt("identity_architect"))
|
| 136 |
-
new_gist_obj = await (gist_prompt | gist_llm).ainvoke({"old_gist": json.dumps(old_gist), "new_history": history_str, "
|
| 137 |
-
if new_gist_obj:
|
| 138 |
-
|
|
|
|
|
|
|
| 139 |
|
| 140 |
async with async_session_factory() as db:
|
| 141 |
from models.user import User
|
|
@@ -153,7 +157,8 @@ async def crystallize_memory(ctx, user_id: UUID, workspace_id: UUID, thread_id:
|
|
| 153 |
await db.commit()
|
| 154 |
break
|
| 155 |
except Exception as e:
|
| 156 |
-
if attempt == 3:
|
|
|
|
| 157 |
await asyncio.sleep(attempt * 7)
|
| 158 |
|
| 159 |
async def summarize_thread_title(ctx, thread_id: UUID, user_query: str, ai_response: str, **kwargs):
|
|
@@ -180,24 +185,27 @@ async def summarize_thread_title(ctx, thread_id: UUID, user_query: str, ai_respo
|
|
| 180 |
await db.execute(
|
| 181 |
update(NexusThread)
|
| 182 |
.where(NexusThread.id == thread_id)
|
| 183 |
-
.values(title=new_title, updated_at=datetime.
|
| 184 |
)
|
| 185 |
await db.commit()
|
| 186 |
logger.info(f"🏷️ Updated Thread Title: {thread_id} -> {new_title}")
|
| 187 |
break
|
| 188 |
except Exception as e:
|
| 189 |
-
if attempt == 3:
|
|
|
|
| 190 |
await asyncio.sleep(attempt * 3)
|
| 191 |
|
| 192 |
async def index_kb_article(ctx, article_id: UUID, **kwargs):
|
| 193 |
"""Full KB indexing lifecycle."""
|
| 194 |
-
if not await check_job_latch(ctx, article_id, "index_kb_article"):
|
|
|
|
| 195 |
|
| 196 |
async with async_session_factory() as db:
|
| 197 |
try:
|
| 198 |
stmt = select(KBArticle).where(KBArticle.id == article_id, KBArticle.deleted_at.is_(None))
|
| 199 |
article = (await db.execute(stmt)).scalar_one_or_none()
|
| 200 |
-
if not article:
|
|
|
|
| 201 |
|
| 202 |
text_model = get_text_embeddings()
|
| 203 |
llm = get_llm()
|
|
@@ -251,7 +259,7 @@ Return as JSON: {"summary": "...", "category": "..."}"""),
|
|
| 251 |
# Only overwrite if it's a generic placeholder
|
| 252 |
if article.category in [None, "Imported", "General", "Uncategorized"]:
|
| 253 |
article.category = ai_data.get("category", "GENERAL").upper()
|
| 254 |
-
except:
|
| 255 |
# Fallback to simple summary if JSON fails
|
| 256 |
article.summary = str(resp.content)
|
| 257 |
|
|
@@ -265,7 +273,8 @@ async def generate_ticket_embedding(ctx, ticket_id: UUID, **kwargs):
|
|
| 265 |
async with async_session_factory() as db:
|
| 266 |
stmt = select(Ticket).where(Ticket.id == ticket_id, Ticket.deleted_at.is_(None))
|
| 267 |
ticket = (await db.execute(stmt)).scalar_one_or_none()
|
| 268 |
-
if not ticket:
|
|
|
|
| 269 |
|
| 270 |
try:
|
| 271 |
await sync_markdown_images(db, ticket.id, ticket.workspace_id, ticket.description, entity_type="ticket", uploader_id=ticket.created_by)
|
|
@@ -297,18 +306,21 @@ async def vectorize_nexus_interaction(ctx, workspace_id: UUID, user_id: UUID, co
|
|
| 297 |
vector = await text_model.aembed_query(content)
|
| 298 |
db.add(NexusMemory(workspace_id=workspace_id, user_id=user_id, content=content, thread_id=thread_id, interaction_id=interaction_id, memory_type=memory_type, embedding=vector))
|
| 299 |
await db.commit()
|
| 300 |
-
if thread_id:
|
|
|
|
| 301 |
|
| 302 |
async def generate_global_insight(ctx, *args, **kwargs):
|
| 303 |
"""Generate platform-wide strategic summary."""
|
| 304 |
from tasks.system import check_cron_lock
|
| 305 |
-
if not await check_cron_lock(ctx, "generate_global_insight", window_seconds=600):
|
|
|
|
| 306 |
|
| 307 |
from models.platform_insight import PlatformInsight
|
| 308 |
async with async_session_factory() as db:
|
| 309 |
stmt = select(NexusMemory.content).where(NexusMemory.memory_type == "interaction").order_by(desc(NexusMemory.created_at)).limit(150)
|
| 310 |
memories = (await db.execute(stmt)).scalars().all()
|
| 311 |
-
if not memories:
|
|
|
|
| 312 |
|
| 313 |
llm = get_llm()
|
| 314 |
resp = await llm.ainvoke(f"Analyze these interactions and provide a JSON summary and trends: {' '.join(memories)}")
|
|
@@ -316,16 +328,16 @@ async def generate_global_insight(ctx, *args, **kwargs):
|
|
| 316 |
insights = json.loads(str(resp.content).strip().replace("```json", "").replace("```", ""))
|
| 317 |
db.add(PlatformInsight(summary=insights.get("summary"), trends=insights.get("trends")))
|
| 318 |
await db.commit()
|
| 319 |
-
except
|
|
|
|
| 320 |
|
| 321 |
async def refresh_active_workspace_insights(ctx, **kwargs):
|
| 322 |
"""Cron task to preemptively refresh insights for active workspaces."""
|
| 323 |
-
from models.workspace import Workspace
|
| 324 |
from tasks.system import enqueue_task
|
| 325 |
|
| 326 |
async with async_session_factory() as db:
|
| 327 |
# Find workspaces with tickets created/updated in the last 24h
|
| 328 |
-
day_ago = datetime.
|
| 329 |
stmt = select(Ticket.workspace_id).where(
|
| 330 |
or_(Ticket.created_at >= day_ago, Ticket.updated_at >= day_ago)
|
| 331 |
).distinct()
|
|
@@ -349,7 +361,7 @@ async def generate_workspace_insights(ctx, workspace_id: str, role: str = "inter
|
|
| 349 |
|
| 350 |
async with async_session_factory() as db:
|
| 351 |
try:
|
| 352 |
-
ws_uuid = _UUID(
|
| 353 |
|
| 354 |
# 1. Ticket counts
|
| 355 |
count_stmt = (
|
|
@@ -361,7 +373,7 @@ async def generate_workspace_insights(ctx, workspace_id: str, role: str = "inter
|
|
| 361 |
total_tickets = sum(r.cnt for r in count_rows)
|
| 362 |
|
| 363 |
# 2. SLA breach count
|
| 364 |
-
now = datetime.
|
| 365 |
breach_stmt = select(sqlfunc.count(Ticket.id)).where(
|
| 366 |
Ticket.workspace_id == ws_uuid,
|
| 367 |
Ticket.deleted_at.is_(None),
|
|
@@ -465,7 +477,7 @@ async def generate_workspace_insights(ctx, workspace_id: str, role: str = "inter
|
|
| 465 |
|
| 466 |
narrative = {
|
| 467 |
"insights": raw_narrative,
|
| 468 |
-
"generated_at": datetime.
|
| 469 |
"status": "COMPLETED"
|
| 470 |
}
|
| 471 |
await set_cached_search(f"insights:narrative:v4:{workspace_id}:{role}", narrative, ttl=43200)
|
|
@@ -474,7 +486,7 @@ async def generate_workspace_insights(ctx, workspace_id: str, role: str = "inter
|
|
| 474 |
# Broadcast to all connected clients in this workspace to trigger auto-refresh
|
| 475 |
await manager.broadcast_to_workspace(ws_uuid, {
|
| 476 |
"type": "WORKSPACE_INSIGHTS_READY",
|
| 477 |
-
"workspace_id":
|
| 478 |
})
|
| 479 |
|
| 480 |
logger.info(f"✅ Background insights generated and broadcasted for workspace: {workspace_id}")
|
|
@@ -498,7 +510,7 @@ async def process_kb_import_task(ctx, workspace_id: UUID, author_id: UUID, file_
|
|
| 498 |
async def ai_dynamic_nudge_pulse(ctx, **kwargs):
|
| 499 |
"""Identifies tickets at >75% SLA and posts resolution advice (parallel LLM calls)."""
|
| 500 |
async with async_session_factory() as db:
|
| 501 |
-
now = datetime.
|
| 502 |
stmt = (
|
| 503 |
select(Ticket, EscalationRule)
|
| 504 |
.join(EscalationRule, (EscalationRule.workspace_id == Ticket.workspace_id) & (EscalationRule.priority_level == cast(Ticket.priority, String)))
|
|
|
|
| 6 |
import asyncio
|
| 7 |
from typing import Any, Dict, Optional
|
| 8 |
from uuid import UUID
|
| 9 |
+
from datetime import datetime, timezone, timedelta
|
| 10 |
+
from sqlalchemy import select, desc, cast, String, or_
|
| 11 |
|
| 12 |
from core.database import async_session_factory
|
| 13 |
from core.logging import get_logger
|
| 14 |
from core.config import get_settings
|
| 15 |
+
from core.llm import get_llm, get_text_embeddings
|
| 16 |
from core.websockets import manager
|
| 17 |
+
from core.vision import extract_visual_context
|
| 18 |
from core.cache import invalidate_cache
|
| 19 |
from core.search import chunk_text
|
| 20 |
from core.sync import sync_markdown_images
|
|
|
|
| 24 |
from models.kb_article import KBArticle
|
| 25 |
from models.kb_article_chunk import KBArticleChunk
|
| 26 |
from models.nexus_memory import NexusMemory
|
|
|
|
|
|
|
|
|
|
| 27 |
from langchain.schema import HumanMessage, SystemMessage
|
| 28 |
from langchain_core.prompts import ChatPromptTemplate
|
| 29 |
from tasks.system import check_job_latch
|
|
|
|
| 32 |
settings = get_settings()
|
| 33 |
|
| 34 |
def truncate_content(text_content: str, max_chars: int = 15000) -> str:
|
| 35 |
+
if not text_content:
|
| 36 |
+
return ""
|
| 37 |
+
if len(text_content) <= max_chars:
|
| 38 |
+
return text_content
|
| 39 |
return text_content[:max_chars] + "\n\n... [Content Truncated] ..."
|
| 40 |
|
| 41 |
async def auto_summarize_ticket(ctx, ticket_id: UUID, **kwargs):
|
| 42 |
"""Background task to generate dual summaries."""
|
| 43 |
+
if not await check_job_latch(ctx, ticket_id, "auto_summarize_ticket"):
|
| 44 |
+
return
|
| 45 |
|
| 46 |
for attempt in range(1, 4):
|
| 47 |
try:
|
| 48 |
async with async_session_factory() as db:
|
| 49 |
stmt = select(Ticket).where(Ticket.id == ticket_id, Ticket.deleted_at.is_(None))
|
| 50 |
ticket = (await db.execute(stmt)).scalar_one_or_none()
|
| 51 |
+
if not ticket:
|
| 52 |
+
return
|
| 53 |
|
| 54 |
limit = 50 if kwargs.get('manual') else 15
|
| 55 |
msg_stmt = select(Message).where(Message.ticket_id == ticket_id, Message.deleted_at.is_(None)).order_by(Message.created_at.desc()).limit(limit)
|
|
|
|
| 72 |
def format_convo(msg_list):
|
| 73 |
return "\n".join([f"{'['+'INTERNAL'+'] ' if m.is_internal else ''}{m.sender_id}: {m.content}" for m in msg_list])
|
| 74 |
|
| 75 |
+
await extract_visual_context(db, ticket.workspace_id, ticket.description, limit=2)
|
| 76 |
|
| 77 |
cust_prompt = [
|
| 78 |
SystemMessage(content="Summarize for a CUSTOMER. Focus on the core issue and final resolution. Max 3 sentences."),
|
|
|
|
| 114 |
await invalidate_cache(f"ticket:detail:{ticket_id}")
|
| 115 |
break
|
| 116 |
except Exception as e:
|
| 117 |
+
if attempt == 3:
|
| 118 |
+
logger.error(f"Summarization failed: {e}")
|
| 119 |
await asyncio.sleep(attempt * 5)
|
| 120 |
|
| 121 |
async def crystallize_memory(ctx, user_id: UUID, workspace_id: UUID, thread_id: Optional[UUID], history_str: str, old_summary: str, old_gist: Dict[str, Any], **kwargs):
|
|
|
|
| 135 |
from schemas.ai import UserIdentityGist
|
| 136 |
gist_llm = get_llm(is_heavy_task=True).with_structured_output(UserIdentityGist)
|
| 137 |
gist_prompt = ChatPromptTemplate.from_template(get_prompt("identity_architect"))
|
| 138 |
+
new_gist_obj = await (gist_prompt | gist_llm).ainvoke({"old_gist": json.dumps(old_gist), "new_history": history_str, "active_persona": str(user_id)})
|
| 139 |
+
if new_gist_obj:
|
| 140 |
+
new_gist = new_gist_obj.model_dump()
|
| 141 |
+
except Exception:
|
| 142 |
+
pass
|
| 143 |
|
| 144 |
async with async_session_factory() as db:
|
| 145 |
from models.user import User
|
|
|
|
| 157 |
await db.commit()
|
| 158 |
break
|
| 159 |
except Exception as e:
|
| 160 |
+
if attempt == 3:
|
| 161 |
+
logger.error(f"Crystallization failed: {e}")
|
| 162 |
await asyncio.sleep(attempt * 7)
|
| 163 |
|
| 164 |
async def summarize_thread_title(ctx, thread_id: UUID, user_query: str, ai_response: str, **kwargs):
|
|
|
|
| 185 |
await db.execute(
|
| 186 |
update(NexusThread)
|
| 187 |
.where(NexusThread.id == thread_id)
|
| 188 |
+
.values(title=new_title, updated_at=datetime.now(timezone.utc))
|
| 189 |
)
|
| 190 |
await db.commit()
|
| 191 |
logger.info(f"🏷️ Updated Thread Title: {thread_id} -> {new_title}")
|
| 192 |
break
|
| 193 |
except Exception as e:
|
| 194 |
+
if attempt == 3:
|
| 195 |
+
logger.error(f"Thread title summarization failed for {thread_id}: {e}")
|
| 196 |
await asyncio.sleep(attempt * 3)
|
| 197 |
|
| 198 |
async def index_kb_article(ctx, article_id: UUID, **kwargs):
|
| 199 |
"""Full KB indexing lifecycle."""
|
| 200 |
+
if not await check_job_latch(ctx, article_id, "index_kb_article"):
|
| 201 |
+
return
|
| 202 |
|
| 203 |
async with async_session_factory() as db:
|
| 204 |
try:
|
| 205 |
stmt = select(KBArticle).where(KBArticle.id == article_id, KBArticle.deleted_at.is_(None))
|
| 206 |
article = (await db.execute(stmt)).scalar_one_or_none()
|
| 207 |
+
if not article:
|
| 208 |
+
return
|
| 209 |
|
| 210 |
text_model = get_text_embeddings()
|
| 211 |
llm = get_llm()
|
|
|
|
| 259 |
# Only overwrite if it's a generic placeholder
|
| 260 |
if article.category in [None, "Imported", "General", "Uncategorized"]:
|
| 261 |
article.category = ai_data.get("category", "GENERAL").upper()
|
| 262 |
+
except Exception:
|
| 263 |
# Fallback to simple summary if JSON fails
|
| 264 |
article.summary = str(resp.content)
|
| 265 |
|
|
|
|
| 273 |
async with async_session_factory() as db:
|
| 274 |
stmt = select(Ticket).where(Ticket.id == ticket_id, Ticket.deleted_at.is_(None))
|
| 275 |
ticket = (await db.execute(stmt)).scalar_one_or_none()
|
| 276 |
+
if not ticket:
|
| 277 |
+
return
|
| 278 |
|
| 279 |
try:
|
| 280 |
await sync_markdown_images(db, ticket.id, ticket.workspace_id, ticket.description, entity_type="ticket", uploader_id=ticket.created_by)
|
|
|
|
| 306 |
vector = await text_model.aembed_query(content)
|
| 307 |
db.add(NexusMemory(workspace_id=workspace_id, user_id=user_id, content=content, thread_id=thread_id, interaction_id=interaction_id, memory_type=memory_type, embedding=vector))
|
| 308 |
await db.commit()
|
| 309 |
+
if thread_id:
|
| 310 |
+
await invalidate_cache(f"nexus:thread:{thread_id}:masked")
|
| 311 |
|
| 312 |
async def generate_global_insight(ctx, *args, **kwargs):
|
| 313 |
"""Generate platform-wide strategic summary."""
|
| 314 |
from tasks.system import check_cron_lock
|
| 315 |
+
if not await check_cron_lock(ctx, "generate_global_insight", window_seconds=600):
|
| 316 |
+
return
|
| 317 |
|
| 318 |
from models.platform_insight import PlatformInsight
|
| 319 |
async with async_session_factory() as db:
|
| 320 |
stmt = select(NexusMemory.content).where(NexusMemory.memory_type == "interaction").order_by(desc(NexusMemory.created_at)).limit(150)
|
| 321 |
memories = (await db.execute(stmt)).scalars().all()
|
| 322 |
+
if not memories:
|
| 323 |
+
return
|
| 324 |
|
| 325 |
llm = get_llm()
|
| 326 |
resp = await llm.ainvoke(f"Analyze these interactions and provide a JSON summary and trends: {' '.join(memories)}")
|
|
|
|
| 328 |
insights = json.loads(str(resp.content).strip().replace("```json", "").replace("```", ""))
|
| 329 |
db.add(PlatformInsight(summary=insights.get("summary"), trends=insights.get("trends")))
|
| 330 |
await db.commit()
|
| 331 |
+
except Exception:
|
| 332 |
+
pass
|
| 333 |
|
| 334 |
async def refresh_active_workspace_insights(ctx, **kwargs):
|
| 335 |
"""Cron task to preemptively refresh insights for active workspaces."""
|
|
|
|
| 336 |
from tasks.system import enqueue_task
|
| 337 |
|
| 338 |
async with async_session_factory() as db:
|
| 339 |
# Find workspaces with tickets created/updated in the last 24h
|
| 340 |
+
day_ago = datetime.now(timezone.utc) - timedelta(days=1)
|
| 341 |
stmt = select(Ticket.workspace_id).where(
|
| 342 |
or_(Ticket.created_at >= day_ago, Ticket.updated_at >= day_ago)
|
| 343 |
).distinct()
|
|
|
|
| 361 |
|
| 362 |
async with async_session_factory() as db:
|
| 363 |
try:
|
| 364 |
+
ws_uuid = _UUID(workspace_id)
|
| 365 |
|
| 366 |
# 1. Ticket counts
|
| 367 |
count_stmt = (
|
|
|
|
| 373 |
total_tickets = sum(r.cnt for r in count_rows)
|
| 374 |
|
| 375 |
# 2. SLA breach count
|
| 376 |
+
now = datetime.now(timezone.utc)
|
| 377 |
breach_stmt = select(sqlfunc.count(Ticket.id)).where(
|
| 378 |
Ticket.workspace_id == ws_uuid,
|
| 379 |
Ticket.deleted_at.is_(None),
|
|
|
|
| 477 |
|
| 478 |
narrative = {
|
| 479 |
"insights": raw_narrative,
|
| 480 |
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 481 |
"status": "COMPLETED"
|
| 482 |
}
|
| 483 |
await set_cached_search(f"insights:narrative:v4:{workspace_id}:{role}", narrative, ttl=43200)
|
|
|
|
| 486 |
# Broadcast to all connected clients in this workspace to trigger auto-refresh
|
| 487 |
await manager.broadcast_to_workspace(ws_uuid, {
|
| 488 |
"type": "WORKSPACE_INSIGHTS_READY",
|
| 489 |
+
"workspace_id": workspace_id
|
| 490 |
})
|
| 491 |
|
| 492 |
logger.info(f"✅ Background insights generated and broadcasted for workspace: {workspace_id}")
|
|
|
|
| 510 |
async def ai_dynamic_nudge_pulse(ctx, **kwargs):
|
| 511 |
"""Identifies tickets at >75% SLA and posts resolution advice (parallel LLM calls)."""
|
| 512 |
async with async_session_factory() as db:
|
| 513 |
+
now = datetime.now(timezone.utc)
|
| 514 |
stmt = (
|
| 515 |
select(Ticket, EscalationRule)
|
| 516 |
.join(EscalationRule, (EscalationRule.workspace_id == Ticket.workspace_id) & (EscalationRule.priority_level == cast(Ticket.priority, String)))
|
tasks/analytics.py
CHANGED
|
@@ -2,9 +2,10 @@
|
|
| 2 |
Analytics and personnel-related background tasks.
|
| 3 |
"""
|
| 4 |
|
|
|
|
| 5 |
from uuid import UUID
|
| 6 |
-
from datetime import datetime, timedelta
|
| 7 |
-
from sqlalchemy import select
|
| 8 |
|
| 9 |
from core.database import async_session_factory
|
| 10 |
from core.logging import get_logger
|
|
@@ -38,20 +39,22 @@ async def harvest_expertise_task(ctx, ticket_id: UUID, **kwargs):
|
|
| 38 |
try:
|
| 39 |
stmt = select(Ticket).where(Ticket.id == ticket_id)
|
| 40 |
ticket = (await db.execute(stmt)).scalar_one_or_none()
|
| 41 |
-
if not ticket or not ticket.assigned_to:
|
|
|
|
| 42 |
|
| 43 |
msg_stmt = select(Message).where(Message.ticket_id == ticket_id).order_by(Message.created_at.asc())
|
| 44 |
msgs = (await db.execute(msg_stmt)).scalars().all()
|
| 45 |
|
| 46 |
agent_stmt = select(User).where(User.id == ticket.assigned_to)
|
| 47 |
agent = (await db.execute(agent_stmt)).scalar_one_or_none()
|
| 48 |
-
if not agent:
|
|
|
|
| 49 |
|
| 50 |
await harvest_agent_skills(db, ticket, msgs, agent)
|
| 51 |
except Exception as e:
|
| 52 |
logger.error(f"Expertise Harvesting failed: {e}")
|
| 53 |
|
| 54 |
-
async def generate_nightly_personnel_analytics(ctx, workspace_id: str = None, user_id: UUID = None, **kwargs):
|
| 55 |
"""
|
| 56 |
Gathers user activity metrics and generates an AI narrative.
|
| 57 |
If workspace_id is provided, it targets only that workspace.
|
|
@@ -59,13 +62,14 @@ async def generate_nightly_personnel_analytics(ctx, workspace_id: str = None, us
|
|
| 59 |
"""
|
| 60 |
# Only check cron lock if this is a nightly run (no workspace_id/user_id)
|
| 61 |
if not workspace_id and not user_id:
|
| 62 |
-
if not await check_cron_lock(ctx, "generate_nightly_personnel_analytics"):
|
|
|
|
| 63 |
|
| 64 |
async with async_session_factory() as db:
|
| 65 |
# 1. Fetch memberships to process
|
| 66 |
stmt = select(UserWorkspace).where(
|
| 67 |
UserWorkspace.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]),
|
| 68 |
-
UserWorkspace.is_active
|
| 69 |
)
|
| 70 |
if workspace_id:
|
| 71 |
stmt = stmt.where(UserWorkspace.workspace_id == UUID(workspace_id))
|
|
@@ -74,7 +78,7 @@ async def generate_nightly_personnel_analytics(ctx, workspace_id: str = None, us
|
|
| 74 |
|
| 75 |
memberships = (await db.execute(stmt)).scalars().all()
|
| 76 |
|
| 77 |
-
now = datetime.
|
| 78 |
last_30d = now - timedelta(days=30)
|
| 79 |
|
| 80 |
# 2. Fetch escalation rules (workspace-aware)
|
|
@@ -188,7 +192,7 @@ async def generate_nightly_personnel_analytics(ctx, workspace_id: str = None, us
|
|
| 188 |
try:
|
| 189 |
await manager.broadcast_to_workspace(UUID(workspace_id), {
|
| 190 |
"type": "PERSONNEL_ANALYTICS_READY",
|
| 191 |
-
"workspace_id":
|
| 192 |
})
|
| 193 |
logger.info(f"✅ Personnel analytics ready signal broadcasted for workspace: {workspace_id}")
|
| 194 |
except Exception as broadcast_err:
|
|
|
|
| 2 |
Analytics and personnel-related background tasks.
|
| 3 |
"""
|
| 4 |
|
| 5 |
+
from typing import Optional, Dict
|
| 6 |
from uuid import UUID
|
| 7 |
+
from datetime import datetime, timezone, timedelta
|
| 8 |
+
from sqlalchemy import select
|
| 9 |
|
| 10 |
from core.database import async_session_factory
|
| 11 |
from core.logging import get_logger
|
|
|
|
| 39 |
try:
|
| 40 |
stmt = select(Ticket).where(Ticket.id == ticket_id)
|
| 41 |
ticket = (await db.execute(stmt)).scalar_one_or_none()
|
| 42 |
+
if not ticket or not ticket.assigned_to:
|
| 43 |
+
return
|
| 44 |
|
| 45 |
msg_stmt = select(Message).where(Message.ticket_id == ticket_id).order_by(Message.created_at.asc())
|
| 46 |
msgs = (await db.execute(msg_stmt)).scalars().all()
|
| 47 |
|
| 48 |
agent_stmt = select(User).where(User.id == ticket.assigned_to)
|
| 49 |
agent = (await db.execute(agent_stmt)).scalar_one_or_none()
|
| 50 |
+
if not agent:
|
| 51 |
+
return
|
| 52 |
|
| 53 |
await harvest_agent_skills(db, ticket, msgs, agent)
|
| 54 |
except Exception as e:
|
| 55 |
logger.error(f"Expertise Harvesting failed: {e}")
|
| 56 |
|
| 57 |
+
async def generate_nightly_personnel_analytics(ctx, workspace_id: Optional[str] = None, user_id: Optional[UUID] = None, **kwargs):
|
| 58 |
"""
|
| 59 |
Gathers user activity metrics and generates an AI narrative.
|
| 60 |
If workspace_id is provided, it targets only that workspace.
|
|
|
|
| 62 |
"""
|
| 63 |
# Only check cron lock if this is a nightly run (no workspace_id/user_id)
|
| 64 |
if not workspace_id and not user_id:
|
| 65 |
+
if not await check_cron_lock(ctx, "generate_nightly_personnel_analytics"):
|
| 66 |
+
return
|
| 67 |
|
| 68 |
async with async_session_factory() as db:
|
| 69 |
# 1. Fetch memberships to process
|
| 70 |
stmt = select(UserWorkspace).where(
|
| 71 |
UserWorkspace.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]),
|
| 72 |
+
UserWorkspace.is_active
|
| 73 |
)
|
| 74 |
if workspace_id:
|
| 75 |
stmt = stmt.where(UserWorkspace.workspace_id == UUID(workspace_id))
|
|
|
|
| 78 |
|
| 79 |
memberships = (await db.execute(stmt)).scalars().all()
|
| 80 |
|
| 81 |
+
now = datetime.now(timezone.utc)
|
| 82 |
last_30d = now - timedelta(days=30)
|
| 83 |
|
| 84 |
# 2. Fetch escalation rules (workspace-aware)
|
|
|
|
| 192 |
try:
|
| 193 |
await manager.broadcast_to_workspace(UUID(workspace_id), {
|
| 194 |
"type": "PERSONNEL_ANALYTICS_READY",
|
| 195 |
+
"workspace_id": workspace_id
|
| 196 |
})
|
| 197 |
logger.info(f"✅ Personnel analytics ready signal broadcasted for workspace: {workspace_id}")
|
| 198 |
except Exception as broadcast_err:
|
tasks/notifications.py
CHANGED
|
@@ -4,7 +4,7 @@ Notification background tasks.
|
|
| 4 |
|
| 5 |
from typing import Optional
|
| 6 |
from uuid import UUID
|
| 7 |
-
from datetime import datetime
|
| 8 |
from sqlalchemy import select
|
| 9 |
|
| 10 |
from core.database import async_session_factory
|
|
@@ -43,7 +43,7 @@ async def send_triple_notification(ctx, user_id: UUID, workspace_id: UUID, title
|
|
| 43 |
"title": title,
|
| 44 |
"message": message,
|
| 45 |
"link": link,
|
| 46 |
-
"created_at": datetime.
|
| 47 |
})
|
| 48 |
|
| 49 |
if delivery_target:
|
|
@@ -57,7 +57,7 @@ async def send_triple_notification(ctx, user_id: UUID, workspace_id: UUID, title
|
|
| 57 |
email_html = template_nexus_email(
|
| 58 |
title=title,
|
| 59 |
message=message,
|
| 60 |
-
action_link=resource_url,
|
| 61 |
action_label="View Details",
|
| 62 |
footer_note=f"Workspace: {workspace_id} | Security Alert level: High"
|
| 63 |
)
|
|
|
|
| 4 |
|
| 5 |
from typing import Optional
|
| 6 |
from uuid import UUID
|
| 7 |
+
from datetime import datetime, timezone
|
| 8 |
from sqlalchemy import select
|
| 9 |
|
| 10 |
from core.database import async_session_factory
|
|
|
|
| 43 |
"title": title,
|
| 44 |
"message": message,
|
| 45 |
"link": link,
|
| 46 |
+
"created_at": datetime.now(timezone.utc).isoformat()
|
| 47 |
})
|
| 48 |
|
| 49 |
if delivery_target:
|
|
|
|
| 57 |
email_html = template_nexus_email(
|
| 58 |
title=title,
|
| 59 |
message=message,
|
| 60 |
+
action_link=resource_url or "",
|
| 61 |
action_label="View Details",
|
| 62 |
footer_note=f"Workspace: {workspace_id} | Security Alert level: High"
|
| 63 |
)
|
tasks/remediation.py
CHANGED
|
@@ -24,7 +24,8 @@ async def execute_remediation_hook(ctx, ticket_id: str, hook_id: str, **kwargs):
|
|
| 24 |
ticket = (await db.execute(ticket_stmt)).scalar_one_or_none()
|
| 25 |
hook = (await db.execute(hook_stmt)).scalar_one_or_none()
|
| 26 |
|
| 27 |
-
if not ticket or not hook:
|
|
|
|
| 28 |
|
| 29 |
if hook.action_type == RemediationActionType.WEBHOOK:
|
| 30 |
async with httpx.AsyncClient() as client:
|
|
@@ -32,8 +33,10 @@ async def execute_remediation_hook(ctx, ticket_id: str, hook_id: str, **kwargs):
|
|
| 32 |
payload_str = str(hook.payload_template).replace("{{ticket_id}}", str(ticket.id))
|
| 33 |
payload = json.loads(payload_str)
|
| 34 |
resp = await client.post(hook.target, json=payload, timeout=10.0)
|
| 35 |
-
if resp.status_code >= 400:
|
| 36 |
-
|
|
|
|
|
|
|
| 37 |
|
| 38 |
ticket.status = TicketStatus.RESOLVED
|
| 39 |
db.add(ticket)
|
|
|
|
| 24 |
ticket = (await db.execute(ticket_stmt)).scalar_one_or_none()
|
| 25 |
hook = (await db.execute(hook_stmt)).scalar_one_or_none()
|
| 26 |
|
| 27 |
+
if not ticket or not hook:
|
| 28 |
+
return
|
| 29 |
|
| 30 |
if hook.action_type == RemediationActionType.WEBHOOK:
|
| 31 |
async with httpx.AsyncClient() as client:
|
|
|
|
| 33 |
payload_str = str(hook.payload_template).replace("{{ticket_id}}", str(ticket.id))
|
| 34 |
payload = json.loads(payload_str)
|
| 35 |
resp = await client.post(hook.target, json=payload, timeout=10.0)
|
| 36 |
+
if resp.status_code >= 400:
|
| 37 |
+
return
|
| 38 |
+
except Exception:
|
| 39 |
+
return
|
| 40 |
|
| 41 |
ticket.status = TicketStatus.RESOLVED
|
| 42 |
db.add(ticket)
|
tasks/stories.py
CHANGED
|
@@ -1,13 +1,13 @@
|
|
| 1 |
-
import asyncio
|
| 2 |
import logging
|
| 3 |
import json
|
| 4 |
import io
|
|
|
|
| 5 |
from uuid import UUID
|
| 6 |
-
from datetime import datetime
|
| 7 |
-
from sqlalchemy import select, update
|
| 8 |
from core.database import async_session_factory
|
| 9 |
from models.workspace_story import WorkspaceStory, StoryStatus
|
| 10 |
-
from models.ticket import Ticket
|
| 11 |
from core.llm import get_llm
|
| 12 |
from core.storage import get_storage_provider
|
| 13 |
from core.websockets import manager
|
|
@@ -53,7 +53,7 @@ def _s(text: str) -> str:
|
|
| 53 |
"""Sanitize LLM-generated text for fpdf Latin-1 helvetica rendering."""
|
| 54 |
if not text:
|
| 55 |
return ""
|
| 56 |
-
text =
|
| 57 |
return text.encode("latin-1", errors="replace").decode("latin-1")
|
| 58 |
|
| 59 |
# ---------------------------------------------------------------------------
|
|
@@ -85,7 +85,7 @@ async def generate_workspace_story_task(ctx, story_id: UUID, user_id: UUID, work
|
|
| 85 |
|
| 86 |
await manager.broadcast_to_workspace(workspace_id, {
|
| 87 |
"event": "nexus_story_updated",
|
| 88 |
-
"story_id":
|
| 89 |
"status": "processing"
|
| 90 |
})
|
| 91 |
|
|
@@ -94,7 +94,7 @@ async def generate_workspace_story_task(ctx, story_id: UUID, user_id: UUID, work
|
|
| 94 |
from datetime import timedelta
|
| 95 |
from models.feedback import Feedback
|
| 96 |
|
| 97 |
-
thirty_days_ago = datetime.
|
| 98 |
|
| 99 |
# --- Snapshot aggregates ---
|
| 100 |
status_stmt = (
|
|
@@ -184,7 +184,7 @@ async def generate_workspace_story_task(ctx, story_id: UUID, user_id: UUID, work
|
|
| 184 |
for t in tickets
|
| 185 |
],
|
| 186 |
"role": role,
|
| 187 |
-
"timestamp": datetime.
|
| 188 |
}
|
| 189 |
|
| 190 |
story_stmt = select(WorkspaceStory).where(WorkspaceStory.id == story_id)
|
|
@@ -305,7 +305,7 @@ Rules:
|
|
| 305 |
|
| 306 |
storage = get_storage_provider()
|
| 307 |
storage_result = await storage.upload(
|
| 308 |
-
file_content=binary_content,
|
| 309 |
filename=file_name,
|
| 310 |
workspace_id=workspace_id,
|
| 311 |
)
|
|
@@ -327,7 +327,7 @@ Rules:
|
|
| 327 |
|
| 328 |
await manager.broadcast_to_workspace(workspace_id, {
|
| 329 |
"event": "nexus_story_updated",
|
| 330 |
-
"story_id":
|
| 331 |
"status": "completed",
|
| 332 |
})
|
| 333 |
|
|
@@ -343,7 +343,7 @@ Rules:
|
|
| 343 |
await db.commit()
|
| 344 |
await manager.broadcast_to_workspace(workspace_id, {
|
| 345 |
"event": "nexus_story_updated",
|
| 346 |
-
"story_id":
|
| 347 |
"status": "failed",
|
| 348 |
"error": str(e),
|
| 349 |
})
|
|
@@ -357,8 +357,8 @@ def generate_enterprise_pdf(report, context):
|
|
| 357 |
"""Production-grade PDF: TOC, KPI summary, trend charts, role-specific sections."""
|
| 358 |
report = _recursive_clean_text(report)
|
| 359 |
context = _recursive_clean_text(context)
|
| 360 |
-
from fpdf import FPDF
|
| 361 |
-
from fpdf.fonts import FontFace
|
| 362 |
|
| 363 |
class EnterprisePDF(FPDF):
|
| 364 |
def header(self):
|
|
@@ -506,7 +506,7 @@ def generate_enterprise_pdf(report, context):
|
|
| 506 |
pdf.add_page()
|
| 507 |
pdf.section_header(1, "Executive Summary")
|
| 508 |
|
| 509 |
-
pdf.set_font("helvetica", "", 10.5)
|
| 510 |
pdf.set_text_color(*TEXT_MAIN)
|
| 511 |
pdf.multi_cell(0, 6, _s(report["executive_summary"]))
|
| 512 |
pdf.ln(8)
|
|
@@ -613,7 +613,7 @@ def generate_enterprise_pdf(report, context):
|
|
| 613 |
pdf.add_page()
|
| 614 |
pdf.section_header(4 + i, _s(section["title"]))
|
| 615 |
|
| 616 |
-
pdf.set_font("helvetica", "", 10.5)
|
| 617 |
pdf.set_text_color(*TEXT_MAIN)
|
| 618 |
pdf.multi_cell(0, 6.5, _s(section.get("content", "")))
|
| 619 |
pdf.ln(8)
|
|
|
|
|
|
|
| 1 |
import logging
|
| 2 |
import json
|
| 3 |
import io
|
| 4 |
+
from typing import Optional, Dict, Any, List
|
| 5 |
from uuid import UUID
|
| 6 |
+
from datetime import datetime, timezone, timedelta
|
| 7 |
+
from sqlalchemy import select, update, func
|
| 8 |
from core.database import async_session_factory
|
| 9 |
from models.workspace_story import WorkspaceStory, StoryStatus
|
| 10 |
+
from models.ticket import Ticket
|
| 11 |
from core.llm import get_llm
|
| 12 |
from core.storage import get_storage_provider
|
| 13 |
from core.websockets import manager
|
|
|
|
| 53 |
"""Sanitize LLM-generated text for fpdf Latin-1 helvetica rendering."""
|
| 54 |
if not text:
|
| 55 |
return ""
|
| 56 |
+
text = text.translate(_UNICODE_REPLACEMENTS)
|
| 57 |
return text.encode("latin-1", errors="replace").decode("latin-1")
|
| 58 |
|
| 59 |
# ---------------------------------------------------------------------------
|
|
|
|
| 85 |
|
| 86 |
await manager.broadcast_to_workspace(workspace_id, {
|
| 87 |
"event": "nexus_story_updated",
|
| 88 |
+
"story_id": story_id,
|
| 89 |
"status": "processing"
|
| 90 |
})
|
| 91 |
|
|
|
|
| 94 |
from datetime import timedelta
|
| 95 |
from models.feedback import Feedback
|
| 96 |
|
| 97 |
+
thirty_days_ago = datetime.now(timezone.utc) - timedelta(days=30)
|
| 98 |
|
| 99 |
# --- Snapshot aggregates ---
|
| 100 |
status_stmt = (
|
|
|
|
| 184 |
for t in tickets
|
| 185 |
],
|
| 186 |
"role": role,
|
| 187 |
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 188 |
}
|
| 189 |
|
| 190 |
story_stmt = select(WorkspaceStory).where(WorkspaceStory.id == story_id)
|
|
|
|
| 305 |
|
| 306 |
storage = get_storage_provider()
|
| 307 |
storage_result = await storage.upload(
|
| 308 |
+
file_content=bytes(binary_content),
|
| 309 |
filename=file_name,
|
| 310 |
workspace_id=workspace_id,
|
| 311 |
)
|
|
|
|
| 327 |
|
| 328 |
await manager.broadcast_to_workspace(workspace_id, {
|
| 329 |
"event": "nexus_story_updated",
|
| 330 |
+
"story_id": story_id,
|
| 331 |
"status": "completed",
|
| 332 |
})
|
| 333 |
|
|
|
|
| 343 |
await db.commit()
|
| 344 |
await manager.broadcast_to_workspace(workspace_id, {
|
| 345 |
"event": "nexus_story_updated",
|
| 346 |
+
"story_id": story_id,
|
| 347 |
"status": "failed",
|
| 348 |
"error": str(e),
|
| 349 |
})
|
|
|
|
| 357 |
"""Production-grade PDF: TOC, KPI summary, trend charts, role-specific sections."""
|
| 358 |
report = _recursive_clean_text(report)
|
| 359 |
context = _recursive_clean_text(context)
|
| 360 |
+
from fpdf import FPDF # type: ignore
|
| 361 |
+
from fpdf.fonts import FontFace # type: ignore
|
| 362 |
|
| 363 |
class EnterprisePDF(FPDF):
|
| 364 |
def header(self):
|
|
|
|
| 506 |
pdf.add_page()
|
| 507 |
pdf.section_header(1, "Executive Summary")
|
| 508 |
|
| 509 |
+
pdf.set_font("helvetica", "", 10.5) # type: ignore
|
| 510 |
pdf.set_text_color(*TEXT_MAIN)
|
| 511 |
pdf.multi_cell(0, 6, _s(report["executive_summary"]))
|
| 512 |
pdf.ln(8)
|
|
|
|
| 613 |
pdf.add_page()
|
| 614 |
pdf.section_header(4 + i, _s(section["title"]))
|
| 615 |
|
| 616 |
+
pdf.set_font("helvetica", "", 10.5) # type: ignore
|
| 617 |
pdf.set_text_color(*TEXT_MAIN)
|
| 618 |
pdf.multi_cell(0, 6.5, _s(section.get("content", "")))
|
| 619 |
pdf.ln(8)
|
tasks/system.py
CHANGED
|
@@ -6,7 +6,7 @@ import time
|
|
| 6 |
import asyncio
|
| 7 |
from typing import Any, Dict, Optional
|
| 8 |
from uuid import UUID
|
| 9 |
-
from datetime import datetime, timedelta
|
| 10 |
from sqlalchemy import select, func, text, cast, String
|
| 11 |
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
| 12 |
|
|
@@ -51,7 +51,7 @@ async def check_cron_lock(ctx, task_name: str, window_seconds: int = 60) -> bool
|
|
| 51 |
|
| 52 |
async with async_session_factory() as db:
|
| 53 |
try:
|
| 54 |
-
limit = datetime.
|
| 55 |
stmt = select(WorkerJob).where(
|
| 56 |
WorkerJob.id == job_id,
|
| 57 |
WorkerJob.status == JobStatus.SUCCESS
|
|
@@ -105,6 +105,7 @@ async def enqueue_task(task_or_pool: Any, *args, **kwargs):
|
|
| 105 |
"""
|
| 106 |
Enqueues an ARQ job and updates the deduplication latch in Redis.
|
| 107 |
"""
|
|
|
|
| 108 |
try:
|
| 109 |
# Always use the internal singleton pool — callers that pass a pool as
|
| 110 |
# the first argument (legacy pattern) still work, but a FastAPI Depends
|
|
@@ -156,7 +157,7 @@ async def enqueue_task(task_or_pool: Any, *args, **kwargs):
|
|
| 156 |
task_kwargs['metadata_json'] = {
|
| 157 |
"entity_id": str(entity_id),
|
| 158 |
"task_group": queue_name.split(':')[-1],
|
| 159 |
-
"enqueued_at": datetime.
|
| 160 |
"latch_key_override": task_name
|
| 161 |
}
|
| 162 |
|
|
@@ -192,7 +193,7 @@ async def enqueue_task(task_or_pool: Any, *args, **kwargs):
|
|
| 192 |
job_uuid = get_deterministic_uuid(raw_job_id)
|
| 193 |
|
| 194 |
try:
|
| 195 |
-
now = datetime.
|
| 196 |
values = dict(
|
| 197 |
id=job_uuid,
|
| 198 |
task_name=task_name,
|
|
@@ -246,7 +247,7 @@ async def record_workflow_step_task(
|
|
| 246 |
step_name=step_name,
|
| 247 |
input_data=input_data,
|
| 248 |
output_data=output_data,
|
| 249 |
-
current_stage=current_stage,
|
| 250 |
duration_ms=duration_ms or 0.0
|
| 251 |
)
|
| 252 |
await db.commit()
|
|
@@ -261,11 +262,10 @@ async def monitor_sla_thresholds(ctx, *args, **kwargs):
|
|
| 261 |
return
|
| 262 |
|
| 263 |
from core.cache import get_redis_client, invalidate_cache
|
| 264 |
-
from tasks.notifications import send_triple_notification
|
| 265 |
|
| 266 |
logger.info("Starting SLA monitoring check...")
|
| 267 |
async with async_session_factory() as db:
|
| 268 |
-
now = datetime.
|
| 269 |
stmt = (
|
| 270 |
select(Ticket, EscalationRule)
|
| 271 |
.join(EscalationRule, (EscalationRule.workspace_id == Ticket.workspace_id) & (EscalationRule.priority_level == cast(Ticket.priority, String)))
|
|
@@ -417,7 +417,8 @@ async def record_system_heartbeat(ctx, *args, **kwargs):
|
|
| 417 |
await db.execute(text("SELECT 1"))
|
| 418 |
db_status = ServiceStatus.UP
|
| 419 |
db_latency = (time.perf_counter() - db_start) * 1000
|
| 420 |
-
except Exception:
|
|
|
|
| 421 |
db.add(MetaInfraHealth(service_name="DATABASE", status=db_status, latency_ms=db_latency, environment="production"))
|
| 422 |
|
| 423 |
# Redis check
|
|
@@ -425,10 +426,11 @@ async def record_system_heartbeat(ctx, *args, **kwargs):
|
|
| 425 |
redis_status = ServiceStatus.DOWN
|
| 426 |
redis_latency = 0
|
| 427 |
try:
|
| 428 |
-
|
| 429 |
redis_status = ServiceStatus.UP
|
| 430 |
redis_latency = (time.perf_counter() - redis_start) * 1000
|
| 431 |
-
except Exception:
|
|
|
|
| 432 |
db.add(MetaInfraHealth(service_name="REDIS", status=redis_status, latency_ms=redis_latency, environment="production"))
|
| 433 |
|
| 434 |
# Ollama check
|
|
@@ -441,7 +443,8 @@ async def record_system_heartbeat(ctx, *args, **kwargs):
|
|
| 441 |
if resp.status_code == 200:
|
| 442 |
ollama_status = ServiceStatus.UP
|
| 443 |
ollama_latency = (time.perf_counter() - ollama_start) * 1000
|
| 444 |
-
except Exception:
|
|
|
|
| 445 |
db.add(MetaInfraHealth(service_name="OLLAMA", status=ollama_status, latency_ms=ollama_latency, environment="production"))
|
| 446 |
|
| 447 |
await db.commit()
|
|
@@ -457,7 +460,7 @@ async def nexus_pulse_check(ctx, *args, **kwargs):
|
|
| 457 |
from core.websockets import manager
|
| 458 |
|
| 459 |
async with async_session_factory() as db:
|
| 460 |
-
fifteen_mins_ago = datetime.
|
| 461 |
stmt = select(Ticket.workspace_id).where(Ticket.updated_at >= fifteen_mins_ago).distinct()
|
| 462 |
workspaces = (await db.execute(stmt)).scalars().all()
|
| 463 |
|
|
@@ -479,7 +482,8 @@ async def nexus_pulse_check(ctx, *args, **kwargs):
|
|
| 479 |
manager.broadcast_to_role(w_id, "3sc_lead", alert),
|
| 480 |
return_exceptions=True
|
| 481 |
)
|
| 482 |
-
except Exception:
|
|
|
|
| 483 |
|
| 484 |
async def purge_stale_semantic_cache(ctx, *args, **kwargs):
|
| 485 |
"""
|
|
@@ -523,7 +527,8 @@ async def recover_nexus_history(ctx, thread_id: UUID, workspace_id: UUID, user_r
|
|
| 523 |
)
|
| 524 |
result = await db.execute(stmt)
|
| 525 |
rows = result.all()
|
| 526 |
-
if not rows:
|
|
|
|
| 527 |
|
| 528 |
interaction_dicts = [dict(
|
| 529 |
id=i.id,
|
|
|
|
| 6 |
import asyncio
|
| 7 |
from typing import Any, Dict, Optional
|
| 8 |
from uuid import UUID
|
| 9 |
+
from datetime import datetime, timedelta, timezone
|
| 10 |
from sqlalchemy import select, func, text, cast, String
|
| 11 |
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
| 12 |
|
|
|
|
| 51 |
|
| 52 |
async with async_session_factory() as db:
|
| 53 |
try:
|
| 54 |
+
limit = datetime.now(timezone.utc) - timedelta(seconds=window_seconds)
|
| 55 |
stmt = select(WorkerJob).where(
|
| 56 |
WorkerJob.id == job_id,
|
| 57 |
WorkerJob.status == JobStatus.SUCCESS
|
|
|
|
| 105 |
"""
|
| 106 |
Enqueues an ARQ job and updates the deduplication latch in Redis.
|
| 107 |
"""
|
| 108 |
+
task_name = "unknown"
|
| 109 |
try:
|
| 110 |
# Always use the internal singleton pool — callers that pass a pool as
|
| 111 |
# the first argument (legacy pattern) still work, but a FastAPI Depends
|
|
|
|
| 157 |
task_kwargs['metadata_json'] = {
|
| 158 |
"entity_id": str(entity_id),
|
| 159 |
"task_group": queue_name.split(':')[-1],
|
| 160 |
+
"enqueued_at": datetime.now(timezone.utc).isoformat(),
|
| 161 |
"latch_key_override": task_name
|
| 162 |
}
|
| 163 |
|
|
|
|
| 193 |
job_uuid = get_deterministic_uuid(raw_job_id)
|
| 194 |
|
| 195 |
try:
|
| 196 |
+
now = datetime.now(timezone.utc)
|
| 197 |
values = dict(
|
| 198 |
id=job_uuid,
|
| 199 |
task_name=task_name,
|
|
|
|
| 247 |
step_name=step_name,
|
| 248 |
input_data=input_data,
|
| 249 |
output_data=output_data,
|
| 250 |
+
current_stage=current_stage or "",
|
| 251 |
duration_ms=duration_ms or 0.0
|
| 252 |
)
|
| 253 |
await db.commit()
|
|
|
|
| 262 |
return
|
| 263 |
|
| 264 |
from core.cache import get_redis_client, invalidate_cache
|
|
|
|
| 265 |
|
| 266 |
logger.info("Starting SLA monitoring check...")
|
| 267 |
async with async_session_factory() as db:
|
| 268 |
+
now = datetime.now(timezone.utc)
|
| 269 |
stmt = (
|
| 270 |
select(Ticket, EscalationRule)
|
| 271 |
.join(EscalationRule, (EscalationRule.workspace_id == Ticket.workspace_id) & (EscalationRule.priority_level == cast(Ticket.priority, String)))
|
|
|
|
| 417 |
await db.execute(text("SELECT 1"))
|
| 418 |
db_status = ServiceStatus.UP
|
| 419 |
db_latency = (time.perf_counter() - db_start) * 1000
|
| 420 |
+
except Exception:
|
| 421 |
+
pass
|
| 422 |
db.add(MetaInfraHealth(service_name="DATABASE", status=db_status, latency_ms=db_latency, environment="production"))
|
| 423 |
|
| 424 |
# Redis check
|
|
|
|
| 426 |
redis_status = ServiceStatus.DOWN
|
| 427 |
redis_latency = 0
|
| 428 |
try:
|
| 429 |
+
await create_pool(get_redis_settings())
|
| 430 |
redis_status = ServiceStatus.UP
|
| 431 |
redis_latency = (time.perf_counter() - redis_start) * 1000
|
| 432 |
+
except Exception:
|
| 433 |
+
pass
|
| 434 |
db.add(MetaInfraHealth(service_name="REDIS", status=redis_status, latency_ms=redis_latency, environment="production"))
|
| 435 |
|
| 436 |
# Ollama check
|
|
|
|
| 443 |
if resp.status_code == 200:
|
| 444 |
ollama_status = ServiceStatus.UP
|
| 445 |
ollama_latency = (time.perf_counter() - ollama_start) * 1000
|
| 446 |
+
except Exception:
|
| 447 |
+
pass
|
| 448 |
db.add(MetaInfraHealth(service_name="OLLAMA", status=ollama_status, latency_ms=ollama_latency, environment="production"))
|
| 449 |
|
| 450 |
await db.commit()
|
|
|
|
| 460 |
from core.websockets import manager
|
| 461 |
|
| 462 |
async with async_session_factory() as db:
|
| 463 |
+
fifteen_mins_ago = datetime.now(timezone.utc) - timedelta(minutes=15)
|
| 464 |
stmt = select(Ticket.workspace_id).where(Ticket.updated_at >= fifteen_mins_ago).distinct()
|
| 465 |
workspaces = (await db.execute(stmt)).scalars().all()
|
| 466 |
|
|
|
|
| 482 |
manager.broadcast_to_role(w_id, "3sc_lead", alert),
|
| 483 |
return_exceptions=True
|
| 484 |
)
|
| 485 |
+
except Exception:
|
| 486 |
+
pass
|
| 487 |
|
| 488 |
async def purge_stale_semantic_cache(ctx, *args, **kwargs):
|
| 489 |
"""
|
|
|
|
| 527 |
)
|
| 528 |
result = await db.execute(stmt)
|
| 529 |
rows = result.all()
|
| 530 |
+
if not rows:
|
| 531 |
+
return []
|
| 532 |
|
| 533 |
interaction_dicts = [dict(
|
| 534 |
id=i.id,
|