Spaces:
3SCError404
/
Paused

nexus / agents /workflow.py
dushyantsingh0
backend stabilization
4405ca9
Raw History Blame Contribute Delete
16.1 kB
print("!!! AGENTS-WORKFLOW LOADED: [V_734] !!!")
import uuid
import logging
import time
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.attachment import Attachment
from models.knowledge_insight import KnowledgeInsight, InsightStatus
from models.knowledge_insight_ticket import KnowledgeInsightTicket
from sqlalchemy import select
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"
async def run_ai_workflow(ctx: Any, ticket_data: Dict[str, Any], **kwargs: Any) -> Dict[str, Any]:
"""
Main entry point to run the agentic workflow for a new ticket.
"""
thread_id = uuid.uuid4()
t_id_raw = ticket_data.get("id")
t_id = uuid.UUID(str(t_id_raw)) if t_id_raw else None
# Version Tag for Verification
v_tag = f"v_{int(time.time() % 1000)}"
logger.info(f"TASK START [{v_tag}]: Orchestrating AI for ticket {t_id} (Thread: {thread_id})")
final_state = {}
try:
# 1. PRE-ORCHESTRATION: Initial Data Fetch (Transient Session)
serialized_atts = []
async with async_session_factory() as db:
att_stmt = select(Attachment).where(Attachment.ticket_id == t_id)
att_res = await db.execute(att_stmt)
attachments = att_res.scalars().all()
serialized_atts = [
{"id": str(a.id), "filename": a.filename, "ai_caption": a.ai_caption}
for a in attachments
]
# 2. AI ORCHESTRATION: Pure Brain Phase (No Outer DB Session)
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)
app = workflow.compile()
initial_state = AgentState(
ticket_id=t_id,
workspace_id=uuid.UUID(str(ticket_data["workspace_id"])),
thread_id=thread_id,
title=ticket_data.get("title", "Hydrating..."),
description=ticket_data.get("description", "Hydrating..."),
attachments=serialized_atts,
embedding=None,
vision_context=[],
is_duplicate=False,
duplicate_of_id=None,
category=None,
priority=None,
sentiment=None,
assigned_to=None,
status=None,
suggested_reply=None,
internal_summary=None,
target_team=None,
next_node=None,
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 = []
logger.info(f"STARTING AI WORKFLOW [{v_tag}] for ticket {t_id}")
# 2. AI ORCHESTRATION: Primary Stream
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),
"db": db # Ensure DB is passed if possible, though nodes often fetch their own
}},
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
# This ensures metadata and processed_steps are MERGED, not overwritten
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 for other fields (embedding, category, etc.)
# We sanitize ONLY for the interaction log (JSON column)
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}")
# 3. POST-ORCHESTRATION: Atomic Persistence (New Dedicated Session)
async with async_session_factory() as db:
logger.info(f"PERSISTING AI RESULTS [{v_tag}] for ticket {t_id}")
# --- Step A: Save Intermediary Interactions ---
for inter_data in interactions_to_save:
interaction = AIInteraction(
workspace_id=initial_state["workspace_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",
duration_ms=sanitize_for_db({"total": 0}),
is_automatic=True,
metadata_json=inter_data["metadata_json"]
)
db.add(interaction)
# --- Step B: Record Triage Result ---
from core.observability import record_workflow_step
await record_workflow_step(
db, t_id, initial_state["workspace_id"], "LIFECYCLE", "AI_TRIAGE_COMPLETE",
input_data={"v": v_tag},
output_data={"next_node": final_state.get("next_node"), "metadata": final_state.get("metadata")},
current_stage="ROUTED_FOR_ACTION"
)
# --- Step C: Final Ticket Sync ---
stmt = select(Ticket).where(Ticket.id == t_id)
res = await db.execute(stmt)
ticket = res.scalar_one_or_none()
if ticket:
# Capture Summaries for Frontend
internal_summary = final_state.get("internal_summary") or "Diagnostic analysis complete."
final_meta = final_state.get("metadata", {})
final_meta.update({
"worker_version": v_tag,
"sync_type": "atomic_persistence",
"processed_steps": final_state.get("processed_steps", []),
"summaries": {
"internal_summary": internal_summary,
"customer_summary": (final_state.get("suggested_reply") or "")[:350] or "AI analysis in progress."
}
})
ticket.ai_metadata = final_meta
ticket.category = final_state.get("category") or ticket.category
ticket.priority = final_state.get("priority") or ticket.priority
if final_state.get("embedding"):
ticket.embedding = final_state.get("embedding")
# --- Step D: Proactive Internal Note (Nexus AI Assistant) ---
# This part remains conditional on having a suggestion
if final_state.get("suggested_reply"):
await record_workflow_step(
db, t_id, initial_state["workspace_id"], "LIFECYCLE", "AI_SUGGESTION_GENERATED",
output_data={"preview": final_state["suggested_reply"][:100] + "..."},
current_stage="REPLY_DRAFTED"
)
# Find Admin to act as Virtual Agent sender
from models.user import User
from models.message import Message
admin_stmt = select(User).where(User.email == settings.SUPER_ADMIN_EMAIL)
admin_res = await db.execute(admin_stmt)
admin_user = admin_res.scalar_one_or_none()
if admin_user:
sources_list = final_meta.get("cited_sources", [])
sources_text = "\n".join([f"- {s}" for s in sources_list]) if sources_list else "General Knowledge"
ai_note = Message(
workspace_id=initial_state["workspace_id"],
ticket_id=t_id,
sender_id=admin_user.id,
is_internal=True,
content=(
f"### ✨ Nexus AI Suggestion\n"
f"> {final_state['suggested_reply']}\n\n"
f"**Forensic Context:**\n{internal_summary}\n\n"
f"**Cited Sources:**\n{sources_text}"
)
)
db.add(ai_note)
# --- Step E: Handle Knowledge Insights ---
# Now unconditional - save insights even without suggestions
for prop in final_state.get("proposed_insights", []):
action = prop.get("action")
if action == "CREATE_NEW":
insight = KnowledgeInsight(
workspace_id=initial_state["workspace_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"),
suggested_content=prop.get("suggested_content"),
reasoning=prop.get("reasoning"),
confidence_score=prop.get("confidence_score", 0.0),
embedding=prop.get("embedding"),
status=InsightStatus.PENDING
)
db.add(insight)
await db.flush()
junction = KnowledgeInsightTicket(
insight_id=insight.id,
ticket_id=t_id,
impact_context=prop.get("impact_context")
)
db.add(junction)
elif action == "UPDATE_EVIDENCE":
insight_id = safe_uuid(prop.get("insight_id"))
if insight_id:
from sqlalchemy import update
await db.execute(
update(KnowledgeInsight)
.where(KnowledgeInsight.id == insight_id)
.values(evidence_count=KnowledgeInsight.evidence_count + 1)
)
junction = KnowledgeInsightTicket(
insight_id=insight_id,
ticket_id=t_id,
impact_context=prop.get("impact_context")
)
db.add(junction)
if ticket:
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]}."
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)
db.add(ticket)
await db.commit()
logger.info(f"AI SUCCESS [{v_tag}]: Atomic persistence complete.")
except Exception as e:
logger.exception(f"CRITICAL WORKFLOW FAILURE [{v_tag}]: {str(e)}")
try:
async with async_session_factory() as db:
err_interaction = AIInteraction(
workspace_id=initial_state["workspace_id"], ticket_id=t_id,
agent_name="workflow_engine", model_info="system", thread_id=thread_id,
input_data={}, output_data=sanitize_for_db({"error": str(e)}),
status="error", is_automatic=True
)
db.add(err_interaction)
await db.commit()
except: pass
raise e
return final_state