"""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"}