Spaces:
Paused
Paused
Download core/tasks.py from 3SCError404/nexus: direct link, hf CLI and curl.
- Browser
- Download file 67.4 kB
-
https://huggingface.co/spaces/3SCError404/nexus/resolve/main/core/tasks.py
- Command line
-
hf download hf://spaces/3SCError404/nexus/core/tasks.py
-
curl -L -o tasks.py https://huggingface.co/spaces/3SCError404/nexus/resolve/main/core/tasks.py
67.4 kB
"""
Background task definitions for Arq worker.
"""
import httpx
from typing import Optional, Dict, Any
from uuid import UUID
from datetime import datetime, timedelta
from sqlalchemy import select, func, desc, text, delete, cast, String
from core.database import async_session_factory
from core.logging import get_logger
from models.ticket import Ticket, TicketStatus
from models.notification import Notification
from models.audit_log import AuditLog
from models.escalation_rule import EscalationRule
from models.message import Message
from models.kb_article import KBArticle
from core.llm import get_llm, get_text_embeddings, get_image_embeddings
from core.vision import extract_visual_context, resolve_image
from langchain_core.prompts import ChatPromptTemplate
from langchain.schema import HumanMessage, SystemMessage
from models.attachment import Attachment
from models.meta_infra_health import MetaInfraHealth, ServiceStatus
from models.kb_article_chunk import KBArticleChunk
from models.workspace import Workspace
from core.search import chunk_text
from core.sync import sync_markdown_images
from core.observability import record_workflow_step
from core.config import get_settings
from core.email import send_email
import time
import json
settings = get_settings()
logger = get_logger(__name__)
async def auto_summarize_ticket(ctx, ticket_id: UUID):
"""
Background task to generate dual summaries (Internal/Customer).
"""
async with async_session_factory() as db:
# 1. Fetch Ticket
stmt = select(Ticket).where(
Ticket.id == ticket_id,
Ticket.deleted_at.is_(None)
)
result = await db.execute(stmt)
ticket = result.scalar_one_or_none()
if not ticket:
return
# 2. Fetch Messages
msg_stmt = select(Message).where(
Message.ticket_id == ticket_id,
Message.deleted_at.is_(None)
).order_by(Message.created_at.asc())
msg_result = await db.execute(msg_stmt)
messages = msg_result.scalars().all()
# 3. Partition Messages
public_messages = [m for m in messages if not m.is_internal]
llm = get_llm()
def format_convo(msg_list):
return "\n".join([f"{'['+'INTERNAL'+'] ' if m.is_internal else ''}{m.sender_id}: {m.content}" for m in msg_list])
# 4. Multimodal Resolution
# Resolve images from description and messages
all_imgs = await extract_visual_context(db, ticket.workspace_id, ticket.description, limit=3)
for m in messages:
if len(all_imgs) >= 10: break
all_imgs.extend(await extract_visual_context(db, ticket.workspace_id, m.content, limit=2))
# Customer Summary
cust_txt = f"Title: {ticket.title}\nDescription: {ticket.description}\n\nConversation:\n{format_convo(public_messages)}"
cust_blocks = [{"type": "text", "text": cust_txt}]
# Only include images found in public messages or description
cust_blocks.extend(all_imgs[:5]) # Hard limit for customer
cust_prompt = [
SystemMessage(content="You are a support assistant. Summarize for a CUSTOMER. No internal jargon. Max 3 sentences."),
HumanMessage(content=cust_blocks)
]
# Internal Summary
intl_txt = f"Title: {ticket.title}\nDescription: {ticket.description}\n\nConversation:\n{format_convo(messages)}"
intl_blocks = [{"type": "text", "text": intl_txt}]
intl_blocks.extend(all_imgs) # Full internal context
intl_prompt = [
SystemMessage(content="You are a support lead. Summarize for an INTERNAL AGENT. Include internal notes. Use visual info if screenshots present. Max 4 sentences."),
HumanMessage(content=intl_blocks)
]
# Execute with safety harness for multimodal potential failures
try:
cust_resp = await llm.ainvoke(cust_prompt)
intl_resp = await llm.ainvoke(intl_prompt)
summary_data = {
"customer_summary": cust_resp.content,
"internal_summary": intl_resp.content
}
except Exception as e:
logger.error(f"❌ AI Summarization Failed for Ticket {ticket_id}: {str(e)}")
summary_data = {
"customer_summary": "Summary temporarily unavailable due to complex context. Our team is investigating.",
"internal_summary": f"AI Summarization Error: {str(e)}. Please review message history manually."
}
# Persist
meta = dict(ticket.ai_metadata or {})
meta["summaries"] = summary_data
ticket.ai_metadata = meta
db.add(ticket)
# --- Observability: Record Summarization ---
from core.observability import record_workflow_step
await record_workflow_step(
db,
entity_id=ticket.id,
workspace_id=ticket.workspace_id,
workflow_type="LIFECYCLE",
step_name="AI_SUMMARIZATION_COMPLETE",
output_data=summary_data,
current_stage="CONTEXT_SUMMARIZED"
)
await db.commit()
# 7. Real-time Summary Hydration (Nexus UI Sync)
from core.websockets import manager
from models.user import UserRole
# A) Broadcast to Customers (Public Summary)
cust_payload = {"event": "summary_updated", "ticket_id": str(ticket.id), "summary": summary_data.get("customer_summary")}
await manager.broadcast_to_role(ticket.workspace_id, UserRole.CUSTOMER_USER, cust_payload)
await manager.broadcast_to_role(ticket.workspace_id, UserRole.CUSTOMER_ADMIN, cust_payload)
# B) Broadcast to Staff (Internal Summary)
staff_payload = {"event": "summary_updated", "ticket_id": str(ticket.id), "summary": summary_data.get("internal_summary")}
await manager.broadcast_to_role(ticket.workspace_id, UserRole.SC_AGENT, staff_payload)
await manager.broadcast_to_role(ticket.workspace_id, UserRole.SC_LEAD, staff_payload)
await manager.broadcast_to_role(ticket.workspace_id, UserRole.SC_ADMIN, staff_payload)
logger.info(f"Manual Auto-summary generated and role-broadcasted for ticket {ticket_id}")
def truncate_content(text: str, max_chars: int = 15000) -> str:
"""
Ensures content stays within a safe character limit for LLM processing,
approximating token limits (1 token ~= 4 chars).
"""
if not text:
return ""
if len(text) <= max_chars:
return text
return text[:max_chars] + "\n\n... [Content Truncated due to Length] ..."
async def index_kb_article(ctx, article_id: UUID):
"""
Durable ARQ worker task for full KB indexing lifecycle:
Syncing images, Categorization, Embedding, Chunking, Vision, Duplicate detection, and Summary.
"""
start_time = time.perf_counter()
async with async_session_factory() as db:
try:
# 1. Fetch Article with Row-Level Lock (FOR UPDATE)
stmt = select(KBArticle).where(
KBArticle.id == article_id,
KBArticle.deleted_at.is_(None)
).with_for_update()
res = await db.execute(stmt)
article = res.scalar_one_or_none()
if not article:
logger.error(f"Unified KB Indexing failed: Article {article_id} not found.")
return
# --- 2. Multi-Model Initialization ---
text_model = get_text_embeddings()
llm = get_llm()
async def _abort_if_deleted():
_chk = await db.execute(select(KBArticle.deleted_at).where(KBArticle.id == article_id))
if _chk.scalar() is not None:
logger.warning(f"KB Indexing Aborted: Article {article_id} was deleted during processing.")
return True
return False
# --- PHASE 1: Sync Markdown Images ---
try:
await sync_markdown_images(db, article.id, article.workspace_id, article.content, entity_type="article", uploader_id=article.author_id)
if await _abort_if_deleted(): return
await db.commit()
await db.refresh(article)
logger.info(f"PHASE 1 [Images] Complete for {article_id}")
except Exception as e:
logger.error(f"PHASE 1 [Images] Failed for {article_id}: {e}")
await db.rollback()
await db.refresh(article)
# --- PHASE 2: Core Embeddings ---
phase2_success = False
try:
text_model = get_text_embeddings()
text_to_embed = truncate_content(f"{article.title} {article.content}", 8000)
logger.info(f"PHASE 2 [Embeddings] Generating for {article_id} (Length: {len(text_to_embed)})")
vector = await text_model.aembed_query(text_to_embed)
# Smart Persistence: Validate Dimension (768 is default for nomic/google-embed)
if vector and len(vector) == settings.AI_EMBEDDING_DIM:
article.embedding = vector
db.add(article)
await db.commit()
await db.refresh(article)
phase2_success = True
logger.info(f"PHASE 2 [Embeddings] Complete for {article_id} (Dim: {len(vector)})")
else:
error_msg = f"Dimension mismatch: Got {len(vector) if vector else 0}, expected {settings.AI_EMBEDDING_DIM}"
logger.error(f"PHASE 2 [Embeddings] Failed for {article_id}: {error_msg}")
except Exception as e:
logger.error(f"PHASE 2 [Embeddings] Failed for {article_id} (Length: {len(text_to_embed)}): {str(e)}")
# --- PHASE 3: Chunking & Architecture Enrichment ---
try:
await db.execute(delete(KBArticleChunk).where(KBArticleChunk.article_id == article_id))
raw_chunks = chunk_text(article.content, chunk_size=1200, chunk_overlap=100)
for i, text_content in enumerate(raw_chunks):
# Architecture Enrichment Step
processed_text = text_content
if "```mermaid" in text_content.lower() or "```json" in text_content.lower() or "graph " in text_content[:50].lower():
try:
logger.info(f"Technical block detected in chunk {i} of {article_id}. Generating TEK_NAV...")
enrich_prompt = (
f"Explain this technical block in ONE concise sentence for search indexing. "
f"Identify what the flow/data represents.\n\nBLOCK:\n{text_content[:2000]}"
)
enrich_res = await llm.ainvoke(enrich_prompt)
if enrich_res and enrich_res.content:
nav_tag = f"[TEK_NAV: {enrich_res.content.strip()}]\n"
processed_text = nav_tag + text_content
except Exception as enrich_err:
logger.warning(f"Architecture Enrichment failed for chunk {i}: {enrich_err}")
chunk_vector = await text_model.aembed_query(f"{article.title}: {processed_text}")
new_chunk = KBArticleChunk(
article_id=article.id,
content=processed_text,
chunk_index=i,
embedding=chunk_vector
)
db.add(new_chunk)
if await _abort_if_deleted(): return
await db.commit()
await db.refresh(article)
logger.info(f"PHASE 3 [Enrichment] Complete for {article_id} ({len(raw_chunks)} chunks)")
except Exception as e:
logger.error(f"PHASE 3 [Chunking] Failed for {article_id}: {e}")
await db.rollback()
await db.refresh(article)
# --- PHASE 4: Auto-Categorization ---
try:
if not article.category or article.category in ["N/A", "General"]:
cat_stmt = select(KBArticle.category).where(
KBArticle.workspace_id == article.workspace_id,
KBArticle.deleted_at.is_(None)
).distinct()
cat_res = await db.execute(cat_stmt)
existing_cats = [c for c in cat_res.scalars().all() if c and c not in ["N/A", "General"]]
cat_context = f"Existing categories: {', '.join(existing_cats)}" if existing_cats else "No existing categories."
cat_prompt = (
f"Categorize this KB article. {cat_context}\n"
f"Title: {article.title}\nContent Snippet: {truncate_content(article.content, 1000)}\n"
f"Return ONLY the category name (1-3 words)."
)
cat_res = await llm.ainvoke(cat_prompt)
if cat_res and cat_res.content:
article.category = cat_res.content.strip().title()
db.add(article)
if await _abort_if_deleted(): return
await db.commit()
await db.refresh(article)
logger.info(f"PHASE 4 [Category] Complete for {article_id}: {article.category}")
except Exception as e:
logger.error(f"PHASE 4 [Category] Failed for {article_id}: {e}")
await db.rollback()
await db.refresh(article)
# --- PHASE 5: Attachment/Multimodal Indexing ---
try:
att_stmt = select(Attachment).where(Attachment.article_id == article.id, Attachment.deleted_at.is_(None))
att_res = await db.execute(att_stmt)
attachments = att_res.scalars().all()
for att in attachments:
if att.file_type.startswith("image/") and not att.embedding:
img_data = await resolve_image(db, article.workspace_id, str(att.id))
if img_data:
img_model = get_image_embeddings()
att.embedding = await img_model.aembed_image(img_data)
db.add(att)
if await _abort_if_deleted(): return
await db.commit()
await db.refresh(article)
logger.info(f"PHASE 5 [Multimodal] Complete for {article_id}")
except Exception as e:
logger.error(f"PHASE 5 [Multimodal] Failed for {article_id}: {e}")
await db.rollback()
await db.refresh(article)
# --- PHASE 6: Duplicate Detection ---
try:
if article.embedding is not None:
dup_stmt = (
select(KBArticle)
.where(KBArticle.workspace_id == article.workspace_id, KBArticle.id != article.id,
KBArticle.is_published, KBArticle.duplicate_of_id.is_(None), KBArticle.deleted_at.is_(None))
.order_by(KBArticle.embedding.cosine_distance(article.embedding))
.limit(1)
)
dup_res = await db.execute(dup_stmt)
match = dup_res.scalar_one_or_none()
if match:
dist_stmt = select(KBArticle.embedding.cosine_distance(article.embedding)).where(KBArticle.id == match.id)
dist_res = await db.execute(dist_stmt)
distance = dist_res.scalar()
if distance is not None and distance <= 0.3:
article.duplicate_of_id = match.id
article.is_published = False
db.add(article)
if await _abort_if_deleted(): return
await db.commit()
await db.refresh(article)
logger.info(f"PHASE 6 [Deduplication] Complete for {article_id}: Hit {match.id}")
except Exception as e:
logger.error(f"PHASE 6 [Deduplication] Failed for {article_id}: {e}")
await db.rollback()
await db.refresh(article)
# --- PHASE 7: Advanced Summarization & Final Hardening ---
try:
# 1. Generate Summary (Vision-Aware if possible, else text-only)
llm = get_llm()
article_imgs = await extract_visual_context(db, article.workspace_id, article.content, limit=5)
truncated_content = truncate_content(article.content, 12000)
content_txt = f"Title: {article.title}\n\nContent:\n{truncated_content}"
try:
content_blocks = [{"type": "text", "text": content_txt}]
if article_imgs:
content_blocks.extend(article_imgs)
prompt = [
SystemMessage(content="Summarize this technical KB article in 2-3 sentences. Focus on clarity. IMPORTANT: DO NOT include any code blocks, backticks, or raw technical snippets in the summary. Keep it plain text."),
HumanMessage(content=content_blocks)
]
resp = await llm.ainvoke(prompt)
article.summary = resp.content
except Exception as vision_err:
logger.warning(f"Vision-aware summary failed for {article_id}, falling back to simple text: {vision_err}")
resp = await llm.ainvoke([
("system", "You are an expert technical writer. Provide a 2-3 sentence internal summary for this article."),
("human", content_txt)
])
if resp and resp.content:
article.summary = resp.content
# 2. Defensive Check: Emergency Embedding Generation if Phase 2 failed
if article.embedding is None:
# SMART PERSISTENCE: Re-fetch from DB first to see if Phase 2 commit was successful but session stale
await db.refresh(article, attribute_names=["embedding"])
if article.embedding is None:
logger.warning(f"PHASE 7 [Critical Check]: Embedding still NULL for {article_id}. Attempting emergency generation with 4k limit.")
try:
emergency_text = truncate_content(f"{article.title} {article.content}", 4000)
article.embedding = await text_model.aembed_query(emergency_text)
logger.info(f"PHASE 7 [Critical Check]: Emergency embedding generation SUCCESSFUL for {article_id}")
except Exception as e_inner:
logger.error(f"PHASE 7 [Critical Check]: Emergency embedding generation FAILED for {article_id}: {str(e_inner)}")
db.add(article)
if await _abort_if_deleted(): return
await db.commit()
await db.refresh(article)
logger.info(f"PHASE 7 [Summarization] Complete for {article_id}")
except Exception as e:
logger.error(f"PHASE 7 [Summarization] Failed for {article_id}: {e}")
await db.rollback()
await db.refresh(article)
# --- 10. Record Trace ---
try:
await record_workflow_step(
db, article_id, article.workspace_id, "LIFECYCLE", "KB_INDEXING_COMPLETE",
output_data={"images": len(attachments) if 'attachments' in locals() else 0, "summary_len": len(article.summary or "")},
current_stage="READY_FOR_SEARCH", duration_ms=(time.perf_counter() - start_time) * 1000
)
await db.commit()
except Exception as e:
logger.warning(f"Final trace recording failed for {article_id}: {e}")
logger.info(f"SUCCESS: Hardened KB indexing complete for {article_id}")
except Exception as e:
await db.rollback()
logger.error(f"CRITICAL FAILURE: Unified KB indexing crashed for {article_id}: {str(e)}")
async def send_triple_notification(ctx, user_id: UUID, workspace_id: UUID, title: str, message: str, link: Optional[str] = None):
"""Send notification to DB, real-time WebSocket, and simulated Email."""
async with async_session_factory() as db:
# 1. Fetch User Emails (Priority Routing: real_email -> primary_email)
from models.user import User
user_stmt = select(User.email, User.real_email).where(User.id == user_id)
u_res = (await db.execute(user_stmt)).first()
primary_email, real_email = u_res if u_res else (None, None)
delivery_target = real_email or primary_email
# 2. DB Persistence
notification = Notification(
workspace_id=workspace_id,
user_id=user_id,
title=title,
message=message,
link=link
)
db.add(notification)
await db.commit()
# 3. WebSocket Real-time (Targeted Delivery)
# We no longer broadcast to the whole workspace to prevent cross-user alerts
from core.websockets import manager
await manager.send_to_user(user_id, {
"type": "notification",
"id": str(notification.id),
"title": title,
"message": message,
"link": link,
"created_at": datetime.utcnow().isoformat()
})
# 4. Email Notification (Simulated Forensics)
if delivery_target:
email_body = f"Hello,\n\n{message}\n\nThis is a priority alert from Nexus AI."
await send_email(delivery_target, title, email_body)
# 5. External Webhook (Slack/Discord) - REAL WORLD DELIVERY
from core.config import get_settings
settings = get_settings()
if settings.NOTIFICATION_WEBHOOK_URL:
try:
import httpx
async with httpx.AsyncClient() as client:
# Generic Webhook Payload (Works for Slack/Discord)
payload = {
"content" if "discord" in settings.NOTIFICATION_WEBHOOK_URL.lower() else "text":
f"🔔 *{title}*\n{message}\n{link if link else ''}"
}
await client.post(settings.NOTIFICATION_WEBHOOK_URL, json=payload, timeout=5.0)
logger.info("Real notification pushed to external webhook.")
except Exception as w_err:
logger.error(f"Failed to push external webhook: {w_err}")
logger.info(f"Triple notification sent to user {user_id} ({delivery_target})")
async def notify_mentions(ctx, workspace_id: UUID, title: str, mentions: list, ticket_id: Optional[UUID] = None):
"""
Background task to notify multiple users about a mention.
mentions: list of dicts [{"user_id": "...", "name": "..."}]
"""
link = f"/dashboard?ticket={ticket_id}" if ticket_id else None
for mention in mentions:
user_id = UUID(mention["user_id"]) if isinstance(mention["user_id"], str) else mention["user_id"]
await send_triple_notification(
ctx,
user_id=user_id,
workspace_id=workspace_id,
title=title,
message=f"You were mentioned in a ticket message: {title}",
link=link
)
logger.info(f"Mention notifications sent to {len(mentions)} users")
async def monitor_sla_thresholds(ctx):
"""
Periodic task to check for SLA breaches and apply escalation rules.
Runs every 5 minutes (configured in worker.py).
"""
logger.info("Starting SLA monitoring check...")
async with async_session_factory() as db:
now = datetime.utcnow()
# 1. BATCH FETCH: Find all potential breaches in a single pass with Rule JOIN
# Optimized to destroy the N+1 query pattern observed in logs
from sqlalchemy import cast, String
stmt = (
select(Ticket, EscalationRule)
.join(EscalationRule, (EscalationRule.workspace_id == Ticket.workspace_id) & (EscalationRule.priority_level == cast(Ticket.priority, String)))
.where(
Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED]),
Ticket.deleted_at.is_(None),
Ticket.is_escalated.is_(None),
EscalationRule.is_active
)
)
result = await db.execute(stmt)
breached_candidates = result.all()
# Cache for managers to avoid N+1 queries during the escalation loop
manager_cache = {}
for ticket, rule in breached_candidates:
# Handle potential offset-naive datetimes from DB
threshold_time = ticket.created_at.replace(tzinfo=None)
age_minutes = (now - threshold_time).total_seconds() / 60
if age_minutes >= rule.threshold_minutes:
logger.warning(f"SLA Breach: Ticket {ticket.id} (Age: {age_minutes:.1f}m) exceeds rule {rule.name}")
if rule.action == "NOTIFY_LEAD":
# Check cache first to prevent N+1 query bottleneck
if ticket.workspace_id not in manager_cache:
from agents.utils import get_workspace_manager
manager_cache[ticket.workspace_id] = await get_workspace_manager(db, ticket.workspace_id)
manager_user = manager_cache[ticket.workspace_id]
if manager_user:
from models.escalation_rule import EscalationAction
await send_triple_notification(
ctx,
manager_user.id,
ticket.workspace_id,
"🚨 SLA Escalation Alert",
f"Ticket '{ticket.title}' of priority {str(ticket.priority)} has exceeded its SLA threshold. This is an official system escalation.",
link=f"/dashboard?ticket={ticket.id}"
)
# MARK AS ESCALATED to avoid duplicates
ticket.is_escalated = now
db.add(ticket)
# --- Observability: Record SLA Breach ---
from core.observability import record_workflow_step
await record_workflow_step(
db, ticket.id, ticket.workspace_id, "LIFECYCLE",
"SLA_BREACH_ENFORCED",
output_data={"rule": rule.name, "action": EscalationAction.NOTIFY_LEAD.value, "notify_user_id": str(manager_user.id)},
current_stage="ESCALATED_SLA"
)
# --- Audit Log Update ---
audit = AuditLog(
workspace_id=ticket.workspace_id,
entity_type="ticket",
entity_id=ticket.id,
action="SLA_ESCALATION",
user_id=None, # System action
new_value={"rule_name": rule.name, "action_taken": "NOTIFY_LEAD"}
)
db.add(audit)
logger.info(f"Ticket {ticket.id} marked as escalated at {now}")
else:
logger.warning(f"SLA Breach: No Lead/Admin found for workspace {ticket.workspace_id} to notify.")
elif rule.action == "REASSIGN" or rule.action == "AUTO_RESOLVE":
# DEPRECATED/CONSOLIDATED Logic: Fallback to NOTIFY_LEAD per new requirements
logger.info(f"SLA Breach: Action '{rule.action}' consolidated to NOTIFY_LEAD for ticket {ticket.id}")
# Recursively handle as NOTIFY_LEAD would be cleaner but for simplicity we duplicate the notification parts
# if needed, but per plan we are strictly focused on NOTIFY_LEAD now.
pass
await db.commit()
async def ai_dynamic_nudge_pulse(ctx):
"""
Proactive AI Nudge: Identifies tickets at >75% SLA and posts resolution advice.
Runs periodically to prevent breaches.
"""
logger.info("Starting AI Dynamic Nudge pulse...")
async with async_session_factory() as db:
now = datetime.utcnow()
# 1. Fetch tickets at 75% - 99% SLA
stmt = (
select(Ticket, EscalationRule)
.join(EscalationRule, (EscalationRule.workspace_id == Ticket.workspace_id) & (EscalationRule.priority_level == cast(Ticket.priority, String)))
.where(
Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED]),
Ticket.deleted_at.is_(None),
Ticket.is_escalated.is_(None)
)
)
result = await db.execute(stmt)
candidates = result.all()
for ticket, rule in candidates:
age_mins = (now - ticket.created_at.replace(tzinfo=None)).total_seconds() / 60
threshold = rule.threshold_minutes
# If between 75% and 100% of the SLA threshold
if age_mins >= (threshold * 0.75) and age_mins < threshold:
# Check if we already nudged about this (prevent spam)
if ticket.ai_metadata.get("last_nudge_at"):
continue
logger.info(f"AI NUDGE: Ticket {ticket.id} reached 75% SLA. Generating proactive note.")
# 2. Invoke LLM for specific resolution advice
llm = get_llm()
msg_stmt = select(Message).where(Message.ticket_id == ticket.id).order_by(Message.created_at.asc())
msgs = (await db.execute(msg_stmt)).scalars().all()
convo = "\n".join([f"{m.sender_id}: {m.content}" for m in msgs])
prompt = [
SystemMessage(content=f"You are a Senior Support Engineer. This ticket is at 75% of its SLA ({threshold} min limit). Provide a GENTLE but TECHNICAL internal nudge to the assigned agent to help them resolve this faster. Max 2 sentences."),
HumanMessage(content=f"Title: {ticket.title}\nDescription: {ticket.description}\nRecent Conversation:\n{convo}")
]
resp = await llm.ainvoke(prompt)
# 3. Post Internal Message
nudge_msg = Message(
workspace_id=ticket.workspace_id,
ticket_id=ticket.id,
sender_id=UUID("00000000-0000-0000-0000-000000000000"), # System/AI
content=f"🤖 **AI SLA Nudge**: {resp.content}",
is_internal=True
)
db.add(nudge_msg)
# 4. Update Metadata to avoid double nudges
meta = dict(ticket.ai_metadata or {})
meta["last_nudge_at"] = now.isoformat()
ticket.ai_metadata = meta
db.add(ticket)
await db.commit()
async def crystallize_memory(
ctx,
workspace_id: UUID,
user_id: UUID,
thread_id: Optional[UUID],
history_str: str,
old_summary: str,
old_gist: Dict[str, Any]
):
"""
Background AI Distillation Task. Takes pruned conversation history and distills
it into an updated interaction summary and identity gist, then physically
commits both to the database and vector store so next query starts fresh.
"""
from core.llm import get_llm, get_text_embeddings
from langchain_core.prompts import ChatPromptTemplate
from agents.prompts import get_prompt
import json
logger.info(f"Crystallizing memory for user {user_id} in thread {thread_id} via ARQ...")
llm = get_llm()
embedder = get_text_embeddings()
try:
# 0) FETCH TECHNICAL SCOPE (Last 5 Assigned Tickets)
# Added to ground 'Technical DNA' in the user's actual work
from models.ticket import Ticket
from sqlalchemy import select, desc
async with async_session_factory() as db:
scope_stmt = (
select(Ticket.title, Ticket.category)
.where(Ticket.assigned_to == user_id, Ticket.deleted_at.is_(None))
.order_by(desc(Ticket.created_at))
.limit(5)
)
scope_res = await db.execute(scope_stmt)
scope_items = scope_res.all()
active_scope = "\n".join([f"- {t[0]} [{t[1] or 'Uncategorized'}]" for t in scope_items]) or "No active ticket assignments."
# A) DISTILL SUMMARY
prompt = ChatPromptTemplate.from_template(get_prompt("memory_distiller"))
chain = prompt | llm
new_summary_resp = await chain.ainvoke({"old_summary": old_summary, "new_history": history_str})
new_thread_summary = new_summary_resp.content.strip()
# B) EXTRACT GIST (Robust Multi-Stage Extraction)
from schemas.ai import UserIdentityGist
import json
import re
new_gist = old_gist # Default fallback
try:
logger.info("Stage 1: Attempting structured gist extraction...")
gist_llm = get_llm().with_structured_output(UserIdentityGist)
gist_prompt = ChatPromptTemplate.from_template(get_prompt("identity_architect"))
new_gist_obj = await (gist_prompt | gist_llm).ainvoke({
"old_gist": json.dumps(old_gist),
"new_history": history_str,
"active_scope": active_scope
})
new_gist = new_gist_obj.model_dump()
new_gist["last_synchronized"] = datetime.utcnow().isoformat()
logger.info("✅ Stage 1 Gist extraction successful.")
except Exception as gist_err:
logger.warning(f"⚠️ Stage 1 Gist Extraction Failed: {str(gist_err)}. Initiating Stage 2 (Raw Parsing)...")
try:
# Stage 2: Fallback to raw JSON prompt to bypass potential structured output issues
raw_llm = get_llm()
raw_prompt = f"""
You are the Nexus Identity Architect. Update the following User Identity Gist based on the new conversation history.
OLD GIST: {json.dumps(old_gist)}
HISTORY: {history_str}
SCOPE: {active_scope}
Respond ONLY with a valid JSON object containing these keys:
- communication_profile (Dict[str, str])
- technical_dna (List[str])
- behavioral_footprint (List[str])
"""
raw_res = await raw_llm.ainvoke(raw_prompt)
# Robust extraction using regex to handle accidental markdown wrapping
content = raw_res.content if hasattr(raw_res, 'content') else str(raw_res)
json_match = re.search(r'(\{.*\})', content, re.DOTALL)
if json_match:
parsed_gist = json.loads(json_match.group())
# Validate minimal key presence
required = ["communication_profile", "technical_dna", "behavioral_footprint"]
if all(k in parsed_gist for k in required):
new_gist = parsed_gist
new_gist["last_synchronized"] = datetime.utcnow().isoformat()
logger.info("✅ Stage 2 Gist recovery successful.")
else:
raise ValueError("Missing required gist fields in parsed JSON.")
else:
raise ValueError("No valid JSON found in raw content.")
except Exception as raw_err:
logger.error(f"❌ Stage 2 Gist Recovery Failed: {str(raw_err)}. Stage 3: Emergency Preservation Active.")
# Stage 3: Preserve existing state to prevent data loss or crashes
new_gist = old_gist
new_gist["last_synchronized"] = datetime.utcnow().isoformat()
# C) ATOMIC PERSISTENCE
async with async_session_factory() as db:
from models.user import User
from models.nexus_interaction import NexusInteraction
from models.nexus_memory import NexusMemory
from sqlalchemy import update
# --- Persist User Gist ---
await db.execute(
update(User)
.where(User.id == user_id)
.values(ai_gist=new_gist)
)
await db.commit()
# --- Vectorize Semantic Facts ---
gist_str = f"USER_FACTS: {json.dumps(new_gist)}"
fact_vector = await embedder.aembed_query(gist_str)
# Upsert into NexusMemory
db.add(NexusMemory(
workspace_id=workspace_id,
user_id=user_id,
thread_id=thread_id,
content=gist_str,
memory_type="fact",
embedding=fact_vector
))
# --- Vectorize Summarized Interaction ---
interaction_vector = await embedder.aembed_query(new_thread_summary)
db.add(NexusMemory(
workspace_id=workspace_id,
user_id=user_id,
thread_id=thread_id,
content=new_thread_summary,
memory_type="interaction",
embedding=interaction_vector
))
# --- Link Summary to Current Interaction Thread ---
if thread_id:
await db.execute(
update(NexusInteraction)
.where(NexusInteraction.thread_id == thread_id)
.values(metadata_json={"internal_summary": new_thread_summary})
)
await db.commit()
logger.info(f"Memory successfully crystallized and vectorized for {user_id}")
except Exception as e:
logger.error(f"Background Memory Crystallization Failed: {str(e)}")
async def execute_remediation_hook(ctx, ticket_id: str, hook_id: str):
"""Execute a specific remediation action safely in the background."""
from models.remediation import RemediationHook, RemediationActionType
async with async_session_factory() as db:
ticket_stmt = select(Ticket).where(
Ticket.id == UUID(ticket_id),
Ticket.deleted_at.is_(None)
)
hook_stmt = select(RemediationHook).where(RemediationHook.id == UUID(hook_id))
ticket = (await db.execute(ticket_stmt)).scalar_one_or_none()
hook = (await db.execute(hook_stmt)).scalar_one_or_none()
if not ticket or not hook:
return
logger.info(f"Executing remediation hook {hook.trigger_category} for ticket {ticket.id}")
import httpx
if hook.action_type == RemediationActionType.WEBHOOK:
async with httpx.AsyncClient() as client:
# Replace placeholders in template
payload = str(hook.payload_template).replace("{{ticket_id}}", str(ticket.id))
try:
resp = await client.post(hook.target, json=payload)
logger.info(f"Webhook {hook.target} responded with {resp.status_code}")
except Exception as e:
logger.error(f"Failed to trigger remediation webhook: {str(e)}")
# Mark ticket as resolved after remediation if configured
ticket.status = TicketStatus.RESOLVED
db.add(ticket)
await db.commit()
logger.info(f"Remediation successful: Ticket {ticket_id} resolved via hook {hook_id}")
async def nexus_pulse_check(ctx):
"""
Proactive AI "Pulse" Nudge.
Runs every 15 minutes to survey workspaces for anomalies (like an SLA breach cluster)
and pushes alerts live to the internal staff UI.
"""
logger.info("Executing Proactive AI Pulse Check...")
from core.websockets import manager
async with async_session_factory() as db:
# 1. Get all active workspaces
workspaces = (await db.execute(select(Workspace.id))).scalars().all()
fifteen_mins_ago = datetime.utcnow() - timedelta(minutes=15)
for w_id in workspaces:
# 2. Heuristic: Spike in critical SLA breaches
sla_breach_count = (
await db.execute(
select(func.count(Ticket.id))
.where(
Ticket.workspace_id == w_id,
Ticket.priority == "P0",
Ticket.status != "CLOSED",
Ticket.updated_at >= fifteen_mins_ago
)
)
).scalar() or 0
# If anomaly detected
if sla_breach_count >= 3:
alert_payload = {
"type": "NEXUS_PULSE_ALERT",
"level": "critical",
"title": "Anomaly Detected",
"message": f"{sla_breach_count} urgent tickets updated in the last 15 minutes. Potential cascading failure."
}
# Push WebSocket alert to Staff UI for this workspace
# We target only internal staff roles (3sc_admin, 3sc_lead) to prevent data leakage to customers
try:
alert_json = json.dumps(alert_payload)
await manager.broadcast_to_role(w_id, "3sc_admin", alert_json)
await manager.broadcast_to_role(w_id, "3sc_lead", alert_json)
logger.info(f"Broadcasted Pulse Anomaly to Staff roles in workspace: {w_id}")
except Exception as e:
logger.error(f"Failed to broadcast pulse alert: {e}")
async def generate_ticket_embedding(ctx, ticket_id: UUID):
"""
Background task to generate vector embeddings for a ticket's content.
Enables semantic search and similarity matching.
"""
import time
from models.ai_interaction import AIInteraction
from core.config import get_settings
settings = get_settings()
start_time = time.perf_counter()
async with async_session_factory() as db:
stmt = select(Ticket).where(
Ticket.id == ticket_id,
Ticket.deleted_at.is_(None)
)
result = await db.execute(stmt)
ticket = result.scalar_one_or_none()
if not ticket:
logger.error(f"Generate Ticket Embedding: Ticket {ticket_id} not found.")
return
# Prepare content: Title + Description
text_to_embed = f"{ticket.title}\n\n{ticket.description}"
start_time = time.perf_counter()
try:
from core.observability import record_workflow_step
from core.sync import sync_markdown_images
# --- 0. Sync Markdown Images ---
sync_start = time.perf_counter()
await sync_markdown_images(db, ticket.id, ticket.workspace_id, ticket.description, entity_type="ticket", uploader_id=ticket.created_by)
await record_workflow_step(
db, ticket.id, ticket.workspace_id, "LIFECYCLE",
"IMAGE_SYNC_COMPLETE",
input_data={"content_len": len(ticket.description)},
duration_ms=(time.perf_counter() - sync_start) * 1000
)
# --- 1. Textual Embedding ---
embed_start = time.perf_counter()
logger.info(f"Generating embedding for ticket {ticket_id}...")
text_model = get_text_embeddings()
vector = await text_model.aembed_query(text_to_embed)
ticket.embedding = vector
db.add(ticket)
await record_workflow_step(
db, ticket.id, ticket.workspace_id, "LIFECYCLE",
"TEXT_EMBEDDING_GEN",
duration_ms=(time.perf_counter() - embed_start) * 1000
)
# --- 1.5 Duplicate Check (Threshold 0.7)
dup_start = time.perf_counter()
from sqlalchemy import desc
dup_stmt = (
select(
Ticket,
(1 - Ticket.embedding.cosine_distance(vector)).label("sim_score")
)
.where(
Ticket.workspace_id == ticket.workspace_id,
Ticket.id != ticket.id,
Ticket.deleted_at.is_(None),
Ticket.duplicate_of_id.is_(None),
Ticket.embedding.isnot(None)
)
.order_by(desc("sim_score"))
.limit(1)
)
dup_res = await db.execute(dup_stmt)
match = dup_res.first()
dup_status = "no_match"
if match and match.sim_score >= 0.7:
ticket.duplicate_of_id = match.Ticket.id
ticket.status = TicketStatus.CLOSED
ticket.resolved_at = datetime.utcnow()
ticket.resolution_text = f"Automated Detection: This ticket has been identified as a duplicate of ticket #{str(match.Ticket.id)[:8]} ({match.Ticket.title})."
dup_status = "duplicate_found"
# Log this as an automated action
audit = AuditLog(
workspace_id=ticket.workspace_id,
entity_type="ticket",
entity_id=ticket.id,
action="AI_AUTO_CLOSE_DUPLICATE",
user_id=None, # System action
old_value={"status": TicketStatus.OPEN},
new_value={
"status": TicketStatus.CLOSED,
"duplicate_of": str(match.Ticket.id),
"resolution": ticket.resolution_text
}
)
db.add(audit)
logger.info(f"Duplicate Ticket detected: {ticket.id} clones {match.Ticket.id} (score: {match.sim_score}). Auto-closed with metadata.")
await record_workflow_step(
db, ticket.id, ticket.workspace_id, "LIFECYCLE",
"DUPLICATE_DETECTION",
output_data={"status": dup_status, "max_score": float(match.sim_score) if match else 0.0},
duration_ms=(time.perf_counter() - dup_start) * 1000
)
# --- 2. Multimodal Attachment Indexing ---
# Fetch all image attachments for this ticket that haven't been processed
att_stmt = select(Attachment).where(
Attachment.ticket_id == ticket_id,
Attachment.content_type.like("image/%"),
Attachment.is_processed.is_(False)
)
att_res = await db.execute(att_stmt)
attachments = att_res.scalars().all()
if attachments:
logger.info(f"Indexing {len(attachments)} images for ticket {ticket_id}...")
llm = get_llm()
for att in attachments:
try:
# A. Generate Text Caption
# We use the existing resolve_image helper to get Base64
resolved = await resolve_image(db, ticket.workspace_id, str(att.id))
if resolved:
try:
caption_prompt = [
SystemMessage(content="Describe this support ticket image/screenshot briefly (1-2 sentences). Focus on technical errors or UI state."),
HumanMessage(content=[resolved])
]
caption_res = await llm.ainvoke(caption_prompt)
if caption_res:
att.ai_caption = caption_res.content
except Exception as cap_err:
logger.warning(f"Vision Caption failed for {att.id}: {cap_err}")
att.is_processed = True
db.add(att)
except Exception as img_err:
logger.error(f"Failed to process attachment metadata for {att.id}: {img_err}")
# Log this as a system AI interaction
duration_ms = (time.perf_counter() - start_time) * 1000
interaction = AIInteraction(
workspace_id=ticket.workspace_id,
ticket_id=ticket.id,
agent_name="system:multimodal_indexing",
model_info=f"{settings.AI_TEXT_EMBEDDING_MODEL} + {settings.AI_IMAGE_EMBEDDING_MODEL}",
input_data={"text_length": len(text_to_embed), "img_count": len(attachments)},
output_data={"status": "completed"},
duration_ms={"total": round(duration_ms, 2)},
is_automatic=True
)
db.add(interaction)
# --- 3. Record Completion Trace ---
await record_workflow_step(
db, ticket.id, ticket.workspace_id, "LIFECYCLE",
"TICKET_INDEXING_COMPLETE",
output_data={"text_length": len(text_to_embed), "img_count": len(attachments), "duration_ms": round(duration_ms, 2)},
current_stage="READY_FOR_SEARCH"
)
await db.commit()
logger.info(f"Ticket {ticket.id} indexing complete and traced.")
except Exception as e:
logger.error(f"Failed to generate multimodal embedding for ticket {ticket_id}: {str(e)}")
async def record_system_heartbeat(ctx):
"""
Periodic task to record infrastructure health snapshots.
Runs every 5 minutes (configured in nexus_worker.py).
"""
from core.config import get_settings
from arq import create_pool
settings = get_settings()
logger.info("Recording system heartbeat...")
async with async_session_factory() as db:
# 1. Database Heartbeat
db_start = time.perf_counter()
db_status = ServiceStatus.DOWN
db_latency = 0
try:
from sqlalchemy import text
await db.execute(text("SELECT 1"))
db_status = ServiceStatus.UP
db_latency = (time.perf_counter() - db_start) * 1000
except Exception as e:
logger.error(f"Heartbeat: Database check failed: {e}")
db_heartbeat = MetaInfraHealth(
service_name="DATABASE",
status=db_status,
latency_ms=db_latency,
environment="production"
)
db.add(db_heartbeat)
# 2. Redis Heartbeat (Arq)
redis_start = time.perf_counter()
redis_status = ServiceStatus.DOWN
redis_latency = 0
redis_metrics = {}
try:
# We use the pool from ctx if available, otherwise create a temp one
pool = ctx.get('redis')
if not pool:
from core.config import get_redis_settings
pool = await create_pool(get_redis_settings())
# Check keys to gauge activity
job_keys = await pool.keys("arq:job:*")
redis_status = ServiceStatus.UP
redis_latency = (time.perf_counter() - redis_start) * 1000
redis_metrics = {"pending_jobs": len(job_keys)}
except Exception as e:
logger.error(f"Heartbeat: Redis check failed: {e}")
redis_heartbeat = MetaInfraHealth(
service_name="REDIS",
status=redis_status,
latency_ms=redis_latency,
metrics=redis_metrics,
environment="production"
)
db.add(redis_heartbeat)
# 3. Ollama Heartbeat
ollama_start = time.perf_counter()
ollama_status = ServiceStatus.DOWN
ollama_latency = 0
ollama_metrics = {}
try:
async with httpx.AsyncClient(timeout=5.0) as client:
resp = await client.get(f"{settings.OLLAMA_BASE_URL}/api/tags")
if resp.status_code == 200:
ollama_status = ServiceStatus.UP
ollama_latency = (time.perf_counter() - ollama_start) * 1000
ollama_metrics = {"models": resp.json().get("models", [])}
except Exception as e:
logger.error(f"Heartbeat: Ollama check failed: {e}")
ollama_heartbeat = MetaInfraHealth(
service_name="OLLAMA",
status=ollama_status,
latency_ms=ollama_latency,
metrics=ollama_metrics,
environment="production"
)
db.add(ollama_heartbeat)
await db.commit()
logger.info("System heartbeat recorded successfully.")
async def vectorize_nexus_interaction(ctx, workspace_id: UUID, user_id: UUID, content: str, interaction_id: Optional[UUID] = None, thread_id: Optional[UUID] = None, memory_type: str = "interaction"):
"""
Background task to embed and store an interaction or fact for long-term semantic memory.
Enables forensic recall and enterprise-grade context retention.
"""
from core.llm import get_text_embeddings
from models.nexus_memory import NexusMemory
async with async_session_factory() as db:
# 1. Semantic Embedding
text_model = get_text_embeddings()
vector = await text_model.aembed_query(content)
# 2. Persistence
memory = 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
)
db.add(memory)
await db.commit()
logger.info(f"SUCCESS: Nexus Memory vectorized and persisted: {memory_type} for workspace {workspace_id}")
# Invalidate thread history cache to ensure fresh hydration on next load
if thread_id:
try:
from core.cache import invalidate_cache
import asyncio
logger.debug(f"Invalidating Nexus thread cache: {thread_id}")
asyncio.create_task(invalidate_cache(f"nexus:thread:{thread_id}:masked"))
except Exception as ie:
logger.warning(f"Nexus cache invalidation failed: {str(ie)}")
async def generate_global_insight(ctx):
"""
Background task to generate a platform-wide strategic summary for Super Admins.
Analyzes cross-tenant NexusMemory clusters identifying global patterns.
"""
from models.nexus_memory import NexusMemory
from models.platform_insight import PlatformInsight
from core.llm import get_llm
from core.database import async_session_factory
from sqlalchemy import select
import json
logger.info("Starting Global Strategic Insight generation...")
async with async_session_factory() as db:
# 1. Fetch recent long-term memories across ALL tenants
# We look at the last 150 interaction-type memories globally
stmt = (
select(NexusMemory.content)
.where(NexusMemory.memory_type == "interaction")
.order_by(desc(NexusMemory.created_at))
.limit(150)
)
mem_res = await db.execute(stmt)
memories = mem_res.scalars().all()
if not memories:
logger.info("Global Insight: No memories found to analyze.")
return
context_txt = "\n".join([f"- {m}" for m in memories])
# 2. Strategic Analysis via LLM
llm = get_llm()
prompt = ChatPromptTemplate.from_template("""
You are the Nexus Platform Architect. Analyze these cross-tenant support interactions and provide:
1. **Platform Mission Summary**: A 3-sentence high-level overview of global platform stability and user sentiment.
2. **Topic Clusters**: Identify 3-5 recurring technical themes or friction points appearing across different tenants.
Global Context Data:
{context}
Respond strictly in JSON format:
{{
"summary": "...",
"trends": {{ "TOPIC_NAME": "reasoning/frequency", ... }}
}}
""")
try:
chain = prompt | llm
resp = await chain.ainvoke({"context": context_txt})
# 3. Parse and Persist
insights = json.loads(resp.content.strip().replace("```json", "").replace("```", ""))
new_report = PlatformInsight(
summary=insights.get("summary", "Analysis complete."),
trends=insights.get("trends", {}),
metrics_snapshot={"memory_scan_count": len(memories)}
)
db.add(new_report)
await db.commit()
logger.info("SUCCESS: Global Platform Insight generated and cached.")
except Exception as e:
logger.error(f"FAILURE: Global Insight generation failed: {str(e)}")
await db.rollback()
async def purge_stale_semantic_cache(ctx):
"""
Periodic task to physically delete semantic cache records older than 12 hours.
Maintains a 6-hour functional TTL buffer for troubleshooting.
"""
from models.nexus_semantic_cache import NexusSemanticCache
from sqlalchemy import delete
logger.info("Executing Semantic Cache Purge...")
async with async_session_factory() as db:
try:
# Delete records older than 12 hours
stmt = delete(NexusSemanticCache).where(
NexusSemanticCache.created_at < (func.now() - text("INTERVAL '12 hours'"))
)
result = await db.execute(stmt)
count = result.rowcount
await db.commit()
logger.info(f"SUCCESS: Purged {count} stale semantic cache entries.")
except Exception as e:
logger.error(f"FAILURE: Semantic Cache Purge failed: {e}")
await db.rollback()
async def harvest_expertise_task(ctx, ticket_id: UUID):
"""
Background task to analyze a resolved ticket and harvest skills for the agent.
"""
from agents.staff_profiler import harvest_agent_skills
from models.user import User
async with async_session_factory() as db:
try:
# 1. Fetch Ticket + Messages
stmt = select(Ticket).where(Ticket.id == ticket_id)
res = await db.execute(stmt)
ticket = res.scalar_one_or_none()
if not ticket or not ticket.assigned_to:
return
msg_stmt = select(Message).where(Message.ticket_id == ticket_id).order_by(Message.created_at.asc())
msgs = (await db.execute(msg_stmt)).scalars().all()
# 2. Fetch Agent
agent_stmt = select(User).where(User.id == ticket.assigned_to)
agent = (await db.execute(agent_stmt)).scalar_one_or_none()
if not agent:
return
# 3. Harvest Skills
await harvest_agent_skills(db, ticket, msgs, agent)
except Exception as e:
logger.info(f"Expertise Harvesting task failed for ticket {ticket_id}: {e}")
async def generate_workspace_insights(ctx, workspace_id: str):
"""
Background task to generate a live AI summary and suggested actions for a workspace.
This helps pre-warm the cache and avoids 524 timeouts for users.
"""
from api.v1.dashboard import get_dashboard_stats, get_agent_queue
from core.deps import get_llm
from core.cache import set_cached_search
from langchain_core.prompts import ChatPromptTemplate
from models.user import User, UserRole
import json
logger.info(f"Generating background AI insights for workspace {workspace_id}...")
async with async_session_factory() as db:
try:
# 1. Mock a system user for context
system_user_stmt = select(User).where(User.role == UserRole.SC_ADMIN).limit(1)
system_user = (await db.execute(system_user_stmt)).scalar_one_or_none()
if not system_user:
logger.error("No system admin user found for AI insights.")
return
# 2. Gather context
stats = await get_dashboard_stats(workspace_id, current_user=system_user, db=db)
queue = await get_agent_queue(workspace_id, current_user=system_user, db=db)
# 3. Invoke LLM
llm = get_llm(timeout=45) # Longer timeout in background is OK
prompt = ChatPromptTemplate.from_template("""
You are the Nexus Workspace Intelligence Engine.
Analyze the following workspace operational data and provide:
1. A concise, professional "Mission Summary" (2-3 sentences).
2. Exactly 3 "Suggested Actions" for the lead agent.
DATA:
- Total Active Tickets: {total}
- Breached/Urgent: {breached}
- Distribution: {status_dist}
- Personnel: {agents}
TICKET SAMPLE:
{ticket_sample}
Respond strictly in JSON format:
{{
"summary": "...",
"actions": ["...", "...", "..."]
}}
""")
sample = "\n".join([f"- {t['title']} ({t['priority']}, {t['status']})" for t in queue[:5]])
chain = prompt | llm
response = await chain.ainvoke({
"total": stats["total_tickets"],
"breached": any(t.get("priority") == "P0" for t in queue),
"status_dist": stats["by_status"],
"agents": len(queue),
"ticket_sample": sample
})
text = response.content if hasattr(response, 'content') else str(response)
if "524: A timeout occurred" in text or "<!DOCTYPE html>" in text:
raise ValueError("LLM Provider Timeout in background (CF 524)")
json_str = text.replace("```json", "").replace("```", "").strip()
insights = json.loads(json_str)
result = {
"summary": insights.get("summary", "Analysis complete."),
"actions": insights.get("actions", ["Review unassigned tickets", "Check SLA trends", "Balance personnel load"])[:3],
"type": "BACKGROUND_AI_INSIGHT",
"last_refreshed": datetime.utcnow().isoformat()
}
# 4. Persistence to cache (global format used by dashboard)
# Note: This cache key must match api/v1/dashboard.py
# Since this is background, we can't easily target a specific user's cache,
# so we'll store it in a general workspace cache that dashboard.py will check.
cache_key = f"dashboard:insights:{workspace_id}:system"
await set_cached_search(cache_key, result, ttl=1800) # 30 min cache
logger.info(f"SUCCESS: Background AI insights generated for workspace {workspace_id}")
except Exception as e:
logger.error(f"FAILURE: Background AI insights failed: {str(e)}")
async def recover_nexus_history(ctx, thread_id: UUID, workspace_id: UUID, user_role: str):
"""
Background worker task to load and mask conversational history for a Nexus thread.
Optimizes performance for heavy threads and ensures zero-trust masking is applied.
"""
from models.nexus_interaction import NexusInteraction
from agents.security import mask_for_role
logger.info(f"💾 Recovering nexus history for thread {thread_id}...")
async with async_session_factory() as db:
from models.user import User as UserTable
stmt = (
select(NexusInteraction, UserTable.full_name)
.join(UserTable, NexusInteraction.user_id == UserTable.id)
.where(
NexusInteraction.thread_id == thread_id,
NexusInteraction.workspace_id == workspace_id
)
.order_by(NexusInteraction.created_at.asc())
)
result = await db.execute(stmt)
rows = result.all()
if not rows:
return []
# Convert to dicts for masking
interaction_dicts = [dict(
id=i.id,
input_query=i.input_query,
ai_answer=i.ai_answer,
sender_name=full_name,
created_at=i.created_at.isoformat()
) for i, full_name in rows]
# Apply role-based masking
masked = mask_for_role(interaction_dicts, user_role)
# Flatten into conversational messages with metadata
history = []
for i in masked:
history.append({
"role": "user",
"content": i["input_query"],
"senderName": i.get("sender_name", "User"),
"timestamp": i["created_at"]
})
history.append({
"role": "assistant",
"content": i["ai_answer"],
"senderName": "Nexus",
"timestamp": i["created_at"]
})
logger.info(f"✅ History recovery complete for {thread_id} ({len(history)} messages)")
return history
"""
Background task definitions for Arq worker.
"""
import httpx
from typing import Optional, Dict, Any
from uuid import UUID
from datetime import datetime, timedelta
from sqlalchemy import select, func, desc, text, delete, cast, String
from core.database import async_session_factory
from core.logging import get_logger
from models.ticket import Ticket, TicketStatus
from models.notification import Notification
from models.audit_log import AuditLog
from models.escalation_rule import EscalationRule
from models.message import Message
from models.kb_article import KBArticle
from core.llm import get_llm, get_text_embeddings, get_image_embeddings
from core.vision import extract_visual_context, resolve_image
from langchain_core.prompts import ChatPromptTemplate
from langchain.schema import HumanMessage, SystemMessage
from models.attachment import Attachment
from models.meta_infra_health import MetaInfraHealth, ServiceStatus
from models.kb_article_chunk import KBArticleChunk
from models.workspace import Workspace
from core.search import chunk_text
from core.sync import sync_markdown_images
from core.observability import record_workflow_step
from core.config import get_settings
from core.email import send_email
import time
import json
settings = get_settings()
logger = get_logger(__name__)
async def auto_summarize_ticket(ctx, ticket_id: UUID):
"""
Background task to generate dual summaries (Internal/Customer).
"""
async with async_session_factory() as db:
# 1. Fetch Ticket
stmt = select(Ticket).where(
Ticket.id == ticket_id,
Ticket.deleted_at.is_(None)
)
result = await db.execute(stmt)
ticket = result.scalar_one_or_none()
if not ticket:
return
# 2. Fetch Messages
msg_stmt = select(Message).where(
Message.ticket_id == ticket_id,
Message.deleted_at.is_(None)
).order_by(Message.created_at.asc())
msg_result = await db.execute(msg_stmt)
messages = msg_result.scalars().all()
# 3. Partition Messages
public_messages = [m for m in messages if not m.is_internal]
llm = get_llm()
def format_convo(msg_list):
return "\n".join([f"{'['+'INTERNAL'+'] ' if m.is_internal else ''}{m.sender_id}: {m.content}" for m in msg_list])
# 4. Multimodal Resolution
# Resolve images from description and messages
all_imgs = await extract_visual_context(db, ticket.workspace_id, ticket.description, limit=3)
for m in messages:
if len(all_imgs) >= 10: break
all_imgs.extend(await extract_visual_context(db, ticket.workspace_id, m.content, limit=2))
# Customer Summary
cust_txt = f"Title: {ticket.title}\nDescription: {ticket.description}\n\nConversation:\n{format_convo(public_messages)}"
cust_blocks = [{"type": "text", "text": cust_txt}]
# Only include images found in public messages or description
cust_blocks.extend(all_imgs[:5]) # Hard limit for customer
cust_prompt = [
SystemMessage(content="You are a support assistant. Summarize for a CUSTOMER. No internal jargon. Max 3 sentences."),
HumanMessage(content=cust_blocks)
]
# Internal Summary
intl_txt = f"Title: {ticket.title}\nDescription: {ticket.description}\n\nConversation:\n{format_convo(messages)}"
intl_blocks = [{"type": "text", "text": intl_txt}]
intl_blocks.extend(all_imgs) # Full internal context
intl_prompt = [
SystemMessage(content="You are a support lead. Summarize for an INTERNAL AGENT. Include internal notes. Use visual info if screenshots present. Max 4 sentences."),
HumanMessage(content=intl_blocks)
]
# Execute with safety harness for multimodal potential failures
try:
cust_resp = await llm.ainvoke(cust_prompt)