Spaces:
Paused

File size: 13,925 Bytes
5eb4857
 
 
 
 
 
 
 
b7980f7
5eb4857
 
 
b7980f7
5eb4857
 
 
 
 
b7980f7
 
5eb4857
 
 
b7980f7
 
5eb4857
 
 
 
 
 
 
 
 
b7980f7
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
5eb4857
 
 
 
 
 
 
 
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
b7980f7
 
 
 
 
 
 
 
 
 
 
 
5eb4857
b7980f7
 
 
 
 
5eb4857
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
b7980f7
5eb4857
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
b7980f7
 
 
 
5eb4857
b7980f7
 
 
 
 
5eb4857
b7980f7
 
 
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
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
print("!!! AGENTS-WORKFLOW LOADED: [V_734] !!!")
import uuid
import json
import logging
import time
from typing import Dict, Any, List
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, CustomEncoder, get_workspace_manager, 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, InsightType, 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 "kb_search"

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,
            {"kb_search": "kb_search", END: END}
        )
        workflow.add_edge("kb_search", "triage")
        workflow.add_edge("triage", "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={},
            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)}},
            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"
            )
            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"
                )

            # --- 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:
                final_meta = final_state.get("metadata", {})
                final_meta.update({
                    "worker_version": v_tag,
                    "sync_type": "atomic_persistence",
                    "processed_steps": final_state.get("processed_steps", [])
                })
                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: Handle Knowledge Insights ---
                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"),
                            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() # Get ID for junction
                        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:
                            # Update existing insight evidence
                            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 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_meta.get("estimated_effort_hours") or 1.0
                ticket.estimated_effort_hours = {"value": float(hours), "complexity": final_meta.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