Introduction
Healthcare AI agents routinely see Protected Health Information in prompts, tool inputs, and logs. HIPAA’s technical safeguards demand unique user identity, PHI-access auditability, integrity protections, and automatic logoff after inactivity. This lesson implements pattern-based PHI detection and redaction, a fixed fifteen-minute session manager, and a FastAPI dashboard that proves non-zero compliance metrics after a demo run.
Highlights
PHI scan and redact for SSN, MRN, DOB, clinical, and email patterns
PHI-tagged audit entries when regulated data appears in input
Session TTL fixed at 900 seconds in the production path
HIPAA 164.312 safeguard map across access, audit, integrity, and authentication
FastAPI dashboard with live counters after
/demoSelf-contained
aiam-day25on officialpython:3.12-slim(port 8125)
What We Build
PHIDetectorfor scan, redact, and type coverageHIPAASessionManagerenforcing automatic logoffHIPAAComplianceServicewith a seven-item checklistFastAPI routes:
/health,/demo,/validate,/metrics,/dashboardOperational scripts:
start.sh,stop.sh,demo.sh,run_tests.sh,cleanup.sh
Connection to Previous Lesson
Day 24 delivered immutable SOC 2 audit trails and chain-hash integrity. Day 25 specializes that layer for HIPAA: PHI touches must be tagged, idle sessions must expire, and safeguards must be demonstrable on a live dashboard.
Enables Next Lesson
Day 26 (Disaster Recovery) assumes PHI handling is already enforced. Recovery must restore agents without losing audit continuity or weakening session and encryption controls.
Architecture Context
Where this component sits: security and compliance perimeter before LLM and tool calls
Why it exists: unredacted PHI in prompts or logs fails HIPAA; idle sessions without auto-logoff fail 164.312(a)(1)
Problem solved: detectable PHI, tagged audits, enforced timeout, and dashboard evidence operators can sample
Integration
Integration Components
Agent input flows through PHIDetector, then PHI-aware audit tagging, then HIPAASessionManager. HIPAAComplianceService scores the checklist, updates MetricsStore, and the FastAPI dashboard renders live counters.
Module Objectives Alignment
Unique user_id per session, fixed 15-minute logoff, PHI tags on audits, six-plus year retention posture, non-root container, and seven checklist items passing after /demo.
Core Concepts
PHI detection is a gate, not a complete privacy program. Regex families catch high-frequency identifiers so pipelines can redact and tag before model or log sinks. Engineering value is fail-closed tagging: if PHI is present, every related audit entry must say so.
Redaction replaces matches with typed labels so downstream systems can process structure without retaining raw identifiers. It complements—not replaces—encryption and access control.
Automatic logoff implements 164.312(a)(1) with a non-configurable 900-second TTL. Demo code may subclass for short TTLs; production managers must not expose a shorter “convenient” timeout API.
Safeguard mapping ties Day 1 perimeter, Day 5 RBAC, Day 24 audit chains, and TLS/KMS into Access, Audit, Integrity, and Authentication. Auditors expect mapped controls, not orphaned features.
Production AI System Design Relevance
After deployment/scaling (Days 22–23) and SOC 2 evidence (Day 24), HIPAA readiness is the regulated-domain gate. Clinical agent platforms need PHI hygiene and session discipline before production traffic—between general compliance tooling and disaster recovery.
Workflow
Request flow:
POST /demoor/validate→ service scan corpus → session logoff proof → checklist → metrics snapshotExecution flow: scan four inputs → redact and tag PHI hits → touch session → expire short-TTL demo session → score seven checks
Data flow: metrics to
/metrics; events on dashboard; optional JSON underdata/State changes: validation counts, PHI detections/redactions, auto-logoffs, checklist score
Production Integration
Fits as an ingress library: scan and session checks before orchestration. Deploy behind TLS; store audits in WORM or KMS-backed stores; require BAAs when PHI leaves the boundary. Keep detectors CPU-cheap; sample validation rather than full-history scans. Observe via
/metrics. Security: no secrets in images, non-root runtime, fixed timeout, least-privilege tool RBAC.
Step-by-Step Implementation
GitHub Link:
https://github.com/sysdr/production-ai-engineering-p/tree/main/lesson25/aiam-day25
Container runs uvicorn as user agent. PHIDetector compiles patterns once and returns typed matches. HIPAASessionManager.touch records activity; assert_valid raises on expiry. Service runs two demo cycles so counters exceed zero. Validation fails closed if any checklist item fails. Production points audits at immutable storage and keeps timeout non-configurable.
Coding Highlights
found = PHIDetector.scan(text)
redacted = PHIDetector.redact(text)
Typed redact labels keep pipelines usable while stripping raw PHI.
SESSION_TIMEOUT_SECS = 900 # not configurable in production path
A constant timeout prevents “just extend TTL” bypasses that break 164.312(a)(1).
Production Considerations
Scale detectors with the API; avoid heavy NLP on the hot path unless required. Secure with BAAs, encryption, and MFA for admin. Monitor PHI hit rates, auto-logoffs, and checklist regressions. Log PHI types—not raw values. Test pattern coverage and expiry. Treat missing sessions as expired. Edge cases: partial MRNs, international IDs, false-positive emails.
Working Demo Link:
Validation
Verify with pytest (detector/session/API), then smoke POST /demo and assert non-zero metrics. Success: checklist 7/7, five PHI types, timeout 900s, dashboard updates. Outputs: redacted samples, auto-logoff events, VALIDATED. Demo completes in seconds with deterministic counters. Production checklist: patterns tested, PHI tagged, timeout fixed, BAAs and encryption documented.
Key Insights
Evidence beats policy PDFs. Fixed timeouts beat configurable “defaults.” Tag PHI types, never raw secrets, in metrics. Common mistakes: shipping detectors without redaction, allowing timeout overrides, and treating dashboard zeros as “healthy idle.”
Important Classes
PHIDetector, HIPAASessionManager, HIPAAComplianceService, MetricsStore
Key Methods
scan / redact, touch / assert_valid, run_demo / run_validation, snapshot
Success Criteria
All seven checklist items pass; dashboard metrics non-zero after demo; session timeout remains 900s; project runs via ./start.sh and ./demo.sh without parent scripts.
Real-World Examples
Hospital scheduling agent: Intake text containing MRN and DOB is redacted before the model call; audit entries mark
MRN/DOB; idle clinician sessions expire at 15 minutes.Payer claims assistant: Email and SSN in uploaded notes are tagged and redacted; compliance dashboard shows detection and auto-logoff counters for monthly HIPAA evidence packs.



