Spaces:
Paused

File size: 14,814 Bytes
4405ca9
b7980f7
 
 
 
 
 
ea4e72d
b7980f7
 
 
 
 
 
a27a4ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a76bcb9
 
a27a4ab
 
 
 
efe35f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
 
 
331f592
 
b7980f7
 
 
 
331f592
 
b7980f7
331f592
b7980f7
 
 
a27a4ab
 
 
 
 
4401584
a27a4ab
4401584
a27a4ab
 
 
4401584
 
 
a27a4ab
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a27a4ab
b7980f7
efe35f7
 
bb9da27
efe35f7
bb9da27
 
 
 
efe35f7
bb9da27
 
 
 
b7980f7
efe35f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
 
 
efe35f7
 
 
 
 
 
 
 
 
 
 
 
b7980f7
efe35f7
 
 
 
b7980f7
 
 
a76bcb9
 
 
 
 
b7980f7
 
 
a27a4ab
b7980f7
a76bcb9
b7980f7
 
a76bcb9
b7980f7
 
 
 
 
efe35f7
 
 
 
 
 
 
 
 
 
 
 
b7980f7
efe35f7
 
 
 
b7980f7
 
 
331f592
 
 
 
 
 
 
 
 
 
17815e9
 
331f592
 
a27a4ab
b7980f7
 
 
a27a4ab
b7980f7
 
a76bcb9
a27a4ab
b7980f7
a76bcb9
b7980f7
 
 
 
 
 
 
 
 
 
a27a4ab
 
b7980f7
 
 
a27a4ab
b7980f7
 
 
 
a27a4ab
 
 
 
 
 
 
 
ea4e72d
a27a4ab
 
ea4e72d
a27a4ab
 
 
 
 
ea4e72d
 
 
17815e9
a27a4ab
 
 
 
efe35f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
from typing import Any, Dict
from datetime import datetime
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from langchain_core.runnables import RunnableConfig

from agents.state import AgentState
from agents.utils import hybrid_search_kb_internal, parse_json_garbage
from core.llm import get_text_embeddings
from models.knowledge_insight import KnowledgeInsight, InsightType, InsightStatus
from core.logging import get_logger

logger = get_logger(__name__)

GAP_ANALYSIS_PROMPT = """
You are a Technical Documentation Specialist. Your task is to perform a side-by-side comparison between a support incident and an existing Knowledge Base article.

TICKET:
Title: {ticket_title}
Description: {ticket_description}

EXISTING ARTICLE:
Title: {article_title}
Content: {article_content}

GOAL:
1. Identify EXACTLY what is missing from the existing article that is present in the ticket (e.g., a specific error code, a specific version quirk, a new troubleshooting step).
2. Draft a "Technical Blog" addendum that can be merged into the existing article.

BLOG FORMATTING RULES:
- Use professional Markdown.
- Use a "### Diagnostic Update" or "### Technical Deep-Dive" header.
- Provide a clear, bulleted fix.
- MANDATORY: Include a technical logic or flow diagram using Mermaid syntax (```mermaid graph TD; ... ```).
- ABSOLUTELY NO mention of "Ticket" or "Issue" in the final draft; write it as a proactive knowledge asset.

EXPLAIN YOUR REASONING:
Identify the specific gap (e.g. "Article covers VPN fix generally, but ticket provides the specific 807 error fix for Linux.")

Respond in the following JSON format:
{{
    "gap_report": "Professional, one-sentence summary of what exactly is missing.",
    "blog_draft": "Full technical addendum in Markdown.",
    "confidence": 0.0 - 1.0
}}
"""

MERGE_INSIGHT_PROMPT = """
You are a Technical Documentation Specialist. 
We have an existing draft Knowledge Base Insight (a pending technical article addendum or new topic) and a new Support Ticket that has encountered the same overarching issue.

YOUR GOAL: 
Merge any NEW technical details, error codes, edge cases, or troubleshooting steps from the New Ticket into the Existing Draft. 

EXISTING DRAFT REASONING: {existing_reasoning}
EXISTING DRAFT CONTENT:
{existing_content}

NEW TICKET TITLE: {ticket_title}
NEW TICKET DESCRIPTION:
{ticket_description}

RULES:
1. Do NOT delete existing technical details from the draft. Add to it.
2. Keep the formatting in Markdown.
3. If the new ticket provides a distinct technical scenario (e.g. Linux instead of Windows), ensure the draft covers BOTH.
4. Provide an updated "reasoning" that summarizes the combined scope of the insight.

Respond in the following JSON format:
{{
    "updated_reasoning": "Professional summary of the expanded scope.",
    "updated_content": "Full technical addendum/article in Markdown.",
    "confidence": 0.0 - 1.0
}}
"""

async def kb_search_node(state: AgentState, config: RunnableConfig) -> Dict[str, Any]:
    """
    Semantic & Keyword search against the KB.
    Identifies 'Knowledge Gaps' and 'Depth Improvements' for human approval.
    """
    skip_ai = config["configurable"].get("skip_ai", False)
    
    db: AsyncSession = 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_kb_search(state, db_session, skip_ai=skip_ai)
    return await _process_kb_search(state, db, skip_ai=skip_ai)

async def _process_kb_search(state: AgentState, db: Any, skip_ai: bool = False) -> Dict[str, Any]:
    """Internal logic with a guaranteed session."""

    try:
        # 1. Generate Query Context
        query_text = f"{state['title']}\n{state['description']}"
        
        # 2. Get Shared Embedding (Provided by Ingestion Node)
        query_embedding = state.get("embedding")
        if not query_embedding and not skip_ai:
            try:
                logger.info(f"[NEXUS_RESILIENCE] Fallback embedding triggered for {state.get('ticket_id')}")
                model = get_text_embeddings()
                query_embedding = await model.aembed_query(query_text)
            except Exception as e:
                logger.warning(f"[NEXUS_RESILIENCE] Fallback embedding failed: {str(e)}")
                # We do NOT return error here, we let hybrid_search handle None embedding
                pass

        # 3. Perform Hybrid Search (Threshold 0.2)
        search_results = await hybrid_search_kb_internal(
            db, 
            state["workspace_id"], 
            state["title"], # Keep keyword search focused on title
            query_embedding,
            limit=5
        )
        
        # Format extracts for State & Metadata
        extracts = []
        best_score = 0.0
        best_article = None
        
        for res in search_results:
            art = res["article"]
            score = res["score"]
            if score > best_score:
                best_score = score
                best_article = art
                
            extracts.append({
                "id": str(art.id),
                "title": art.title,
                "category": art.category,
                "score": round(score, 3),
                "preview": art.content[:500] + "..."
            })

        # 4. Forensic Gap Detection & De-duplication (HIL Logic)
        proposed_insights = []
        is_new_topic = False
        ticket_category = state.get("category") or "GENERAL"
        
        # 4.1. Check for existing PENDING insights
        existing_new_topic = None
        if query_embedding:
            new_topic_stmt = (
                select(KnowledgeInsight)
                .where(
                    KnowledgeInsight.workspace_id == state["workspace_id"],
                    KnowledgeInsight.status == InsightStatus.PENDING,
                    KnowledgeInsight.insight_type == InsightType.NEW_TOPIC,
                    KnowledgeInsight.embedding.isnot(None)
                )
                .order_by(KnowledgeInsight.embedding.cosine_distance(query_embedding))
                .limit(1)
            )
            existing_new_topic = (await db.execute(new_topic_stmt)).scalar_one_or_none()
            
        existing_depth = None
        if best_article:
            depth_stmt = (
                select(KnowledgeInsight)
                .where(
                    KnowledgeInsight.workspace_id == state["workspace_id"],
                    KnowledgeInsight.status == InsightStatus.PENDING,
                    KnowledgeInsight.insight_type == InsightType.DEPTH_IMPROVEMENT,
                    KnowledgeInsight.target_article_id == best_article.id
                )
                .limit(1)
            )
            existing_depth = (await db.execute(depth_stmt)).scalar_one_or_none()
        
        # 4.2. Logic (Draft Article vs. Existing Improvement)
        if best_score < 0.3:
            is_new_topic = True
            
            if existing_new_topic:
                # DYNAMIC MERGE: Update existing New Topic draft with new ticket details
                merge_data = {}
                if not skip_ai:
                    logger.info(f"KB Search: Merging New Topic insight {existing_new_topic.id}")
                    merge_data = await _perform_insight_merge(
                        state["title"], 
                        state["description"], 
                        existing_new_topic.reasoning, 
                        existing_new_topic.suggested_content
                    )
                
                proposed_insights.append({
                    "action": "UPDATE_AND_MERGE_EVIDENCE",
                    "insight_id": str(existing_new_topic.id),
                    "reasoning": merge_data.get("updated_reasoning"),
                    "suggested_content": merge_data.get("updated_content"),
                    "impact_context": f"Hybrid Score: {best_score}"
                })
            else:
                # Generate Refined Reasoning for New Topic
                reasoning = f"No relevant KB articles found. Max hybrid relevance score was {best_score}."
                if best_score < 0.1:
                    reasoning = f"Architecture Anomaly: This incident involves technical patterns (Category: {ticket_category}) completely unmapped in the current knowledge base."
                
                proposed_insights.append({
                    "action": "CREATE_NEW",
                    "insight_type": InsightType.NEW_TOPIC,
                    "category": ticket_category,
                    "suggested_title": f"Knowledge Gap: {state['title']}",
                    "suggested_content": f"# [DRAFT] {state['title']}\n\nNo existing articles cover this issue effectively.\n\n### Incident Details\n- Title: {state['title']}\n- Context: {state['description'][:1000]}\n\n### Suggested Technical Flow\n```mermaid\ngraph TD;\n    A[Start] --> B[Investigate {ticket_category}];\n    B --> C{{Issue Resolved?}};\n    C -- Yes --> D[Finalize Documentation];\n    C -- No --> E[Escalate to Specialist];\n```",
                    "confidence_score": round(1.0 - best_score, 3),
                    "embedding": query_embedding,
                    "reasoning": reasoning,
                    "impact_context": f"Hybrid Score: {best_score}"
                })

        elif best_score < 0.7 and best_article:
            # Depth improvement logic
            if existing_depth:
                 # DYNAMIC MERGE: Update existing Depth Improvement draft with new ticket details
                 merge_data = {}
                 if not skip_ai:
                    logger.info(f"KB Search: Merging Depth Improvement insight {existing_depth.id}")
                    merge_data = await _perform_insight_merge(
                        state["title"], 
                        state["description"], 
                        existing_depth.reasoning, 
                        existing_depth.suggested_content
                    )

                 proposed_insights.append({
                    "action": "UPDATE_AND_MERGE_EVIDENCE",
                    "insight_id": str(existing_depth.id),
                    "reasoning": merge_data.get("updated_reasoning"),
                    "suggested_content": merge_data.get("updated_content"),
                    "impact_context": f"Hybrid Score: {best_score}"
                 })
            else:
                # NEW: High-Fidelity Gap Analysis (Gated)
                gap_data = {}
                if not skip_ai:
                    logger.info(f"KB Search: Triggering AI Gap Analysis for article {best_article.id}")
                    gap_data = await _perform_high_fidelity_gap_analysis(
                        state["title"], 
                        state["description"], 
                        best_article.title, 
                        best_article.content
                    )
                    if not isinstance(gap_data, dict):
                        gap_data = {}
                else:
                    logger.info(f"KB Search: Skipping AI Gap Analysis for article {best_article.id} (Express Mode)")
                
                proposed_insights.append({
                    "action": "CREATE_NEW",
                    "insight_type": InsightType.DEPTH_IMPROVEMENT,
                    "category": ticket_category,
                    "target_article_id": str(best_article.id),
                    "suggested_title": best_article.title,
                    "suggested_content": gap_data.get("blog_draft", f"IMPROVEMENT SUGGESTION: The existing article '{best_article.title}' conceptually matches but lacks specific corrective details from this incident."),
                    "confidence_score": gap_data.get("confidence", round(best_score, 3)),
                    "embedding": query_embedding,
                    "reasoning": gap_data.get("gap_report", f"Specific technical delta detected for article '{best_article.title}'."),
                    "impact_context": f"Hybrid Score: {best_score}"
                })

        return {
            "kb_extracts": extracts,
            "is_new_topic": is_new_topic,
            "proposed_insights": proposed_insights,
            "processed_steps": [{"name": "KB_SEARCH", "status": "success", "timestamp": datetime.utcnow().isoformat()}],
            "metadata": {
                "kb_relevance_score": round(best_score, 3),
                "is_knowledge_gap": is_new_topic,
                "ticket_department": ticket_category
            }
        }
    except Exception as e:
        logger.exception(f"KB Search node failed for ticket {state.get('ticket_id')}: {str(e)}")
        return {
            "errors": [f"KB Search failed: {str(e)}"],
            "processed_steps": [{"name": "KB_SEARCH", "status": "error", "timestamp": datetime.utcnow().isoformat()}]
        }


async def _perform_high_fidelity_gap_analysis(t_title: str, t_desc: str, a_title: str, a_content: str) -> Dict[str, Any]:
    """Uses LLM to perform side-by-side gap analysis between ticket and existing article."""
    from core.llm import get_llm
    from langchain_core.prompts import ChatPromptTemplate
    llm = get_llm()
    prompt = ChatPromptTemplate.from_template(GAP_ANALYSIS_PROMPT)
    chain = prompt | llm
    
    try:
        raw_res = await chain.ainvoke({
            "ticket_title": t_title,
            "ticket_description": t_desc,
            "article_title": a_title,
            "article_content": a_content
        })
        
        content = raw_res.content if hasattr(raw_res, 'content') else str(raw_res)
        res = parse_json_garbage(content)
        return res if isinstance(res, dict) else {}
    except Exception as e:
        logger.error(f"Gap Analysis Failed: {str(e)}")
        return {}


async def _perform_insight_merge(t_title: str, t_desc: str, e_reasoning: str, e_content: str) -> Dict[str, Any]:
    """Uses LLM to merge new ticket context into an existing pending insight."""
    from core.llm import get_llm
    from langchain_core.prompts import ChatPromptTemplate
    llm = get_llm()
    prompt = ChatPromptTemplate.from_template(MERGE_INSIGHT_PROMPT)
    chain = prompt | llm
    
    try:
        raw_res = await chain.ainvoke({
            "ticket_title": t_title,
            "ticket_description": t_desc,
            "existing_reasoning": e_reasoning or "N/A",
            "existing_content": e_content or "N/A"
        })
        
        content = raw_res.content if hasattr(raw_res, 'content') else str(raw_res)
        res = parse_json_garbage(content)
        return res if isinstance(res, dict) else {}
    except Exception as e:
        logger.error(f"Insight Merge Failed: {str(e)}")
        return {}