Spaces:
Paused
Paused
File size: 24,625 Bytes
5eb4857 0509823 4405ca9 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 4405ca9 5eb4857 0509823 5eb4857 4405ca9 b7980f7 5eb4857 d8eb3eb 5eb4857 1df9c69 5eb4857 0509823 6ba1c48 0509823 5eb4857 0509823 b7980f7 a27a4ab b7980f7 a27a4ab b7980f7 0509823 b7980f7 0509823 b7980f7 0509823 37c3bcb 6bf2d17 37c3bcb 0509823 12dfdef 0509823 b7980f7 4d5026d 1049d57 4d5026d b7980f7 0509823 b7980f7 12dfdef 7617cb0 0509823 b7980f7 7617cb0 b7980f7 0509823 12dfdef 0509823 b7980f7 0509823 b7980f7 0509823 b7980f7 0509823 b7980f7 0509823 1df9c69 0509823 db68795 0509823 6bf2d17 0509823 6bf2d17 2ca66ce 0509823 2ca66ce 0509823 d8eb3eb 0509823 2ca66ce d8eb3eb 8a5320a 0509823 2ca66ce 0509823 041d536 0509823 db68795 d8eb3eb 0509823 d8eb3eb 0509823 db68795 0509823 db68795 0509823 1df9c69 0509823 1df9c69 0509823 1df9c69 0509823 efe35f7 0509823 1df9c69 efe35f7 0509823 5eb4857 0509823 b7980f7 5efb6af 832828a 5efb6af d8eb3eb 5eb4857 b7980f7 0509823 b7980f7 0509823 5eb4857 b7980f7 5eb4857 b7980f7 0509823 6bf2d17 0509823 5eb4857 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 | import uuid
import logging
import time
import asyncio
from typing import Dict, Any
from datetime import datetime, timedelta
from langgraph.graph import StateGraph, START, END
from langgraph.types import RetryPolicy
from agents.state import AgentState
from agents.ingestion import ingestion_node
from agents.triage import triage_node
from agents.duplication import duplication_node
from agents.remediation import remediation_node, should_continue_remediation
from agents.routing import routing_node
from agents.suggestion import suggestion_node
from agents.kb_node import kb_search_node # Added KB Node
from agents.utils import sanitize_for_db, safe_uuid
from core.database import async_session_factory
from models.ticket import Ticket, TicketStatus
from models.user import User
from models.attachment import Attachment
from models.knowledge_insight import KnowledgeInsight, InsightStatus
from models.knowledge_insight_ticket import KnowledgeInsightTicket
from sqlalchemy import select
from core.cache import invalidate_cache
logger = logging.getLogger(__name__)
def should_proceed_after_duplication(state: AgentState) -> str:
"""Router to exit early if ticket is a duplicate."""
if state.get("is_duplicate"):
logger.warning(f"Workflow: Exiting early for duplicate ticket {state['ticket_id']}")
return END
return "triage"
# --- SINGLETON WORKFLOW APP (GAP-3 Fix) ---
_workflow_app = None
_workflow_lock = None
async def get_workflow_app():
global _workflow_app, _workflow_lock
if _workflow_app is not None:
return _workflow_app
if _workflow_lock is None:
_workflow_lock = asyncio.Lock()
async with _workflow_lock:
if _workflow_app is not None:
return _workflow_app
workflow = StateGraph(AgentState)
retry_policy = RetryPolicy(max_attempts=3)
workflow.add_node("ingestion", ingestion_node, retry=retry_policy)
workflow.add_node("duplication", duplication_node, retry=retry_policy)
workflow.add_node("kb_search", kb_search_node, retry=retry_policy)
workflow.add_node("triage", triage_node, retry=retry_policy)
workflow.add_node("remediation", remediation_node, retry=retry_policy)
workflow.add_node("routing", routing_node, retry=retry_policy)
workflow.add_node("suggestion", suggestion_node, retry=retry_policy)
workflow.add_edge(START, "ingestion")
workflow.add_edge("ingestion", "duplication")
workflow.add_conditional_edges(
"duplication",
should_proceed_after_duplication,
{"triage": "triage", END: END}
)
workflow.add_edge("triage", "kb_search")
workflow.add_edge("kb_search", "remediation")
workflow.add_conditional_edges(
"remediation",
should_continue_remediation,
{"routing": "routing", "suggestion": "suggestion"}
)
workflow.add_edge("routing", "suggestion")
workflow.add_edge("suggestion", END)
_workflow_app = workflow.compile()
return _workflow_app
async def run_ai_workflow(ctx: Any, ticket_id: Any, workspace_id: Any = None, **kwargs: Any) -> Dict[str, Any]:
"""
Main entry point to run the agentic workflow for a new ticket.
Hydrates data purely from DB (GAP-9 Fix).
"""
from core.tasks import check_job_latch, enqueue_task
t_id = uuid.UUID(str(ticket_id)) if ticket_id else None
ws_id = uuid.UUID(str(workspace_id)) if workspace_id else None
if not await check_job_latch(ctx, t_id, "ai_workflow"):
return {}
thread_id = uuid.uuid4()
v_tag = f"v_{int(time.time() % 1000)}"
logger.info(f"TASK START [{v_tag}]: Orchestrating AI for ticket {t_id}")
# FETCH DATA (GAP-9: hydrate source of truth)
async with async_session_factory() as db:
stmt = select(Ticket).where(Ticket.id == t_id)
res = await db.execute(stmt)
ticket = res.scalar_one_or_none()
if not ticket:
logger.error(f"Workflow: Ticket {t_id} not found.")
return {}
ws_id = ws_id or ticket.workspace_id
ticket_title = ticket.title
ticket_desc = ticket.description
ticket_cat = ticket.category
ticket_prio = ticket.priority
# --- PHASE 0: Hash & Fast-Path Deduplication (GAP-DEDUP) ---
if not ticket.content_hash:
import hashlib
payload_str = f"{ticket_title.strip()}|{ticket_desc.strip()}"
ticket.content_hash = hashlib.sha256(payload_str.encode('utf-8')).hexdigest()
db.add(ticket)
await db.commit()
# Check for existing UNRESOLVED duplicate in this workspace
dup_stmt = select(Ticket.id).where(
Ticket.workspace_id == ws_id,
Ticket.content_hash == ticket.content_hash,
Ticket.id != t_id,
Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]),
Ticket.deleted_at.is_(None)
).limit(1)
dup_res = await db.execute(dup_stmt)
fast_dup = dup_res.scalar()
if fast_dup and not kwargs.get("force_skip_duplication"):
logger.warning(f"Workflow Fast-Dedup: Ticket {t_id} is identical to {fast_dup} (AUTO-CLOSING)")
ticket.status = TicketStatus.CLOSED
ticket.duplicate_of_id = fast_dup
ticket.resolved_at = datetime.utcnow()
ticket.resolution_text = f"Automated Workflow: Marked as fast-duplicate of #{str(fast_dup)[:8]}."
await db.commit()
# TRIGGER: Immediate summarization for fast-duplicates (even with 0 messages)
from core.tasks import enqueue_task
await enqueue_task(
ctx.get("redis") if isinstance(ctx, dict) else None,
'auto_summarize_ticket',
t_id,
manual=True,
_job_id=f"summarize_init_{t_id}"
)
return {"is_duplicate": True, "duplicate_of_id": fast_dup}
app = await get_workflow_app()
initial_state = AgentState(
ticket_id=t_id,
workspace_id=ws_id,
thread_id=thread_id,
title=ticket_title,
description=ticket_desc,
attachments=[], # Ingestion node handles hydration
embedding=None,
vision_context=[],
is_duplicate=False,
duplicate_of_id=None,
category=ticket_cat,
priority=ticket_prio,
sentiment=None,
assigned_to=None,
status=None,
suggested_reply=None,
internal_summary=None,
target_team=None,
next_node=None,
kb_extracts=[],
is_new_topic=False,
kb_suggested_solution=None,
proposed_insights=[],
errors=[],
metadata={"force_skip_duplication": kwargs.get("force_skip_duplication", False)},
processed_steps=[]
)
from agents.state import merge_dict, merge_list
from models.ai_interaction import AIInteraction
from core.config import get_settings
settings = get_settings()
final_state = initial_state.copy()
interactions_to_save = []
# Accumulate mid-flight deltas here β one DB write after the stream instead of per-node
_pending_sync: dict = {}
logger.info(f"STARTING AI WORKFLOW [{v_tag}] for ticket {t_id}")
# 2. AI ORCHESTRATION: Primary Stream
try:
async for event in app.astream(
initial_state,
config={"configurable": {
"force_reroute": kwargs.get("force_reroute", False),
"force_skip_duplication": kwargs.get("force_skip_duplication", False),
"arq_pool": ctx.get("redis") if isinstance(ctx, dict) else None
}},
stream_mode="updates"
):
if not event: continue
# --- Capture PRE-NODE State for Forensic Input Log ---
# We take a lightweight snapshot of the current state before applying node updates
node_input_snapshot = {
"title": final_state.get("title"),
"description": final_state.get("description")[:1000] if final_state.get("description") else None,
"category": final_state.get("category"),
"priority": final_state.get("priority"),
"metadata": final_state.get("metadata"),
"errors_count": len(final_state.get("errors", [])),
"v_tag": v_tag
}
for node_name, updates in event.items():
# Manually replicate LangGraph's reducers for the final_state
for key, val in updates.items():
if key == "metadata":
final_state["metadata"] = merge_dict(final_state.get("metadata"), val)
elif key in ["processed_steps", "proposed_insights", "errors"]:
final_state[key] = merge_list(final_state.get(key), val)
else:
final_state[key] = val # Standard overwrite
# --- Mid-Flight Delta Accumulation (Resilience Layer) ---
# Accumulate critical field updates from each node. A single DB write
# is performed after the stream completes β eliminates N per-node sessions.
if updates.get("category"):
_pending_sync["category"] = updates["category"]
if updates.get("priority"):
_pending_sync["priority"] = updates["priority"]
if updates.get("assigned_to"):
_pending_sync["assigned_to"] = updates["assigned_to"]
node_meta = updates.get("metadata", {})
if node_meta.get("estimated_effort_hours"):
_pending_sync.setdefault("metadata", {}).update({
"estimated_effort_hours": node_meta["estimated_effort_hours"],
"complexity": node_meta.get("complexity", "low"),
})
# Use sanitize_for_db for the interaction log
clean_updates = sanitize_for_db(updates)
interactions_to_save.append({
"agent_name": node_name,
"input_data": sanitize_for_db(node_input_snapshot),
"output_data": clean_updates,
"metadata_json": clean_updates.get("metadata", {})
})
logger.info(f"NODE COMPLETE [{v_tag}]: {node_name}")
except Exception as stream_err:
logger.error(f"AI Stream failed for ticket {t_id}: {stream_err}")
# We proceed to save whatever progress we have in the atomic layer
# 2b. SINGLE MID-FLIGHT SYNC β one session for all accumulated node deltas
if _pending_sync:
try:
async with async_session_factory() as db:
stmt = select(Ticket).where(Ticket.id == t_id)
t = (await db.execute(stmt)).scalar_one_or_none()
if t:
if _pending_sync.get("category"):
t.category = _pending_sync["category"]
if _pending_sync.get("priority"):
t.priority = _pending_sync["priority"]
if _pending_sync.get("assigned_to"):
try:
t.assigned_to = uuid.UUID(str(_pending_sync["assigned_to"]))
t.status = TicketStatus.ACKNOWLEDGED
except Exception:
logger.warning(f"Mid-flight sync: invalid assigned_to value {_pending_sync['assigned_to']}")
sync_meta = _pending_sync.get("metadata", {})
if sync_meta.get("estimated_effort_hours"):
hours = float(sync_meta["estimated_effort_hours"])
t.estimated_effort_hours = {"value": hours, "complexity": sync_meta.get("complexity", "low")}
t.expected_resolution_at = (t.created_at or datetime.utcnow()) + timedelta(hours=hours)
await db.commit()
logger.debug(f"[NEXUS_RESILIENCE] Single consolidated mid-flight sync complete for ticket {t_id}")
except Exception as mse:
logger.warning(f"Consolidated mid-flight sync failed: {mse}")
# 3. ATOMIC PERSISTENCE LAYER (Merged Phases - BUG-4/ISSUE-1 Fix)
# We now use a single session and a single commit for all AI outputs.
try:
async with async_session_factory() as db:
logger.info(f"ATOMIC PERSISTENCE [{v_tag}] for ticket {t_id}")
# --- Step A: Re-fetch Ticket ---
stmt = select(Ticket).where(Ticket.id == t_id)
res = await db.execute(stmt)
ticket = res.scalar_one_or_none()
if not ticket:
raise ValueError("Ticket disappeared during workflow.")
# --- Step B: Save AI Interactions ---
for inter_data in interactions_to_save:
interaction = AIInteraction(
workspace_id=ws_id, ticket_id=t_id,
agent_name=inter_data["agent_name"], model_info=settings.AI_MODEL,
thread_id=thread_id, input_data=inter_data["input_data"],
output_data=inter_data["output_data"], status="success",
is_automatic=True, metadata_json=inter_data["metadata_json"]
)
db.add(interaction)
# --- Step C: Triage & Field Enrichment ---
hours = final_state.get("metadata", {}).get("estimated_effort_hours") or 1.0
ticket.estimated_effort_hours = {"value": float(hours), "complexity": final_state.get("metadata", {}).get("complexity") or "low"}
ticket.expected_resolution_at = (ticket.created_at or datetime.utcnow()) + timedelta(hours=hours)
ticket.category = final_state.get("category") or ticket.category or "OTHER"
ticket.priority = final_state.get("priority") or ticket.priority or "P2"
if final_state.get("assigned_to"):
try: ticket.assigned_to = uuid.UUID(str(final_state.get("assigned_to")))
except: pass
if final_state.get("is_duplicate"):
ticket.status = TicketStatus.CLOSED
ticket.duplicate_of_id = final_state.get("duplicate_of_id")
ticket.resolved_at = datetime.utcnow()
ticket.resolution_text = f"Automated Workflow: Marked as duplicate of #{str(ticket.duplicate_of_id)[:8]}."
if final_state.get("embedding"):
ticket.embedding = final_state.get("embedding")
# --- Step D: AI Metadata & Root Cause Analysis ---
final_meta = final_state.get("metadata", {})
is_duplicate = final_state.get("is_duplicate")
internal_summary = final_state.get("internal_summary") or "Diagnostic analysis complete."
# For duplicates, we don't want to pollute with "Under investigation" placeholders
# The internal portal will hide the RCA section anyway, but the data should be clean.
rca = final_state.get("root_cause_analysis")
if not rca:
rca = "Marked as duplicate." if is_duplicate else "Under investigation."
tech_solution = final_state.get("proposed_technical_solution")
if not tech_solution:
tech_solution = "See original ticket." if is_duplicate else "Diagnostics in progress."
# ββ FORENSIC TRAIL FIX ββββββββββββββββββββββββββββββββββββββββββ
# processed_steps are accumulated in final_state by the merge_list reducer
# but were never written into ai_metadata β so the frontend always saw an
# empty array and displayed "Awaiting initiation...".
processed_steps = final_state.get("processed_steps", [])
final_meta.update({
"worker_version": v_tag,
"processed_steps": processed_steps, # β Forensic Trail data for the UI
"kb_extracts": final_state.get("kb_extracts", []),
"summaries": {
"internal_summary": internal_summary,
"customer_summary": final_state.get("customer_summary") or "Technical analysis is complete. Our specialists are reviewing the findings to provide you with a resolution."
},
"initial_analysis": {
"rca": rca,
"technical_solution": tech_solution,
"relevant_article": final_meta.get("cited_sources", [])[0] if final_meta.get("cited_sources", []) else None,
"timestamp": datetime.utcnow().isoformat(),
"cited_sources": final_meta.get("cited_sources", [])
}
})
ticket.rca_notes = rca
ticket.ai_metadata = final_meta
db.add(ticket)
# --- Step E: Post-Analysis Message (Debounced) ---
if final_state.get("suggested_reply"):
from models.message import Message
from models.user_workspace import UserWorkspace
from models.user import UserRole
# Resolve Sender ID (Fallback to first SC_ADMIN if Super Admin missing)
sender_stmt = select(User.id).where(User.email == settings.SUPER_ADMIN_EMAIL)
sender_id = (await db.execute(sender_stmt)).scalar()
if not sender_id:
# Fallback: Get first staff member linked to this workspace
fallback_stmt = select(User.id).join(UserWorkspace).where(
UserWorkspace.workspace_id == ws_id,
UserWorkspace.role.in_([UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT])
).limit(1)
sender_id = (await db.execute(fallback_stmt)).scalar()
if sender_id:
ai_note = Message(
workspace_id=ws_id, ticket_id=t_id,
sender_id=sender_id,
is_internal=True,
content=(
f"### π‘οΈ Nexus Initial Analysis\n"
f"**Root Cause Analysis (RCA):**\n{rca}\n\n"
f"**Proposed Technical Solution:**\n{tech_solution}\n\n"
f"---\n"
f"**β¨ AI Draft Reply for Customer:**\n"
f"> {final_state.get('suggested_reply', 'Analysis in progress.')}"
)
)
db.add(ai_note)
# --- Step F: Knowledge Insights ---
for prop in final_state.get("proposed_insights", []):
action = prop.get("action")
if action == "CREATE_NEW":
insight = KnowledgeInsight(
workspace_id=ws_id, source_ticket_id=t_id,
target_article_id=safe_uuid(prop.get("target_article_id")),
insight_type=prop.get("insight_type"), category=prop.get("category"),
suggested_title=prop.get("suggested_title"), reasoning=prop.get("reasoning"),
suggested_content=final_state.get("kb_suggested_solution") or prop.get("suggested_content"),
confidence_score=prop.get("confidence_score", 0.0), embedding=prop.get("embedding"),
status=InsightStatus.PENDING
)
db.add(insight)
await db.flush()
db.add(KnowledgeInsightTicket(insight_id=insight.id, ticket_id=t_id, impact_context=prop.get("impact_context")))
elif action in ["UPDATE_EVIDENCE", "UPDATE_AND_MERGE_EVIDENCE"]:
i_id = safe_uuid(prop.get("insight_id"))
if i_id:
from sqlalchemy import update
update_vals = {"evidence_count": KnowledgeInsight.evidence_count + 1}
# Only update content if merging was successful and provided in payload
if action == "UPDATE_AND_MERGE_EVIDENCE":
if prop.get("reasoning"):
update_vals["reasoning"] = prop["reasoning"]
if prop.get("suggested_content"):
update_vals["suggested_content"] = prop["suggested_content"]
await db.execute(
update(KnowledgeInsight)
.where(KnowledgeInsight.id == i_id)
.values(**update_vals)
)
db.add(KnowledgeInsightTicket(insight_id=i_id, ticket_id=t_id, impact_context=prop.get("impact_context")))
# --- Step G: Telemetry (Citation Increments - ISSUE-5 Fix) ---
cited = final_meta.get("cited_sources", [])
if cited:
from models.kb_article import KBArticle
from sqlalchemy import update
await db.execute(update(KBArticle).where(KBArticle.title.in_(cited), KBArticle.workspace_id == ws_id).values(citation_count=KBArticle.citation_count + 1))
# --- FINAL COMMIT ---
await db.commit()
logger.info(f"AI SUCCESS [{v_tag}]: Atomic persistence complete.")
# --- WebSocket Broadcast: notify connected clients that enrichment is done ---
try:
from core.websockets import manager
await manager.broadcast_to_workspace(
workspace_id=ws_id,
message={
"type": "ticket_enriched",
"ticket_id": str(t_id),
"category": ticket.category,
"priority": str(ticket.priority) if ticket.priority else None,
"assigned_to": str(ticket.assigned_to) if ticket.assigned_to else None,
"internal_summary": internal_summary[:300] if internal_summary else None,
}
)
logger.info(f"[Workflow] WebSocket broadcast sent for ticket {t_id}")
except Exception as ws_err:
# Non-fatal: broadcast failure must never abort the workflow
logger.debug(f"[Workflow] WebSocket broadcast skipped (no active connections or manager unavailable): {ws_err}")
# --- 4. Cache Invalidation ---
# Ensure fresh ticket details are served after AI enrichment
await invalidate_cache(f"ticket:detail:{t_id}")
except Exception as e:
logger.exception(f"CRITICAL WORKFLOW FAILURE [{v_tag}]: {str(e)}")
# Failure Sink: Ensure ticket is at least reachable
try:
async with async_session_factory() as db:
stmt = select(Ticket).where(Ticket.id == t_id)
t = (await db.execute(stmt)).scalar_one_or_none()
if t:
if not t.category or t.category == "PENDING": t.category = "OTHER"
if not t.priority: t.priority = "P2"
await db.commit()
from models.ai_interaction import AIInteraction
db.add(AIInteraction(
workspace_id=ws_id, ticket_id=t_id, agent_name="workflow_engine",
model_info="system", thread_id=thread_id, input_data={},
output_data={"error": str(e)}, status="error", is_automatic=True
))
await db.commit()
except: pass
raise e
try:
await enqueue_task(
ctx.get("redis") if isinstance(ctx, dict) else None,
'auto_summarize_ticket',
t_id,
manual=True, # Ensure it runs even for immediate duplicates/resolutions
_job_id=f"summarize_init_{t_id}"
)
except: pass
return final_state
|