⚖️ Navigating the World's First Comprehensive AI Law: Engineering Compliance for the EU AI Act
The EU AI Act establishes a legally binding, risk-based regulatory framework for artificial intelligence systems deployed within or affecting the European Union. Unlike voluntary ethical guidelines, non-compliance carries severe financial penalties reaching up to €35 million or 7% of global annual turnover. Engineering teams must systematically classify their AI models into statutory risk tiers—ranging from prohibited practices and high-risk applications (e.g., critical infrastructure, biometric identification, credit scoring, HR recruitment) to generative AI transparency obligations—and embed technical safeguards, data governance, and automated audit logging directly into their MLOps deployment pipelines.
from enum import Enum
from pydantic import BaseModel, Field
class RiskTier(str, Enum):
UNACCEPTABLE = "Unacceptable Risk (Prohibited)"
HIGH = "High Risk (Strict Conformity Required)"
TRANSPARENCY = "Specific Transparency Risk (Labeling Required)"
MINIMAL = "Minimal / No Risk"
class ModelMetadata(BaseModel):
model_name: str
domain: str = Field(description="e.g., HR, Healthcare, Finance, Entertainment")
is_biometric_categorization: bool = False
is_critical_infrastructure: bool = False
is_generative_synthetic_media: bool = False
def classify_eu_ai_risk(metadata: ModelMetadata) -> RiskTier:
if metadata.is_biometric_categorization or metadata.domain.lower() == "social_scoring":
return RiskTier.UNACCEPTABLE
if metadata.is_critical_infrastructure or metadata.domain.lower() in ["hr_recruitment", "credit_scoring", "healthcare"]:
return RiskTier.HIGH
if metadata.is_generative_synthetic_media:
return RiskTier.TRANSPARENCY
return RiskTier.MINIMAL
# Test classification
meta = ModelMetadata(model_name="CandidateRanker-v2", domain="hr_recruitment", is_critical_infrastructure=False)
print(f"Assigned EU AI Act Tier: {classify_eu_ai_risk(meta)}")
import json
from datetime import datetime
def generate_annex_iv_dossier(model_name: str, accuracy: float, dataset_hash: str) -> str:
dossier = {
"regulatory_framework": "EU AI Act - Annex IV Technical Documentation",
"system_name": model_name,
"timestamp": datetime.utcnow().isoformat(),
"intended_purpose": "Automated candidate assessment in HR recruitment.",
"metrics": {
"test_accuracy": accuracy,
"fairness_demographic_parity": 0.98
},
"data_governance": {
"training_dataset_sha256": dataset_hash,
"copyright_compliance": "Opt-outs verified via robots.txt parser"
}
}
filename = f"{model_name}_Annex_IV_Dossier.json"
with open(filename, "w") as f:
json.dump(dossier, f, indent=4)
print(f"[✔] Generated regulatory compliance dossier: {filename}")
return filename
def enforce_eu_transparency_label(response_text: str, is_ai_generated: bool = True) -> dict:
"""
Appends mandatory machine-readable metadata and human-readable notices
complying with EU AI Act Article 52 transparency mandates.
"""
payload = {
"content": response_text,
"regulatory_notice": "Generated by artificial intelligence in accordance with EU AI Act Article 52." if is_ai_generated else "Human generated.",
"machine_readable_tag": "urn:eu:europa:reg:ai-act:art52:synthetic-content"
}
return payload
import numpy as np
def calculate_demographic_parity(predictions: np.ndarray, protected_group: np.ndarray) -> float:
"""
Computes ratio of positive outcomes between protected demographic group
and baseline population to ensure compliance with anti-discrimination mandates.
"""
privileged_positive = np.mean(predictions[protected_group == 1])
unprivileged_positive = np.mean(predictions[protected_group == 0])
parity_ratio = unprivileged_positive / (privileged_positive + 1e-8)
print(f"[Audit] Demographic Parity Ratio: {parity_ratio:.3f}")
return float(parity_ratio)
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class HighRiskDecisionRequest(BaseModel):
applicant_id: str
ai_risk_score: float
@app.post("/v1/high-risk/evaluate")
def evaluate_high_risk_decision(req: HighRiskDecisionRequest):
if req.ai_risk_score > 0.75:
# EU AI Act Article 14: High-risk decisions must include human oversight pause
return {
"status": "PENDING_HUMAN_OVERSIGHT",
"message": "Automated decision flagged for mandatory human compliance review."
}
return {"status": "APPROVED", "message": "Automated approval granted."}
def measure_model_robustness(model, test_features, perturbation_sigma: float = 0.05) -> float:
"""
Measures prediction stability when input features are perturbed with Gaussian noise.
"""
baseline_preds = model.predict(test_features)
noisy_features = test_features + np.random.normal(0, perturbation_sigma, test_features.shape)
perturbed_preds = model.predict(noisy_features)
stability_score = np.mean(baseline_preds == perturbed_preds)
print(f"[Robustness] Prediction Stability Score: {stability_score * 100:.2f}%")
return float(stability_score)
import logging
reg_logger = logging.getLogger("EUComplianceAuditor")
reg_logger.setLevel(logging.ERROR)
def log_regulatory_incident(system_id: str, incident_description: str):
reg_logger.error(
f"REGULATORY_INCIDENT | SystemID: {system_id} | Timestamp: {datetime.utcnow().isoformat()} | Details: {incident_description}"
)
# Configures AWS S3 bucket with Object Lock in Compliance mode
# ensuring regulatory audit logs cannot be deleted or modified for statutory retention periods (e.g. 10 years).
# Automatically creates ServiceNow compliance review ticket when a high-risk model is promoted to staging,
# blocking production deployment until legal sign-off is logged in the MLOps metadata store.
name: EU AI Act CI/CD Compliance Gate
on: [pull_request]
jobs:
compliance-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run Fairness & Risk Validation
run: python3 scripts/verify_eu_compliance.py --max_bias_ratio 0.80