Spaces:
Paused

File size: 5,141 Bytes
b7980f7
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
5eb4857
 
 
b7980f7
 
 
 
5eb4857
b7980f7
 
 
 
5eb4857
b7980f7
 
 
 
 
 
 
 
 
 
 
5eb4857
b7980f7
5eb4857
 
 
 
 
 
428a35c
 
 
 
5eb4857
428a35c
 
 
 
 
5eb4857
428a35c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
b7980f7
5eb4857
 
 
b7980f7
5eb4857
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
5eb4857
 
 
b7980f7
5eb4857
 
 
 
 
 
b7980f7
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
import logging
import uuid
from typing import Any, Dict, List, Optional
from datetime import datetime
from langchain_core.runnables import RunnableConfig
from agents.state import AgentState
from core.llm import get_text_embeddings, get_image_embeddings
from core.vision import resolve_image
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"]
    
    # 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
        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:
                # Meta-data-First: If no caption yet, we skip visual duplication for this specific item
                # (Captioning happens in background tasks)
                if not att.ai_caption:
                    continue
                
                # Fuzzy Search: Find other attachments with nearly identical AI descriptions
                img_stmt = (
                    select(
                        Attachment,
                        func.similarity(Attachment.ai_caption, att.ai_caption).label("text_sim")
                    )
                    .where(
                        Attachment.workspace_id == workspace_id,
                        Attachment.ticket_id != ticket_id,
                        Attachment.ticket_id.isnot(None),
                        Attachment.ai_caption.isnot(None)
                    )
                    .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.8: # High threshold for textual '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,
                 "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()}]
        }