Skip to main content

PromptVeil — API Reference

Reference for the public API of PromptVeil 0.3.0. For setup and walkthroughs, see the Quickstart.

PromptVeil is alpha software, so this API may change between releases. Anything not listed here, including PolicyEngine, promptveil.actions, and names starting with an underscore, is internal.

Import fromNames
promptveilShield, ScanResult, EntityResult, PseudonymVault, PromptVeilError, SensitiveDataError, ConfigurationError
promptveil.policyAction, Rule, PolicyConfig
promptveil.configload_config
promptveil.profilesload_profile, available_profiles, Profile
promptveil.detectorBaseDetector, DetectedEntity, RegexDetector, IndiaDetector
promptveil.detector.us_detectorUSDetector
promptveil.loggerAuditLogger
promptveil.adapterswrap_openai, get_langchain_callback
promptveil.middlewarePromptVeilMiddleware

Shield​

Shield(config_path=None, config=None, detectors=None, logger=None)

Runs detection, policy evaluation, masking, and audit logging.

ParamTypeDescription
config_pathstr | PathPath to a YAML policy file. See YAML policy files
configPolicyConfigPre-built policy, used instead of a YAML file
detectorslist[BaseDetector]Detectors to run, in order
loggerAuditLoggerAudit logger. Default: JSON lines to stdout

Provide exactly one of config_path or config. Anything else raises ConfigurationError, as does a missing or invalid YAML file.

Detectors are chosen in this order: the detectors argument, then the detectors of the YAML file's profile:, then [RegexDetector()].

scan​

shield.scan(prompt: str) -> str

Returns prompt with mask entities redacted. The original string is returned when nothing needs masking.

Raises: SensitiveDataError if any detected entity resolves to block. TypeError if prompt is not a str.

Block rules are checked against every match before any masking happens. If mask spans overlap, the longer span wins. On a tie, the span that starts first wins, then the detector registered first.

scan_response​

shield.scan_response(response: str) -> str

Same as scan, for LLM output. It can raise SensitiveDataError too.

scan_detailed​

shield.scan_detailed(prompt: str) -> ScanResult

Same policy behavior as scan, including raising on block, but returns a ScanResult with per-entity detail and a risk score.

scan_with_vault​

shield.scan_with_vault(
prompt: str,
vault: PseudonymVault | None = None,
) -> tuple[str, PseudonymVault]

Replaces mask entities with reversible tokens such as <EMAIL_1> instead of masked values. Entities that resolve to block still raise SensitiveDataError, and allow entities are left as they are. Pass the same vault on each turn of a conversation to keep tokens consistent. A new vault is created when vault is None.

safe, vault = shield.scan_with_vault("Email john@acme.com")
# safe → "Email <EMAIL_1>"

reply = call_llm(safe)
print(vault.restore(reply))

add_detector​

shield.add_detector(detector: BaseDetector) -> None

Appends a detector to the end of the list this Shield is using.

Warning: That list isn't copied. For a Shield built from a YAML profile: it's the list shared by every Shield using that profile, so the new detector applies to all of them. To add a detector to one profile-based Shield, pass your own list instead:

detectors = [*load_profile("us_hipaa").detectors, MyDetector()]
shield = Shield(config_path="policy.yaml", detectors=detectors)

Results​

ScanResult​

Frozen dataclass returned by scan_detailed.

FieldTypeDescription
safe_textstrText with masks applied
entitieslist[EntityResult]Entities and the action taken on each
risk_scorefloatComposite risk from 0.0 to 1.0, rounded to 4 places
risk_levelstrNONE, LOW, MEDIUM, HIGH, or CRITICAL
was_mutatedboolTrue if any masking was applied

entities includes allow entities. It leaves out mask entities that lost an overlap with a longer span.

risk_levelrisk_score
NONE0.0
LOWbelow 0.30
MEDIUMbelow 0.60
HIGHbelow 0.85
CRITICAL0.85 or above

The score combines every reported entity:

score = 1 - product(1 - weight × confidence × allow_factor)

allow_factor is 0.3 for allow entities and 1.0 otherwise. Weights are listed under Entity types. Any other type uses 0.35.

EntityResult​

Frozen dataclass describing one entity in a ScanResult.

FieldTypeDescription
entity_typestrFor example "email"
actionstr"mask" or "allow". A block raises, so no result is produced
startintStart index in the original prompt
endintEnd index in the original prompt (exclusive)
masked_valuestrThe masked form. For allow, this is the original value
confidencefloatDetector confidence from 0.0 to 1.0

Exceptions​

Exception
└── PromptVeilError
├── SensitiveDataError
└── ConfigurationError
ExceptionRaised when
PromptVeilErrorNever directly. Catch it to handle both errors below
SensitiveDataErrorAn entity resolves to block. entity_type holds the type. Neither the message nor the attribute contains the sensitive value
ConfigurationErrorA policy can't be loaded or is invalid, or a profile name is unknown
from promptveil import SensitiveDataError

try:
safe = shield.scan(prompt)
except SensitiveDataError as exc:
print(f"Blocked: {exc.entity_type}")

Policy​

Import these from promptveil.policy.

Action​

String enum with the values Action.MASK ("mask"), Action.BLOCK ("block"), and Action.ALLOW ("allow").

Rule​

Rule(type: str, action: Action, min_confidence: float = 0.0)
FieldDescription
typeEntity type to match. See Entity types
actionAction to take
min_confidenceMinimum detector confidence for the rule to apply

An entity below min_confidence gets the policy's default_action, not the rule's action. If a policy has more than one rule for a type, the last one wins.

PolicyConfig​

PolicyConfig(rules: list[Rule], default_action: Action = Action.ALLOW, version: str = "1.0")

default_action applies to detected entities with no matching rule. PolicyConfig and Rule don't validate their values. Only YAML files are validated, so a min_confidence outside 0.0–1.0 is accepted in code.

from promptveil import Shield
from promptveil.policy import Action, PolicyConfig, Rule

shield = Shield(
config=PolicyConfig(
rules=[
Rule(type="email", action=Action.MASK, min_confidence=0.8),
Rule(type="api_key", action=Action.BLOCK),
],
),
)

YAML policy files​

KeyRequiredDescription
versionNoSchema version string. Default: "1.0"
default_actionNomask, block, or allow. Default: the profile's value, otherwise allow
profileNoBuilt-in profile to use as the base policy
rulesNoList of rules. With profile, each one replaces that profile's rule for the same type

Each rule takes type, action, and optionally min_confidence.

profile: eu_gdpr
default_action: allow
rules:
- type: email
action: allow
- type: phone
action: mask
min_confidence: 0.8

load_config​

load_config(config_path: str | Path) -> PolicyConfig

Loads and validates a YAML policy without building a Shield. Profile rules are merged in, but the profile's detectors aren't returned, so use Shield(config_path=...) when you need them.

Raises: ConfigurationError if the file is missing, isn't valid YAML, or has invalid fields. A non-numeric min_confidence raises ValueError instead.


Compliance profiles​

Import these from promptveil.profiles.

ProfileDetectorsMasksBlocks
india_dpdpaRegexDetector, IndiaDetectorin_voter_id, in_phone, in_gstin, in_ifsc, email, phonein_aadhaar, in_pan, in_passport, credit_card, api_key
eu_gdprRegexDetectoremail, phonecredit_card, api_key
us_hipaaRegexDetector, USDetectoremail, phone, us_passport, us_einssn, credit_card, api_key

All three have a default_action of allow.

Disclaimer: Profiles are starting-point policy presets, not legal advice and not a certification of compliance with DPDPA, GDPR, HIPAA, or any other regulation. Detection is heuristic and may miss sensitive data. You remain responsible for your own compliance obligations.

load_profile​

load_profile(name: str) -> Profile

Returns a built-in profile. Raises ConfigurationError if the name is unknown.

The returned object is shared, so copy its lists before changing them:

profile = load_profile("us_hipaa")
shield = Shield(config=profile.policy, detectors=list(profile.detectors))

available_profiles​

available_profiles() -> list[str]

Returns the registered profile names, sorted.

Profile​

Dataclass with the fields name: str, policy: PolicyConfig, and detectors: list[BaseDetector].


Detectors​

Import these from promptveil.detector, except USDetector, which is in promptveil.detector.us_detector.

Built-in detectors​

DetectorEntity types
RegexDetectoremail, phone, credit_card, api_key
IndiaDetectorin_aadhaar, in_pan, in_phone, in_passport, in_voter_id, in_ifsc, in_gstin
USDetectorssn, us_passport, us_ein

All three take no arguments and report matches with a confidence of 1.0. Use IndiaDetector or USDetector alongside RegexDetector, not in place of it, unless you don't need the global types.

Entity types​

TypeExampleMasked formRisk weight
emailalice@example.coma***@example.com0.40
phone555-867-5309***-***-53090.40
credit_card4111-1111-1111-1111****-****-****-11110.90
api_keysk-abcdefghij1234567890sk-a...78900.85
in_aadhaar2345 6789 0124XXXX-XXXX-01240.90
in_panABCPE1234FAB*******F0.80
in_phone+91 98765 43210+91-***-***-32100.40
in_passportA1234567A*******0.85
in_voter_idABC1234567ABC*******0.70
in_ifscSBIN0001234SBIN0******0.50
in_gstin27ABCPE1234F1Z527*************0.60
ssn123-45-6789***-**-67890.90
us_passportA12345678A********0.80
us_ein12-345678912-*******0.65

Custom types are masked to their first and last two characters (My***et), or *** if the value has 4 characters or fewer.

DetectedEntity​

Frozen dataclass.

FieldTypeDescription
entity_typestrType label, matched against Rule.type
valuestrThe matched substring
startintStart index in the text (inclusive)
endintEnd index in the text (exclusive)
confidencefloatConfidence from 0.0 to 1.0. Default: 1.0

BaseDetector​

Abstract base class for custom detectors. Implement both members:

MemberDescription
detect(text: str) -> list[DetectedEntity]Return every match, or an empty list
supported_types -> list[str] (property)Return the type labels this detector can emit

start and end must be exact offsets, so that text[start:end] == value. Masking replaces that span rather than searching for the value.

import re

from promptveil.detector import BaseDetector, DetectedEntity


class EmployeeIdDetector(BaseDetector):
_PATTERN = re.compile(r"\bEMP-\d{6}\b")

def detect(self, text: str) -> list[DetectedEntity]:
return [
DetectedEntity("employee_id", m.group(), m.start(), m.end())
for m in self._PATTERN.finditer(text)
]

@property
def supported_types(self) -> list[str]:
return ["employee_id"]

A new type needs a matching rule. Otherwise it gets default_action.


PseudonymVault​

PseudonymVault()

Stores the mapping between tokens and original values for one session. Tokens look like <ENTITY_TYPE_N>, using the uppercased type and a per-type counter, for example <IN_PHONE_1>. A value keeps the same token for the life of the vault.

MemberDescription
restore(text) -> strReplace every known token in text with its original value
pseudonymize(text, entities) -> strReplace non-overlapping entity spans with tokens. scan_with_vault calls this for you
get_token(value) -> str | NoneReturn the token for an original value, or None
token_map (property)Copy of the {token: original_value} mapping
clear() -> NoneRemove all mappings and reset the counters
len(vault)Number of unique values stored

A vault holds raw sensitive values in memory, so treat token_map as sensitive. Use a separate vault for each user or session. restore only matches exact tokens, so a token the LLM reformats won't be restored.

Token creation and clear are guarded by a lock. restore, get_token, and token_map aren't.


AuditLogger​

AuditLogger(name: str = "promptveil.audit", stream: IO[str] | None = None)

Writes one JSON object per line to stream, or to stdout by default.

Warning: AuditLogger only attaches a handler if the named Python logger has none. stream is ignored if that name is already set up, which includes the default name once any Shield has been created with the default logger. To write to a different stream, also pass a new name.

When it does attach a handler, it sets the level to INFO and turns off propagation to the root logger.

Shield calls these two methods, so override them to send events elsewhere. Both receive keyword-only metadata (below), so a custom logger must accept **metadata or the named keywords.

MethodEventLevel
log_scan_result(entity_records, prompt_length, *, scan_id, method, risk_score, risk_level)prompt_scanINFO
log_blocked(entity, *, scan_id, method, prompt_length)prompt_blockedWARNING

entity_records is a list of (entity, action, masked_value) tuples. A prompt_scan event is written only when something was masked, so scans with no findings or only allow entities produce no log line.

Metadata fields:

FieldEventsMeaning
scan_idbothRandom hex ID for one scan call
methodbothscan, scan_response, scan_detailed or scan_with_vault
risk_score, risk_levelprompt_scanSame model as ScanResult
prompt_lengthbothCharacters in the scanned text
entities[].confidence / confidencebothDetector confidence, 0.0–1.0
positionprompt_blocked (and each entity in prompt_scan)start/end in the original text

Fields a caller doesn't supply are omitted. Raw values are never logged.

{"event": "prompt_scan", "timestamp": "2026-05-03T07:34:19.800456+00:00", "prompt_length": 44, "detections": 1, "entities": [{"entity_type": "email", "action": "mask", "value_preview": "a***@example.com", "confidence": 1.0, "position": {"start": 26, "end": 43}}], "scan_id": "886a7d3fbf38460e9f2bbf221727b3e0", "method": "scan", "risk_score": 0.4, "risk_level": "MEDIUM"}
{"event": "prompt_blocked", "timestamp": "2026-05-03T07:34:19.800456+00:00", "entity_type": "api_key", "action": "block", "confidence": 1.0, "position": {"start": 5, "end": 34}, "scan_id": "0b9c1e5a7d3f4c2e8a6b1d4f9e7c3a52", "method": "scan", "prompt_length": 34}

Logs contain masked previews, or vault tokens for scan_with_vault, and never full raw values. Masked previews do keep part of the value, such as the last four digits of a card.


Integrations​

wrap_openai​

wrap_openai(
client,
shield: Shield,
vault: PseudonymVault | None = None,
scan_responses: bool = False,
)

Requires pip install "promptveil[openai]". Raises ImportError otherwise.

Patches client.chat.completions.create in place and returns the same client. Each call scans the messages before sending them, with shield.scan, or with shield.scan_with_vault if you pass a vault. SensitiveDataError is raised to the caller, and the request isn't sent.

from openai import OpenAI
from promptveil.adapters import wrap_openai

client = wrap_openai(OpenAI(), shield)

With scan_responses=True, the string message.content of every returned choice is also passed through shield.scan_response, for both OpenAI and AsyncOpenAI clients:

  • Mask: the content is masked in the returned response object.
  • Block: SensitiveDataError is raised. The API call has already been made.
  • Tool calls: choices whose content is None are skipped.
  • Streaming: calling with stream=True raises ConfigurationError before any request is sent, because a stream can't be scanned before it reaches you.

Audit events for replies use method: "scan_response". Vault tokens such as <EMAIL_1> aren't detected, so vault and scan_responses can be combined.

Some content isn't scanned:

  • List content: only string content is scanned. Multimodal messages, where content is a list of parts, are sent as they are.
  • Responses: without scan_responses=True, replies aren't scanned. Replies are never restored; with a vault, call vault.restore() on the reply yourself.
  • Other endpoints: only chat.completions.create is patched, so calls such as client.responses.create aren't scanned.

get_langchain_callback​

get_langchain_callback() -> type

Requires pip install "promptveil[langchain]". Raises ImportError otherwise.

Returns a callback handler class. Create it with CallbackClass(shield).

Model typemaskblock
Chat modelsMessage content is masked in placeRaises SensitiveDataError
String LLMsRaises SensitiveDataErrorRaises SensitiveDataError

In every SensitiveDataError case, the prompt isn't sent.

String LLMs raise on mask because a callback can't change the prompt LangChain sends, so the only safe option is to stop the call. To send a masked prompt, scan it first. The callback then lets it through:

from promptveil.adapters import get_langchain_callback

CallbackClass = get_langchain_callback()
callback = CallbackClass(shield)

# Chat models
chat_model.invoke(prompt, config={"callbacks": [callback]})

# String LLMs
llm.invoke(shield.scan(prompt), config={"callbacks": [callback]})

Warning: The handler sets raise_error = True because LangChain otherwise swallows callback errors and sends the prompt anyway. Don't set it to False.

When a string LLM prompt is rejected for masking, the audit log still shows a prompt_scan event with the action mask, even though the call was stopped.

The callback only reads string content, so list content isn't scanned. Responses aren't scanned either.

PromptVeilMiddleware​

app.add_middleware(PromptVeilMiddleware, shield=shield, prompt_field="prompt")

Requires pip install "promptveil[fastapi]". Importing promptveil.middleware raises ImportError otherwise.

ParamTypeDescription
shieldShieldThe configured Shield
prompt_fieldstrTop-level JSON key holding the prompt. Default: "prompt"
response_fieldstr | NoneTop-level JSON response key holding the model output. Default: None (responses aren't scanned)

For a POST request with a JSON body containing prompt_field, the middleware masks that field and passes the request on. A blocked prompt returns 400 without calling the route handler:

{
"error": "Blocked: sensitive data detected in prompt.",
"detail": "Sensitive data of type 'api_key' was detected and blocked by the active policy. Remove or redact the value before sending this prompt.",
"code": "SENSITIVE_DATA_BLOCKED"
}

All other requests pass through unscanned, including other HTTP methods, non-JSON bodies, and bodies without the field. Nested fields aren't scanned, so this won't cover an OpenAI-style messages array.

A request returns 500 if prompt_field holds a non-string value, or if the JSON body is an array that contains the field name.

When response_field is set, every response is checked after the route handler runs, whether or not the request had a prompt. If the response is 2xx, has a JSON content type, and its body is an object whose response_field is a string, that field is scanned with shield.scan_response and masked in place. A blocked reply is replaced with a 502:

{
"error": "Blocked: sensitive data detected in response.",
"detail": "Sensitive data of type 'credit_card' was detected and blocked by the active policy. ...",
"code": "SENSITIVE_DATA_BLOCKED_RESPONSE"
}

All other responses pass through unchanged, including error statuses, non-JSON responses such as text/event-stream, and JSON without a string field. A streamed response with a JSON content type is read in full before scanning.