from typing import Any, Dict from datetime import datetime from langchain_core.runnables import RunnableConfig from agents.state import AgentState from core.llm import get_text_embeddings from core.logging import get_logger from models.ticket import Ticket, TicketStatus from models.attachment import Attachment from sqlalchemy import select, desc, func logger = get_logger(__name__) async def duplication_node(state: AgentState, config: RunnableConfig) -> Dict[str, Any]: """ Node that checks for duplicate tickets based on semantic similarity. Consolidated to identify visual and secondary textual matches. """ 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_duplication(state, db_session) return await _process_duplication(state, db) async def _process_duplication(state: AgentState, db: Any) -> Dict[str, Any]: """Internal logic with a guaranteed session.""" workspace_id = state["workspace_id"] ticket_id = state["ticket_id"] # 0. Global Skip (Manual Override) force_skip_duplication = state.get("metadata", {}).get("force_skip_duplication", False) if force_skip_duplication: return { "is_duplicate": False, "processed_steps": [{"name": "DUPLICATION", "status": "skipped", "timestamp": datetime.utcnow().isoformat()}], "metadata": {"duplication_skipped": True} } # 1. Fast Exit: If Ingestion node already caught a textual duplicate if state.get("is_duplicate"): return {"processed_steps": [{"name": "DUPLICATION", "status": "skipped", "timestamp": datetime.utcnow().isoformat()}]} # 2. Reuse Shared Embedding (Provided by Ingestion Node) query_vector = state.get("embedding") if not query_vector: # Fallback (Safety only, Ingestion Node is primary authority) content = f"{state['title']}\n\n{state['description']}" query_vector = await get_text_embeddings().aembed_query(content) try: # 3. Advanced Visual Forensic Search (30-Day Window) from datetime import timedelta thirty_days_ago = datetime.utcnow() - timedelta(days=30) att_stmt = select(Attachment).where(Attachment.ticket_id == ticket_id, Attachment.content_type.like("image/%")) current_attachments = (await db.execute(att_stmt)).scalars().all() img_matches = [] if current_attachments: for att in current_attachments: if not att.ai_caption: continue # Find other attachments with nearly identical AI descriptions within 30 days img_stmt = ( select( Attachment, func.similarity(Attachment.ai_caption, att.ai_caption).label("text_sim") ) .join(Ticket, Attachment.ticket_id == Ticket.id) .where( Attachment.workspace_id == workspace_id, Attachment.ticket_id != ticket_id, Attachment.ticket_id.isnot(None), Attachment.ai_caption.isnot(None), Ticket.created_at >= thirty_days_ago # 30-Day Limit ) .order_by(desc("text_sim")) .limit(1) ) sim_res = await db.execute(img_stmt) match = sim_res.first() if match and match.text_sim >= 0.92: # INCREASED THRESHOLD: 92% for visual identity img_matches.append({ "other_ticket_id": match.Attachment.ticket_id, "score": match.text_sim, "caption_match": match.Attachment.ai_caption }) # 4. Final Decision Logic if img_matches: img_matches.sort(key=lambda x: x["score"], reverse=True) best_img = img_matches[0] logger.warning(f"VISUAL DUPLICATE: Ticket {ticket_id} matches {best_img['other_ticket_id']} (sim: {best_img['score']:.2%})") return { "is_duplicate": True, "duplicate_of_id": best_img["other_ticket_id"], "status": TicketStatus.CLOSED, "processed_steps": [{"name": "DUPLICATION", "status": "success", "timestamp": datetime.utcnow().isoformat()}], "metadata": { "duplication_match_id": str(best_img["other_ticket_id"]), "duplication_type": "visual", "duplication_similarity": round(best_img["score"], 4), "duplication_reason": f"Visual match ({best_img['score']:.2%}) detected via CLIP similarity." } } # 5. Semantic Check finished in Ingestion Node. # Duplication Node focused on Visual/Forensic validation. return { "processed_steps": [{"name": "DUPLICATION", "status": "success", "timestamp": datetime.utcnow().isoformat()}], "metadata": {"duplication_check_performed": True, "vision_check": len(img_matches) > 0} } except Exception as e: logger.error(f"Duplication node failed for ticket {ticket_id}: {str(e)}") return { "errors": [f"Duplication check failed: {str(e)}"], "processed_steps": [{"name": "DUPLICATION", "status": "error", "timestamp": datetime.utcnow().isoformat()}] }