Spaces:
Paused

File size: 6,679 Bytes
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import Any, Dict, List, Optional
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, sanitize_for_db
from core.llm import get_text_embeddings
from models.knowledge_insight import KnowledgeInsight, InsightType, InsightStatus
from models.knowledge_insight_ticket import KnowledgeInsightTicket
from core.logging import get_logger

logger = get_logger(__name__)

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.
    """
    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)
    return await _process_kb_search(state, db)

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

    # 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:
        try:
            logger.warning(f"KB Search: Embedding missing in state for {state['ticket_id']}. Generating fallback...")
            model = get_text_embeddings()
            query_embedding = await model.aembed_query(query_text)
        except Exception as e:
            logger.error(f"KB Search: Embedding failure: {str(e)}")
            return {"errors": [f"Embedding failed: {str(e)}"]}

    # 3. Perform Hybrid Search (Threshold 0.2)
    try:
        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
        
        # 4.1. Check for existing PENDING insights to avoid duplicates
        insight_stmt = (
            select(KnowledgeInsight)
            .where(
                KnowledgeInsight.workspace_id == state["workspace_id"],
                KnowledgeInsight.status == InsightStatus.PENDING,
                KnowledgeInsight.embedding.isnot(None)
            )
            .order_by(KnowledgeInsight.embedding.cosine_distance(query_embedding))
            .limit(1)
        )
        existing_insight = (await db.execute(insight_stmt)).scalar_one_or_none()
        
        # 4.2. Logic (Draft Article vs. Existing Improvement)
        if best_score < 0.3:
            is_new_topic = True
            
            # Check if we can merge into an existing gap (Threshold 0.8 Similarity / 0.2 Distance)
            if existing_insight and existing_insight.insight_type == InsightType.NEW_TOPIC:
                proposed_insights.append({
                    "action": "UPDATE_EVIDENCE",
                    "insight_id": str(existing_insight.id),
                    "impact_context": f"Hybrid Score: {best_score}"
                })
            else:
                proposed_insights.append({
                    "action": "CREATE_NEW",
                    "insight_type": InsightType.NEW_TOPIC,
                    "suggested_title": f"Knowledge Gap: {state['title']}",
                    "suggested_content": f"AI-IDENTIFIED GAP: No existing articles cover this issue effectively.\n\nDescription: {state['description']}",
                    "confidence_score": round(1.0 - best_score, 3),
                    "embedding": query_embedding,
                    "reasoning": f"Max hybrid score was only {best_score}. No relevant KB content found.",
                    "impact_context": f"Hybrid Score: {best_score}"
                })

        elif best_score < 0.7 and best_article:
            # Depth improvement logic
            if existing_insight and existing_insight.target_article_id == best_article.id:
                 proposed_insights.append({
                    "action": "UPDATE_EVIDENCE",
                    "insight_id": str(existing_insight.id),
                    "impact_context": f"Hybrid Score: {best_score}"
                 })
            else:
                proposed_insights.append({
                    "action": "CREATE_NEW",
                    "insight_type": InsightType.DEPTH_IMPROVEMENT,
                    "target_article_id": str(best_article.id),
                    "suggested_title": best_article.title,
                    "suggested_content": f"IMPROVEMENT SUGGESTION: The existing article matches at {best_score*100}% but lacks specific detail from this incident.",
                    "confidence_score": round(best_score, 3),
                    "embedding": query_embedding,
                    "reasoning": f"Article '{best_article.title}' matches but score {best_score} suggests depth gaps.",
                    "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
            }
        }

    except Exception as e:
        logger.exception(f"KB Search node failed for ticket {state['ticket_id']}: {str(e)}")
        return {
            "errors": [f"KB Search failed: {str(e)}"],
            "processed_steps": [{"name": "KB_SEARCH", "status": "error", "timestamp": datetime.utcnow().isoformat()}]
        }