Skip to main content

PromptVeil

Catch PII and secrets in prompts before they reach the LLM. Mask, block or allow them, with an audit log for compliance.

PyPI Tests License: MIT Python

▶ Try it live on Hugging Face (runs in your browser, nothing to install) · Docs · Roadmap · Discussions

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.

Interactive demo

Try scanning, masking, blocking, compliance profiles, and vault pseudonymization without installing anything:

Or run the Gradio app locally:

pip install promptveil gradio
python demo/huggingface/app.py   # http://localhost:7860

To host the Space: create a Static Space on Hugging Face, then set the HF_TOKEN secret and HF_SPACE_ID variable on this repo — the Hugging Face Space workflow syncs demo/huggingface/ on every push to master.

Documentation

Community

  • Tell us what to detect next in the detector request thread.
  • See what's planned in the roadmap, and vote with 👍 on the items you need.
  • Contribute a detector: good first issues cover HIPAA identifiers, EU national IDs and more, and each one explains what to build.
  • Ask questions in Q&A.

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.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for promptveil 0.3.0
File Size Uploaded Provenance Actions
promptveil-0.3.0.tar.gz 61.4 kB With provenance Details for promptveil-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for promptveil 0.3.0
File Interpreter ABI Platform Actions
promptveil-0.3.0-py3-none-any.whl Python 3 none any Details for promptveil-0.3.0-py3-none-any.whl

Total release size: 105.4 kB

Release files / promptveil-0.3.0.tar.gz

Download URL promptveil-0.3.0.tar.gz
Size 61.4 kB
Tags Source
SHA-256 checksum
How to use checksums
1b4b7050938d8aef701fed52e875e61e0badd5e22a58221e366a7054f697083e
BLAKE2b-256 checksum
How to use checksums
18ae196d8acd39361b2eb685a1d1bf3657e2072be06f43a2f49f12a12fd73aea
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 21, 2026.

Transparency log

Release files / promptveil-0.3.0-py3-none-any.whl

Download URL promptveil-0.3.0-py3-none-any.whl
Size 44.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9b195c041e77f398df34d6b7da34f0acc036041535b2a8870625346de1f24fd6
BLAKE2b-256 checksum
How to use checksums
9e5ad227eff86325109a7ee339afd1c9ccaeec4e6588d5a7f28a625b3929cb09
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 21, 2026.

Transparency log

Security for promptveil 0.3.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.

Select from 2 files

Attestation for promptveil-0.3.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 21, 2026.

Transparency log

A 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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page