from typing import Any, Dict, List, Optional from uuid import UUID from datetime import datetime from langchain_core.runnables import RunnableConfig from agents.state import AgentState from agents.utils import get_available_agents from sqlalchemy import select, func from models.ticket import Ticket, TicketStatus from models.user import User, UserRole from core.logging import get_logger logger = get_logger(__name__) async def routing_node(state: AgentState, config: RunnableConfig) -> Dict[str, Any]: """ Node that assigns the ticket to an agent based on workload (Load Balancing). Filters by department (team) if specified in the state. Autonomous Bypassing: Skips assignment if ticket is already owned. """ # 0. Autonomous Ownership Check (Zero-Trust Logic) existing_assignee = state.get("assigned_to") force_reroute = state.get("metadata", {}).get("force_reroute", False) if existing_assignee and not force_reroute: logger.info(f"ROUTING: Assignment Lock active for ticket {state['ticket_id']}. Ownership preserved.") return { "processed_steps": [{"name": "ROUTING", "status": "locked", "timestamp": datetime.utcnow().isoformat()}], "metadata": {"routing_skipped": True, "reason": "Ticket already assigned."} } db = config["configurable"].get("db") if not db: from core.database import async_session_factory async with async_session_factory() as db_session: return await _process_routing(state, db_session) return await _process_routing(state, db) async def _process_routing(state: AgentState, db: Any) -> Dict[str, Any]: """Internal logic with a guaranteed session.""" workspace_id = UUID(state["workspace_id"]) if isinstance(state["workspace_id"], str) else state["workspace_id"] priority = state.get("priority", "P2") target_team = state.get("target_team") logger.debug(f"Routing node calculating workload for workspace {workspace_id} (Team: {target_team})") # 1. Fetch all SC agents in the workspace agents = await get_available_agents(db, workspace_id) # 2. Team Filtering (Targeting Subject Matter Experts) team_agents = [] if target_team and agents: team_agents = [ a for a in agents if (a.ai_gist or {}).get("department") == target_team ] # Decision Pool Selection (Fallback logic to General Queue) final_pool = team_agents if team_agents else agents pool_type = f"team:{target_team}" if team_agents else "general_fallback" # 2.5. Manager Fallback (If Pool is EMPTY) if not final_pool: logger.warning(f"Routing fallback: No active agents found in pool {pool_type}. Searching for Lead/Admin...") stmt = select(User).where( User._legacy_role.in_([UserRole.SC_LEAD, UserRole.SC_ADMIN]), User.is_active.is_(True), User.deleted_at.is_(None) ).limit(1) # Note: We query global SC_LEAD/ADMIN as a high-level fallback res = await db.execute(stmt) manager = res.scalar_one_or_none() if manager: logger.info(f"Routing fallback success: Assigned to Manager {manager.id}") return { "assigned_to": manager.id, "status": TicketStatus.ACKNOWLEDGED, "processed_steps": [{"name": "ROUTING", "status": "fallback", "timestamp": datetime.utcnow().isoformat()}], "metadata": { "routing_fallback_assigned": True, "routing_assigned_to": str(manager.id), "routing_reason": "Expert pool empty, assigned to Lead/Admin." } } return { "errors": ["Critical routing failure: No agents or managers available."], "processed_steps": [{"name": "ROUTING", "status": "error", "timestamp": datetime.utcnow().isoformat()}] } # 3. Load Balancing: Count open tickets per agent in the selected POOL agent_ids = [a.id for a in final_pool] stmt = ( select(Ticket.assigned_to, func.count(Ticket.id)) .where( Ticket.assigned_to.in_(agent_ids), Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]), Ticket.deleted_at.is_(None) ) .group_by(Ticket.assigned_to) ) result = await db.execute(stmt) workloads = {row[0]: row[1] for row in result.all()} for aid in agent_ids: if aid not in workloads: workloads[aid] = 0 # 4. Final Assignment Logic # Preference for leads in high-priority tickets within the experts leads = [a for a in final_pool if a.role in [UserRole.SC_LEAD, UserRole.SC_ADMIN]] target_agent = None if priority in ["P0", "P1"] and leads: target_agent = min(leads, key=lambda a: workloads.get(a.id, 0)) reason = f"High priority ({priority}) within {pool_type} experts" else: target_agent = min(final_pool, key=lambda a: workloads.get(a.id, 0)) reason = f"Load-balanced within {pool_type} specialists" return { "assigned_to": target_agent.id, "status": TicketStatus.ACKNOWLEDGED, "processed_steps": [{"name": "ROUTING", "status": "success", "timestamp": datetime.utcnow().isoformat()}], "metadata": { "routing_assigned_to": str(target_agent.id), "routing_success": True, "routing_reason": reason, "routing_team": target_team, "routing_pool_type": pool_type, "routing_workload": workloads.get(target_agent.id, 0) } }