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 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": "...", "blog_draft": "...", "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. """ 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.""" 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: try: logger.warning(f"KB Search: Embedding missing in state for {state.get('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)}"], "processed_steps": [{"name": "KB_SEARCH", "status": "error", "timestamp": datetime.utcnow().isoformat()}] } # 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 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 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, "category": ticket_category, "suggested_title": f"Knowledge Gap: {state['title']}", "suggested_content": f"# AI-Identified Technical Gap\n\nNo existing articles cover this issue effectively.\n\n### Incident Details\n- Title: {state['title']}\n- Context: {state['description'][:500]}\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": 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: # NEW: High-Fidelity Gap Analysis 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 ) 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", "IMPROVEMENT SUGGESTION: The existing article matches conceptually but lacks detail from this incident."), "confidence_score": gap_data.get("confidence", round(best_score, 3)), "embedding": query_embedding, "reasoning": gap_data.get("gap_report", 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, "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 from langchain_core.output_parsers import JsonOutputParser llm = get_llm() prompt = ChatPromptTemplate.from_template(GAP_ANALYSIS_PROMPT) chain = prompt | llm | JsonOutputParser() try: return await chain.ainvoke({ "ticket_title": t_title, "ticket_description": t_desc, "article_title": a_title, "article_content": a_content }) except Exception as e: logger.error(f"Gap Analysis Failed: {str(e)}") return {}