Download code/src/api/routes.py from DuyTa/cve-kgrag-db: direct link, hf CLI and curl.
- Browser
- Download file 29.3 kB
-
https://huggingface.co/datasets/DuyTa/cve-kgrag-db/resolve/main/code/src/api/routes.py
- Command line
-
hf download hf://datasets/DuyTa/cve-kgrag-db/code/src/api/routes.py
-
curl -L -o routes.py https://huggingface.co/datasets/DuyTa/cve-kgrag-db/resolve/main/code/src/api/routes.py
29.3 kB
| # src/api/routes.py | |
| from fastapi import APIRouter, HTTPException | |
| from fastapi.responses import StreamingResponse | |
| from typing import Dict, Any, List, Optional | |
| import asyncio | |
| import time | |
| import json | |
| import logging | |
| from datetime import datetime | |
| import traceback | |
| from pydantic import BaseModel | |
| from langchain_core.messages import HumanMessage | |
| from src.agents.agent_config import AGENT_GENERATION_TIMEOUT | |
| from src.agents.tracing import get_langfuse_handler, get_langfuse_client, push_score, get_current_trace_id | |
| logger = logging.getLogger(__name__) | |
| # Global app state (will be set by main.py) | |
| app_state = {} | |
| router = APIRouter() | |
| # Import models with fallback | |
| try: | |
| from .models import QueryRequest, QueryResponse, SearchResult, QueryType | |
| except ImportError: | |
| from pydantic import BaseModel | |
| from enum import Enum | |
| class QueryType(str, Enum): | |
| SEARCH = "search" | |
| CVE_LOOKUP = "cve_lookup" | |
| GENERAL = "general" | |
| class QueryRequest(BaseModel): | |
| query: str | |
| top_k: int = 10 | |
| years: Optional[List[str]] = None | |
| max_context_docs: int = 5 | |
| use_large_model: bool = False | |
| stream: bool = False | |
| severity_filter: Optional[str] = None | |
| vendor_filter: Optional[str] = None | |
| class SearchResult(BaseModel): | |
| id: str | |
| text: str | |
| metadata: Dict[str, Any] | |
| score: float | |
| distance: float | |
| class QueryResponse(BaseModel): | |
| query: str | |
| response: str | |
| search_results: List[SearchResult] | |
| query_type: QueryType | |
| processing_time: float | |
| model_used: str | |
| def get_rag_system(): | |
| """Get RAG system from app state""" | |
| if 'rag_system' not in app_state: | |
| raise HTTPException(status_code=503, detail="RAG system not initialized") | |
| return app_state['rag_system'] | |
| def get_llm_client(): | |
| """Get LLM client from app state (optional)""" | |
| return app_state.get('llm_client', None) | |
| def get_enhanced_processor(): | |
| """Get enhanced processor from app state (optional)""" | |
| return app_state.get('enhanced_processor', None) | |
| async def health_check(): | |
| """Fast health check endpoint""" | |
| try: | |
| # Quick health check with timeout | |
| rag_system = get_rag_system() | |
| # Get basic stats quickly | |
| stats = await asyncio.wait_for( | |
| asyncio.to_thread(rag_system.get_collection_stats), | |
| timeout=5.0 # 5 second timeout for health check | |
| ) | |
| llm_client = get_llm_client() | |
| llm_status = llm_client is not None | |
| return { | |
| "status": "healthy", | |
| "documents": stats.get("total_documents", 0), | |
| "llm_available": llm_status, | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| except asyncio.TimeoutError: | |
| return { | |
| "status": "slow", | |
| "message": "System responding slowly", | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| except Exception as e: | |
| logger.error(f"Health check failed: {e}") | |
| raise HTTPException(status_code=503, detail=f"System unhealthy: {str(e)}") | |
| async def optimized_search(request: QueryRequest): | |
| """Optimized search endpoint with better performance""" | |
| start_time = time.time() | |
| try: | |
| # Validate input | |
| if not request.query or len(request.query.strip()) == 0: | |
| raise HTTPException(status_code=400, detail="Query cannot be empty") | |
| # Limit parameters for performance | |
| top_k = min(request.top_k, 20) # Reduced from 50 | |
| query = request.query.strip()[:500] # Limit query length | |
| rag_system = get_rag_system() | |
| # Determine timeout based on query complexity | |
| search_timeout = 15.0 # Default timeout | |
| if len(query) > 100 or top_k > 10: | |
| search_timeout = 20.0 | |
| # Execute search with timeout | |
| try: | |
| search_results = await asyncio.wait_for( | |
| asyncio.to_thread(rag_system.search_cves, query, top_k), | |
| timeout=search_timeout | |
| ) | |
| except asyncio.TimeoutError: | |
| logger.warning(f"Search timeout for query: {query[:50]}...") | |
| raise HTTPException( | |
| status_code=408, | |
| detail=f"Search timed out after {search_timeout}s. Try a more specific query." | |
| ) | |
| # Convert results | |
| formatted_results = [] | |
| for result in search_results: | |
| formatted_results.append(SearchResult( | |
| id=result.get('id', ''), | |
| text=result.get('text', result.get('content', '')), | |
| metadata=result.get('metadata', {}), | |
| score=result.get('score', 0.0), | |
| distance=result.get('distance', 1.0) | |
| )) | |
| processing_time = time.time() - start_time | |
| return { | |
| "results": formatted_results, | |
| "query": query, | |
| "total_results": len(formatted_results), | |
| "processing_time": processing_time, | |
| "status": "success" | |
| } | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| processing_time = time.time() - start_time | |
| logger.error(f"Search failed: {e}") | |
| raise HTTPException( | |
| status_code=500, | |
| detail=f"Search failed after {processing_time:.2f}s: {str(e)}" | |
| ) | |
| async def optimized_query(request: QueryRequest): | |
| """Optimized query endpoint with LLM integration""" | |
| start_time = time.time() | |
| try: | |
| if not request.query or len(request.query.strip()) == 0: | |
| raise HTTPException(status_code=400, detail="Query cannot be empty") | |
| top_k = min(request.top_k, 15) | |
| query = request.query.strip()[:500] | |
| rag_system = get_rag_system() | |
| llm_client = get_llm_client() | |
| search_results = await asyncio.wait_for( | |
| asyncio.to_thread(rag_system.search_cves, query, top_k), | |
| timeout=15.0 | |
| ) | |
| formatted_results = [] | |
| for result in search_results: | |
| formatted_results.append(SearchResult( | |
| id=result.get('id', ''), | |
| text=result.get('text', result.get('content', '')), | |
| metadata=result.get('metadata', {}), | |
| score=result.get('score', 0.0), | |
| distance=result.get('distance', 1.0) | |
| )) | |
| processing_time = time.time() - start_time | |
| if llm_client and search_results: | |
| try: | |
| context = "\n\n".join( | |
| f"[{i+1}] {r.get('metadata', {}).get('cve_id', r.get('id', ''))}\n{r.get('text', '')[:800]}" | |
| for i, r in enumerate(search_results[:request.max_context_docs]) | |
| ) | |
| llm_prompt = f"Using the CVE search results below, answer the question.\n\nRESULTS:\n{context}\n\nQUESTION: {query}\n\nANSWER:" | |
| llm_response = await asyncio.wait_for( | |
| asyncio.to_thread(llm_client.generate, llm_prompt), | |
| timeout=30.0 | |
| ) | |
| model_used = llm_client.get_model_info().get("model_name", "llm") | |
| except asyncio.TimeoutError: | |
| llm_response = "LLM generation timed out." | |
| model_used = "llm_timeout" | |
| elif search_results: | |
| cve_count = len(search_results) | |
| top_cve = search_results[0]['metadata'].get('cve_id', 'Unknown') | |
| llm_response = f"Found {cve_count} relevant vulnerabilities. Top result: {top_cve}. LLM processing unavailable — using basic search." | |
| model_used = "basic_search" | |
| else: | |
| llm_response = f"No vulnerabilities found for: {query}" | |
| model_used = "basic_search" | |
| return QueryResponse( | |
| query=query, | |
| response=llm_response, | |
| search_results=formatted_results, | |
| query_type=QueryType.GENERAL, | |
| processing_time=processing_time, | |
| model_used=model_used | |
| ) | |
| except asyncio.TimeoutError: | |
| raise HTTPException(status_code=408, detail="Query processing timed out") | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| processing_time = time.time() - start_time | |
| logger.error(f"Query processing failed: {e}") | |
| raise HTTPException(status_code=500, detail=f"Query failed after {processing_time:.2f}s: {str(e)}") | |
| async def optimized_summary(request: QueryRequest): | |
| """Optimized summary endpoint""" | |
| start_time = time.time() | |
| try: | |
| query = request.query.strip() | |
| if not query: | |
| raise HTTPException(status_code=400, detail="Query cannot be empty") | |
| rag_system = get_rag_system() | |
| # Get more results for summary | |
| max_results = min(request.max_context_docs * 10, 50) | |
| search_results = await asyncio.wait_for( | |
| asyncio.to_thread(rag_system.search_cves, query, max_results), | |
| timeout=20.0 | |
| ) | |
| # Analyze results | |
| severities = {} | |
| vendors = [] | |
| total_results = len(search_results) | |
| for result in search_results: | |
| metadata = result.get('metadata', {}) | |
| # Count severities | |
| severity = metadata.get('severity', 'Unknown') | |
| severities[severity] = severities.get(severity, 0) + 1 | |
| # Collect vendors (simplified) | |
| affected_products = metadata.get('affected_products', []) | |
| if affected_products: | |
| vendors.extend(affected_products[:2]) # Limit to avoid performance issues | |
| # Get top vendors | |
| from collections import Counter | |
| vendor_counts = Counter(vendors) | |
| top_vendors = [vendor for vendor, count in vendor_counts.most_common(5)] | |
| processing_time = time.time() - start_time | |
| return { | |
| "query": query, | |
| "total_results": total_results, | |
| "severity_distribution": severities, | |
| "top_vendors": top_vendors, | |
| "processing_time": processing_time, | |
| "sample_results": search_results[:5] # Return top 5 as samples | |
| } | |
| except asyncio.TimeoutError: | |
| raise HTTPException(status_code=408, detail="Summary generation timed out") | |
| except Exception as e: | |
| processing_time = time.time() - start_time | |
| logger.error(f"Summary failed: {e}") | |
| raise HTTPException( | |
| status_code=500, | |
| detail=f"Summary failed after {processing_time:.2f}s: {str(e)}" | |
| ) | |
| async def get_stats(): | |
| """Fast stats endpoint""" | |
| try: | |
| rag_system = get_rag_system() | |
| llm_client = get_llm_client() | |
| # Get basic stats with timeout | |
| stats = await asyncio.wait_for( | |
| asyncio.to_thread(rag_system.get_collection_stats), | |
| timeout=5.0 | |
| ) | |
| return { | |
| "status": "operational", | |
| "total_documents": stats.get("total_documents", 0), | |
| "collection_name": stats.get("collection_name", "unknown"), | |
| "llm_available": llm_client is not None, | |
| "llm_model": llm_client.get_model_info().get("model_name") if llm_client else None, | |
| "version": "2.0.0-optimized" | |
| } | |
| except asyncio.TimeoutError: | |
| return { | |
| "status": "slow", | |
| "message": "Stats loading slowly", | |
| "version": "2.0.0-optimized" | |
| } | |
| except Exception as e: | |
| logger.error(f"Stats failed: {e}") | |
| raise HTTPException(status_code=500, detail=f"Stats unavailable: {str(e)}") | |
| # ── Neo4j graph endpoints ───────────────────────────────────────────────────── | |
| def get_graph_service(): | |
| return app_state.get("graph_service", None) | |
| class SimilarCVERequest(BaseModel if "BaseModel" in dir() else object): | |
| cve_id: str | |
| k: int = 10 | |
| try: | |
| from pydantic import BaseModel as _BM | |
| class SimilarCVERequest(_BM): | |
| cve_id: str | |
| k: int = 10 | |
| except Exception: | |
| pass | |
| async def graph_similar_cves(request: SimilarCVERequest): | |
| """Find CVEs related to the given CVE via the Neo4j knowledge graph.""" | |
| graph = get_graph_service() | |
| if graph is None: | |
| raise HTTPException(status_code=503, detail="Neo4j graph service not initialised") | |
| try: | |
| results = await asyncio.wait_for( | |
| asyncio.to_thread(graph.similar_cves, request.cve_id, request.k), | |
| timeout=10.0, | |
| ) | |
| return {"cve_id": request.cve_id, "similar": results, "count": len(results)} | |
| except asyncio.TimeoutError: | |
| raise HTTPException(status_code=408, detail="Graph query timed out") | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def graph_stats(): | |
| """Return Neo4j node counts per label.""" | |
| graph = get_graph_service() | |
| if graph is None: | |
| raise HTTPException(status_code=503, detail="Neo4j graph service not initialised") | |
| stats = await asyncio.to_thread(graph.get_stats) | |
| return {"neo4j_counts": stats} | |
| # ── Cross-collection search ─────────────────────────────────────────────────── | |
| async def search_collection(collection: str, request: QueryRequest): | |
| """Hybrid search across a specific Qdrant collection (cve/mitre/capec/cwe).""" | |
| valid = {"cve", "mitre", "capec", "cwe"} | |
| if collection not in valid: | |
| raise HTTPException(status_code=400, detail=f"Unknown collection. Choose from: {valid}") | |
| rag_system = get_rag_system() | |
| start_time = time.time() | |
| try: | |
| results = await asyncio.wait_for( | |
| asyncio.to_thread(rag_system.search, request.query, min(request.top_k, 20), collection), | |
| timeout=15.0, | |
| ) | |
| formatted = [ | |
| SearchResult( | |
| id=r.get("id", ""), | |
| text=r.get("text", ""), | |
| metadata=r.get("metadata", {}), | |
| score=r.get("score", 0.0), | |
| distance=r.get("distance", 1.0), | |
| ) | |
| for r in results | |
| ] | |
| return { | |
| "results": formatted, | |
| "collection": collection, | |
| "query": request.query, | |
| "total_results": len(formatted), | |
| "processing_time": time.time() - start_time, | |
| } | |
| except asyncio.TimeoutError: | |
| raise HTTPException(status_code=408, detail="Search timed out") | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| # Health endpoint that doesn't require authentication | |
| async def ping(): | |
| """Ultra-fast ping endpoint""" | |
| return {"status": "alive", "timestamp": datetime.now().isoformat()} | |
| async def query_stream(request: QueryRequest): | |
| """SSE streaming query endpoint with LLM integration.""" | |
| if not request.query or len(request.query.strip()) == 0: | |
| raise HTTPException(status_code=400, detail="Query cannot be empty") | |
| rag_system = get_rag_system() | |
| llm_client = get_llm_client() | |
| async def event_generator(): | |
| try: | |
| yield f"data: {json.dumps({'phase': 'searching', 'status': 'started'})}\n\n" | |
| search_results = await asyncio.wait_for( | |
| asyncio.to_thread(rag_system.search_cves, request.query.strip()[:500], min(request.top_k, 15)), | |
| timeout=15.0, | |
| ) | |
| formatted = [ | |
| { | |
| "id": r.get("id", ""), | |
| "text": r.get("text", r.get("content", ""))[:500], | |
| "metadata": r.get("metadata", {}), | |
| "score": r.get("score", 0.0), | |
| } | |
| for r in search_results | |
| ] | |
| yield f"data: {json.dumps({'phase': 'found', 'count': len(formatted), 'results': formatted})}\n\n" | |
| if not llm_client: | |
| yield f"data: {json.dumps({'phase': 'generate', 'status': 'llm_unavailable'})}\n\n" | |
| yield f"data: {json.dumps({'phase': 'done', 'response': 'LLM not available. Use /query/agent for agentic processing.'})}\n\n" | |
| yield "data: [DONE]\n\n" | |
| return | |
| context = "\n\n".join( | |
| f"[{i+1}] {r.get('metadata', {}).get('cve_id', r.get('id', ''))}\n{r.get('text', '')[:800]}" | |
| for i, r in enumerate(search_results[:request.max_context_docs]) | |
| ) | |
| llm_prompt = f"Using the CVE search results below, answer the question.\n\nRESULTS:\n{context}\n\nQUESTION: {request.query.strip()[:500]}\n\nANSWER:" | |
| yield f"data: {json.dumps({'phase': 'generating', 'status': 'started'})}\n\n" | |
| for token in llm_client.stream(llm_prompt): | |
| if token: | |
| yield f"data: {json.dumps({'token': token})}\n\n" | |
| yield "data: [DONE]\n\n" | |
| except asyncio.TimeoutError: | |
| yield f"data: {json.dumps({'phase': 'error', 'error': 'timeout', 'message': 'Request timed out'})}\n\n" | |
| except Exception as e: | |
| yield f"data: {json.dumps({'phase': 'error', 'error': str(e)[:200], 'message': 'Internal error'})}\n\n" | |
| return StreamingResponse( | |
| event_generator(), | |
| media_type="text/event-stream", | |
| headers={ | |
| "Cache-Control": "no-cache", | |
| "Connection": "keep-alive", | |
| }, | |
| ) | |
| # ── Agentic RAG endpoints ───────────────────────────────────────────────────── | |
| def get_agent_graph(): | |
| return app_state.get("agent_graph", None) | |
| def get_memory(): | |
| return app_state.get("memory", None) | |
| try: | |
| from .models import AgentQueryRequest, AgentResponse, AgentEvent | |
| except ImportError: | |
| class AgentQueryRequest(BaseModel if "BaseModel" in dir() else object): | |
| query: str | |
| session_id: str = "default_session" | |
| top_k: int = 10 | |
| max_context_docs: int = 6 | |
| async def agentic_query(request: AgentQueryRequest): | |
| """Full agentic RAG query with adaptive retrieval, KG enrichment, and self-reflection.""" | |
| start_time = time.time() | |
| try: | |
| if not request.query or len(request.query.strip()) == 0: | |
| raise HTTPException(status_code=400, detail="Query cannot be empty") | |
| agent_graph = get_agent_graph() | |
| if agent_graph is None: | |
| raise HTTPException(status_code=503, detail="Agent graph not initialized") | |
| llm_client = get_llm_client() | |
| model_name = "none" | |
| if llm_client: | |
| try: | |
| model_name = llm_client.get_model_info().get("model_name", "llm") | |
| except Exception: | |
| model_name = "llm" | |
| trace_id = "" | |
| lf_client = get_langfuse_client() | |
| if lf_client: | |
| try: | |
| trace = lf_client.trace( | |
| name="agentic-rag-query", | |
| session_id=request.session_id, | |
| input=request.query.strip()[:500], | |
| metadata={"model": model_name}, | |
| ) | |
| trace_id = trace.id | |
| except Exception: | |
| pass | |
| initial_state = { | |
| "messages": [HumanMessage(content=request.query.strip())], | |
| "original_query": request.query.strip()[:500], | |
| "rewritten_query": "", | |
| "route_decision": "", | |
| "rewrite_reason": "", | |
| "search_collections": ["cve"], | |
| "retrieved_docs": [], | |
| "kg_context": "", | |
| "kg_enriched": False, | |
| "memory_context": "", | |
| "generation": "", | |
| "reflection": {}, | |
| "retry_count": 0, | |
| "_relevant_count": 0, | |
| "mem0_user_id": request.session_id, | |
| "tracing_trace_id": trace_id, | |
| } | |
| langfuse_handler = get_langfuse_handler() | |
| callbacks = [langfuse_handler] if langfuse_handler else [] | |
| final_state = await asyncio.wait_for( | |
| asyncio.to_thread( | |
| agent_graph.invoke, initial_state, | |
| { | |
| "configurable": {"thread_id": request.session_id}, | |
| "callbacks": callbacks, | |
| }, | |
| ), | |
| timeout=AGENT_GENERATION_TIMEOUT, | |
| ) | |
| processing_time = time.time() - start_time | |
| if trace_id and lf_client: | |
| reflection = final_state.get("reflection", {}) | |
| push_score(trace_id, "hallucination_score", reflection.get("hallucination_score", 0.0)) | |
| push_score(trace_id, "completeness_score", reflection.get("completeness_score", 0.0)) | |
| verdict_val = 1.0 if reflection.get("verdict", "pass") == "pass" else 0.0 | |
| push_score(trace_id, "verdict", verdict_val) | |
| push_score(trace_id, "retries_used", final_state.get("retry_count", 0)) | |
| push_score(trace_id, "docs_retrieved", len(final_state.get("retrieved_docs", []))) | |
| push_score(trace_id, "processing_time", round(processing_time, 3)) | |
| return { | |
| "query": request.query, | |
| "answer": final_state.get("generation", ""), | |
| "route_decision": final_state.get("route_decision", "unknown"), | |
| "search_collections": final_state.get("search_collections", []), | |
| "rewritten_query": final_state.get("rewritten_query", "") or None, | |
| "docs_retrieved": len(final_state.get("retrieved_docs", [])), | |
| "docs_relevant": final_state.get("_relevant_count", 0), | |
| "kg_enriched": final_state.get("kg_enriched", False), | |
| "hallucination_check": final_state.get("reflection", {}).get("hallucination"), | |
| "completeness_check": final_state.get("reflection", {}).get("completeness"), | |
| "retries_used": final_state.get("retry_count", 0), | |
| "memory_context_used": bool(final_state.get("memory_context", "")), | |
| "processing_time": processing_time, | |
| "model_used": model_name, | |
| "search_results": [ | |
| { | |
| "id": r.get("id", ""), | |
| "text": r.get("text", "")[:300], | |
| "metadata": r.get("metadata", {}), | |
| "score": r.get("score", 0.0), | |
| } | |
| for r in final_state.get("retrieved_docs", [])[:5] | |
| ], | |
| } | |
| except asyncio.TimeoutError: | |
| raise HTTPException(status_code=408, detail="Agent query timed out") | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| logger.error(f"Agent query failed: {e}") | |
| raise HTTPException(status_code=500, detail=f"Agent query failed: {str(e)[:200]}") | |
| async def agentic_query_stream(request: AgentQueryRequest): | |
| """SSE streaming agentic RAG — emits events for each graph node phase.""" | |
| if not request.query or len(request.query.strip()) == 0: | |
| raise HTTPException(status_code=400, detail="Query cannot be empty") | |
| agent_graph = get_agent_graph() | |
| if agent_graph is None: | |
| raise HTTPException(status_code=503, detail="Agent graph not compiled") | |
| config = {"configurable": {"thread_id": request.session_id}} | |
| langfuse_handler = get_langfuse_handler() | |
| if langfuse_handler: | |
| config["callbacks"] = [langfuse_handler] | |
| lf_client = get_langfuse_client() | |
| trace_id = "" | |
| if lf_client: | |
| try: | |
| trace = lf_client.trace( | |
| name="agentic-rag-query", | |
| session_id=request.session_id, | |
| input=request.query.strip()[:500], | |
| ) | |
| trace_id = trace.id | |
| except Exception: | |
| pass | |
| async def event_generator(): | |
| try: | |
| initial_state = { | |
| "messages": [HumanMessage(content=request.query.strip())], | |
| "original_query": request.query.strip()[:500], | |
| "rewritten_query": "", | |
| "route_decision": "", | |
| "rewrite_reason": "", | |
| "search_collections": ["cve"], | |
| "retrieved_docs": [], | |
| "kg_context": "", | |
| "kg_enriched": False, | |
| "memory_context": "", | |
| "generation": "", | |
| "reflection": {}, | |
| "retry_count": 0, | |
| "_relevant_count": 0, | |
| "mem0_user_id": request.session_id, | |
| "tracing_trace_id": trace_id, | |
| } | |
| ref = {} | |
| # astream_events(v2) fires per-event including on_chain_stream for | |
| # BaseLLMRunnable.stream() tokens inside the generate_answer node. | |
| async for ev in agent_graph.astream_events(initial_state, config, version="v2"): | |
| et = ev["event"] | |
| name = ev.get("name", "") | |
| data = ev.get("data", {}) | |
| metadata = ev.get("metadata", {}) | |
| # ── Node completion events → phase SSE ────────────────────── | |
| if et == "on_chain_end" and metadata.get("langgraph_node") == name: | |
| node_name = name | |
| state = data.get("output", {}) | |
| if node_name == "memory_retrieve": | |
| ctx = state.get("memory_context", "") | |
| yield f"data: {json.dumps({'phase': 'memory_retrieve', 'has_context': bool(ctx)})}\n\n" | |
| elif node_name == "route_query": | |
| yield f"data: {json.dumps({'phase': 'route_query', 'decision': state.get('route_decision', ''), 'collections': state.get('search_collections', [])})}\n\n" | |
| elif node_name == "rewrite_query": | |
| rq = state.get("rewritten_query", "") | |
| yield f"data: {json.dumps({'phase': 'rewrite_query', 'rewritten': rq[:100]})}\n\n" | |
| elif node_name == "retrieve": | |
| docs = state.get("retrieved_docs", []) | |
| yield f"data: {json.dumps({'phase': 'retrieve', 'found': len(docs), 'kg_enriched': state.get('kg_enriched', False)})}\n\n" | |
| elif node_name == "grade_documents": | |
| relevant = state.get("_relevant_count", 0) | |
| yield f"data: {json.dumps({'phase': 'grade_documents', 'relevant': relevant})}\n\n" | |
| elif node_name == "generate_answer": | |
| gen = state.get("generation", "") | |
| yield f"data: {json.dumps({'phase': 'generation_complete', 'chars': len(gen)})}\n\n" | |
| elif node_name == "self_reflect": | |
| ref = state.get("reflection", {}) | |
| yield f"data: {json.dumps({'phase': 'self_reflect', 'verdict': ref.get('verdict', 'pass'), 'hallucination': ref.get('hallucination'), 'completeness': ref.get('completeness')})}\n\n" | |
| elif node_name == "memory_store": | |
| yield f"data: {json.dumps({'phase': 'memory_store', 'saved': True})}\n\n" | |
| # ── Token streaming from BaseLLMRunnable inside generate_answer ── | |
| elif et == "on_chain_stream" and metadata.get("langgraph_node") == "generate_answer": | |
| token = data.get("chunk", "") | |
| if token: | |
| yield f"data: {json.dumps({'token': token})}\n\n" | |
| yield "data: [DONE]\n\n" | |
| if trace_id and lf_client: | |
| push_score(trace_id, "hallucination_score", ref.get("hallucination_score", 0.0)) | |
| push_score(trace_id, "completeness_score", ref.get("completeness_score", 0.0)) | |
| verdict_val = 1.0 if ref.get("verdict", "pass") == "pass" else 0.0 | |
| push_score(trace_id, "verdict", verdict_val) | |
| except asyncio.TimeoutError: | |
| yield f"data: {json.dumps({'phase': 'error', 'error': 'timeout', 'fallback': 'search_only', 'message': 'Agent processing timed out'})}\n\n" | |
| except Exception as e: | |
| yield f"data: {json.dumps({'phase': 'error', 'error': 'internal', 'fallback': 'search_only', 'message': str(e)[:200]})}\n\n" | |
| return StreamingResponse( | |
| event_generator(), | |
| media_type="text/event-stream", | |
| headers={ | |
| "Cache-Control": "no-cache", | |
| "Connection": "keep-alive", | |
| }, | |
| ) | |
| async def agent_health(): | |
| """Agent-specific health check with degradation flags.""" | |
| return { | |
| "agent_graph_compiled": get_agent_graph() is not None, | |
| "mem0_enabled": (get_memory() is not None and get_memory().enabled) if get_memory() else False, | |
| "llm_available": get_llm_client() is not None, | |
| "neo4j_available": app_state.get("graph_service") is not None, | |
| "agent_degraded": get_agent_graph() is None, | |
| } | |