Skip to content

Eval Lab & AI Guardrails ​

Every tool invocation, A2A task, and agent workflow step in @latticedx/plugin-dxos-ai passes through runtime governance checks (ai-governance.js) before and after interacting with an LLM or database repository. The subsystem combines a 9-rule Vietnamese PII and secret redaction pipeline, PostgreSQL-backed daily quota enforcement, structured audit logging in latticeAiAuditLogs, and the built-in Eval Lab (ai-eval-lab.js).

All governance collections (latticeAiAuditLogs, latticeAiQuotaPolicies, latticeAiQuotaUsage, latticeAiTraces) enforce tenant isolation via PostgreSQL FORCE ROW LEVEL SECURITY and reject unmediated client writes.

Eval Lab and Waterfall Trace Inspector ​

Eval Lab lets administrators benchmark the deterministic Vietnamese natural-language intent router or a configured live LLM against capability and security suites, while the trace inspector merges OpenTelemetry GenAI spans with audit records into per-traceId waterfall trees.

GET/api/dxosAi:listEvalSuites
Bearer JWTAdmin
Lists available evaluation suites with case counts and preview samples.
POST/api/dxosAi:runEvalBenchmark
Bearer JWTAdmin
Executes an evaluation suite in deterministic or llm mode and computes passRate, avgLatencyMs, and p95LatencyMs.
GET/api/dxosAi:listAgentTraces
Bearer JWTAdmin
Lists tenant-scoped agent execution traces aggregated from latticeAiTraces, OTel buffers, and latticeAiAuditLogs.
GET/api/dxosAi:getAgentTraceDetail
Bearer JWTAdmin
Returns an ordered waterfall span tree for a traceId including token totals and redacted PII counts.

Built-in Evaluation Suites (listEvalSuites) ​

Suite IDScopeSupported Modes
vietnamese-nl-agentFull Vietnamese natural-language routing suite spanning RAG, task inbox, radar, GraphRAG, workflow architect, App Builder, BI charts, memory, A2A, approvals, omnichannel notifications, public forms, and security refusals.deterministic, llm
wave1-3-capabilitiesFocused capability suite covering App Builder plan/patch/rollback, DxosBiChartBlockModel, ReAct loops and agent memory, A2A delegation, workflow publishing, multi-level approvals, and notification channel testing.deterministic, llm
security-red-teamSECURITY_RED_TEAM_CASES testing prompt injection refusal, .env/AGENT_API_KEY exfiltration, root privilege escalation, SSRF to 169.254.169.254, unauthenticated public-form credential leaks, and M-of-N self-approval bypasses.deterministic, llm
customEvaluates administrator-supplied customCases payloads (up to 200 cases per run).deterministic, llm
Parameters for POST /api/dxosAi:runEvalBenchmark
ParameterTypeDefaultDescription
suiteId
stringvietnamese-nl-agentTarget suite: vietnamese-nl-agent, wave1-3-capabilities, security-red-team, or custom.
mode
stringdeterministicEither deterministic (local parseVietnameseNaturalIntent router) or llm (live configured LLM).
modelName
string—Optional model override when executing in llm mode.
limit
integer—Caps total executed test cases between 1 and 500.
customCases
EvalCase[]—Array of up to 200 custom cases with prompt, isAdmin, portalSlug, expectedTool, expectedIntent, refused, and expectedKeywords.

Waterfall Trace Aggregation (latticeAiTraces) ​

gatherTenantSpans merges spans from latticeAiTraces, the in-process otel-exporter buffer (strictly filtering norm.organizationId === organizationId), and latticeAiAuditLogs fallback entries. Direct REST or Chart access to latticeAiTraces is rejected with DXOS_TRACES_DIRECT_CRUD_FORBIDDEN so all trace queries pass through sanitizeTraceAttributes and tenant RLS checks.

Vietnamese PII and Secret Redaction (9 Rules) ​

Before payloads leave to an external LLM (redactPiiForLlm), an A2A peer (redactPiiDeep), or audit log storage, ai-governance.js runs three layers of scrubbing:

  1. Key-name masking (SENSITIVE_KEY_RE): replaces values with [REDACTED] for 17 sensitive key patterns (token, secret, password, apikey, api_key, authorization, cookie, credential, jwt, bearer, privatekey, private_key, sessionid, session_id, passphrase, access_key, client_secret).
  2. Inline key-value scrubbing (SECRET_KV_RE): redacts inline key=value and key: value secret assignments inside strings to [REDACTED].
  3. Nine ordered regex rules inside redactPiiText: masks international credentials and Vietnamese personal/tax identifiers.
#Detected PatternMatching ScopeReplacement Marker
1JSON Web TokenThree-segment Base64URL string prefixed with eyJ...[REDACTED_JWT]
2Bearer TokenBearer prefix followed by an 8+ character tokenBearer [REDACTED]
3sk- API KeyPrefix sk- followed by 6 or more alphanumeric/_/- characters[REDACTED_KEY]
4Email AddressStandard <local>@<domain>.<tld> pattern[REDACTED_EMAIL]
5Bank Account / IBANKeywords stk, số tài khoản, tài khoản ngân hàng, iban followed by account digits or IBAN$1[REDACTED_BANK]
6Labeled CCCD / CMNDKeywords cccd, cmnd, căn cước công dân followed by 9 to 12 digits$1[REDACTED_CCCD]
7Unlabeled 12-Digit CCCDStandalone 12-digit identifier starting with 0 (0\d{11})[REDACTED_CCCD]
8Vietnamese Mobile Phone`(+840)prefix followed by carrier prefixes3, 5, 7, 8, 9` and 8 digits
9Vietnamese Tax ID (MST)Keywords mst, mã số thuế followed by 10 digits and optional -3 branch suffix$1[REDACTED_MST]

Token/Cost Quotas and Audit Logging ​

Every tool or model call executes checkAndConsumeAiQuotaPersistent prior to dispatch. On PostgreSQL, the check runs inside withTenantRlsContext using SELECT ... FOR UPDATE against latticeAiQuotaUsage to enforce four daily thresholds (keyed by UTC YYYY-MM-DD). Exceeding any threshold returns HTTP 429 (AI_QUOTA_EXCEEDED).

GET/api/dxosAi:quotaSummary
Bearer JWTAdmin
Returns active daily quota limits, current day usage metrics, and all-time audit totals.
POST/api/dxosAi:saveQuotaPolicy
Bearer JWTAdmin
Persists per-organization daily call, token, and USD cost limits in latticeAiQuotaPolicies.
GET/api/dxosAi:auditLogs
Bearer JWTAdmin
Queries paginated latticeAiAuditLogs records filtered by channel, status, toolName, aiEmployee, or search term q.

Default Daily Quotas and Model Pricing ​

Environment Variables for Daily AI Quotas and Pricing
ParameterTypeDefaultDescription
DXOS_AI_DAILY_ORG_CALL_LIMIT
integer5000Daily organization-wide AI invocation limit (orgDailyCalls).
DXOS_AI_DAILY_USER_CALL_LIMIT
integer500Daily per-user AI invocation limit (userDailyCalls).
DXOS_AI_DAILY_ORG_TOKEN_LIMIT
bigInt5000000Daily organization total token ceiling (orgDailyTokens).
DXOS_AI_DAILY_ORG_USD_LIMIT
double50Daily organization estimated cost ceiling in USD (orgDailyUsd).
DXOS_AI_USD_PER_1M_INPUT / OUTPUT
number—Overrides built-in per-1M token input and output pricing.

Built-in MODEL_PRICING_USD_PER_1M rates (USD per 1 million tokens) used to compute estimatedCostUsd when environment overrides are unset:

Model FamilyInput ($ / 1M tokens)Output ($ / 1M tokens)
ag/gemini-3.8-flash, gemini-2.5-flash, gpt-4o-mini0.150.60
gemini-2.0-flash0.100.40
gemini-2.5-pro1.2510.00
gpt-4o2.5010.00
claude-sonnet-4, claude-3-5-sonnet, claude-sonnet3.0015.00
ollama / local/*0.000.00
combo (fallback pricing)0.351.05

latticeAiAuditLogs Record Schema ​

All tool executions across chat, workflows, MCP Gateway, A2A Gateway, and Eval Lab emit an audit entry in latticeAiAuditLogs. Key columns include actorUserId, actorUsername, organizationId, channel, aiEmployee, toolName, argsSummary (scrubbed via sanitizeAuditSummary), status (allowed | degraded | denied | error), durationMs, promptTokens, completionTokens, totalTokens, tokenSource (provider | estimated), estimatedCostUsd, piiRedactedCount, errorCode, and resultSummary.

bash
curl -s -X POST https://lattice.example.com/api/dxosAi:runEvalBenchmark \
  -H "Authorization: Bearer $ADMIN_JWT" \
  -H "Content-Type: application/json" \
  -d '{
    "suiteId": "security-red-team",
    "mode": "deterministic"
  }'

Apache-2.0 · LatticeDX v0.4.2 · Powered by NocoBase · v2.2.50 · Apache-2.0 (Clause 5.2)