Metadata-Version: 2.5
Name: redactllm
Version: 0.1.1
Summary: Keep personal data out of LLM APIs and put it back in the answer. Streaming-safe, one line, no models. India-first IDs (Aadhaar, PAN, GSTIN, UPI).
Project-URL: Homepage, https://github.com/Agentdrops/redactllm
Project-URL: Issues, https://github.com/Agentdrops/redactllm/issues
Project-URL: Changelog, https://github.com/Agentdrops/redactllm/blob/main/CHANGELOG.md
Author: Agentdrops
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: aadhaar,adk,anonymization,anthropic,dpdp,gdpr,gemini,google-adk,langchain,litellm,llm,openai,pii,privacy,redaction
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries
Classifier: Typing :: Typed
Requires-Python: >=3.10
Provides-Extra: dev
Requires-Dist: anthropic>=0.30; extra == 'dev'
Requires-Dist: google-adk>=1.14; extra == 'dev'
Requires-Dist: httpx>=0.23; extra == 'dev'
Requires-Dist: langchain>=1.0; extra == 'dev'
Requires-Dist: litellm>=1.60; extra == 'dev'
Requires-Dist: openai>=1.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Provides-Extra: google-adk
Requires-Dist: google-adk>=1.14; extra == 'google-adk'
Provides-Extra: langchain
Requires-Dist: langchain>=1.0; extra == 'langchain'
Provides-Extra: litellm
Requires-Dist: litellm>=1.60; extra == 'litellm'
Description-Content-Type: text/markdown

<div align="center">

<img src="https://raw.githubusercontent.com/Agentdrops/redactllm/main/docs/assets/logo.png" alt="redactllm logo: a padlock with an eye" width="128" height="128">

# redactllm

**Keep personal data out of LLM APIs, and put it back in the answer.**

[![CI](https://github.com/Agentdrops/redactllm/actions/workflows/ci.yml/badge.svg)](https://github.com/Agentdrops/redactllm/actions/workflows/ci.yml)
[![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-3776AB?logo=python&logoColor=white)](https://github.com/Agentdrops/redactllm/blob/main/pyproject.toml)
[![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue)](https://github.com/Agentdrops/redactllm/blob/main/LICENSE)
[![Dependencies: 0](https://img.shields.io/badge/dependencies-0-brightgreen)](https://github.com/Agentdrops/redactllm/blob/main/pyproject.toml)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)

[Install](#install) · [Quick start](#quick-start) · [Integrations](#integrations) · [What it detects](#what-it-detects) · [Examples](#examples) · [Contributing](#contributing)

</div>

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`/`httpx2` your SDK already has, and works with current
  SDKs (`httpx2`) and older ones (`httpx`). Python 3.10+. Apache-2.0.

## Contents

- [Install](#install)
- [Quick start](#quick-start)
- [Integrations](#integrations): [LangChain](#langchain-agents), [LiteLLM](#litellm), [Google ADK](#google-adk)
- [Plain text](#plain-text) and [partial restore](#restore-with-part-of-each-value-hidden)
- [What it detects](#what-it-detects)
- [Policies](#policies), [one vault per request](#one-vault-per-request) and [fake values](#realistic-fake-values-instead-of-tags)
- [Production safety](#production-safety)
- [How it works](#how-it-works)
- [Examples](#examples)
- [Limits](#limits-v01) and [roadmap](#roadmap)
- [Contributing](#contributing), [security](#security) and [license](#license)

## Install

```bash
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

```python
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:

```python
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

```bash
pip install "redactllm[langchain]"
```

```python
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

```bash
pip install "redactllm[litellm]"
```

**SDK:** use redactllm's `completion` / `acompletion` in place of LiteLLM's. Same arguments, any
provider, streaming included:

```python
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:

```yaml
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

```bash
pip install "redactllm[google-adk]"
```

```python
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

```python
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](#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.

```bash
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:

```python
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:

```python
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

```python
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:

```python
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:

```python
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:

```python
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:

```python
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 reserved `example.com` domain, 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 just `Arjun` or `Mehta` on their own all restore to the real value. Works
  with streaming, tool-call arguments and `restore_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:

```python
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:**

```python
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):

```dotenv
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:

```python
@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/`](https://github.com/Agentdrops/redactllm/tree/main/examples). The ones marked "no key" run offline.

| Script | Shows |
|---|---|
| [`01_redact_text.py`](https://github.com/Agentdrops/redactllm/blob/main/examples/01_redact_text.py) | Redact and restore plain text (no key) |
| [`02_openai_install.py`](https://github.com/Agentdrops/redactllm/blob/main/examples/02_openai_install.py) | `install()` with OpenAI, streaming included |
| [`03_anthropic_wrap.py`](https://github.com/Agentdrops/redactllm/blob/main/examples/03_anthropic_wrap.py) | `wrap()` one Anthropic client |
| [`04_custom_and_known.py`](https://github.com/Agentdrops/redactllm/blob/main/examples/04_custom_and_known.py) | Custom patterns, known values, policies, dry run (no key) |
| [`05_langchain_agent.py`](https://github.com/Agentdrops/redactllm/blob/main/examples/05_langchain_agent.py) | LangChain agent with `RedactionMiddleware` |
| [`06_litellm.py`](https://github.com/Agentdrops/redactllm/blob/main/examples/06_litellm.py) | LiteLLM with any provider |
| [`07_google_adk.py`](https://github.com/Agentdrops/redactllm/blob/main/examples/07_google_adk.py) | Google ADK agent with `RedactionPlugin` |
| [`09_restore_partial.py`](https://github.com/Agentdrops/redactllm/blob/main/examples/09_restore_partial.py) | Partial restore, per label (no key) |
| [`10_openai_restore_partial.py`](https://github.com/Agentdrops/redactllm/blob/main/examples/10_openai_restore_partial.py) | Partial restore of an OpenAI answer |
| [`12_fake_values.py`](https://github.com/Agentdrops/redactllm/blob/main/examples/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=...)` and `add_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 with `wrap()`/`http_client()`.
- **LiteLLM:** `install()` only sees LiteLLM calls that go through the OpenAI SDK. For every other
  provider use `redactllm.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:** `RedactionPlugin` masks the request as the plugins see it. Text that an agent's own
  `before_model_callback` adds afterwards is not masked; put that logic in a plugin listed before
  `RedactionPlugin`. Live (bidirectional audio/video) sessions via `run_live` are 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/messages` and `/responses` endpoints
- 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](https://github.com/Agentdrops/redactllm/blob/main/CONTRIBUTING.md) first: detection stays
rule-based with no remote calls, and tests use synthetic data only. Release notes are in
[CHANGELOG.md](https://github.com/Agentdrops/redactllm/blob/main/CHANGELOG.md).

## Security

A missed detection or a leak is a security issue. Report it privately as described in
[SECURITY.md](https://github.com/Agentdrops/redactllm/blob/main/SECURITY.md), not in a public issue.

## License

[Apache-2.0](https://github.com/Agentdrops/redactllm/blob/main/LICENSE). Free for personal and commercial use.

## Acknowledgements

Logo: [Privacy](https://icons8.com/icon/UKIDdZvg0h3g/privacy) icon by [Icons8](https://icons8.com).
