Production AI Agent Ops
SQL-First LangGraph State Machine with Pre-LLM PDPA PII Redaction, FOR UPDATE HITL Approval Gates, Idempotency + Retry/DLQ, n8n Integration, and 62.78% LLM Cost Reduction.
Built for operations and customer service teams automating sensitive workflows such as refunds, escalations, and account requests. Typical AI agents are risky in production because they can expose customer personal data to external AI APIs, trigger duplicate actions, or overuse expensive models on simple tasks. This system masks sensitive data before any AI call, pauses high-risk actions for human sign-off, and routes routine work to lightweight models so teams stay compliant and cost-efficient.
Problem Solved
Naive AI agents fail in enterprise operations because they leak customer PII to external LLM APIs, execute duplicate refunds when webhooks fire twice, fail silently on transient downstream errors, and send every trivial classification task to expensive frontier models.
Architecture & Engineering Decisions
1. SQL-First LangGraph Explicit State Machine
- Executes through deterministic states (
RECEIVED -> PII_REDACTED -> INTENT_ROUTED -> CONTEXT_FETCHED -> DRAFT_GENERATED -> AWAITING_APPROVAL / EXECUTING_ACTION -> COMPLETED / FAILED_RETRYING / DLQ). - Instead of an opaque checkpointer, every state transition is persisted 1:1 into PostgreSQL 16 (
agent_runsandagent_state_transitions) with actor, model used, routing tier, token counts, cost (USD), and latency (ms).
2. Pre-LLM & Pre-DB PDPA PII Redaction (0.00 Leak Rate)
- Intercepts incoming Thai, English, and Code-Mixed requests at the API boundary and masks Thai National IDs, Thai mobile numbers, emails, bank account numbers, and personal names before calling Gemini or writing to PostgreSQL.
- The database stores only
redacted_inputandredaction_summary, while the live UI shows a real-time PII Redaction Diff Viewer.
3. Human-in-the-Loop (HITL) Gate, Idempotency & DLQ Replay
- HITL Approval Gate: High-impact actions (refunds, credits, cancellations) or low-confidence drafts pause at
AWAITING_APPROVALwith a structuredaction_preview. Human approval/rejection acquires a PostgreSQLFOR UPDATErow lock to prevent concurrent race conditions. - Idempotency-Key: Enforced via PostgreSQL unique constraints (
INSERT ... ON CONFLICT (idempotency_key)) + payload hash validation, returningX-Idempotency-Replayed: trueon duplicate webhook deliveries. - Retry + Dead-Letter Queue (DLQ): Transient execution errors retry with exponential backoff + jitter; exhausted jobs move to
dead_letter_jobsand can be safely replayed underFOR UPDATElocking viaPOST /api/v1/dlq/{job_id}/replay.
4. Tiered Model Routing (62.78% Cost Reduction) & n8n Integration
- Low-complexity classification and drafting route to
gemini-3.5-flash-lite(FAST), reservinggemini-3.8-flash(COMPLEX) for high-risk or multi-step reasoning, withgemini-3.1-flash-lite429fallback and deterministic offline fallback. - Includes exportable
n8n/workflow JSONs secured byX-Webhook-Secret,AUTH_MODE=token|demo_sandbox, and Same-Origin Next.js proxy routing (/api/proxy/agent/*) with 10x5s cold-start polling.
Verified Benchmarks (eval/run_benchmark.py)
- 24 Synthetic TH/EN Operations Cases (
16 FAST/8 COMPLEX,32PII entities): - PDPA PII Leak Rate:
0.00(32/32redacted pre-LLM & pre-DB). - HITL Policy Enforcement:
1.00(100%high-impact actions gated). - Intent & Routing Accuracy:
100.00%. - LLM Cost Reduction:
62.78%($0.1211tiered vs$0.3254always-frontier per 1,000 runs). - Automated Tests:
40 / 40 pytestpassed (31 unit + 7 live PG16 integration + 2 eval gates) + green GitHub Actions CI (backend-ci+frontend-ci).