Trong bối cảnh an ninh mạng ngày càng phức tạp với hàng triệu log events mỗi ngày, việc phân tích và phát hiện mối đe dọa theo cách truyền thống không còn đáp ứng được nhu cầu của các đội ngũ SOC (Security Operations Center). Bài viết này sẽ hướng dẫn bạn xây dựng một hệ thống SOC thông minh sử dụng HolySheep AI với chi phí tiết kiệm đến 85% so với các giải pháp truyền thống.
Bảng so sánh: HolySheep vs API chính thức vs Dịch vụ Relay
| Tiêu chí | HolySheep AI | API chính thức | Dịch vụ Relay |
|---|---|---|---|
| DeepSeek V3.2 | $0.42/M tokens | $0.27/M tokens | $0.50-$2/M tokens |
| Claude Sonnet 4.5 | $15/M tokens | $3/M tokens | $5-$20/M tokens |
| GPT-4.1 | $8/M tokens | $2-$10/M tokens | $10-$30/M tokens |
| Độ trễ trung bình | <50ms | 100-300ms | 200-500ms |
| Thanh toán | WeChat/Alipay/VNPay | Thẻ quốc tế | Hạn chế |
| Tín dụng miễn phí | Có | Không | Ít khi |
| Cloud Security Use Case | Tối ưu | Tốt | Trung bình |
HolySheep 云安全 SOC 助手 là gì?
Đây là giải pháp AI-powered SOC Assistant được xây dựng trên nền tảng HolySheep AI, kết hợp sức mạnh của:
- DeepSeek V3.2 - Mô hình ngôn ngữ lớn chi phí thấp cho log clustering và pattern recognition
- Claude Sonnet 4.5 - Khả năng phân tích tấn công chuỗi (attack chain) và reasoning logic mạnh mẽ
- GPT-4.1 - Tổng hợp báo cáo và documentation
- Gemini 2.5 Flash - Xử lý real-time alerts với độ trễ cực thấp
Kiến trúc hệ thống SOC thông minh
+------------------+ +------------------+ +------------------+
| Cloud Logs | | SIEM/Splunk | | CloudTrail |
| (AWS/GCP/Azure) | | /Elasticsearch | | /CloudWatch |
+--------+---------+ +--------+---------+ +--------+---------+
| | |
+-------------------------+-------------------------+
|
+--------------+--------------+
| HolySheep SOC Gateway |
| - DeepSeek: Log Clustering |
| - Claude: Attack Analysis |
| - Gemini: Real-time Alert |
+--------------+--------------+
|
+-------------------------+-------------------------+
| | |
+--------+---------+ +--------+---------+ +--------+---------+
| Threat Intel | | SOC Dashboard | | SLA Monitor |
| Enrichment | | /PagerDuty | | /Prometheus |
+-------------------+ +-----------------+ +------------------+
Cài đặt môi trường và cấu hình HolySheep API
Để bắt đầu, bạn cần đăng ký tài khoản HolySheep AI và lấy API key. Dưới đây là hướng dẫn cài đặt đầy đủ.
# Cài đặt các thư viện cần thiết
pip install openai httpx pandas python-dotenv elasticsearch
pip install prometheus-client pydantic pymsteams
Cấu hình biến môi trường (.env)
cat > .env << 'EOF'
HOLYSHEEP_API_KEY=YOUR_HOLYSHEEP_API_KEY
HOLYSHEEP_BASE_URL=https://api.holysheep.ai/v1
LOG_ENDPOINT=https://api.holysheep.ai/v1/chat/completions
CLAUDE_ENDPOINT=https://api.holysheep.ai/v1/chat/completions
DEEPSEEK_ENDPOINT=https://api.holysheep.ai/v1/chat/completions
Cấu hình Cloud Logs
AWS_REGION=ap-southeast-1
ELASTICSEARCH_HOST=localhost
ELASTICSEARCH_PORT=9200
SLA Configuration
SLA_THRESHOLD_P99=500
SLA_THRESHOLD_AVG=200
EOF
Load environment variables
export $(cat .env | xargs)
Module 1: DeepSeek Log Clustering - Phân cụm log thông minh
DeepSeek V3.2 với giá chỉ $0.42/M tokens là lựa chọn tối ưu cho việc phân tích hàng triệu log entries. Chi phí tiết kiệm đến 85% so với GPT-4 để xử lý cùng khối lượng công việc.
"""
SOC Log Clustering Module sử dụng DeepSeek V3.2
Chi phí: $0.42/M tokens - Tiết kiệm 85%+ so với GPT-4
"""
import os
import json
import httpx
from typing import List, Dict, Tuple
from collections import defaultdict
from datetime import datetime, timedelta
class SOCLogClustering:
def __init__(self, api_key: str = None, base_url: str = "https://api.holysheep.ai/v1"):
self.api_key = api_key or os.getenv("HOLYSHEEP_API_KEY")
self.base_url = base_url
self.model = "deepseek-v3.2"
def _call_deepseek(self, system_prompt: str, user_message: str) -> str:
"""Gọi DeepSeek V3.2 qua HolySheep API - Chi phí cực thấp"""
url = f"{self.base_url}/chat/completions"
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
payload = {
"model": self.model,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_message}
],
"temperature": 0.3,
"max_tokens": 2000
}
with httpx.Client(timeout=30.0) as client:
response = client.post(url, headers=headers, json=payload)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"]
def cluster_logs(self, raw_logs: List[Dict]) -> Dict[str, List[Dict]]:
"""
Phân cụm log events theo pattern sử dụng DeepSeek
Input: Danh sách log entries
Output: Dict với key là cluster_name, value là list logs
"""
# Format logs thành text
log_text = "\n".join([
f"[{log.get('timestamp')}] {log.get('level')} | {log.get('service')}: {log.get('message')}"
for log in raw_logs[:500] # Giới hạn 500 logs mỗi batch
])
system_prompt = """Bạn là chuyên gia phân tích bảo mật SOC.
Nhiệm vụ: Phân cụm các log events thành các nhóm có pattern tương tự.
Trả về JSON format:
{
"clusters": {
"cluster_name_1": {
"description": "Mô tả pattern chung",
"severity": "critical/high/medium/low",
"logs": ["log1", "log2", ...]
}
}
}
Chỉ phân tích logs được cung cấp, không suy luận thêm."""
user_message = f"""Phân cụm các log events sau đây:
{log_text}
Trả về kết quả phân cụm JSON."""
try:
result = self._call_deepseek(system_prompt, user_message)
clusters = json.loads(result)
# Logging chi phí ước tính
tokens_used = len(log_text.split()) * 1.3 # Rough estimate
cost_usd = (tokens_used / 1_000_000) * 0.42
print(f"[INFO] DeepSeek V3.2 - Tokens: ~{tokens_used:.0f}, Cost: ${cost_usd:.4f}")
return clusters
except Exception as e:
print(f"[ERROR] Clustering failed: {e}")
return {}
def detect_anomalies(self, clusters: Dict) -> List[Dict]:
"""Phát hiện anomaly dựa trên clustering results"""
anomalies = []
for cluster_name, cluster_data in clusters.items():
if cluster_data.get("severity") in ["critical", "high"]:
anomalies.append({
"cluster": cluster_name,
"description": cluster_data.get("description"),
"severity": cluster_data.get("severity"),
"log_count": len(cluster_data.get("logs", [])),
"recommendation": "Cần điều tra ngay"
})
return anomalies
Sử dụng module
if __name__ == "__main__":
clustering = SOCLogClustering()
# Sample logs từ cloud environment
sample_logs = [
{"timestamp": "2026-05-23T01:51:00Z", "level": "ERROR", "service": "auth-service", "message": "Failed login attempt for user admin"},
{"timestamp": "2026-05-23T01:51:05Z", "level": "WARNING", "service": "auth-service", "message": "Multiple failed authentication attempts"},
{"timestamp": "2026-05-23T01:51:10Z", "level": "ERROR", "service": "auth-service", "message": "Failed login attempt for user root"},
{"timestamp": "2026-05-23T01:51:15Z", "level": "INFO", "service": "api-gateway", "message": "Request processed successfully"},
]
clusters = clustering.cluster_logs(sample_logs)
anomalies = clustering.detect_anomalies(clusters)
print(f"[RESULT] Found {len(anomalies)} anomalies")
Module 2: Claude Attack Chain Analysis - Phân tích chuỗi tấn công
Claude Sonnet 4.5 với khả năng reasoning vượt trội là lựa chọn hoàn hảo cho việc phân tích attack chain. Mặc dù giá $15/M tokens cao hơn DeepSeek, nhưng độ chính xác và depth analysis là không thể so sánh.
"""
SOC Attack Chain Analysis Module sử dụng Claude Sonnet 4.5
Khả năng reasoning vượt trội cho MITRE ATT&CK mapping
"""
import os
import json
import httpx
from typing import List, Dict, Optional
from dataclasses import dataclass, asdict
from enum import Enum
class Severity(Enum):
CRITICAL = "critical"
HIGH = "high"
MEDIUM = "medium"
LOW = "low"
INFO = "informational"
@dataclass
class AttackStep:
step_id: int
tactic: str
technique: str
evidence: str
confidence: float
timestamp: str
@dataclass
class AttackChain:
chain_id: str
title: str
severity: str
steps: List[AttackStep]
mitre_mapping: List[str]
ioc_list: List[str]
recommendation: str
class SOCAttackAnalyzer:
def __init__(self, api_key: str = None, base_url: str = "https://api.holysheep.ai/v1"):
self.api_key = api_key or os.getenv("HOLYSHEEP_API_KEY")
self.base_url = base_url
self.model = "claude-sonnet-4.5"
def _call_claude(self, system_prompt: str, user_message: str) -> str:
"""Gọi Claude Sonnet 4.5 qua HolySheep API"""
url = f"{self.base_url}/chat/completions"
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
payload = {
"model": self.model,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_message}
],
"temperature": 0.2,
"max_tokens": 4000
}
with httpx.Client(timeout=60.0) as client:
response = client.post(url, headers=headers, json=payload)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"]
def analyze_attack_chain(self, security_events: List[Dict]) -> AttackChain:
"""
Phân tích chuỗi tấn công từ các security events
Sử dụng Claude cho reasoning và MITRE ATT&CK mapping
"""
# Format events
events_text = "\n".join([
f"[{e.get('timestamp')}] {e.get('source')}: {e.get('description')}"
for e in security_events
])
system_prompt = """Bạn là chuyên gia phân tích APT và Red Team với 15 năm kinh nghiệm.
Nhiệm vụ: Phân tích chuỗi tấn công (Attack Chain) và map với MITRE ATT&CK framework.
Trả về JSON format chính xác:
{
"chain_id": "AC-2026-XXXX",
"title": "Tên mô tả cuộc tấn công",
"severity": "critical/high/medium/low",
"steps": [
{
"step_id": 1,
"tactic": "Initial Access",
"technique": "T1190 - Exploit Public-Facing Application",
"evidence": "Mô tả evidence cụ thể",
"confidence": 0.85,
"timestamp": "2026-05-23T01:51:00Z"
}
],
"mitre_mapping": ["T1190", "T1059", "T1566"],
"ioc_list": ["192.168.1.100", "malware.exe", "hash123"],
"recommendation": "Hành động cần thực hiện ngay"
}"""
user_message = f"""Phân tích chuỗi tấn công từ các security events sau:
{events_text}
Xác định:
1. Thứ tự các bước tấn công (kill chain)
2. Tactic và technique theo MITRE ATT&CK
3. Indicators of Compromise (IOCs)
4. Hành động khuyến nghị"""
try:
result = self._call_claude(system_prompt, user_message)
attack_chain = json.loads(result)
# Tính chi phí
total_chars = len(events_text) + len(result)
cost_usd = (total_chars / 4) / 1_000_000 * 15 # ~4 chars/token
print(f"[INFO] Claude Sonnet 4.5 - Chars: ~{total_chars}, Cost: ${cost_usd:.4f}")
return AttackChain(**attack_chain)
except Exception as e:
print(f"[ERROR] Attack chain analysis failed: {e}")
return None
def generate_incident_report(self, attack_chain: AttackChain) -> str:
"""Generate incident report từ attack chain analysis"""
report_prompt = """Generate a detailed SOC incident report in Vietnamese.
Include: Executive Summary, Technical Details, Impact Assessment, Remediation Steps."""
details = json.dumps(asdict(attack_chain), indent=2)
user_msg = f"""Tạo báo cáo incident chi tiết cho cuộc tấn công sau:
{details}
Format: Markdown với các section:
1. Tóm tắt điều hành
2. Chi tiết kỹ thuật
3. Đánh giá tác động
4. Các bước khắc phục
5. Timeline"""
return self._call_claude(report_prompt, user_msg)
Demo usage
if __name__ == "__main__":
analyzer = SOCAttackAnalyzer()
# Sample security events
events = [
{"timestamp": "2026-05-23T01:45:00Z", "source": "WAF", "description": "SQL Injection attempt from 203.0.113.50"},
{"timestamp": "2026-05-23T01:46:30Z", "source": "Firewall", "description": "Port scan detected from 203.0.113.50"},
{"timestamp": "2026-05-23T01:48:00Z", "source": "Auth-Log", "description": "Brute force admin login attempts"},
{"timestamp": "2026-05-23T01:50:00Z", "source": "EDR", "description": "Suspicious PowerShell execution detected"},
{"timestamp": "2026-05-23T01:51:00Z", "source": "DLP", "description": "Large data exfiltration attempt"},
]
attack_chain = analyzer.analyze_attack_chain(events)
if attack_chain:
print(f"[RESULT] Attack Chain: {attack_chain.title}")
print(f"[RESULT] Severity: {attack_chain.severity}")
print(f"[RESULT] MITRE Mapping: {', '.join(attack_chain.mitre_mapping)}")
print(f"[RESULT] IOCs: {', '.join(attack_chain.ioc_list)}")
Module 3: SLA Monitoring Dashboard - Giám sát SLA thời gian thực
Với Gemini 2.5 Flash chỉ $2.50/M tokens và độ trễ <50ms, bạn có thể xây dựng dashboard giám sát SLA real-time với chi phí cực kỳ hiệu quả.
"""
SOC SLA Monitoring Dashboard sử dụng Gemini 2.5 Flash
Real-time monitoring với chi phí thấp và độ trễ cực thấp
"""
import os
import time
import httpx
import json
from typing import Dict, List, Optional
from datetime import datetime, timedelta
from dataclasses import dataclass
from prometheus_client import Counter, Histogram, Gauge, start_http_server
Prometheus metrics
LOG_PROCESSING_TIME = Histogram(
'log_processing_seconds',
'Time spent processing logs',
buckets=[0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0]
)
LOG_PROCESSING_COUNT = Counter('log_processing_total', 'Total logs processed')
SLA_VIOLATION_COUNT = Counter('sla_violation_total', 'Total SLA violations')
ACTIVE_ALERTS = Gauge('active_alerts', 'Number of active alerts')
API_LATENCY = Histogram('api_latency_seconds', 'HolySheep API latency')
@dataclass
class SLAConfig:
name: str
threshold_p99_ms: int
threshold_avg_ms: int
error_rate_threshold: float
@dataclass
class SLAMetrics:
service_name: str
avg_latency_ms: float
p99_latency_ms: float
error_rate: float
requests_count: int
violations: List[str]
status: str # "healthy", "degraded", "down"
class SOCSLAMonitor:
def __init__(self, api_key: str = None, base_url: str = "https://api.holysheep.ai/v1"):
self.api_key = api_key or os.getenv("HOLYSHEEP_API_KEY")
self.base_url = base_url
self.model = "gemini-2.5-flash"
# Default SLA configs
self.sla_configs = {
"auth-service": SLAConfig("auth-service", 200, 100, 0.01),
"api-gateway": SLAConfig("api-gateway", 500, 200, 0.05),
"payment-service": SLAConfig("payment-service", 1000, 500, 0.001),
"data-pipeline": SLAConfig("data-pipeline", 2000, 1000, 0.1),
}
self.current_metrics: Dict[str, SLAMetrics] = {}
def _call_gemini(self, prompt: str) -> str:
"""Gọi Gemini 2.5 Flash qua HolySheep API - Độ trễ <50ms"""
url = f"{self.base_url}/chat/completions"
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
payload = {
"model": self.model,
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.1,
"max_tokens": 500
}
start_time = time.time()
try:
with httpx.Client(timeout=10.0) as client:
response = client.post(url, headers=headers, json=payload)
response.raise_for_status()
latency = time.time() - start_time
API_LATENCY.observe(latency)
# Log với độ trễ thực tế
print(f"[METRIC] Gemini 2.5 Flash latency: {latency*1000:.2f}ms")
return response.json()["choices"][0]["message"]["content"]
except httpx.TimeoutException:
print(f"[WARNING] Gemini API timeout - Latency exceeded 10s")
return None
def process_log_entry(self, log: Dict) -> Optional[Dict]:
"""Xử lý log entry và phát hiện SLA violations"""
LOG_PROCESSING_COUNT.inc()
start_time = time.time()
service = log.get("service", "unknown")
latency = log.get("latency_ms", 0)
status_code = log.get("status_code", 200)
error = status_code >= 400
# Quick check với Gemini
prompt = f"""Analyze this log entry for SLA compliance:
Service: {service}
Latency: {latency}ms
Status: {status_code}
Error: {error}
Respond with JSON:
{{"violation": true/false, "reason": "brief reason", "severity": "high/medium/low"}}
"""
with LOG_PROCESSING_TIME.time():
result = self._call_gemini(prompt)
if result:
try:
analysis = json.loads(result)
if analysis.get("violation"):
SLA_VIOLATION_COUNT.inc()
ACTIVE_ALERTS.inc()
return {
"service": service,
"latency": latency,
"reason": analysis.get("reason"),
"severity": analysis.get("severity"),
"timestamp": log.get("timestamp")
}
except json.JSONDecodeError:
pass
return None
def calculate_sla_metrics(self, service: str, log_batch: List[Dict]) -> SLAMetrics:
"""Tính toán SLA metrics cho một service"""
latencies = [log.get("latency_ms", 0) for log in log_batch]
errors = sum(1 for log in log_batch if log.get("status_code", 200) >= 400)
avg_latency = sum(latencies) / len(latencies) if latencies else 0
latencies_sorted = sorted(latencies)
p99_index = int(len(latencies_sorted) * 0.99)
p99_latency = latencies_sorted[p99_index] if latencies_sorted else 0
error_rate = errors / len(log_batch) if log_batch else 0
violations = []
config = self.sla_configs.get(service)
if config:
if avg_latency > config.threshold_avg_ms:
violations.append(f"Avg latency {avg_latency:.2f}ms > {config.threshold_avg_ms}ms")
if p99_latency > config.threshold_p99_ms:
violations.append(f"P99 latency {p99_latency:.2f}ms > {config.threshold_p99_ms}ms")
if error_rate > config.error_rate_threshold:
violations.append(f"Error rate {error_rate:.4f} > {config.error_rate_threshold}")
status = "healthy"
if len(violations) >= 2 or any("critical" in v.lower() for v in violations):
status = "down"
elif violations:
status = "degraded"
return SLAMetrics(
service_name=service,
avg_latency_ms=avg_latency,
p99_latency_ms=p99_latency,
error_rate=error_rate,
requests_count=len(log_batch),
violations=violations,
status=status
)
def generate_sla_report(self) -> str:
"""Generate SLA report tổng hợp"""
report_lines = [
f"# SOC SLA Report - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
"",
"## Service Health Summary",
""
]
for service, metrics in self.current_metrics.items():
icon = "🟢" if metrics.status == "healthy" else ("🟡" if metrics.status == "degraded" else "🔴")
report_lines.append(f"{icon} **{service}**: {metrics.status.upper()}")
report_lines.append(f" - Avg: {metrics.avg_latency_ms:.2f}ms | P99: {metrics.p99_latency_ms:.2f}ms")
report_lines.append(f" - Error Rate: {metrics.error_rate:.4f} | Requests: {metrics.requests_count}")
if metrics.violations:
report_lines.append(f" - ⚠️ Violations:")
for v in metrics.violations:
report_lines.append(f" - {v}")
report_lines.append("")
return "\n".join(report_lines)
Khởi tạo Prometheus metrics server
if __name__ == "__main__":
# Start Prometheus server on port 9090
start_http_server(9090)
print("[INFO] Prometheus metrics server started on :9090")
# Initialize monitor
monitor = SOCSLAMonitor()
# Sample log processing
sample_logs = [
{"service": "auth-service", "latency_ms": 150, "status_code": 200, "timestamp": "2026-05-23T01:51:00Z"},
{"service": "auth-service", "latency_ms": 250, "status_code": 200, "timestamp": "2026-05-23T01:51:01Z"},
{"service": "api-gateway", "latency_ms": 800, "status_code": 500, "timestamp": "2026-05-23T01:51:02Z"},
]
for log in sample_logs:
result = monitor.process_log_entry(log)
if result:
print(f"[ALERT] SLA Violation: {result}")
# Calculate metrics
metrics = monitor.calculate_sla_metrics("auth-service", sample_logs[:2])
print(f"[METRIC] {metrics.service_name}: status={metrics.status}, violations={metrics.violations}")
Full SOC Pipeline - Tích hợp đầy đủ
"""
HolySheep SOC Assistant - Full Pipeline Integration
Kết hợp DeepSeek + Claude + Gemini cho cloud security operations
"""
import os
import json
import asyncio
import httpx
from typing import List, Dict, Optional
from datetime import datetime
from queue import Queue
import threading
class HolySheepSOCAssistant:
"""
SOC Assistant hoàn chỉnh sử dụng HolySheep AI
- DeepSeek V3.2 ($0.42/M): Log clustering, pattern detection
- Claude Sonnet 4.5 ($15/M): Attack chain analysis, threat hunting
- Gemini 2.5 Flash ($2.50/M): Real-time alerts, SLA monitoring
"""
def __init__(self, api_key: str = None):
self.api_key = api_key or os.getenv("HOLYSHEEP_API_KEY")
self.base_url = "https://api.holysheep.ai/v1"
# Initialize components
self.deepseek = DeepSeekClient(self.api_key, self.base_url)
self.claude = ClaudeClient(self.api_key, self.base_url)
self.gemini = GeminiClient(self.api_key, self.base_url)
# Event queue
self.event_queue = Queue(maxsize=10000)
self.alert_history: List[Dict] = []
# Cost tracking
self.total_cost = 0.0
self.tokens_used = {"deepseek": 0, "claude": 0, "gemini": 0}
def _track_cost(self, model: str, tokens: int, price_per_m: float):
"""Track chi phí API usage"""
cost = (tokens / 1_000_000) * price_per_m
self.total_cost += cost
self.tokens_used[model] += tokens
print(f"[COST] {model.upper()}: +{tokens} tokens, +${cost:.4f}")
async def process_security_event(self, event: Dict) -> Dict:
"""Process một security event qua full pipeline"""
result = {
"event_id": event.get("id", "unknown"),
"timestamp": datetime.now().isoformat(),
"cluster_analysis": None,
"attack_chain": None,
"sla_impact": None,
"final_recommendation": None,
"processing_time_ms": 0
}
start_time = asyncio.get_event_loop().time()
# Step 1: Quick classification với Gemini (<50ms)
print("[STEP 1] Gemini 2.5 Flash - Event classification")
classification = await self.gemini.classify_event(event)
result["classification"] = classification
# Step 2: DeepSeek log clustering nếu cần
if classification.get("needs_clustering"):
print("[STEP 2] DeepSeek V3.2 - Log pattern clustering")
result["cluster_analysis"] = await self.deepseek.cluster_pattern(event)
# Step 3: Claude attack chain analysis cho critical events
if classification.get("severity") in ["critical", "high"]:
print("[STEP 3] Claude Sonnet 4.5 - Attack chain analysis")
result["attack_chain"] = await self.claude.analyze_attack(event)
# Step 4: SLA impact assessment
print("[STEP 4] Gemini 2.5 Flash - SLA impact assessment")
result["sla_impact"] = await self.gemini.assess_sla_impact(event)
# Step 5: Final recommendation
print("[STEP 5] Claude Sonnet 4.5 - Generate recommendation")
result["final_recommendation"] = await self.claude.generate_recommendation(result)
result["processing_time_ms"] = (asyncio.get_event_loop().time() - start_time) * 1000
return result
async def process_batch(self, events: List[Dict]) -> List[