Field guide · Safety and compliance
AI safety and compliance: from data flow to a launch gate
Many teams add “do not leak user data” to a support bot and call safety done. When something goes wrong, the problem is rarely that sentence. It is which orders the bot can read, who it can send what to, and how long the logs keep it. Draw the assets and data flow before talking about guardrails.
- Name the assets first: people, data, money, availability, reputation and legal exposure.
- Map where data enters, who touches it, where it is stored and who can still read it.
- Guardrails sit at four layers: input, output, retrieval and tools. Each layer needs a test.
The full guide starts below. Use the tables for reference; you do not need to memorise them.
Take one concrete job: a knowledge-base bot inside Feishu that can read contracts, send messages and look up customer orders. Draw the data flow first, then decide which tools are off by default.
1 · Define what to protect: people, data, money, availability, reputation, legal exposure
“AI safety” is too broad to accept. List the assets: users’ physical and psychological safety, personal and commercial data, accounts and funds, service availability, brand reputation, legal and contractual obligations. Each has different harms, exposure and evidence. Writing only “prevent harmful content” misses data exfiltration, tool overreach, account takeover and outage.
Write each asset as a testable sentence: “the support agent must not read another tenant’s orders”, “generated output must not execute a shell”, “unreviewed model output must not enter outbound email”. The more specific, the easier to design permissions, evaluation and alerts.
| Asset | Harm | Exposure | Evidence |
|---|---|---|---|
| People | Harassment, discrimination, self-harm inducement, privacy | Dialogue, recommendation, generation, avatars | Red-team samples, human review, incident log |
| Data | Personal data, trade secrets, training-data leak | Retrieval, tools, logs, caches, third parties | Data-flow map, access logs, DLP tests |
| Money / accounts | Fraud, unauthorised transactions, quota abuse | Payment tools, API keys, session takeover | Approval records, limits, reconciliation |
| Availability | Outage, runaway cost, resource exhaustion | Long context, batch calls, retry storms | Load test, rate limits, cost curve |
| Reputation | Wrong answers, brand offence, synthetic-media controversy | Publication, social media, avatars | Pre-release review, labelling, withdrawal log |
| Legal / contract | Licence, privacy, sector rules or client contract breach | Data sources, model terms, transfer, retention | Rule register, contracts, audit evidence |
2 · Draw the data flow: where data enters, who sees it, where it rests, who can still read it
Draw one map: user input → application → model/retrieval → tools/third parties → logs/caches → output. Label every arrow with data type, trust boundary, encryption, retention and owner. Without it, permissions, redaction, retention and cross-border transfer are guesswork.
A trust boundary is not just “internal / external”. Model output entering tool arguments, retrieval results entering prompts, logs entering analytics and subprocessors touching data are all boundaries. At each crossing ask again: does this data still need to be kept in full, who may read it, and for how long?
| Stage | Data | Boundary question | Record |
|---|---|---|---|
| Input | User text, files, audio, images | Personal data, secrets, minors | Purpose, notice, retention |
| Application | Session, user ID, permissions, config | Who can read, cross-tenant access | Tenant isolation, least privilege |
| Model / retrieval | Prompts, context, knowledge chunks | Over-permissioned documents, cache residue | Retrieval filtering, context clearing |
| Tools / third parties | Arguments, results, credentials, callbacks | Tool scope, egress, subprocessors | Per-tool scope, approval, audit |
| Logs / caches | Raw text, summaries, errors, metrics | Secondary retention of sensitive data | Redaction, access control, retention |
| Output | Answers, files, images, actions | Direct execution, publication, outbound | Human confirmation, citation, labelling |
3 · Threat model: enumerate by scenario, not by model quality
A threat model says who, through which entry point, wants what, under which conditions. Prompt injection, tool abuse, data exfiltration, insecure output, supply chain, resource exhaustion, overreliance and privacy inference are scenario problems, not one line about “the model not being safe enough”. A stronger model does not fix tool permissions or egress boundaries.
Pair each threat with an observable indicator, a mitigation and a way to know it failed. A mitigation without detection is an assumption; detection without an indicator drowns in alerts.
| Threat | Scenario | Indicator | Mitigation and detection |
|---|---|---|---|
| Prompt injection | Web pages, documents, email or tool results enter the prompt | Instruction-like text hits, out-of-scope tool calls | Source marking, instruction isolation, tool allowlist; log triggers |
| Tool abuse | Model can message, mutate data, pay or execute code | High-privilege calls, unusual arguments, rate | Least privilege, human confirmation, quotas; audit each call |
| Data exfiltration | Retrieval, logs, errors, third-party callbacks | Sensitive fields in output, logs or egress | Field-level redaction, egress allowlist, DLP alerts |
| Insecure output | Generated code, commands, config or HTML executed directly | Unescaped output, dangerous arguments, excess privilege | Sandbox, escaping, static checks, human review |
| Supply chain | Unknown model, plugin, dependency or dataset | Version drift, permission growth, missing provenance | Version pinning, signature checks, licence and provenance manifest |
| Resource exhaustion | Long context, batch requests, retry storms | Cost curve, queue latency, error rate | Quotas, timeouts, backoff, circuit breaker; cost alerts |
| Overreliance | Users treat output as fact or professional advice | No citations, no confirmation, correction rate | Citations, confidence cues, human confirmation, domain limits |
| Privacy inference | Model infers personal attributes from public or semi-public data | Sensitive-attribute inference, re-identification | Use limits, output filters, no-inference list |
4 · Permissions and tools: deny by default, open one scope at a time
Agent risk sits less in what it says than in what it can do. File access, messaging, database mutation, payment, code execution and intranet access each need separate authorisation, quota and audit. Deny by default, open the minimum scope per task: read-only before write, draft before send, sandbox before production.
High-risk actions need human confirmation that shows the exact arguments, impact and reversibility, not a generic “agree” button. Secrets do not enter prompts, logs or model context. Tool credentials are isolated per user, session and task, and revoked when the task ends.
Deny by default
How: Tool list off by default; request per task
Acceptance: No extra tools on a new task
Least scope
How: Read-only, one directory, one recipient, one quota
Acceptance: Out-of-scope calls rejected and logged
Human confirmation
How: Show arguments, impact and reversibility
Acceptance: Record traces to the exact action
Sandbox
How: Code, file parsing and browser in isolation
Acceptance: Cannot read host credentials or roam the network
Egress allowlist
How: Only necessary domains and protocols
Acceptance: Unknown domains blocked and alerted
Credential isolation
How: Short-lived tokens, per session, revoked after task
Acceptance: No plaintext secrets in logs or context
Quotas and breaker
How: Limit calls and spend per user, task and time
Acceptance: Automatic stop on abnormal spikes
5 · Guardrails: input, output, retrieval and tools each have limits
A guardrail is not one classifier. Input checks intent and source; retrieval filters permission and freshness; output checks schema, escaping, citations and sensitive data; tools validate arguments and scope. Each layer must state what it blocks and what it does not, or it will kill legitimate requests or leave bypasses to the next layer.
Classifiers have false positives and false negatives and cannot be the only gate. High-risk cases combine rules, human review, quotas and audit; low-risk cases must not be blocked indefinitely, or users learn to bypass. Acceptance measures block rate, false-positive rate, latency and explainable records together.
Input
Blocks: Clearly disallowed intent, oversized input, suspicious files
Does not block: Paraphrase, multi-turn inducement
Acceptance: Block rate, false positives, latency
Retrieval
Blocks: Over-permissioned documents, stale versions, unauthorised sources
Does not block: Wrong facts inside an authorised document
Acceptance: Permission hits, citation resolves to source
Output
Blocks: Sensitive fields, unescaped code, uncited claims
Does not block: Tone, metaphor, contextual misleading
Acceptance: Schema pass, DLP hits, citation rate
Tools
Blocks: Out-of-scope arguments, dangerous commands, unknown domains
Does not block: Malicious content returned by a tool
Acceptance: Rejection log, sandbox, human confirmation
6 · Evaluation and red teaming: a rerunnable set, not a one-off demo
Safety evaluation needs an item set, scorer, thresholds and rerun records. Items cover normal, boundary, adversarial, multilingual, multi-turn and tool scenarios. The scorer can be rules, humans or a model, but its agreement must be known. Thresholds separate “must block”, “may warn” and “allowed”. A few successful demos is not an evaluation.
Red teaming looks for how the system fails in the real chain, not for a pile of prompts. Record entry point, permissions, model version, tool config, expected and actual result. After a fix, rerun the same item to confirm it is not a different model happening to block it.
Item set
Write: Normal, boundary, adversarial, multi-turn, multilingual, tool
Acceptance: Minimum sample size and source per class
Scorer
Write: Rules, human or model-assisted; criteria
Acceptance: Agreement measurable, disputes adjudicable
Threshold
Write: Must block, may warn, allowed
Acceptance: Threshold tied to risk tier
Red team
Write: Entry, permissions, config, real chain
Acceptance: Findings reproducible, fixes rerunnable
Regression
Write: Rerun on every model, prompt or tool change
Acceptance: No score drop, old issues do not return
Record
Write: Version, date, samples, results, owner
Acceptance: Trace to the same item and config
7 · Monitoring, logs and incident response: detect before containing
Logs must answer who, when, which model, which tool, which data, which action and what result. But logs are also sensitive: raw text, prompts and tool arguments may contain personal or confidential data. Redact, restrict access, set retention and limit who can read them.
Incident response needs severity, containment, evidence, notification and review. First be able to disable one tool, model or tenant; then investigate. Preserve evidence before cleaning up, and write notification audiences and deadlines into the runbook. Without a kill switch and rollback, monitoring only watches the incident grow.
Log fields
Minimum: User/tenant, model version, tool, argument summary, result, latency
Acceptance: Reconstruct one full call
Redaction
Minimum: Personal data, secrets, confidential data in prompts and arguments
Acceptance: Sampled logs contain no plaintext sensitive fields
Alerting
Minimum: Scope violations, unusual egress, cost spikes, error rate
Acceptance: Threshold, owner, noise control
Containment
Minimum: Disable per tool, model or tenant
Acceptance: One action works, rollback available
Evidence
Minimum: Timeline, versions, calls, affected scope
Acceptance: Exportable, reviewable
Notification / review
Minimum: Regulator, client, user, internal
Acceptance: Audiences and deadlines in the runbook
8 · Vendors and model changes: check capability and obligation separately
A model vendor is not only a capability provider but also a data processor, subprocessor and continuity party. Check residency and transfer, logging and training use, subprocessor list, security certifications, model-version change notice, service levels, exit and data export. A good capability evaluation does not replace contract and data-processing terms.
A model upgrade changes output, cost and failure modes. On every version change, rerun the safety set, regress the business evaluation, check pricing and quotas, then decide. Do not skip the release gate because “the new model is stronger”.
Residency / transfer
Look for: Region, storage, backup, transfer path
What does not substitute: One line saying “global service”
Training use
Look for: Whether customer data trains the model, whether it can be disabled
What does not substitute: A privacy-policy summary
Subprocessors
Look for: List, change notice, responsibility chain
What does not substitute: One main contract
Security evidence
Look for: Certifications, audit reports, vulnerability response
What does not substitute: A badge on the product page
Version change
Look for: Notice period, deprecation, rollback
What does not substitute: “Automatic upgrade”
Exit / export
Look for: Export format, deadline, deletion proof
What does not substitute: A verbal promise
9 · Compliance: rules, evidence and owners in three columns, not “should be fine”
Compliance is not one universal checklist. Register applicable rules: statutes, regulator interpretations, sector norms, client contracts, platform terms and internal policy. For each, write scope, obligation, evidence, owner and review date. Different jurisdictions and sectors may apply at once; when they conflict, seek professional advice rather than concluding on this page.
Evidence must be independently reviewable: policy versions, training records, review minutes, log samples, contract clauses, test reports. “Compliant” without evidence is nothing in an audit. Rules change; when the review date arrives, check again rather than reusing one conclusion for three years.
Rule
Write: Name, clause, scope, effective date
Example: A sector privacy rule applies to support chats
Obligation
Write: Must do, must not do, must notify, must retain
Example: Keep authorisation records and support deletion
Evidence
Write: Documents, logs, tests, contracts, minutes
Example: Quarterly permission audit and samples
Owner
Write: Who maintains, signs and reviews
Example: Security owner plus business owner
Review date
Write: Next check and trigger
Example: Rule change, model upgrade, incident
10 · Release gate: risk tier, evidence list, sign-off and rollback
A release gate is not a nod from the security team. Tier the risk first: public-facing, personal data, ability to spend money, mutate data or execute code, minors, sector regulation. The tier determines evidence, signatories, rollout scope and rollback conditions.
The gate may allow a conditional launch, but conditions must be specific, checkable and time-bound: internal only, read-only, 50 manual samples daily, review in two weeks. Do not bypass with “launch first” or replace a fix with a permanent exception.
Low
Typical case: Internal draft, read-only, no personal data
Minimum evidence: Basic evaluation, usage limits
Rollout: Small scope, kill switch
Medium
Typical case: External users, limited tools, possible personal data
Minimum evidence: Safety set, permission audit, logs and rollback
Rollout: Canary, quotas, human sampling
High
Typical case: Payment, data mutation, code execution, minors, regulated
Minimum evidence: Red team, human review, contract/DPA, incident drill
Rollout: Small traffic, per-action confirmation, strong monitoring
Blocked
Typical case: Unmitigable high harm, unclear licence, no rollback
Minimum evidence: Do not ship
Rollout: Redesign or change scope
11 · Failure branches: contain first, locate second, explain last
The expensive part of a safety incident is not that something failed, but that it was detected and not stopped. Contain by tool, model, tenant or entry point first, then preserve evidence, scope impact and notify owners. Do not spend the containment window explaining that “the model does this sometimes”.
Out-of-scope tool call
First action: Disable the tool or session
Then check: Permission config, arguments, call chain
Do not: Let the agent retry
Sensitive data in output
First action: Stop output or recall the message
Then check: Retrieval permission, logs, caches
Do not: Only edit the prompt
Cost spike
First action: Quota or circuit breaker
Then check: Retries, batching, long context
Do not: Optimise the model first
Regression after model change
First action: Roll back the version
Then check: Item set, config, pricing
Do not: Accept the new version
Licence or compliance challenge
First action: Remove the data or feature
Then check: Source, terms, contract
Do not: Issue a statement before evidence
Alert flood
First action: Reduce noise, tier, assign owner
Then check: Threshold, duplicates, root cause
Do not: Turn all alerts off
12 · A minimum path: from protected asset to rollback-ready launch
This path fits an AI feature that uses tools, reads data or ships externally. Each step leaves evidence before the next begins.
- List protected assets: people, data, money, availability, reputation, legal duty; write one testable sentence each.
- Draw the data flow: input, application, model/retrieval, tools/third parties, logs/caches, output; mark trust boundaries.
- Write the threat model: who, entry, goal, conditions; pair each threat with an indicator and detection.
- Set permissions: deny by default, per-tool least scope, human confirmation, quotas, sandbox, egress allowlist.
- Build guardrails across input, retrieval, output and tools; state what is blocked, what is not, false positives and latency.
- Build evaluation: item set, scorer, thresholds, red team, regression and records.
- Connect monitoring: log fields, redaction, alerts, kill switch, rollback and incident runbook.
- Check vendors and rules: residency, training use, subprocessors, contracts, applicable rules and evidence.
- Pass the release gate: risk tier, evidence list, sign-off, canary scope, rollback conditions.
- Rerun after launch: model/prompt/tool changes, alert review, permission audit, rule review dates.
Sources and further reading
These links are for checking facts, licences and official scope. External pages may change; cite the original text and check date.
- NIST AI Risk Management FrameworkA framework for AI risk identification, governance, mapping and evidence; not a sector compliance conclusion.
- NIST AI 600-1 · Generative AI risksA lifecycle-oriented list of trust, safety and misuse risks for generative AI.
- OWASP · LLM Top 10Application-level risk categories including prompt injection, data leakage, tool abuse and supply chain.
- MITRE ATLASA matrix of attack techniques and cases against AI systems; use for threat modelling and red-team comparison.
- AI Incident DatabaseDocumented AI incidents and failures for review and scenario comparison.
- Google · Secure AI FrameworkSix principles and a risk map for secure AI system design.
- EU AI Act · Official textThe EU AI Act’s articles and obligation structure; application needs professional interpretation.
- China · Interim Measures for Generative AI ServicesThe scope, obligations and regulatory basis for generative AI services in China.
- Not what you’ve signed up for · Prompt injectionHow prompt injection conflates application and model boundaries; a reference for defensive design.
Next
If you get stuck while following it, go back to the matching route instead of rereading the whole guide.