Spaces:
Running

ioc-core / src /services /huggingface.py
hellium1999's picture
feat: write-through async dashboard with in-memory cache
dd1eee1
Raw History Blame
11.1 kB
"""
Hugging Face Inference API service for AI-powered threat explanations.
Staff-Level Architecture:
- Risk assessment is DETERMINISTIC (via ThreatAnalyzer)
- AI only generates natural language prose
- Responses are cached in Redis (24h TTL)
- Fallback templates when AI is unavailable
- Compressed prompts to stay within HF token limits
"""
import logging
import time
from typing import Any
from huggingface_hub import InferenceClient
from src.config import settings
from src.exceptions import APIKeyMissingError, ExternalAPIError
from src.services.cache import cache
from src.services.threat_analyzer import ThreatAnalyzer, ThreatResult
logger = logging.getLogger(__name__)
# AI explanation cache TTL: 24 hours
AI_CACHE_TTL = 24 * 60 * 60
class HuggingFaceService:
"""
Service for AI-powered threat intelligence explanations.
Staff-level design:
- Uses ThreatAnalyzer for deterministic risk assessment
- AI only generates natural language summaries
- Redis caching for AI responses (24h TTL)
- Automatic fallback to templates when AI fails
"""
def __init__(self, api_token: str | None = None):
"""
Initialize HuggingFace Inference service.
Args:
api_token: HuggingFace API token
"""
self.api_token = api_token or settings.HF_API_TOKEN
if not self.api_token:
raise APIKeyMissingError("HuggingFace")
# Chat-compatible models (serverless inference)
self.models = [
"meta-llama/Llama-3.2-3B-Instruct", # Primary: Good balance
"Qwen/Qwen2.5-1.5B-Instruct", # Backup 1: Fast
"HuggingFaceH4/zephyr-7b-beta", # Backup 2: Reliable
"microsoft/Phi-3-mini-4k-instruct", # Backup 3: Compact
]
self.model = self.models[0]
self.client = InferenceClient(token=self.api_token)
self.threat_analyzer = ThreatAnalyzer()
def _make_request(self, prompt: str, max_tokens: int = 512) -> str:
"""
Make a request to HuggingFace API with automatic model fallback.
Args:
prompt: The prompt to send
max_tokens: Maximum tokens in response (reduced for speed)
Returns:
Generated text response
"""
system_prompt = """You are a cybersecurity analyst writing threat intelligence reports.
Write clear, professional summaries. Be concise - maximum 3-4 sentences.
Do NOT include sections, headers, or bullet points.
Just write a natural paragraph explaining the threat."""
last_error = None
for i, model in enumerate(self.models):
if i > 0:
time.sleep(1)
logger.info(f"Attempting AI request with model: {model}")
try:
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
]
response = self.client.chat_completion(
model=model,
messages=messages,
max_tokens=max_tokens,
temperature=0.3,
)
content = response.choices[0].message.content
if content:
logger.info(f"AI response generated with model: {model}")
return content.strip()
logger.warning(f"Empty response from model {model}")
last_error = ExternalAPIError("HuggingFace", message="Empty response")
except Exception as e:
error_str = str(e).lower()
logger.warning(f"Model {model} failed: {e}")
if "rate limit" in error_str or "429" in error_str:
last_error = ExternalAPIError(
"HuggingFace",
status_code=429,
message=f"Rate limited on {model}"
)
elif "unauthorized" in error_str or "401" in error_str:
raise ExternalAPIError(
"HuggingFace",
status_code=401,
message="Invalid API token"
) from e
else:
last_error = ExternalAPIError(
"HuggingFace",
message=f"Model {model} failed: {str(e)}"
)
continue
if last_error:
raise last_error
raise ExternalAPIError("HuggingFace", message="All models failed")
def _get_cached_explanation(self, cache_hash: str) -> str | None:
"""Get cached AI explanation if available."""
if not cache.is_available:
return None
key = f"ai:explanation:{cache_hash}"
try:
cached = cache.client.get(key)
if cached:
logger.info(f"AI explanation cache HIT: {cache_hash}")
return cached
except Exception as e:
logger.warning(f"Cache read error: {e}")
return None
def _cache_explanation(self, cache_hash: str, explanation: str) -> None:
"""Cache AI explanation with 24h TTL."""
if not cache.is_available:
return
key = f"ai:explanation:{cache_hash}"
try:
cache.client.setex(key, AI_CACHE_TTL, explanation)
logger.debug(f"AI explanation cached: {cache_hash} (TTL: 24h)")
except Exception as e:
logger.warning(f"Cache write error: {e}")
def _build_compressed_prompt(self, result: ThreatResult) -> str:
"""
Build a compressed prompt to reduce token usage.
This format minimizes tokens while providing enough context.
"""
# Compact threat data representation
detection_parts = []
# Add key findings in compressed format
for finding in result.findings[:3]:
# Extract key info from finding
if "VirusTotal" in finding:
detection_parts.append(finding.split(":")[1].strip()[:50])
elif "ThreatFox" in finding:
detection_parts.append("ThreatFox:FOUND")
elif "URLhaus" in finding:
detection_parts.append("URLhaus:FOUND")
elif "MalwareBazaar" in finding:
detection_parts.append("MalwareBazaar:MALWARE")
elif "OTX" in finding:
detection_parts.append(finding.split(":")[1].strip()[:30])
elif "AbuseIPDB" in finding:
detection_parts.append(finding.split(":")[1].strip()[:30])
detections = " | ".join(detection_parts) if detection_parts else "No detections"
prompt = f"""IOC: {result.ioc_value}
TYPE: {result.ioc_type.upper()}
VERDICT: {result.verdict} ({result.risk_level})
SCORE: {result.risk_score}/100
DATA: {detections}
Write a 2-3 sentence professional threat summary for a security analyst.
Explain what this {result.ioc_type} is and why it's rated {result.verdict}.
Reference the specific threat data. Do not use bullet points or headers."""
return prompt
def explain_ioc(
self,
ioc_value: str,
ioc_type: str,
source_data: dict[str, Any]
) -> dict[str, Any]:
"""
Generate AI explanation of threat intelligence results.
Architecture:
1. ThreatAnalyzer computes deterministic risk (SOURCE OF TRUTH)
2. Check Redis cache for AI explanation
3. If not cached, generate AI prose or use fallback
4. Return structured result with computed verdict
Args:
ioc_value: The IOC being analyzed
ioc_type: Type of IOC (ip, domain, url, hash)
source_data: Raw data from all sources
Returns:
Dictionary with explanation, verdict, and recommendations
"""
logger.info(f"Explaining IOC: {ioc_type}:{ioc_value}")
# Step 1: DETERMINISTIC threat analysis (SOURCE OF TRUTH)
result = self.threat_analyzer.analyze(ioc_value, ioc_type, source_data)
logger.info(f"Threat analysis: {result.verdict} ({result.risk_level}, score={result.risk_score})")
# Step 2: Check cache for AI explanation
cached_prose = self._get_cached_explanation(result.cache_hash)
if cached_prose:
# Use cached AI prose with fresh deterministic data
explanation = self._build_full_explanation(result, cached_prose)
return self._build_response(result, explanation, "cached")
# Step 3: Try AI generation
try:
prompt = self._build_compressed_prompt(result)
ai_prose = self._make_request(prompt)
# Cache the AI prose
self._cache_explanation(result.cache_hash, ai_prose)
explanation = self._build_full_explanation(result, ai_prose)
return self._build_response(result, explanation, "success")
except ExternalAPIError as e:
logger.warning(f"AI generation failed, using fallback: {e}")
# Step 4: Use fallback template
explanation = self.threat_analyzer.get_fallback_explanation(result)
return self._build_response(result, explanation, "fallback")
def _build_full_explanation(self, result: ThreatResult, ai_prose: str) -> str:
"""
Build the full explanation combining AI prose with deterministic data.
"""
parts = [
"**SUMMARY**",
ai_prose,
"",
"**RISK LEVEL**",
f"{result.risk_level}",
f"Risk Score: {result.risk_score}/100 - Verdict: {result.verdict}",
"",
"**KEY FINDINGS**",
]
if result.findings:
for finding in result.findings[:5]:
parts.append(f"- {finding}")
else:
parts.append("- No significant threat indicators detected")
parts.extend([
"",
"**RECOMMENDED ACTIONS**",
])
for i, rec in enumerate(result.recommendations[:5], 1):
parts.append(f"{i}. {rec}")
return "\n".join(parts)
def _build_response(
self,
result: ThreatResult,
explanation: str,
status: str
) -> dict[str, Any]:
"""Build the final response dictionary."""
return {
"ioc_value": result.ioc_value,
"ioc_type": result.ioc_type,
"explanation": explanation,
"status": status,
# Include deterministic verdict for programmatic use
"verdict": result.verdict,
"risk_level": result.risk_level,
"risk_score": result.risk_score,
"findings": result.findings,
"recommendations": result.recommendations,
}
# Module-level function for backward compatibility
def get_huggingface_service() -> HuggingFaceService:
"""Get a HuggingFace service instance."""
return HuggingFaceService()