Spaces:
Running

File size: 3,254 Bytes
54559aa
 
 
 
 
 
 
 
 
9c30f2e
54559aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c30f2e
54559aa
9c30f2e
54559aa
 
 
9c30f2e
54559aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c30f2e
 
 
 
 
 
54559aa
9c30f2e
 
54559aa
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
"""AI API endpoints for threat intelligence explanations."""

import logging

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from src.exceptions import APIKeyMissingError, ExternalAPIError
from src.services.cache import cache
from src.services.huggingface import HuggingFaceService

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/ai", tags=["AI"])


class ExplainRequest(BaseModel):
    """Request model for AI explanation."""
    ioc_value: str
    ioc_type: str
    source_data: dict


class ExplainResponse(BaseModel):
    """Response model for AI explanation."""
    ioc_value: str
    ioc_type: str
    explanation: str
    status: str
    cached: bool = False


@router.post("/explain", response_model=ExplainResponse)
async def explain_ioc(request: ExplainRequest):
    """
    Generate an AI-powered explanation of threat intelligence results.

    Args:
        request: Contains IOC value, type, and source data from all providers

    Returns:
        AI-generated explanation with risk assessment and recommendations
    """
    logger.info(f"AI explain request for {request.ioc_type}: {request.ioc_value}")

    # Check cache first
    cached_explanation = cache.get("ai_explain", request.ioc_type, request.ioc_value)

    if cached_explanation:
        logger.info(f"Returning cached AI explanation for {request.ioc_value}")
        return ExplainResponse(
            ioc_value=request.ioc_value,
            ioc_type=request.ioc_type,
            explanation=cached_explanation.get("explanation", ""),
            status="success",
            cached=True
        )

    # Initialize HuggingFace AI service
    try:
        ai_service = HuggingFaceService()
    except APIKeyMissingError as e:
        raise HTTPException(
            status_code=503,
            detail="AI service not configured. Please add HF_API_TOKEN to environment."
        ) from e

    # Generate explanation
    try:
        result = ai_service.explain_ioc(
            ioc_value=request.ioc_value,
            ioc_type=request.ioc_type,
            source_data=request.source_data
        )
    except ExternalAPIError as e:
        raise HTTPException(
            status_code=502,
            detail=f"AI service error: {str(e)}"
        ) from e

    # Cache successful responses (24 hour TTL)
    if result.get("status") == "success":
        cache.set(
            "ai_explain",
            request.ioc_type,
            request.ioc_value,
            {"explanation": result.get("explanation", "")},
            ttl=86400  # 24 hours
        )

    return ExplainResponse(
        ioc_value=result.get("ioc_value", request.ioc_value),
        ioc_type=result.get("ioc_type", request.ioc_type),
        explanation=result.get("explanation", ""),
        status=result.get("status", "error"),
        cached=False
    )


@router.get("/health")
async def ai_health():
    """Check if AI service is available."""
    try:
        ai_service = HuggingFaceService()
        return {
            "status": "ok",
            "service": "huggingface",
            "model": ai_service.model
        }
    except APIKeyMissingError:
        return {"status": "unavailable", "reason": "HF_API_TOKEN not configured"}