บทนำ: ทำไม Compliance ถึงสำคัญในยุค GenAI

ในปี 2025 องค์กรที่ใช้ Large Language Models (LLM) ต้องเผชิญกับความท้าทายด้านกฎหมายที่ซับซ้อนมากขึ้น ทั้ง GDPR ในยุโรปและ CCPA ในแคลิฟอร์เนียได้วางกรอบกฎหมายที่เข้มงวดสำหรับการประมวลผลข้อมูลส่วนบุคคล บทความนี้จะอธิบายวิธีการสร้างระบบ AI ที่ปฏิบัติตามข้อกำหนดเหล่านี้อย่างเคร่งครัด โดยใช้ HolySheep AI เป็นโครงสร้างพื้นฐาน

หลักการพื้นฐานของ GDPR และ CCPA สำหรับ AI Systems

GDPR: สิทธิของเจ้าของข้อมูล

GDPR (General Data Protection Regulation) กำหนดสิทธิ์สำคัญสำหรับเจ้าของข้อมูลในยุโรป ซึ่งรวมถึง:

CCPA: สิทธิ์ความเป็นส่วนตัวของผู้บริโภค

California Consumer Privacy Act มีข้อกำหนดสำคัญ:

สถาปัตยกรรมระบบ Compliant AI Pipeline

1. Data Anonymization Layer

ก่อนส่งข้อมูลไปยัง LLM ต้องผ่านชั้น anonymization ที่มีประสิทธิภาพ:
"""
Compliant AI Data Pipeline with PII Redaction
สถาปัตยกรรม: Data → Anonymizer → Validator → LLM → Response
"""
import re
import hashlib
from dataclasses import dataclass, field
from typing import Optional, List, Dict, Any
from enum import Enum
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class ComplianceLevel(Enum):
    GDPR_STRICT = "gdpr_strict"
    CCPA_COMPLIANT = "ccpa_compliant"
    HIPAA_COMPLIANT = "hipaa_compliant"

@dataclass
class PIIPattern:
    """รูปแบบข้อมูล PII ที่ต้องตรวจจับ"""
    name: str
    pattern: re.Pattern
    category: str
    gdpr_sensitive: bool = True

class PIIRedactor:
    """
    ชั้น Anonymization สำหรับ LLM Input
    รองรับ GDPR Article 17 - Right to Erasure
    """
    
    PII_PATTERNS = [
        PIIPattern(
            name="email",
            pattern=re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'),
            category="contact",
            gdpr_sensitive=True
        ),
        PIIPattern(
            name="phone",
            pattern=re.compile(r'\b(?:\+?1[-.\s]?)?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}\b'),
            category="contact",
            gdpr_sensitive=True
        ),
        PIIPattern(
            name="ssn",
            pattern=re.compile(r'\b\d{3}[-\s]?\d{2}[-\s]?\d{4}\b'),
            category="government_id",
            gdpr_sensitive=True
        ),
        PIIPattern(
            name="credit_card",
            pattern=re.compile(r'\b(?:\d{4}[-\s]?){3}\d{4}\b'),
            category="financial",
            gdpr_sensitive=True
        ),
        PIIPattern(
            name="ip_address",
            pattern=re.compile(r'\b(?:\d{1,3}\.){3}\d{1,3}\b'),
            category="digital_identifier",
            gdpr_sensitive=False
        ),
        PIIPattern(
            name="thai_id",
            pattern=re.compile(r'\b[0-9]{13}\b'),
            category="government_id",
            gdpr_sensitive=True
        ),
    ]
    
    def __init__(self, compliance_level: ComplianceLevel = ComplianceLevel.GDPR_STRICT):
        self.compliance_level = compliance_level
        self.redaction_map: Dict[str, str] = {}
        self.audit_log: List[Dict[str, Any]] = []
    
    def redact(self, text: str, user_id: str, session_id: str) -> str:
        """
        ทำ PII Redaction พร้อม Audit Trail
        Returns: (redacted_text, audit_id)
        """
        audit_id = hashlib.sha256(f"{user_id}{session_id}".encode()).hexdigest()[:16]
        redacted_text = text
        
        for pii_pattern in self.PII_PATTERNS:
            if self.compliance_level == ComplianceLevel.GDPR_STRICT and not pii_pattern.gdpr_sensitive:
                continue
            
            matches = pii_pattern.pattern.finditer(redacted_text)
            for match in matches:
                original_value = match.group()
                placeholder = self._generate_placeholder(pii_pattern.category, audit_id)
                self.redaction_map[f"{audit_id}:{placeholder}"] = original_value
                redacted_text = redacted_text.replace(original_value, placeholder, 1)
        
        self._log_audit(audit_id, user_id, session_id, "REDACTED")
        logger.info(f"[{audit_id}] Redacted {len(self.redaction_map)} PII fields")
        
        return redacted_text
    
    def restore(self, redacted_text: str, audit_id: str) -> str:
        """Restore original text from redacted version (for authorized access)"""
        restored_text = redacted_text
        for key, original_value in self.redaction_map.items():
            if key.startswith(audit_id):
                placeholder = key.split(":")[1]
                restored_text = restored_text.replace(placeholder, original_value)
        return restored_text
    
    def _generate_placeholder(self, category: str, audit_id: str) -> str:
        """สร้าง Placeholder ที่สามารถ Reverse ได้"""
        return f"[{category.upper()}_{audit_id}]"
    
    def _log_audit(self, audit_id: str, user_id: str, session_id: str, action: str):
        """บันทึก Audit Log ตามข้อกำหนด GDPR Article 30"""
        self.audit_log.append({
            "audit_id": audit_id,
            "user_id": hashlib.sha256(user_id.encode()).hexdigest(),
            "session_id": session_id,
            "action": action,
            "compliance_level": self.compliance_level.value,
            "timestamp": "2025-01-15T10:30:00Z"
        })


class ConsentManager:
    """
    จัดการ Consent ตาม GDPR Article 7
    Consent ต้อง: ให้อย่างอิสระ, ชัดเจน, ถอนได้ง่าย
    """
    
    def __init__(self):
        self.consent_store: Dict[str, Dict[str, bool]] = {}
        self.consent_audit: List[Dict] = []
    
    def grant_consent(
        self, 
        user_id: str, 
        consent_type: str,
        purpose: str,
        data_categories: List[str]
    ) -> str:
        """บันทึก Consent พร้อม Proof"""
        consent_id = hashlib.sha256(
            f"{user_id}{consent_type}".encode()
        ).hexdigest()[:16]
        
        self.consent_store[user_id] = self.consent_store.get(user_id, {})
        self.consent_store[user_id][consent_type] = True
        
        self.consent_audit.append({
            "consent_id": consent_id,
            "user_id": hashlib.sha256(user_id.encode()).hexdigest(),
            "consent_type": consent_type,
            "purpose": purpose,
            "data_categories": data_categories,
            "granted_at": "2025-01-15T10:30:00Z",
            "status": "ACTIVE"
        })
        
        logger.info(f"[{consent_id}] Consent granted for {purpose}")
        return consent_id
    
    def revoke_consent(self, user_id: str, consent_type: str) -> bool:
        """GDPR Article 7(3): สิทธิ์ในการถอน Consent"""
        if user_id in self.consent_store:
            self.consent_store[user_id][consent_type] = False
            logger.warning(f"Consent revoked for user {user_id[:8]}...")
            return True
        return False
    
    def check_consent(self, user_id: str, consent_type: str) -> bool:
        """ตรวจสอบสถานะ Consent ก่อนประมวลผล"""
        return self.consent_store.get(user_id, {}).get(consent_type, False)


ทดสอบการทำงาน

if __name__ == "__main__": redactor = PIIRedactor(ComplianceLevel.GDPR_STRICT) consent_mgr = ConsentManager() # ทดสอบ PII Redaction test_text = """ สวัสดีครับ ผมชื่อ สมชาย ใช้ email: [email protected] โทรศัพท์: 081-234-5678 เลขบัตรประชาชน: 1234567890123 ต้องการสอบถามเกี่ยวกับบริการ """ redacted = redactor.redact( test_text, user_id="user_12345", session_id="session_abc" ) print("Original Text:") print(test_text) print("\nRedacted Text:") print(redacted) # ทดสอบ Consent Management consent_mgr.grant_consent( user_id="user_12345", consent_type="ai_processing", purpose="customer_service", data_categories=["name", "contact"] ) has_consent = consent_mgr.check_consent("user_12345", "ai_processing") print(f"\nUser has consent: {has_consent}")

2. Compliant LLM Integration กับ HolySheep

"""
Compliant LLM Integration สำหรับ Enterprise
ใช้ HolySheep AI API รองรับ GDPR/CCPA
ราคาประหยัด: DeepSeek V3.2 $0.42/MTok (ประหยัด 85%+)
"""
import requests
import json
import time
from typing import Dict, List, Optional, Any, Generator
from dataclasses import dataclass
from datetime import datetime
import logging
from concurrent.futures import ThreadPoolExecutor, as_completed
import hashlib

logger = logging.getLogger(__name__)

@dataclass
class LLMRequest:
    """Structured Request สำหรับ LLM"""
    model: str
    messages: List[Dict[str, str]]
    temperature: float = 0.7
    max_tokens: int = 2048
    user_id: str = ""
    session_id: str = ""
    purpose: str = ""
    consent_id: Optional[str] = None
    retention_policy: str = "30_days"

@dataclass
class LLMResponse:
    """Structured Response พร้อม Metadata สำหรับ Compliance"""
    content: str
    model: str
    usage: Dict[str, int]
    latency_ms: float
    compliance_metadata: Dict[str, Any]
    audit_id: str

class HolySheepCompliantClient:
    """
    HolySheep AI Client ที่ออกแบบมาสำหรับ Enterprise Compliance
    
    ฟีเจอร์:
    - PII Redaction อัตโนมัติ
    - Consent Verification
    - Audit Trail ตามข้อกำหนด GDPR Article 30
    - Data Retention Policy
    - Response Sanitization
    """
    
    BASE_URL = "https://api.holysheep.ai/v1"
    
    # Model Pricing (2026/MTok) - ประหยัด 85%+
    MODEL_PRICING = {
        "gpt-4.1": {"input": 8.0, "output": 8.0},
        "claude-sonnet-4.5": {"input": 15.0, "output": 15.0},
        "gemini-2.5