

Topic: Water Sector Cyberattacks Reportedly Hit at Least 12 States Context: As cyberattacks target water treatment facilities across multiple states, organizations must transition from reactive to proactive security. This guide demonstrates how to build an AI-Powered Threat Intelligence Monitor that parses news feeds, identifies critical infrastructure threats, and alerts security teams.
Before building the intelligence pipeline, ensure you have the following:
python-dotenv (for managing secrets).axios (for JS HTTP requests).Run these commands in your terminal to prepare your environment.
# Create a virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install openai newsapi-python python-dotenv requests
# Initialize project
npm init -y
# Install dependencies
npm install openai axios dotenv
We will build a system that fetches news about "Water Sector Cyberattacks" and uses LLMs to categorize the severity of the threat.
import os
from newsapi import NewsApiClient
from openai import OpenAI
from dotenv import load_dotenv
# Load environment variables from.env file
load_dotenv()
class ThreatIntelligenceEngine:
def __init__(self):
# Initialize clients
self.newsapi = NewsApiClient(api_key=os.getenv("NEWS_API_KEY"))
self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
def fetch_critical_infrastructure_news(self, query: str):
"""Fetches recent news articles related to the query."""
try:
articles = self.newsapi.get_everything(
q=query,
language='en',
sort_by='publishedAt',
page_size=5
)
return articles.get('articles', [])
except Exception as e:
print(f"Error fetching news: {e}")
return []
def analyze_threat_severity(self, article_content: str) -> dict:
"""Uses AI to classify the severity of the reported cyberattack."""
prompt = f"""
Analyze the following news snippet regarding critical infrastructure.
Determine the 'Severity Level' (Low, Medium, High, Critical) and
extract the 'Target Sector' (e.g., Water, Power, Healthcare).
Text: {article_content}
Return ONLY a JSON object:
{{"severity": "string", "target": "string", "reasoning": "string"}}
"""
try:
response = self.client.chat.completions.create(
model="gpt-3.5-turbo-0125", # or gpt-4
messages=[{"role": "user", "content": prompt}],
response_format={ "type": "json_object" }
)
return response.choices[0].message.content
except Exception as e:
return f"AI Analysis Error: {str(e)}"
def run_pipeline(self, query: str):
print(f"--- Starting Intelligence Scan for: {query} ---")
articles = self.fetch_critical_infrastructure_news(query)
for art in articles:
print(f"\n[NEWS]: {art['title']}")
analysis = self.analyze_threat_severity(art['description'])
print(f"[AI ANALYSIS]: {analysis}")
if __name__ == "__main__":
engine = ThreatIntelligenceEngine()
# Target specifically the water sector attacks mentioned in the report
engine.run_pipeline("water sector cyberattack states")
import 'dotenv/config';
import axios from 'axios';
import OpenAI from 'openai';
class ThreatMonitor {
constructor() {
this.openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
this.newsApiKey = process.env.NEWS_API_KEY;
}
async fetchNews(query) {
try {
const response = await axios.get(`https://newsapi.org/v2/everything?q=${query}&language=en&sortBy=publishedAt&apiKey=${this.newsApiKey}`);
return response.data.articles;
} catch (error) {
console.error("Error fetching news:", error.message);
return [];
}
}
async analyzeArticle(text) {
try {
const response = await this.openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [
{
role: "system",
content: "You are a cybersecurity analyst. Respond only in JSON."
},
{
role: "user",
content: `Analyze this threat: ${text}. Return JSON: {severity: 'Low|Medium|High|Critical', sector: 'tring'}`
}
],
response_format: { type: "json_object" }
});
return JSON.parse(response.choices[0].message.content);
} catch (error) {
return { error: "Analysis failed", details: error.message };
}
}
async startMonitoring(query) {
console.log(`Monitoring: ${query}...`);
const articles = await this.fetchNews(query);
for (const article of articles.slice(0, 3)) {
const analysis = await this.analyzeArticle(article.description || article.title);
console.log('-----------------------------------');
console.log(`TITLE: ${article.title}`);
console.log(`ANALYSIS:`, analysis);
}
}
}
const monitor = new ThreatMonitor();
monitor.startMonitoring("water sector cyberattack");
Never hardcode your API keys. Use a .env file in your root directory.
File: .env
# AI Provider
OPENAI_API_KEY=sk-your-actual-openai-key-here
# News Provider
NEWS_API_KEY=your-news-api-key-here
# System Settings
ENVIRONMENT=development
LOG_LEVEL=info
When building production-grade AI security tools, developers typically use these patterns:
| Error | Cause | Solution |
|---|---|---|
401 Unauthorized | Invalid API Key | Verify your .env file and ensure keys are active. |
Rate Limit Exceeded | Too many requests to OpenAI | Implement Exponential Backoff (retry after increasing delays). |
JSON Decode Error | AI returned non-JSON text | Use response_format={ "type": "json_object" } in OpenAI API. |
Timeout Error | Network issues or large payloads | Increase the timeout setting in Axios or the Requests library. |
Before deploying this intelligence system to a production environment:
.env is added to your .gitignore to prevent leaking keys.Zod (TypeScript) or Pydantic (Python) to validate the JSON schema returned by the AI.Source: Security Week AI
Follow ICARAX for more AI insights and tutorials.
