redactllm
Keep personal data out of LLM APIs, and put it back in the answer.
Install · Quick start · Integrations · What it detects · Examples · Contributing
Your users type phone numbers, emails, Aadhaar and PAN numbers, card numbers and API keys into your AI app, and all of it goes straight to OpenAI, Anthropic or Google. redactllm masks it before the request leaves your server and restores it in the response, so your app works exactly as before and the provider never sees the real values.
Your app: "I'm Ravi, Aadhaar 2345 6789 0124, call 98450 12345"
To the API: "I'm Ravi, Aadhaar <AADHAAR_1·k3f9>, call <PHONE_1·k3f9>"
Model: "Thanks! We'll call <PHONE_1·k3f9> today."
Your app: "Thanks! We'll call 98450 12345 today."
Why redactllm
- One line:
redactllm.install(). Your client code doesn't change. - Works with streaming: placeholders split across stream chunks are put back correctly.
- OpenAI, Anthropic and Gemini formats: Chat Completions, Responses API, Messages API,
generateContent. Covers sync and async calls, tool-call arguments and tool results. - India first: Aadhaar (Verhoeff checksum), PAN, GSTIN (checksum), IFSC, UPI IDs, Indian phone formats, passport and voter ID. Numbers written in Hindi and other Indic digits (२३४५…) are caught too.
- No LLMs, no models, no network calls: detection is regex + checksums + context rules. It's fast (well under a millisecond for a typical prompt), deterministic and easy to audit.
- Safe to adopt in production: dry-run mode, an explicit failure policy, an environment-variable off switch, and an audit log that records counts, never values.
- Zero dependencies. Uses the
httpx/httpx2your SDK already has, and works with current SDKs (httpx2) and older ones (httpx). Python 3.10+. Apache-2.0.
Contents
- Install
- Quick start
- Integrations: LangChain, LiteLLM, Google ADK
- Plain text and partial restore
- What it detects
- Policies, one vault per request and fake values
- Production safety
- How it works
- Examples
- Limits and roadmap
- Contributing, security and license
Install
pip install redactllm
Optional extras add framework integrations:
| Extra | For |
|---|---|
redactllm[langchain] |
LangChain 1.0+ agents (RedactionMiddleware) |
redactllm[litellm] |
LiteLLM SDK and Proxy (completion, RedactLLMGuardrail) |
redactllm[google-adk] |
Google ADK 1.14+ agents (RedactionPlugin) |
Quick start
import redactllm
redactllm.install() # protects every OpenAI / Anthropic client created afterwards
from openai import OpenAI
client = OpenAI() # unchanged
client.chat.completions.create(model="gpt-6-luna", messages=[{"role": "user", "content": user_text}])
Prefer to be explicit? Protect one client, or pass a protected HTTP client:
client = redactllm.wrap(OpenAI()) # an existing client
client = OpenAI(http_client=redactllm.http_client()) # full control
aclient = AsyncAnthropic(http_client=redactllm.async_http_client())
install() covers OpenAI, AsyncOpenAI, AzureOpenAI, Anthropic and AsyncAnthropic,
including clients created inside frameworks that use these SDKs. Clients created before
install() aren't affected; use wrap() for those.
Integrations
For agent frameworks, add redactllm where the framework calls the model. Tools still get the real values.
LangChain agents
pip install "redactllm[langchain]"
from langchain.agents import create_agent
from redactllm.integrations.langchain import RedactionMiddleware
agent = create_agent(model="google_genai:gemini-3-pro", tools=[send_sms], middleware=[RedactionMiddleware()])
Works with any chat model LangChain supports (Gemini, Bedrock, Ollama, Mistral...), not only
OpenAI and Anthropic. The model sees <PHONE_1>; the agent's state keeps the real values, and the
model's reply, its tool-call arguments and structured output are restored before your tools run, so
send_sms gets the real number. Needs LangChain 1.0 or newer.
LiteLLM
pip install "redactllm[litellm]"
SDK: use redactllm's completion / acompletion in place of LiteLLM's. Same arguments, any
provider, streaming included:
from redactllm.integrations import litellm as rl
resp = rl.completion(model="bedrock/anthropic.claude-sonnet-5-5", messages=[...])
async_resp = await rl.acompletion(model="gemini/gemini-3-pro", messages=[...], stream=True)
Proxy: add the guardrail to your LiteLLM Proxy config.yaml (redactllm must be installed where
the proxy runs). Every /chat/completions request is masked before it reaches the provider and the
response is restored, streamed or not:
guardrails:
- guardrail_name: redactllm
litellm_params:
guardrail: redactllm.integrations.litellm.RedactLLMGuardrail
mode: [pre_call, post_call] # both: pre_call masks, post_call restores
default_on: true
Each proxy request gets its own placeholder numbering, so one caller's values can never be restored into another caller's response.
All integrations follow the same settings as the rest of redactllm: policies, custom patterns,
mode, on_error (a blocked request raises redactllm.RedactionError), audit callbacks, and the
off switches.
Google ADK
pip install "redactllm[google-adk]"
from google.adk.agents import Agent
from google.adk.apps import App
from redactllm.integrations.google_adk import RedactionPlugin
agent = Agent(name="support", model="gemini-3-pro", tools=[send_sms])
app = App(name="support", root_agent=agent, plugins=[RedactionPlugin()])
Then run it with Runner(app=app, session_service=...). One plugin covers every agent in the
app and every model ADK calls, Gemini or others through LiteLlm. The model sees <PHONE_1>; session
history keeps the real values. The model's reply and its function-call arguments are restored before
ADK records them, so send_sms gets the real number. Streamed (SSE) replies are restored chunk by chunk.
Each model call gets its own placeholder numbering, so on a server shared by many users one user's values
can never be restored into another user's reply. Needs google-adk 1.14 or newer.
Plain text
r = redactllm.redact("call 98450 12345, mail ravi@example.com")
r.text # 'call <PHONE_1·k3f9>, mail <EMAIL_1·k3f9>'
r.counts # {'PHONE': 1, 'EMAIL': 1}
r.restore("We'll call <PHONE_1·k3f9>") # "We'll call 98450 12345": only values masked in r
k3f9 is a random tag, different for every vault (see One vault per request).
Later examples leave it out for brevity. redactllm.restore(text) also works, against the process-wide
vault; it's handy in scripts, but on a server use r.restore() or a session() per user.
echo "call 98450 12345" | redactllm # try it from the terminal
Restore with part of each value hidden
Showing the answer to someone who shouldn't see the full number (a support agent, a log, a screen
share)? restore_partial() puts values back with most characters starred, chosen per label:
redactllm.restore_partial("Thanks <PERSON_1>, we'll call <PHONE_1> and mail <EMAIL_1>")
# "Thanks Ravi, we'll call ***** *2345 and mail r***@example.com"
| Label | Shown as |
|---|---|
PHONE, AADHAAR, CREDIT_CARD, IBAN, PAN, GSTIN, VOTER_ID |
last 4: **** **** 0124 |
PASSPORT |
last 3 |
EMAIL, UPI_ID |
first letter + domain: r***@okhdfcbank |
IFSC |
bank code: HDFC******* |
API_KEY, IP_ADDRESS |
first 4 / first 3 characters |
PERSON (from context(known=...)) and your own labels |
in full |
Spaces, dashes and + are kept, so values keep their shape. Change any label with a function, an int
(keep that many last characters), "show" or "hide", and pick another mask character:
from redactllm.reveal import keep_first
redactllm.restore_partial(text, rules={"PHONE": 2, "PERSON": "hide", "EMPLOYEE_ID": keep_first(3)}, char="X")
What it detects
| Label | Examples | How it's validated |
|---|---|---|
EMAIL |
ravi.k@example.co.in | format |
PHONE |
+91 98450 12345, 098450-12345, 984-501-2345, +44 20 7946 0958 | Indian mobile rules, international length |
CREDIT_CARD |
4111 1111 1111 1111 | Luhn checksum |
IBAN |
GB82 WEST 1234 5698 7654 32 | mod-97 checksum |
IP_ADDRESS |
203.0.113.9, 2001:db8::1 | real IPv4/IPv6 (not localhost) |
API_KEY |
OpenAI, Anthropic, AWS, GitHub, Slack, Google, Hugging Face keys | known prefixes |
AADHAAR |
2345 6789 0124 | 12 digits, first digit 2-9, Verhoeff checksum |
PAN |
AAPFU0939F | structure + valid holder-type letter |
GSTIN |
27AAPFU0939F1ZV | state code + embedded PAN + check character |
IFSC |
HDFC0001234 | structure |
UPI_ID |
ravi@okhdfcbank, 9845012345@ybl | known UPI handles, or any handle near the word "UPI" |
PASSPORT |
K1234567 | format + the word "passport" nearby |
VOTER_ID |
ABC1234567 | format + "voter"/"EPIC" nearby |
Checksums and context words matter: an order number that merely looks like an Aadhaar or a card fails the checksum and is left alone, so your prompts aren't over-redacted.
Add your own
redactllm.add_pattern("EMPLOYEE_ID", r"\bEMP-\d{6}\b") # your ID formats
redactllm.add_terms("PROJECT", ["Project Falcon"]) # names, codenames, hostnames
redactllm.allow_terms(["support@acme.com"]) # never redact these
Values your app already knows
If your app has the user's record, tell redactllm exactly what to hide. Names are covered without any model, in any spacing, case or digit script:
with redactllm.context(known={"PERSON": [user.name], "PHONE": [user.phone]}):
client.chat.completions.create(...)
Policies
Every label is masked (reversible) by default. Change it per label:
redactllm.set_policy(
{
"PHONE": "fake", # +91 87316 40925: a realistic fake, reversible (see below)
"EMAIL": "hash", # <EMAIL#1f3a9c2e>: stable, not reversible
"API_KEY": "drop", # <API_KEY>: removed, not reversible
"IP_ADDRESS": "allow", # sent as-is
}
)
The same value always gets the same placeholder (+91 98450 12345 and 98450-12345 are both
<PHONE_1>), so the model can tell they're the same. Restore uses the first spelling it saw.
One vault per request
Every LLM call gets its own vault (placeholder ↔ value map), whether it goes through install(),
wrap() or an integration. A placeholder in a response can only be restored with values from that
same request, so on a server shared by many users, one user's data can never appear in another
user's answer. Numbering restarts with each request; multi-turn chats still work because the
history you send is masked again, consistently, every time.
Placeholders can't be forged either: each vault has a random tag, <PHONE_1·k3f9>, and restores
only placeholders carrying its own tag. If a user types <PHONE_1>, or pastes a placeholder copied
from somewhere else, it comes back exactly as typed. Small changes a model makes (case, spaces,
. or - in place of ·) still restore. Vault(tag="") gives the old untagged <PHONE_1> form.
If the provider keeps earlier turns for you (OpenAI previous_response_id, Conversations or
Assistants threads), keep one vault per conversation so the numbering stays stable across calls:
vault = vaults.setdefault(conversation_id, redactllm.Vault()) # one per conversation, never per process
with redactllm.session(vault):
client.responses.create(model=..., input=text, previous_response_id=last_id)
redactllm logs a warning once if it sees previous_response_id or conversation without a session.
Never share one session between users.
Realistic fake values instead of tags
Some models handle <PHONE_1> worse than natural text: they drop it, reformat it, or answer less
well. The fake policy sends a made-up value of the same kind instead, and still puts the real one
back in the answer:
redactllm.set_policy(fake=True) # every label that can be faked
redactllm.set_policy({"PHONE": "fake", "PERSON": "fake"}) # or only some labels
redactllm.set_policy(fake=False) # back to placeholders (the default)
Your app: "I'm Ravi Kumar, call +91 98450 12345, mail ravi@example.com"
To the API: "I'm Arjun Mehta, call +91 87316 40925, mail kavya.iyer@example.com"
Model: "Sure Arjun, I'll call +91 87316 40925."
Your app: "Sure Ravi, I'll call +91 98450 12345."
- Same kind and shape: fakes keep the original's layout (
+91, spaces, dashes) and pass the same checks as real values: Luhn for cards, Verhoeff for Aadhaar, the PAN holder type, the GSTIN and IBAN check characters. Emails use the reservedexample.comdomain, IP addresses the documentation ranges, API keys keep their provider prefix. - Reversible, even when the model rewrites them:
87316-40925,8731640925, the number without+91,ARJUN MEHTA, or justArjunorMehtaon their own all restore to the real value. Works with streaming, tool-call arguments andrestore_partial(). - Never ambiguous: a fake is never a real value in the vault, never another value's fake, and never text already in the request. The same value always gets the same fake.
- Labels with no faker (
ADDRESS, your own labels) keep using placeholders. Teach it yours:
redactllm.set_faker("EMPLOYEE_ID", lambda value, rng: f"EMP-{rng.randint(0, 999999):06d}")
configure(fake=True) does the same as set_policy(fake=True). Fakes are random, so a fake number
can by chance belong to a real person (never to anyone in your request). Text the model invents that
happens to equal a fake is restored too, which is why fakes avoid everything in the request.
Production safety
Roll out in stages:
redactllm.configure(mode="detect") # 1. dry run: logs what it WOULD redact, changes nothing
redactllm.configure(mode="redact") # 2. enforce (the default)
Turn it off completely, with no code change, by adding one line to your .env file
(or setting it as an environment variable):
REDACTLLM_ENABLED=false
When it is off, install() and wrap() patch nothing, the LangChain, LiteLLM and Google ADK integrations pass requests
through unchanged, and redact() returns the text as it is. Remove the line, or set it to true, to turn
protection back on. redactllm reads the first .env it finds in the current folder or a folder above it,
once, at the first call; restart your app after you change the file. A real environment variable wins over
.env. Values other than true/false (1/0, yes/no, on/off) are ignored with a warning, and
protection stays on. REDACTLLM_MODE=off (or detect) also works, in the environment or in .env, and only
stops requests from being rewritten.
Decide what happens on failure:
on_error= |
If redaction itself fails |
|---|---|
"block" (default) |
Nothing is sent. Your SDK raises its normal BadRequestError with a message starting "redactllm blocked this request". |
"passthrough" |
The original request is sent and a warning is logged. |
Audit without leaking: the redactllm logger and on_redact callbacks report counts, never values:
@redactllm.on_redact
def audit(event):
metrics.increment("pii.redacted", tags=event["counts"]) # {"PHONE": 1, "EMAIL": 1}
Other guarantees:
- Only user text is rewritten: message content, system prompts, tool results and tool-call arguments. Model names, roles, IDs, tool schemas and images are never touched.
- Unknown endpoints (files, models, batches...) and non-JSON requests pass through unchanged.
- Each request gets its own vault (placeholder ↔ original value), in your process memory and dropped when the response is done. Nothing is written to disk or sent anywhere, and nothing is shared between users.
- When streaming, at most a few characters (a possible partial placeholder) are held back, and always released before the end of the text.
How it works
redactllm wraps the transport of the httpx/httpx2 client that the OpenAI and Anthropic SDKs use.
It reads each outgoing request, rewrites only the text fields for that API format, and restores
placeholders in the JSON response or in each server-sent event of a stream. Because it works at the
HTTP layer rather than patching SDK methods, it keeps working when the SDKs change.
Examples
Runnable scripts are in examples/. The ones marked "no key" run offline.
| Script | Shows |
|---|---|
01_redact_text.py |
Redact and restore plain text (no key) |
02_openai_install.py |
install() with OpenAI, streaming included |
03_anthropic_wrap.py |
wrap() one Anthropic client |
04_custom_and_known.py |
Custom patterns, known values, policies, dry run (no key) |
05_langchain_agent.py |
LangChain agent with RedactionMiddleware |
06_litellm.py |
LiteLLM with any provider |
07_google_adk.py |
Google ADK agent with RedactionPlugin |
09_restore_partial.py |
Partial restore, per label (no key) |
10_openai_restore_partial.py |
Partial restore of an OpenAI answer |
12_fake_values.py |
Realistic fake values instead of tags (no key) |
Limits (v0.1)
- Names and addresses aren't detected automatically yet (no models, by design). Cover them with
context(known=...)andadd_terms(). Optional local name and address detection is on the roadmap. - The google-genai SDK isn't hooked by
install()yet. The Gemini request format is supported when you call the REST API through an httpx client wrapped withwrap()/http_client(). - LiteLLM:
install()only sees LiteLLM calls that go through the OpenAI SDK. For every other provider useredactllm.integrations.litellm.completion()or the Proxy guardrail. The guardrail covers/chat/completions; other Proxy endpoints (/v1/messages,/responses, embeddings) pass through unchanged for now. - LangChain streaming: with
RedactionMiddleware, tokens streamed while the model is still answering (stream_mode="messages") show placeholders. The final messages in the agent's state are restored. - Google ADK:
RedactionPluginmasks the request as the plugins see it. Text that an agent's ownbefore_model_callbackadds afterwards is not masked; put that logic in a plugin listed beforeRedactionPlugin. Live (bidirectional audio/video) sessions viarun_liveare not covered. - Detection is rule-based: it catches the formats listed above, not every possible personal detail.
Test with
mode="detect"on your real traffic before relying on it for compliance.
Roadmap
- google-genai integration
- LiteLLM Proxy:
/v1/messagesand/responsesendpoints - Optional local NER taggers (
redactllm[ner]), never LLMs and never remote calls - Health and finance presets (ABHA numbers, clinical field labels, date shifting)
Contributing
Issues and pull requests are welcome. Read CONTRIBUTING.md first: detection stays rule-based with no remote calls, and tests use synthetic data only. Release notes are in CHANGELOG.md.
Security
A missed detection or a leak is a security issue. Report it privately as described in SECURITY.md, not in a public issue.
License
Apache-2.0. Free for personal and commercial use.
Acknowledgements
Metadata
Release files for redactllm 0.1.1
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 |
|---|---|---|---|---|
| redactllm-0.1.1.tar.gz | 82.9 kB | With provenance | Details for redactllm-0.1.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| redactllm-0.1.1-py3-none-any.whl | Python 3 | none | any | Details for redactllm-0.1.1-py3-none-any.whl |
Total release size: 148.7 kB
Release files / redactllm-0.1.1.tar.gz
| Download URL | redactllm-0.1.1.tar.gz |
|---|---|
| Size | 82.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
1c1998944cc810c30aad452a2732a47eea312122eda34cbdd83646a297079e2c
|
|
BLAKE2b-256 checksum How to use checksums |
125895df4a7cb807854f0705dbe2c7250201fe8455d5db7c2289631f01abcbc5
|
| 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 Dec 4, 2026.
Transparency logRelease files / redactllm-0.1.1-py3-none-any.whl
| Download URL | redactllm-0.1.1-py3-none-any.whl |
|---|---|
| Size | 65.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
52e3caf940bf17c0b51b45d7a5d8ec92904f782fc0595d0a539cfc603d26270c
|
|
BLAKE2b-256 checksum How to use checksums |
8e7fc6281850800a000a39aa93f609f43de23f86c96958c87c4a2de68428dfcd
|
| 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 Dec 4, 2026.
Transparency logSecurity for redactllm 0.1.1
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 redactllm-0.1.1.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 Dec 4, 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.