File size: 29,301 Bytes
27f6252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
# 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)


@router.get("/health")
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)}")


@router.post("/search")
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)}"
        )


@router.post("/query")
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)}")


@router.post("/summary")
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)}"
        )


@router.get("/stats")
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


@router.post("/graph/similar")
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))


@router.get("/graph/stats")
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 ───────────────────────────────────────────────────

@router.post("/search/{collection}")
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
@router.get("/ping")
async def ping():
    """Ultra-fast ping endpoint"""
    return {"status": "alive", "timestamp": datetime.now().isoformat()}


@router.post("/query/stream")
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


@router.post("/query/agent")
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]}")


@router.post("/query/agent/stream")
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",
        },
    )


@router.get("/query/agent/health")
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,
    }