PromptVeil
Privacy and safety middleware for LLM applications.
PromptVeil intercepts prompts before they reach an LLM API, detects sensitive information (PII, secrets), applies configurable policies (mask · block · allow), and produces structured JSON audit logs for compliance.
Features
| Capability | Detail |
|---|---|
| PII detection | Email, phone, credit card, API keys (regex, extensible) |
| India PII | Aadhaar (Verhoeff checksum), PAN, GSTIN, IFSC, Passport, Voter ID |
| US PII | SSN (segment-validated), US Passport, EIN |
| Policy engine | YAML-driven rules: mask, block, allow; per-rule confidence thresholds |
| Masking | Type-aware redaction (domain preserved for email, last-4 for cards) |
| Blocking | Raises SensitiveDataError before the prompt is forwarded |
| Audit logging | Structured JSON lines — raw values never logged |
| Confidence scoring | Each detected entity carries a confidence float; rules can require a minimum |
| Rich scan results | scan_detailed() returns ScanResult with risk_score, risk_level, and per-entity EntityResult |
| Compliance profiles | One-line activation of india_dpdpa, eu_gdpr, or us_hipaa rule packs |
| Pseudonymization vault | scan_with_vault() replaces PII with reversible <TYPE_N> tokens; restore after LLM response |
| OpenAI adapter | wrap_openai(client, shield) patches chat.completions.create in-place |
| LangChain adapter | get_langchain_callback() returns a BaseCallbackHandler that scans prompts automatically |
| Plug-in detectors | Subclass BaseDetector to add spaCy, ML models, custom patterns |
| FastAPI middleware | Drop-in Starlette/FastAPI middleware (optional extra) |
Installation
# Core (only requires PyYAML)
pip install promptveil
# With FastAPI middleware support
pip install "promptveil[fastapi]"
# With OpenAI adapter
pip install "promptveil[openai]"
# With LangChain adapter
pip install "promptveil[langchain]"
# Everything
pip install "promptveil[fastapi,openai,langchain,dev]"
# Development (includes pytest)
pip install "promptveil[dev]"
Requires Python ≥ 3.10.
Documentation
Quick Start
from promptveil import Shield
shield = Shield(config_path="policy.yaml")
safe = shield.scan("Bill me at alice@example.com, card 4111-1111-1111-1111")
# ↑ raises SensitiveDataError — credit card is blocked by default policy
safe = shield.scan("Contact alice@example.com for the invoice.")
# → "Contact a***@example.com for the invoice."
Activate a compliance profile in one line
# policy.yaml
profile: india_dpdpa # or eu_gdpr / us_hipaa
# optional rule overrides go here under `rules:`
shield = Shield(config_path="policy.yaml") # profile detectors loaded automatically
Rich scan result with risk scoring
result = shield.scan_detailed("Call me on +91 98765 43210")
print(result.risk_score) # e.g. 0.42
print(result.risk_level) # "MEDIUM"
print(result.safe_text) # sanitised prompt
Reversible pseudonymization
from promptveil import PseudonymVault
vault = PseudonymVault()
pseudo_text, vault = shield.scan_with_vault("Email alice@example.com", vault=vault)
# pseudo_text → "Email <EMAIL_1>"
llm_response = call_llm(pseudo_text) # LLM sees tokens, not PII
final = vault.restore(llm_response) # restore originals in the reply
Drop-in OpenAI integration
import openai
from promptveil.adapters import wrap_openai
client = openai.OpenAI()
wrap_openai(client, shield=shield) # patches client in-place
# All subsequent calls are automatically scanned:
client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}],
)
Policy Configuration (policy.yaml)
version: "1.0"
default_action: allow # fallback: mask | block | allow
# Optional: activate a built-in compliance profile (india_dpdpa | eu_gdpr | us_hipaa)
# profile: eu_gdpr
rules:
- type: email
action: mask # a***@example.com
min_confidence: 0.8 # optional: only apply rule when confidence ≥ this value
- type: phone
action: mask # ***-***-5309
- type: credit_card
action: block # raises SensitiveDataError
- type: api_key
action: block # raises SensitiveDataError
Built-in entity types: email, phone, credit_card, api_key,
in_aadhaar, in_pan, in_phone, in_passport, in_voter_id, in_ifsc, in_gstin,
ssn, us_passport, us_ein.
Custom detectors can introduce any additional type labels.
Compliance Profiles
Profiles bundle a pre-configured PolicyConfig and the appropriate detectors
for a jurisdiction. Activate via the YAML profile: key or programmatically:
from promptveil.profiles import load_profile
profile = load_profile("us_hipaa") # or india_dpdpa / eu_gdpr
shield = Shield(config=profile.policy, detectors=profile.detectors)
| Profile | Detectors | Key rules |
|---|---|---|
india_dpdpa |
RegexDetector + IndiaDetector |
Aadhaar/PAN/Passport → BLOCK; phone/GSTIN/IFSC → MASK |
eu_gdpr |
RegexDetector |
email/phone → MASK; credit card/API key → BLOCK |
us_hipaa |
RegexDetector + USDetector |
SSN → BLOCK; email/phone/passport/EIN → MASK |
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.
API Reference
See the API reference for the full public API.
Programmatic Config (no YAML file)
from promptveil import Shield
from promptveil.policy.models import Action, PolicyConfig, Rule
config = PolicyConfig(
rules=[
Rule(type="email", action=Action.MASK, min_confidence=0.8),
Rule(type="api_key", action=Action.BLOCK),
],
default_action=Action.ALLOW,
)
shield = Shield(config=config)
min_confidence is optional (defaults to 0.0). When a detector reports
confidence < min_confidence for an entity, the rule is skipped and
default_action applies instead.
Custom Detectors
Subclass BaseDetector to add any detection logic:
import re
from promptveil.detector.base import BaseDetector, DetectedEntity
class SSNDetector(BaseDetector):
_PATTERN = re.compile(r"\b\d{3}-\d{2}-\d{4}\b")
def detect(self, text: str) -> list[DetectedEntity]:
return [
DetectedEntity("ssn", m.group(), m.start(), m.end())
for m in self._PATTERN.finditer(text)
]
@property
def supported_types(self) -> list[str]:
return ["ssn"]
shield = Shield(
config=PolicyConfig(rules=[Rule(type="ssn", action=Action.MASK)]),
detectors=[SSNDetector()],
)
FastAPI Middleware
from fastapi import FastAPI
from promptveil import Shield
from promptveil.middleware import PromptVeilMiddleware
app = FastAPI()
shield = Shield(config_path="policy.yaml")
app.add_middleware(PromptVeilMiddleware, shield=shield, prompt_field="prompt")
POST requests with Content-Type: application/json that contain the
prompt_field key are intercepted automatically. Blocked prompts receive a
400 response with a structured error body.
LangChain Adapter
from promptveil.adapters import get_langchain_callback
CallbackClass = get_langchain_callback() # lazy-imported; requires langchain-core
callback = CallbackClass(shield)
chat_model.invoke(prompt, config={"callbacks": [callback]})
Chat messages are masked in place, and block rules raise SensitiveDataError.
String LLM prompts can't be masked by a callback, so they raise
SensitiveDataError too. Call shield.scan(prompt) first to send a masked
prompt. See the API reference.
Audit Log Format
Each log line is a self-contained JSON object:
{
"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",
"position": {"start": 26, "end": 43}
}
]
}
Raw sensitive values are never stored in logs.
Project Structure
promptveil/
├── __init__.py # Public API: Shield, exceptions
├── shield.py # Main Shield class — orchestration
├── exceptions.py # SensitiveDataError, ConfigurationError
├── config/
│ └── loader.py # YAML loader & validator
├── detector/
│ ├── base.py # BaseDetector ABC + DetectedEntity dataclass
│ └── regex_detector.py # Built-in regex patterns (email/phone/card/key)
├── policy/
│ ├── models.py # Action enum, Rule, PolicyConfig dataclasses
│ └── engine.py # PolicyEngine — entity → action lookup
├── actions/
│ ├── masker.py # Per-type masking + apply_masks()
│ └── blocker.py # block() — raises SensitiveDataError
├── logger/
│ └── audit_logger.py # Structured JSON audit logger
└── middleware/
└── fastapi_middleware.py # Optional Starlette/FastAPI middleware
policy.yaml # Example policy (mask email/phone, block card/key)
example_usage.py # Runnable demo
Running Tests
uv run pytest -v
# or: python -m pytest -v
234 tests, < 1 s.
Metadata
Release files for promptveil 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| promptveil-0.2.0.tar.gz | 55.8 kB | With provenance | Details for promptveil-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| promptveil-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for promptveil-0.2.0-py3-none-any.whl |
Total release size: 98.8 kB
Release files / promptveil-0.2.0.tar.gz
| Download URL | promptveil-0.2.0.tar.gz |
|---|---|
| Size | 55.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
f70145d42ca6832129c97ae09084cc65ac010958d567046522810483f92db758
|
|
BLAKE2b-256 checksum How to use checksums |
5bb271f2c4dced8111988bd67a0e59626740e0a919249bddd2bffc8fb49cc31d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 3, 2026.
Transparency logRelease files / promptveil-0.2.0-py3-none-any.whl
| Download URL | promptveil-0.2.0-py3-none-any.whl |
|---|---|
| Size | 43.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c3edfec6dc8dfbcb5ce4a94f505b7c53e463d584837022a9ee888146ed1d105a
|
|
BLAKE2b-256 checksum How to use checksums |
8d10e55e53052a1047f6154414de6be47ca543f51132e2d3246594d87978258f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 3, 2026.
Transparency logSecurity for promptveil 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for promptveil-0.2.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 3, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.