Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
4e5499d
1
Parent(s): 3a775fd
backend stabilization
Browse files- agents/nexus_master.py +6 -2
- api/v1/kb.py +3 -3
- api/v1/tickets.py +0 -1
- core/tasks.py +18 -17
agents/nexus_master.py
CHANGED
|
@@ -142,7 +142,9 @@ async def nexus_context_hydrator(state: NexusState) -> Dict[str, Any]:
|
|
| 142 |
history_str = "\n".join(history_lines) if history_lines else "No previous messages."
|
| 143 |
|
| 144 |
findings = ticket.ai_metadata.get("processed_steps", [])
|
| 145 |
-
|
|
|
|
|
|
|
| 146 |
|
| 147 |
context = f"""
|
| 148 |
TICKET_CONTEXT:
|
|
@@ -209,7 +211,9 @@ async def nexus_pre_processor(state: NexusState) -> Dict[str, Any]:
|
|
| 209 |
)
|
| 210 |
res = await db.execute(stmt)
|
| 211 |
last = res.scalar_one_or_none()
|
| 212 |
-
summary =
|
|
|
|
|
|
|
| 213 |
return {"internal_summary": summary}
|
| 214 |
|
| 215 |
# Parallelize ALL initialization heavy-lifting
|
|
|
|
| 142 |
history_str = "\n".join(history_lines) if history_lines else "No previous messages."
|
| 143 |
|
| 144 |
findings = ticket.ai_metadata.get("processed_steps", [])
|
| 145 |
+
if not isinstance(findings, list):
|
| 146 |
+
findings = []
|
| 147 |
+
findings_str = "\n".join([f"- {s.get('name') if isinstance(s, dict) else 'Unknown'}: {s.get('status') if isinstance(s, dict) else 'N/A'}" for s in findings])
|
| 148 |
|
| 149 |
context = f"""
|
| 150 |
TICKET_CONTEXT:
|
|
|
|
| 211 |
)
|
| 212 |
res = await db.execute(stmt)
|
| 213 |
last = res.scalar_one_or_none()
|
| 214 |
+
summary = ""
|
| 215 |
+
if last and isinstance(last, dict):
|
| 216 |
+
summary = last.get("internal_summary", "")
|
| 217 |
return {"internal_summary": summary}
|
| 218 |
|
| 219 |
# Parallelize ALL initialization heavy-lifting
|
api/v1/kb.py
CHANGED
|
@@ -63,7 +63,7 @@ async def create_kb_article(
|
|
| 63 |
|
| 64 |
# Unified ARQ Indexing Lifecycle (Categorization, Embedding, Chunking, Summary)
|
| 65 |
from core.tasks import enqueue_task
|
| 66 |
-
await enqueue_task(arq_pool, "index_kb_article", new_article.id
|
| 67 |
|
| 68 |
logger.info(f"KB Article created and enqueued: {new_article.id} by user {current_user.id}")
|
| 69 |
|
|
@@ -624,7 +624,7 @@ async def update_kb_article(
|
|
| 624 |
# Unified ARQ Indexing Lifecycle (Re-index if content/title changed)
|
| 625 |
if "content" in update_data or "title" in update_data:
|
| 626 |
from core.tasks import enqueue_task
|
| 627 |
-
await enqueue_task(arq_pool, "index_kb_article", article.id
|
| 628 |
logger.info(f"KB Article {article_id} updated, re-indexing enqueued...")
|
| 629 |
|
| 630 |
return article
|
|
@@ -740,7 +740,7 @@ async def bulk_publish_articles(
|
|
| 740 |
# Trigger Unified ARQ Indexing Lifecycle ONLY if needed
|
| 741 |
if should_index:
|
| 742 |
from core.tasks import enqueue_task
|
| 743 |
-
await enqueue_task(arq_pool, "index_kb_article", article.id
|
| 744 |
logger.info(f"KB Bulk: Indexing enqueued for {article.id}")
|
| 745 |
else:
|
| 746 |
logger.info(f"KB Bulk: Indexing skipped for {article.id} (no content changes)")
|
|
|
|
| 63 |
|
| 64 |
# Unified ARQ Indexing Lifecycle (Categorization, Embedding, Chunking, Summary)
|
| 65 |
from core.tasks import enqueue_task
|
| 66 |
+
await enqueue_task(arq_pool, "index_kb_article", new_article.id)
|
| 67 |
|
| 68 |
logger.info(f"KB Article created and enqueued: {new_article.id} by user {current_user.id}")
|
| 69 |
|
|
|
|
| 624 |
# Unified ARQ Indexing Lifecycle (Re-index if content/title changed)
|
| 625 |
if "content" in update_data or "title" in update_data:
|
| 626 |
from core.tasks import enqueue_task
|
| 627 |
+
await enqueue_task(arq_pool, "index_kb_article", article.id)
|
| 628 |
logger.info(f"KB Article {article_id} updated, re-indexing enqueued...")
|
| 629 |
|
| 630 |
return article
|
|
|
|
| 740 |
# Trigger Unified ARQ Indexing Lifecycle ONLY if needed
|
| 741 |
if should_index:
|
| 742 |
from core.tasks import enqueue_task
|
| 743 |
+
await enqueue_task(arq_pool, "index_kb_article", article.id)
|
| 744 |
logger.info(f"KB Bulk: Indexing enqueued for {article.id}")
|
| 745 |
else:
|
| 746 |
logger.info(f"KB Bulk: Indexing skipped for {article.id} (no content changes)")
|
api/v1/tickets.py
CHANGED
|
@@ -287,7 +287,6 @@ async def create_ticket(
|
|
| 287 |
arq_pool,
|
| 288 |
'auto_summarize_ticket',
|
| 289 |
new_ticket.id,
|
| 290 |
-
new_ticket.id,
|
| 291 |
_job_id=f"summarize_init_{new_ticket.id}"
|
| 292 |
)
|
| 293 |
|
|
|
|
| 287 |
arq_pool,
|
| 288 |
'auto_summarize_ticket',
|
| 289 |
new_ticket.id,
|
|
|
|
| 290 |
_job_id=f"summarize_init_{new_ticket.id}"
|
| 291 |
)
|
| 292 |
|
core/tasks.py
CHANGED
|
@@ -113,7 +113,7 @@ async def enqueue_task(pool: Any, task_name: str, entity_id: Any, *args, **kwarg
|
|
| 113 |
if hasattr(pool, 'enqueue_job'):
|
| 114 |
await pool.enqueue_job(task_name, *args, **kwargs)
|
| 115 |
|
| 116 |
-
async def auto_summarize_ticket(ctx, ticket_id: UUID):
|
| 117 |
"""
|
| 118 |
Background task to generate dual summaries (Internal/Customer).
|
| 119 |
"""
|
|
@@ -334,7 +334,7 @@ def truncate_content(text: str, max_chars: int = 15000) -> str:
|
|
| 334 |
return text
|
| 335 |
return text[:max_chars] + "\n\n... [Content Truncated due to Length] ..."
|
| 336 |
|
| 337 |
-
async def index_kb_article(ctx, article_id: UUID):
|
| 338 |
"""
|
| 339 |
Durable ARQ worker task for full KB indexing lifecycle:
|
| 340 |
Syncing images, Categorization, Embedding, Chunking, Vision, Duplicate detection, and Summary.
|
|
@@ -592,7 +592,7 @@ async def index_kb_article(ctx, article_id: UUID):
|
|
| 592 |
await db.rollback()
|
| 593 |
logger.error(f"CRITICAL FAILURE: Unified KB indexing crashed for {article_id}: {str(e)}")
|
| 594 |
|
| 595 |
-
async def send_triple_notification(ctx, user_id: UUID, workspace_id: UUID, title: str, message: str, link: Optional[str] = None):
|
| 596 |
"""Send notification to DB, real-time WebSocket, and simulated Email."""
|
| 597 |
async with async_session_factory() as db:
|
| 598 |
# 1. Fetch User Emails (Priority Routing: real_email -> primary_email)
|
|
@@ -652,7 +652,7 @@ async def send_triple_notification(ctx, user_id: UUID, workspace_id: UUID, title
|
|
| 652 |
|
| 653 |
logger.info(f"Triple notification sent to user {user_id} ({delivery_target})")
|
| 654 |
|
| 655 |
-
async def notify_mentions(ctx, workspace_id: UUID, title: str, mentions: list, ticket_id: Optional[UUID] = None):
|
| 656 |
"""
|
| 657 |
Background task to notify multiple users about a mention.
|
| 658 |
mentions: list of dicts [{"user_id": "...", "name": "..."}]
|
|
@@ -670,7 +670,7 @@ async def notify_mentions(ctx, workspace_id: UUID, title: str, mentions: list, t
|
|
| 670 |
)
|
| 671 |
logger.info(f"Mention notifications sent to {len(mentions)} users")
|
| 672 |
|
| 673 |
-
async def monitor_sla_thresholds(ctx):
|
| 674 |
"""
|
| 675 |
Periodic task to check for SLA breaches and apply escalation rules.
|
| 676 |
Runs every 5 minutes (configured in worker.py).
|
|
@@ -754,7 +754,7 @@ async def monitor_sla_thresholds(ctx):
|
|
| 754 |
|
| 755 |
await db.commit()
|
| 756 |
|
| 757 |
-
async def ai_dynamic_nudge_pulse(ctx):
|
| 758 |
"""
|
| 759 |
Proactive AI Nudge: Identifies tickets at >75% SLA and posts resolution advice.
|
| 760 |
Runs periodically to prevent breaches.
|
|
@@ -825,7 +825,8 @@ async def crystallize_memory(
|
|
| 825 |
thread_id: Optional[UUID],
|
| 826 |
history_str: str,
|
| 827 |
old_summary: str,
|
| 828 |
-
old_gist: Dict[str, Any]
|
|
|
|
| 829 |
):
|
| 830 |
"""
|
| 831 |
Background AI Distillation Task. Takes pruned conversation history and distills
|
|
@@ -942,7 +943,7 @@ async def crystallize_memory(
|
|
| 942 |
else:
|
| 943 |
logger.error(f"FAILURE: All crystallization attempts failed: {str(e)}")
|
| 944 |
|
| 945 |
-
async def execute_remediation_hook(ctx, ticket_id: str, hook_id: str):
|
| 946 |
"""Execute a specific remediation action safely in the background."""
|
| 947 |
from models.remediation import RemediationHook, RemediationActionType
|
| 948 |
|
|
@@ -978,7 +979,7 @@ async def execute_remediation_hook(ctx, ticket_id: str, hook_id: str):
|
|
| 978 |
await db.commit()
|
| 979 |
logger.info(f"Remediation successful: Ticket {ticket_id} resolved via hook {hook_id}")
|
| 980 |
|
| 981 |
-
async def nexus_pulse_check(ctx):
|
| 982 |
"""
|
| 983 |
Proactive AI "Pulse" Nudge.
|
| 984 |
Runs every 15 minutes to survey workspaces for anomalies (like an SLA breach cluster)
|
|
@@ -1033,7 +1034,7 @@ async def nexus_pulse_check(ctx):
|
|
| 1033 |
batch = workspaces[i:i+5]
|
| 1034 |
await asyncio.gather(*[process_workspace(wid) for wid in batch])
|
| 1035 |
|
| 1036 |
-
async def generate_ticket_embedding(ctx, ticket_id: UUID):
|
| 1037 |
"""
|
| 1038 |
Background task to generate vector embeddings for a ticket's content.
|
| 1039 |
Enables semantic search and similarity matching.
|
|
@@ -1203,7 +1204,7 @@ async def generate_ticket_embedding(ctx, ticket_id: UUID):
|
|
| 1203 |
except Exception as e:
|
| 1204 |
logger.error(f"Failed to generate multimodal embedding for ticket {ticket_id}: {str(e)}")
|
| 1205 |
|
| 1206 |
-
async def record_system_heartbeat(ctx):
|
| 1207 |
"""
|
| 1208 |
Periodic task to record infrastructure health snapshots.
|
| 1209 |
Runs every 5 minutes (configured in nexus_worker.py).
|
|
@@ -1291,7 +1292,7 @@ async def record_system_heartbeat(ctx):
|
|
| 1291 |
await db.commit()
|
| 1292 |
logger.info("System heartbeat recorded successfully.")
|
| 1293 |
|
| 1294 |
-
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"):
|
| 1295 |
"""
|
| 1296 |
Background task to embed and store an interaction or fact for long-term semantic memory.
|
| 1297 |
Enables forensic recall and enterprise-grade context retention.
|
|
@@ -1328,7 +1329,7 @@ async def vectorize_nexus_interaction(ctx, workspace_id: UUID, user_id: UUID, co
|
|
| 1328 |
except Exception as ie:
|
| 1329 |
logger.warning(f"Nexus cache invalidation failed: {str(ie)}")
|
| 1330 |
|
| 1331 |
-
async def generate_global_insight(ctx):
|
| 1332 |
"""
|
| 1333 |
Background task to generate a platform-wide strategic summary for Super Admins.
|
| 1334 |
Analyzes cross-tenant NexusMemory clusters identifying global patterns.
|
|
@@ -1397,7 +1398,7 @@ async def generate_global_insight(ctx):
|
|
| 1397 |
logger.error(f"FAILURE: Global Insight generation failed: {str(e)}")
|
| 1398 |
await db.rollback()
|
| 1399 |
|
| 1400 |
-
async def purge_stale_semantic_cache(ctx):
|
| 1401 |
"""
|
| 1402 |
Periodic task to physically delete semantic cache records older than 12 hours.
|
| 1403 |
Maintains a 6-hour functional TTL buffer for troubleshooting.
|
|
@@ -1420,7 +1421,7 @@ async def purge_stale_semantic_cache(ctx):
|
|
| 1420 |
logger.error(f"FAILURE: Semantic Cache Purge failed: {e}")
|
| 1421 |
await db.rollback()
|
| 1422 |
|
| 1423 |
-
async def harvest_expertise_task(ctx, ticket_id: UUID):
|
| 1424 |
"""
|
| 1425 |
Background task to analyze a resolved ticket and harvest skills for the agent.
|
| 1426 |
"""
|
|
@@ -1451,7 +1452,7 @@ async def harvest_expertise_task(ctx, ticket_id: UUID):
|
|
| 1451 |
except Exception as e:
|
| 1452 |
logger.info(f"Expertise Harvesting task failed for ticket {ticket_id}: {e}")
|
| 1453 |
|
| 1454 |
-
async def generate_workspace_insights(ctx, workspace_id: str):
|
| 1455 |
"""
|
| 1456 |
Background task to generate a live AI summary and suggested actions for a workspace.
|
| 1457 |
This helps pre-warm the cache and avoids 524 timeouts for users.
|
|
@@ -1538,7 +1539,7 @@ async def generate_workspace_insights(ctx, workspace_id: str):
|
|
| 1538 |
|
| 1539 |
except Exception as e:
|
| 1540 |
logger.error(f"FAILURE: Background AI insights failed: {str(e)}")
|
| 1541 |
-
async def recover_nexus_history(ctx, thread_id: UUID, workspace_id: UUID, user_role: str):
|
| 1542 |
"""
|
| 1543 |
Background worker task to load and mask conversational history for a Nexus thread.
|
| 1544 |
Optimizes performance for heavy threads and ensures zero-trust masking is applied.
|
|
|
|
| 113 |
if hasattr(pool, 'enqueue_job'):
|
| 114 |
await pool.enqueue_job(task_name, *args, **kwargs)
|
| 115 |
|
| 116 |
+
async def auto_summarize_ticket(ctx, ticket_id: UUID, **kwargs):
|
| 117 |
"""
|
| 118 |
Background task to generate dual summaries (Internal/Customer).
|
| 119 |
"""
|
|
|
|
| 334 |
return text
|
| 335 |
return text[:max_chars] + "\n\n... [Content Truncated due to Length] ..."
|
| 336 |
|
| 337 |
+
async def index_kb_article(ctx, article_id: UUID, **kwargs):
|
| 338 |
"""
|
| 339 |
Durable ARQ worker task for full KB indexing lifecycle:
|
| 340 |
Syncing images, Categorization, Embedding, Chunking, Vision, Duplicate detection, and Summary.
|
|
|
|
| 592 |
await db.rollback()
|
| 593 |
logger.error(f"CRITICAL FAILURE: Unified KB indexing crashed for {article_id}: {str(e)}")
|
| 594 |
|
| 595 |
+
async def send_triple_notification(ctx, user_id: UUID, workspace_id: UUID, title: str, message: str, link: Optional[str] = None, **kwargs):
|
| 596 |
"""Send notification to DB, real-time WebSocket, and simulated Email."""
|
| 597 |
async with async_session_factory() as db:
|
| 598 |
# 1. Fetch User Emails (Priority Routing: real_email -> primary_email)
|
|
|
|
| 652 |
|
| 653 |
logger.info(f"Triple notification sent to user {user_id} ({delivery_target})")
|
| 654 |
|
| 655 |
+
async def notify_mentions(ctx, workspace_id: UUID, title: str, mentions: list, ticket_id: Optional[UUID] = None, **kwargs):
|
| 656 |
"""
|
| 657 |
Background task to notify multiple users about a mention.
|
| 658 |
mentions: list of dicts [{"user_id": "...", "name": "..."}]
|
|
|
|
| 670 |
)
|
| 671 |
logger.info(f"Mention notifications sent to {len(mentions)} users")
|
| 672 |
|
| 673 |
+
async def monitor_sla_thresholds(ctx, **kwargs):
|
| 674 |
"""
|
| 675 |
Periodic task to check for SLA breaches and apply escalation rules.
|
| 676 |
Runs every 5 minutes (configured in worker.py).
|
|
|
|
| 754 |
|
| 755 |
await db.commit()
|
| 756 |
|
| 757 |
+
async def ai_dynamic_nudge_pulse(ctx, **kwargs):
|
| 758 |
"""
|
| 759 |
Proactive AI Nudge: Identifies tickets at >75% SLA and posts resolution advice.
|
| 760 |
Runs periodically to prevent breaches.
|
|
|
|
| 825 |
thread_id: Optional[UUID],
|
| 826 |
history_str: str,
|
| 827 |
old_summary: str,
|
| 828 |
+
old_gist: Dict[str, Any],
|
| 829 |
+
**kwargs
|
| 830 |
):
|
| 831 |
"""
|
| 832 |
Background AI Distillation Task. Takes pruned conversation history and distills
|
|
|
|
| 943 |
else:
|
| 944 |
logger.error(f"FAILURE: All crystallization attempts failed: {str(e)}")
|
| 945 |
|
| 946 |
+
async def execute_remediation_hook(ctx, ticket_id: str, hook_id: str, **kwargs):
|
| 947 |
"""Execute a specific remediation action safely in the background."""
|
| 948 |
from models.remediation import RemediationHook, RemediationActionType
|
| 949 |
|
|
|
|
| 979 |
await db.commit()
|
| 980 |
logger.info(f"Remediation successful: Ticket {ticket_id} resolved via hook {hook_id}")
|
| 981 |
|
| 982 |
+
async def nexus_pulse_check(ctx, **kwargs):
|
| 983 |
"""
|
| 984 |
Proactive AI "Pulse" Nudge.
|
| 985 |
Runs every 15 minutes to survey workspaces for anomalies (like an SLA breach cluster)
|
|
|
|
| 1034 |
batch = workspaces[i:i+5]
|
| 1035 |
await asyncio.gather(*[process_workspace(wid) for wid in batch])
|
| 1036 |
|
| 1037 |
+
async def generate_ticket_embedding(ctx, ticket_id: UUID, **kwargs):
|
| 1038 |
"""
|
| 1039 |
Background task to generate vector embeddings for a ticket's content.
|
| 1040 |
Enables semantic search and similarity matching.
|
|
|
|
| 1204 |
except Exception as e:
|
| 1205 |
logger.error(f"Failed to generate multimodal embedding for ticket {ticket_id}: {str(e)}")
|
| 1206 |
|
| 1207 |
+
async def record_system_heartbeat(ctx, **kwargs):
|
| 1208 |
"""
|
| 1209 |
Periodic task to record infrastructure health snapshots.
|
| 1210 |
Runs every 5 minutes (configured in nexus_worker.py).
|
|
|
|
| 1292 |
await db.commit()
|
| 1293 |
logger.info("System heartbeat recorded successfully.")
|
| 1294 |
|
| 1295 |
+
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", **kwargs):
|
| 1296 |
"""
|
| 1297 |
Background task to embed and store an interaction or fact for long-term semantic memory.
|
| 1298 |
Enables forensic recall and enterprise-grade context retention.
|
|
|
|
| 1329 |
except Exception as ie:
|
| 1330 |
logger.warning(f"Nexus cache invalidation failed: {str(ie)}")
|
| 1331 |
|
| 1332 |
+
async def generate_global_insight(ctx, **kwargs):
|
| 1333 |
"""
|
| 1334 |
Background task to generate a platform-wide strategic summary for Super Admins.
|
| 1335 |
Analyzes cross-tenant NexusMemory clusters identifying global patterns.
|
|
|
|
| 1398 |
logger.error(f"FAILURE: Global Insight generation failed: {str(e)}")
|
| 1399 |
await db.rollback()
|
| 1400 |
|
| 1401 |
+
async def purge_stale_semantic_cache(ctx, **kwargs):
|
| 1402 |
"""
|
| 1403 |
Periodic task to physically delete semantic cache records older than 12 hours.
|
| 1404 |
Maintains a 6-hour functional TTL buffer for troubleshooting.
|
|
|
|
| 1421 |
logger.error(f"FAILURE: Semantic Cache Purge failed: {e}")
|
| 1422 |
await db.rollback()
|
| 1423 |
|
| 1424 |
+
async def harvest_expertise_task(ctx, ticket_id: UUID, **kwargs):
|
| 1425 |
"""
|
| 1426 |
Background task to analyze a resolved ticket and harvest skills for the agent.
|
| 1427 |
"""
|
|
|
|
| 1452 |
except Exception as e:
|
| 1453 |
logger.info(f"Expertise Harvesting task failed for ticket {ticket_id}: {e}")
|
| 1454 |
|
| 1455 |
+
async def generate_workspace_insights(ctx, workspace_id: str, **kwargs):
|
| 1456 |
"""
|
| 1457 |
Background task to generate a live AI summary and suggested actions for a workspace.
|
| 1458 |
This helps pre-warm the cache and avoids 524 timeouts for users.
|
|
|
|
| 1539 |
|
| 1540 |
except Exception as e:
|
| 1541 |
logger.error(f"FAILURE: Background AI insights failed: {str(e)}")
|
| 1542 |
+
async def recover_nexus_history(ctx, thread_id: UUID, workspace_id: UUID, user_role: str, **kwargs):
|
| 1543 |
"""
|
| 1544 |
Background worker task to load and mask conversational history for a Nexus thread.
|
| 1545 |
Optimizes performance for heavy threads and ensures zero-trust masking is applied.
|