SurrogateShield finds the personal data in a message, replaces it with realistic, consistent surrogates before the request reaches an LLM provider, and puts the real values back in the reply. On 3,677 personal values placed in real ShareGPT, WildChat and oasst1 messages it let 0.8% through. GLiNER-PII let through 9.1%, Microsoft Presidio 31.6% and LLM Guard 56.3%. It trailed on only a few tests, listed in one line under Limitations. The surrogate map is encrypted with AES-256-GCM and stays on your machine. Ships as a Python library with a CLI, plus an interactive terminal app.
Every message goes through detection, surrogate generation, an encrypted map, the LLM call and restoration. Detected values are replaced before the request is made. If a detection model is missing, mask() raises DetectorUnavailable and the text is not sent half-masked.
With address_mode="auto" (the default), a question that needs a location to be answered (e.g. pharmacies near…) keeps the street and city and shifts the house number by ±1. If the question is about a sensitive topic (HIV, abortion, rehab, therapy, mental health, shelter, immigration and similar), the street becomes my area. Every other address is replaced in full.
PatternScan finds structured values with regex and validators. The canonicaliser also reads them when they are written in words, spelled out or disguised with look-alike characters. EntityTrace (spaCy) and PIITagger (a fine-tuned DeBERTa-v3-small) find names, organisations, places, addresses, handles and IDs. Structural passes then read CSV columns, signatures and “my name is” frames. A relation gate keeps public figures and companies you only mention.
Draws a surrogate of the same type and shape for each value: real-looking names, an e-mail built from the surrogate name, a phone in the same format, Luhn-passing card numbers, IDs with the same letter and digit pattern. A value gets the same surrogate every time it appears in a session, and no two values share one.
The {surrogate → original} pairs are kept in memory by default. When saved, they are encrypted with AES-256-GCM under a per-session key derived with HKDF-SHA256 from a 32-byte device secret. The file cannot be read without that secret.
Receives the masked text over HTTPS: the prompt, the earlier turns and any RAG context, each with its detected values replaced. On real chat text 0.8% of placed values reached it, against 9.1% for GLiNER-PII and 31.6% for Presidio.
Three-tier substitution on the response: exact match → component match (handles partial name mentions) → fuzzy match (rapidfuzz score ≥ 85). Restores originals before the user sees anything.
±1 and the street and city are kept, because replacing the address would make the answer useless. Sensitive topics (HIV, abortion, rehab, addiction, mental health, therapy, domestic violence, shelter, immigration, self-harm and others) coarsen the street to my area instead. Turn the feature off with service=False. The benchmark redraws every address, so these kept parts are not part of its leak figures.
On the default balanced preset, the stages run in this order: PatternScan with the canonicaliser, EntityTrace, PIITagger, then the structural passes. A relation gate keeps names that are not tied to the writer, and a resolver settles each value on one type. Removing any stage raises the leak rate. Without the pattern rules it goes from 0.8% to 1.4%, without the canonicaliser to 3.9%, and without the tagger to 10.8%.
Regex with format validators: Luhn for cards, checksums for IBANs, VINs and routing numbers, and range checks for SSNs and ZIPs. The canonicaliser reads the same message in other written forms, such as numbers in words, “at”/“dot” e-mails, ordinal dates and look-alike or zero-width characters. A value found that way gets its surrogate written back in the same form.
Named-entity recognition with spaCy. In balanced it reads places only, because its names cost more harmless edits than they find, so names come from the tagger. In strict and classic it reads names too and sends borderline spans to ContextGuard. The fast preset skips it, and the tagger reads places instead.
A token tagger fine-tuned for personal data. It reads names, organisations, places, addresses, phones, handles, IDs and credentials, and long text is read in overlapping windows. The weights (~565 MB) are on Hugging Face: they download once, at a fixed commit, must match their SHA-256 pin, and then load from the local cache with no network. If they cannot be fetched, mask() raises DetectorUnavailable instead of sending the text with less protection. The classic preset runs without it.
| Pass | Behaviour |
|---|---|
| S | Structure-driven detection. It covers CSV columns, chat speakers, signatures, “my name is” / “lives in” frames, payees after “PAYMENT TO”, and streets written the French or Portuguese way. Each rule needs its own structural evidence, so none of them fires on a bare word. |
| A · E · H | Structural ORG (<name> Inc / LLC / Corp…), structural PERSON in all-lowercase or all-caps text, and the card brand written right before a card number. |
| F · G · B · C | Drops implausible ORGs, merges adjacent name pieces, turns an ORG that matches an e-mail username into a PERSON, and removes a surname already inside a detected full name. |
| R | Relation gate. An organisation or place is replaced only when it is tied to the writer (“I work at…”, “my son’s school…”). Public figures, public companies and places that are only the topic of a question are kept. |
| resolver | One candidate per value. Source priority is applied first, then a rule for each type conflict, then the score. |
| CG | ContextGuard (dslim/distilbert-NER) checks borderline spaCy spans. It is off in balanced and fast, and on in strict and classic. |
Flags combinations of fields that together can re-identify a person. The result is logged with the detections, and the terminal app shows a warning. The scorer does not change what gets replaced.
| Combination | Risk | Source |
|---|---|---|
| ZIP + DOB + Gender | high | 87% of the US population uniquely identifiable (Sweeney 2000) |
| Postcode + DOB | high | UK equivalent |
| Name + SSN · Name + DOB | high | Direct identity pairing |
| Name + Employer + City | medium | Professional cross-reference |
| Email / Phone / IP + Name or Location | medium | Contact or network triangulation |
| DOB + Location + Employer | medium | Three-field narrowing |
Each public type groups finer internal types, for example ID covers ssn, passport, iban, vin and credit_card. Any type can be left alone with pii_off. On real chat text, SurrogateShield had the lowest or joint-lowest leak rate of every tool on 10 of the 13 types, and no leaks at all on 7 of them.
| Type | Examples | Validator | Source |
|---|---|---|---|
| PERSON | Priya Raman · my coworker Dana | relation gate | model |
| ORG | Mercy General (when you work there) | relation gate | model |
| LOCATION | Tempe · “we live near Reno” | relation gate | model |
| ADDRESS | 1847 Alder Street, Portland, OR 97214 · SW1A 1AA | ZIP / postcode format | regex model |
| priya.raman@northwind.io · priya at northwind dot io | structure | regex | |
| PHONE | +1 415 555 0142 · +44 7911 123456 · in words | format | regex model |
| URL | https://priyaraman.dev/notes · hostnames | structure | regex |
| HANDLE | @priyaraman | — | regex model |
| ID | SSN · passport · VIN · card · IBAN · routing no. · licence · plate · crypto | Luhn · IBAN · VIN · ABA | regex model |
| CREDENTIAL | sk-ant-… · ghp_… · AKIA… · passwords | prefix match | regex model |
| NETWORK | 192.168.1.100 · MAC addresses | octet bounds | regex |
| AGE | 34 years old | phrase | regex |
| DATE_OF_BIRTH | March 14, 1991 · the 14th of March | date | regex |
priya at northwind dot io, ordinal dates (the 14th of March), and text with full-width, look-alike or zero-width characters. The surrogate is written back in the same form. On formats that were held out while the detector was built (phones in words and month-ordinal birth dates), SurrogateShield missed 0 of 30 values and GLiNER-PII missed 3 of 30.
Every surrogate has the same type and shape as the value it replaces, and stays the same for the whole session. Fake names look like names, a fake card passes Luhn, and a fake IBAN passes its checksum. The model reads a coherent message and writes a coherent reply, and that reply can be restored. Placeholder tools such as Presidio and GLiNER-PII send [PERSON] instead.
Real output of the default balanced preset. The company is kept because you only mention it, and the complaint still goes to the right company. Surrogates are drawn at random for each session; pass seed= for repeatable output.
Kept in memory by default. With pii_mem set to a folder (or in the CLI and the app), it is saved as SSv1 ‖ nonce (12 bytes) ‖ AES-256-GCM ciphertext and cannot be read without the device key.
| Entity type | Generated surrogate looks like |
|---|---|
| PERSON | Adya Nath — the same person gets the same name all session |
| adya.nath@vance.io — built from the surrogate name | |
| PHONE | +1 213 581 8333 — same country code and grouping |
| ADDRESS | 9351 Meyer Street, Charlottesville, TN 19093 |
| ID · ssn | 841-69-1543 — valid format |
| ID · credit_card | 4159 0830 1661 3181 — passes Luhn |
| ID · iban | DE02786579754323194875 — passes mod-97 |
| ID · other | VW-02898-Z — same letter and digit pattern |
| CREDENTIAL | sk-ant-api03-Hw90uUn0Hb8Ej6EtDu4Tx2Du — prefix kept, rest random |
| NETWORK | 192.168.63.243 — same private range |
| URL · HANDLE | https://forumrao.dev/notes · @forumrao |
| AGE · DATE_OF_BIRTH | 31 years old · June 26, 1991 — same format; a birth date moves by at most two years |
All tools ran on the same real ShareGPT, WildChat and oasst1 user messages, with the same scorer. The messages were sealed until the detector was final. 3,677 personal values were placed in 1,308 messages. SurrogateShield let 30 of them (0.8%) reach the provider. The others let through: GLiNER-PII tuned to 0.3, 7.3%; GLiNER-PII at its default 0.5, 9.1%; Microsoft Presidio, 31.6% (with Faker, the same); Presidio with the obi/deid_roberta_i2b2 transformer, 54.0%; LLM Guard, 56.3%. That is 11× fewer leaks than GLiNER-PII and 39× fewer than Presidio. The difference from GLiNER-PII is −8.3 points, with a 95% interval of [−9.3, −7.3]. Commands and every split: bench/results.
Both outputs are real runs on the same sentence. Presidio sent the order number and the street name in plain text and read the house number as a date. GLiNER-PII at 0.5 also sent the order number in plain text. It replaced the rest with [PERSON], [ADDRESS] and even [ORGANIZATION], so the complaint can no longer name the right company.
Leak, clean and spurious figures are on the injected slice: 3,677 values in 1,059 prompts and conversations (1,308 messages). Clean means the whole prompt or conversation reached the provider with no value left. Untouched means PII-free natural messages left unchanged (of 2,433). Odd formats are 530 values written the way a regex may not expect: lower-case names, an SSN without dashes, a phone number in words, an e-mail as "name at domain dot com". Nemotron is an outside dataset of 1,000 records. Speed is the median per message on CPU. Lower is better except for clean and untouched.
| Tool | Leaked | Clean | Spurious | Untouched | Odd-format leak | Nemotron leak | p50 ms |
|---|---|---|---|---|---|---|---|
| SurrogateShield | 0.8% | 97.4% | 13.9% | 88.5% | 0.2% | 14.5% | 43.5 |
| GLiNER-PII @0.3 | 7.3% | 79.5% | 41.3% | 20.0% | 7.5% | 22.5% | 79.9 |
| GLiNER-PII @0.5 | 9.1% | 75.4% | 35.4% | 28.9% | 8.3% | 25.8% | 82.1 |
| Presidio | 31.6% | 30.8% | 32.6% | 59.6% | 43.6% | 40.1% | 8.2 |
| Presidio + Faker | 31.6% | 30.8% | 32.6% | 59.6% | 43.6% | 40.2% | 8.4 |
| Presidio + RoBERTa | 54.0% | 11.7% | 22.0% | 70.9% | 66.0% | 56.6% | 83.5 |
| LLM Guard | 56.3% | 9.1% | 16.4% | 83.9% | 61.5% | 61.0% | 58.0 |
SurrogateShield has the best number in every column except raw speed, where plain Presidio is faster. It is the fastest tool here that runs a transformer: 1.9× faster than GLiNER-PII, using about 970 MB less memory. Per dataset, its leak rate was 0.7% on oasst1, 0.9% on ShareGPT and 0.8% on WildChat. GLiNER-PII at 0.5 was 8.4%, 10.1% and 8.8%.
SurrogateShield is lowest or joint-lowest on 10 of the 13 types and leaks nothing on 7. It is behind GLiNER-PII on PERSON and LOCATION, and behind Presidio on URL.
| Type (values) | SS | GLiNER 0.5 | GLiNER 0.3 | Presidio | + RoBERTa | LLM Guard |
|---|---|---|---|---|---|---|
| ADDRESS 197 | 0 | 8.6 | 7.1 | 97.0 | 93.9 | 100 |
| AGE 326 | 0.3 | 0.9 | 0.6 | 40.8 | 69.3 | 100 |
| CREDENTIAL 195 | 0 | 7.2 | 5.1 | 95.4 | 96.9 | 76.9 |
| DATE_OF_BIRTH 190 | 0 | 6.3 | 5.8 | 7.9 | 38.4 | 100 |
| EMAIL 300 | 0 | 3.0 | 2.3 | 8.3 | 8.3 | 8.3 |
| HANDLE 202 | 0 | 6.9 | 3.5 | 93.1 | 86.6 | 82.7 |
| ID 248 | 1.2 | 33.1 | 25.4 | 22.2 | 22.2 | 52.0 |
| LOCATION 217 | 2.8 | 6.5 | 1.4 | 15.7 | 65.9 | 93.1 |
| NETWORK 196 | 0 | 18.4 | 16.3 | 0 | 19.9 | 19.9 |
| ORG 254 | 3.5 | 8.7 | 5.5 | 85.4 | 73.6 | 91.7 |
| PERSON 867 | 1.2 | 0.3 | 0.1 | 10.6 | 76.5 | 21.3 |
| PHONE 272 | 0 | 3.7 | 3.3 | 9.2 | 9.2 | 5.9 |
| URL 213 | 0.5 | 46.9 | 45.1 | 0 | 0 | 99.5 |
The messages are real user turns from ShareGPT, WildChat and oasst1, held back until the detector was frozen. Personal values were placed using the halves of the word lists that were never used for building. Intervals are 95% bootstrap intervals with the conversation as the unit (2,000 resamples). Every number here can be rerun, and the commands are in bench/results/README.md.
3,677 values placed in 1,308 real messages (1,059 prompts and conversations), across 13 types. Shorter is better. Command: python -m bench.realdata.score --split test3 --out bench/results/realdata_test3.json.
Each tool's masked version of 298 prompts was answered by claude-sonnet-4-6. The answer was compared with the answer to the original prompt (roberta-large, rescaled). SurrogateShield scored +0.077 [+0.053, +0.103] above Presidio + Faker and +0.072 [+0.046, +0.098] above GLiNER-PII. A judge model (claude-opus-5-5) preferred SurrogateShield's answer over Presidio + Faker's 195 times and the other way 62 times, with 39 ties: +0.449 [+0.355, +0.540]. Against GLiNER-PII it preferred SurrogateShield's answer 132 times and GLiNER-PII's 117 times, with 47 ties: +0.051 [−0.051, +0.152].
On 150 natural prompts, most of which hold no personal data, SurrogateShield changed 23, Presidio 59 and GLiNER-PII 108. Answering the original prompt a second time scores 0.508. SurrogateShield's answers score 0.490, Presidio's 0.440 and GLiNER-PII's 0.365.
60 multi-turn conversations with personal values placed in them, 20 per dataset. Only SurrogateShield puts the values back in the replies, because the other tools keep no map.
| Tool | Values restored | Final answer correct / partly | Real value sent upstream |
|---|---|---|---|
| SurrogateShield | 81 / 82 | 32 / 18 | 5 / 150 |
| GLiNER-PII | 0 / 54 | 2 / 5 | 30 / 150 |
| Presidio + Faker | 0 / 80 | 0 / 19 | 78 / 150 |
The judge preferred SurrogateShield's conversations by +0.576 [+0.467, +0.685] over Presidio + Faker and +0.649 [+0.527, +0.770] over GLiNER-PII.
2,476 natural messages, 2,433 of them with nothing to protect. Every change to those is a harmless word altered for no reason. GLiNER-PII at 0.5 makes 5.7× more of these than SurrogateShield. Every SurrogateShield operating point sits below and to the left of every GLiNER-PII threshold from 0.3 to 0.9, both pooled and per dataset.
| Tool | Untouched (of 2,433) | Spurious edits / all edits |
|---|---|---|
| SurrogateShield | 2,153 · 88.5% | 1,053 / 1,389 |
| LLM Guard | 2,041 · 83.9% | 1,391 / 1,710 |
| Presidio + RoBERTa | 1,725 · 70.9% | 2,259 / 2,749 |
| Presidio | 1,450 · 59.6% | 3,438 / 4,044 |
| GLiNER-PII @0.5 | 704 · 28.9% | 6,012 / 6,697 |
| GLiNER-PII @0.3 | 486 · 20.0% | 7,789 / 8,496 |
1,000 records and 4,627 values from a dataset none of the tools was built on. SurrogateShield has the lowest leak rate in all four strata: 11.9%, 12.5%, 16.9% and 16.8%.
| Tool | Leaked | Span F1 |
|---|---|---|
| SurrogateShield | 14.5% | 0.886 |
| GLiNER-PII @0.3 | 22.5% | 0.751 |
| GLiNER-PII @0.5 | 25.8% | 0.758 |
| Presidio | 40.1% | 0.716 |
| Presidio + Faker | 40.2% | 0.716 |
| Presidio + RoBERTa | 56.6% | 0.594 |
| LLM Guard | 61.0% | 0.530 |
200 messages on a 10-CPU Mac, warm. Plain Presidio is the fastest. Among tools that run a transformer, SurrogateShield is the fastest.
| Tool | Median ms / message | Peak memory |
|---|---|---|
| Presidio | 8.2 | 1,084 MB |
| Presidio + Faker | 8.4 | 1,010 MB |
| SurrogateShield | 43.5 | 1,348 MB |
| LLM Guard | 58.0 | 1,565 MB |
| GLiNER-PII @0.3 | 79.9 | 2,333 MB |
| GLiNER-PII @0.5 | 82.1 | 2,318 MB |
| Presidio + RoBERTa | 83.5 | 1,611 MB |
The same injected slice was run with each preset, and with one part of balanced switched off at a time. Even with every regex broken, the leak rate stays below Presidio's 31.6%.
| Configuration | Leaked | Untouched (of 2,433) | p50 ms |
|---|---|---|---|
| strict | 0.2% | 1,264 | 67.1 |
| balanced (default) | 0.8% | 2,153 | 47.1 |
| fast | 0.8% | 2,147 | 38.2 |
| classic (no tagger weights) | 2.5% | 1,885 | 29.2 |
| balanced, no pattern rules | 1.4% | — | — |
| balanced, no canonicaliser | 3.9% | — | — |
| balanced, no tagger | 10.8% | — | — |
| balanced, no models | 15.7% | — | — |
| balanced, every regex broken | 26.1% | — | — |
claude-opus-5-5 was given the text each tool sent to the provider for 180 real prompts holding 636 placed values. It was told that a filter may have replaced some values, changed parts of others or left them alone, and asked to give back every original. A value counts as known if the tool left it in plain text or the attacker named it letter for letter. SurrogateShield let the attacker know 1.8% of the values. GLiNER-PII let it know 12.6%, Presidio 34.2% and LLM Guard 61.0%.
claude-sonnet-4-6, attacker claude-opus-5-5, one run. Command: python -m bench.realdata.attacker_exact --split test3, details in bench/results.
| Tool | Left in plain text | Recovered exactly | Known letter for letter |
|---|---|---|---|
| SurrogateShield | 7 | 4 / 620 | 11 / 627 · 1.8% |
| GLiNER-PII | 73 | 6 / 556 | 79 / 629 · 12.6% |
| Presidio + Faker | 201 | 8 / 428 | 209 / 629 · 33.2% |
| Presidio | 201 | 14 / 428 | 215 / 629 · 34.2% |
| LLM Guard | 364 | 19 / 264 | 383 / 628 · 61.0% |
The map from surrogates back to your values is kept on your machine. In the library it lives in memory unless you give it a directory. On disk it is sealed with a key derived from a device secret that is never sent anywhere, and a file that will not decrypt raises an error instead of quietly becoming an empty map.
~/.surrogateshield/device.key, created once0600, home directory 0700SSv1 ‖ nonce (12 B) ‖ AES-256-GCM, fresh nonce on every saveCorruptStoreError raisedDetectorUnavailable; nothing is sent half-checkedconversations/ and *.shadowmap — history and sealed maps*.key, .surrogateshield/ — the device secret.env — API keys
Local RAG via ChromaDB + sentence-transformers (all-MiniLM-L6-v2), in process, with no server. Detected values are replaced before a document is indexed, so the index holds surrogates.
document.txt
│
▼
SentinelLayer ▸ detect PII
│
▼
MimicGen ▸ generate surrogates
│
▼
rag_global ShadowMap
{ surrogate → original } persisted
│
▼
Anonymised document
│
▼
chunk @ RAG_CHUNK_SIZE = 512
│
▼
sentence-transformers
all-MiniLM-L6-v2
│
▼
ChromaDB ▸ ~/.surrogateshield/rag
user query
│
▼
SentinelLayer ▸ anonymise query
│
▼
embed ▸ ChromaDB ▸ retrieve top-3
│
▼
Prepend anonymised context
│
▼
LLM API ← receives the masked text
│
▼
ResolvePass
restores your values + document values
via rag_global ShadowMap
│
▼
Display to user
Detection, surrogates, storage and restore live once, in the package. The terminal app's modules are thin wrappers that read config.py, and the benchmark runs the same code against the other tools.
SurrogateShield/ ├── python-library/ # The engine: pip install ./python-library │ └── surrogateshield/ │ ├── __init__.py # config · scan · mask · unmask · forget · flush │ ├── session.py # Session — sync and async │ ├── cli.py # scan · mask · unmask · bench · doctor · download │ └── core/ │ ├── detection/ # SentinelLayer │ │ ├── pipeline.py # stages, passes, relation gate, resolver │ │ ├── config.py # presets: fast · balanced · strict · classic │ │ ├── pattern_scan.py # PatternScan — regex + validators │ │ ├── canonical.py # views of spaced, spelled-out and obfuscated values │ │ ├── entity_trace.py # EntityTrace — spaCy en_core_web_lg │ │ ├── pii_tagger.py # PIITagger — DeBERTa-v3-small │ │ ├── context_guard.py # ContextGuard — distilbert-NER │ │ ├── structural.py # Passes A–H and S │ │ └── service_query.py # address shift for service queries │ ├── generation/ # MimicGen — same-shape surrogates, no collisions │ ├── storage/ # ShadowMap — AES-256-GCM │ └── reconstruction/ # ResolvePass — exact · component · fuzzy │ ├── main.py # Terminal app: dashboard and commands ├── pipeline.py # App message flow: mask, send, restore ├── config.py # App settings: models, thresholds, paths ├── detection/ generation/ # Wrappers over the package ├── storage/ reconstruction/ # Wrappers over the package ├── chatbot/ │ ├── chat.py # Claude / Gemini / OpenAI / Ollama, sealed history │ └── rag.py # RAGStore — Chroma + sentence-transformers ├── presidio/ # Side-by-side comparison in the app │ ├── bench/ # The benchmark │ ├── arms/ # SS, GLiNER-PII, Presidio (+ Faker, RoBERTa), LLM Guard │ ├── realdata/ # build, inject, label, score, live runs │ ├── perf_arms.py # speed and memory per tool │ └── results/ # every committed number + README of commands │ └── tests/ # pytest, no API key needed
Activate a virtual environment before installing. Installing into the system or base conda Python is the most common cause of "package not found" errors at runtime. Then run surrogateshield doctor: it checks that every detection stage loads before you send anything.
# Clone $ git clone https://github.com/sherwinvishesh/SurrogateShield.git $ cd SurrogateShield # Create and activate a virtual environment ← required $ python -m venv .venv $ source .venv/bin/activate # Windows: .venv\Scripts\activate # App + library (editable) + benchmark dependencies $ pip install -r requirements.txt # Library only, for your own code $ pip install ./python-library $ python -m spacy download en_core_web_lg # Fetch the PIITagger weights now (~565 MB, Hugging Face); # otherwise the first scan downloads them once $ surrogateshield download # Check every stage $ surrogateshield doctor # Set your API key and launch the terminal app $ echo "ANTHROPIC_API_KEY=sk-ant-..." > .env $ ./run.sh
HF_HUB_OFFLINE with nothing cached), it stops with DetectorUnavailable rather than run without them. Use preset="classic", which needs only spaCy and ContextGuard's dslim/distilbert-NER (downloaded from Hugging Face on first use). It leaked 2.5% on the benchmark, still far below GLiNER-PII's 9.1%. To use only the engine in your own code, see Library.
| Provider | Model | Env var |
|---|---|---|
| Claude default | claude-sonnet-4-6 | ANTHROPIC_API_KEY |
| Gemini | gemini-2.5-flash | GEMINI_API_KEY |
| ChatGPT | gpt-4o-mini | OPENAI_API_KEY |
| Local (Ollama) | llama3.2 (configurable) | none — offline |
Each model can be changed without editing code: SURROGATESHIELD_CLAUDE_MODEL, SURROGATESHIELD_GEMINI_MODEL, SURROGATESHIELD_OPENAI_MODEL, LOCAL_LLM_MODEL.
# Interactive dashboard (recommended) $ python main.py $ ./run.sh # Start a new conversation directly $ python main.py chat $ python main.py chat --load <conversation-id> $ python main.py chat --rag # PII detection sandbox — no API calls, no credits $ python main.py pii-finder # Index a document into the RAG store $ python main.py add-doc path/to/document.txt
# List what would be masked (no provider call) $ surrogateshield scan "Call Priya on +1 415 555 0142" --json # Mask: prints the text to send, and the session id on stderr $ surrogateshield mask --preset fast < prompt.txt # Put the originals back in the reply; --close erases the stored map $ surrogateshield unmask -s <session-id> --close < reply.txt # Latency on built-in samples · check models, dependencies, key storage $ surrogateshield bench $ surrogateshield doctor --smoke
No dashboard, just the detection and masking engine as a Python API. The package is self-contained: it imports nothing from the terminal app, which is built on top of it. Use a Session per conversation, or the module functions for a quick script. It is the same engine that leaked 0.8% on real chat text, against 9.1% for GLiNER-PII and 31.6% for Presidio.
# From the repository root $ pip install ./python-library $ python -m spacy download en_core_web_lg # Optional: Rich colour tables for detected PII / surrogates $ pip install "./python-library[display]" # Optional: fetch the PIITagger weights now (else on first use) $ surrogateshield download # Check that every stage loads $ surrogateshield doctor
balanced, needs spaCy's en_core_web_lg and the PIITagger weights, sherwinvishesh/surrogateshield-pii-tagger on Hugging Face (~565 MB, MIT). The weights download once on first use, or with surrogateshield download, and are checked against their SHA-256 pin; a folder of the same name under $SURROGATESHIELD_MODELS is used instead when there is one. If either model is missing or cannot be fetched, mask() raises DetectorUnavailable and sends nothing. On a machine without the tagger weights, use preset="classic".
| Function | Description |
|---|---|
| shield.Session(id, *, config, storage_dir, seed) | Masking state for one conversation. Use it as a context manager; amask / aunmask / ascan for asyncio |
| shield.config(**kwargs) | Preset, storage, pii_off, address mode and display settings for new sessions and the current one |
| shield.scan(text) | Detect only: a list of Detection (text, type, start, end, score, source, masked); as_dict=True for {value: type}. Alias pii_finder |
| shield.mask(text) | Replace detected values with surrogates and store the mapping; returns the text to send |
| shield.mask_result(text) | Like mask, plus the detections, the replacements, and the pii_off values sent as typed |
| shield.unmask(response) | Restore your values in a reply: a string, or an Anthropic, OpenAI or Gemini response object |
| shield.forget(original) | Erase every mapping for one value from the session |
| shield.flush() | End the current session: discard its mappings and its file, if any |
import anthropic import surrogateshield as shield client = anthropic.Anthropic() text = ( "Hi, I'm Priya Raman. Email me at priya.raman@northwind.io or call " "+1 415 555 0142. My order NW-48213-K hasn't arrived at 1847 Alder " "Street, Portland. Can you draft a complaint to Northwind Outfitters?" ) with shield.Session() as s: sanitized = s.mask(text) # → "Hi, I'm Adya Nath. Email me at adya.nath@vance.io or call # +1 213 581 8333. My order VW-02898-Z hasn't arrived at 6237 # James Street, Olympia. Can you draft a complaint to Northwind # Outfitters?" (surrogates differ per run; pass seed= to fix them) response = client.messages.create( model="claude-sonnet-5-5", max_tokens=1024, messages=[{"role": "user", "content": sanitized}], ) # unmask() takes the SDK object directly and puts your values back print(s.unmask(response)) # the letter is signed "Priya Raman" # leaving the block discards the map
The provider receives the surrogates for every value the detector found; the answer you see has your own values back. The company you are complaining to is kept, because it is only mentioned. The same flow works with OpenAI, Gemini and local Ollama models; unmask() detects the response format.
Runs the full pipeline and returns each detection with its offsets, type, score and the stage that found it. It never changes the text or the session's map.
masked=False marks a value kept by pii_offpii_finder alias for data-pipeline readabilityshield.Session().scan("warm up")shield.config(detection="fast"), or SURROGATESHIELD_PRESET in the environment. Benchmark leak and median time per message:
balanced (default) — 0.8%, 47.1 msfast — 0.8%, 38.2 ms, no spaCystrict — 0.2%, 67.1 ms, edits far more harmless textclassic — 2.5%, 29.2 ms, no tagger weights neededThe default is in memory. Give a directory and the map persists across processes, sealed with AES-256-GCM, for web servers and multi-worker setups.
shield.Session("user-42", storage_dir="/var/app/maps")0600flush() or close() deletes the .shadowmap fileunmask() reads Anthropic, OpenAI and Gemini response objects and dicts, and plain strings from local models.
Message · OpenAI ChatCompletion · Gemini responseKeep two histories: one in surrogates for the API, one with your values for display. The session map lives across turns, so a surrogate made in turn 1 still resolves in turn 5. On the benchmark's 60 conversations, SurrogateShield put back 81 of 82 values; Presidio + Faker and GLiNER-PII put back none.
from openai import OpenAI import surrogateshield as shield client = OpenAI() session = shield.Session() api_history, display_history = [], [] # surrogates vs your values def chat(user_input): sanitized = session.mask(user_input) api_history.append({"role": "user", "content": sanitized}) display_history.append({"role": "user", "content": user_input}) response = client.chat.completions.create( model="gpt-4o-mini", messages=api_history, ) raw = response.choices[0].message.content # surrogate text restored = session.unmask(response) # your values api_history.append({"role": "assistant", "content": raw}) display_history.append({"role": "assistant", "content": restored}) return restored chat("My name is Priya Raman and I live at 1847 Alder Street, Portland.") print(chat("What was the address I mentioned earlier?")) # → "1847 Alder Street, Portland", restored from turn 1's map session.close()
# asyncio — the models run in a worker thread async with shield.Session() as s: sanitized = await s.amask(user_text) restored = await s.aunmask(await llm.achat(sanitized)) # Google Gemini — unmask() reads response.text model = genai.GenerativeModel("gemini-2.5-flash") sanitized = shield.mask("My card is 4532015112830366, IP 192.168.1.100.") print(shield.unmask(model.generate_content(sanitized))) shield.flush() # Local / Ollama — unmask() also accepts a plain string sanitized = shield.mask("My phone is +44 7911 123456, postcode SW1A 1AA.") raw_reply = ask_ollama(sanitized) # your own HTTP call print(shield.unmask(raw_reply)) shield.flush()
Each pass only runs on surrogates the previous one did not resolve, so partial matches never corrupt unrelated text.
| Pass | Method | Handles |
|---|---|---|
| 1 | exact replacement | Surrogate appears verbatim in the response — the vast majority of cases |
| 2 | component matching | Multi-word surrogate used partially (the model wrote "Adya" from "Adya Nath") — scoped to unresolved surrogates only |
| 3 | fuzzy · rapidfuzz | partial_ratio ≥ fuzzy_threshold (default 85) — reformatted casing, added punctuation, minor edits |
| Parameter | Default | Effect |
|---|---|---|
| detection | None | A preset name ("fast", "balanced", "strict", "classic"), a DetectionConfig or a dict. None = the environment's choice, else balanced |
| detailed_view | False | Print Rich tables after each call. They show your original values, so it is off by default |
| pii_mem | "temp" | "temp" = in memory; an existing directory = sealed AES-256-GCM files |
| pii_off | [] | Types detected but sent as typed — aliases or raw type strings |
| service | True | Recognise service queries ("pharmacies near…"); drives address_mode="auto" |
| address_mode | "auto" | "auto": shift in a service query, replace otherwise · "shift": always shift the house number · "replace": always a fake address of the same shape |
| address_shift_range | 1 | Largest house-number change in shift mode |
| spacy_model | en_core_web_lg | EntityTrace model |
| context_guard_enabled | False | Run distilbert-NER as well; on in strict and classic |
| entity_trace_high_threshold | 0.90 | spaCy type score at/above which an entity is confirmed |
| entity_trace_low_threshold | 0.70 | spaCy type score at/above which an entity is borderline |
| context_guard_threshold | 0.70 | distilbert score required to confirm a borderline entity |
| entity_trace_fallback_threshold | 0.75 | Promotes a borderline entity when ContextGuard is off |
| fuzzy_threshold | 85 | rapidfuzz partial_ratio (0–100) for pass 3 of unmask() — below 70 not recommended |
| context_guard_model / _device | dslim/distilbert-NER · -1 | ContextGuard model and device (-1 = CPU, ≥ 0 = GPU id) |
| tagger_model / _revision / _device | pii-tagger-dv3s-40k · sha256:f9e58… · -1 | PIITagger: a name, local folder or Hugging Face id; a sha256: pin or a commit; CPU, GPU id or "mps" |
| phone | phone_us · phone_uk · phone_intl |
| postal_code | zip_us · postcode_uk |
| name / names | PERSON |
| location | GPE · LOC |
| org · facility | ORG · FAC |
| username · password | handle · credential |
| bank · license · crypto | us_bank_number · us_driver_license · crypto |
A question like "find a coffee shop near 99 Market Street" would be useless with a random fake address. With address_mode="auto" (default), a service query keeps the street and city and shifts the house number by ±1.
shield.config(service=False) or address_mode="replace" to always replaceWhen one of these combinations appears in a message, the match is logged and attached to the detection result as a warning. It does not change what gets replaced.
| Combination | Risk | Basis |
|---|---|---|
| ZIP + DOB + Gender | high | 87% of US population uniquely identified — Sweeney 2000 |
| Postcode + DOB | high | UK ICO guidance — sufficient for re-identification |
| Name + SSN | high | Enables direct identity theft |
| Name + DOB | high | Standard identity-verification combination worldwide |
| Phone + Name | high | Directly identifies an individual |
| IP Address + Name | high | Enables device-level identification |
| Name + Employer + City | medium | Uniquely identifies in most cities |
| Email + Location | medium | Narrows to a specific named individual |
| Phone + Location | medium | Narrows to a local individual |
| DOB + Location + Employer | medium | Highly specific triple |
| faker | Realistic fake values per type |
| cryptography | AES-256-GCM for the disk shadow map |
| rapidfuzz | Fuzzy reconstruction pass |
| spacy | EntityTrace; the model is a separate download |
| transformers + torch | PIITagger and ContextGuard |
DetectorUnavailable? Run surrogateshield doctor; it names the missing modelshield.Session().scan("warm up")shield.config(detection="fast"): same leak rate on the benchmark, no spaCyfuzzy_threshold toward 75 to recover heavily reformatted values~/.cache/huggingface/ when ContextGuard is onpytest tests python-library/tests covers the package end to end: detection, surrogates, ShadowMap memory and disk modes, the response parser, pii_off, presets, ResolvePass, the CLI and the public API.
The first version of SurrogateShield is described in a preprint on arXiv. The numbers on this page come from the v2 benchmark in bench/results/, not from the preprint. Pick a format and copy — BibTeX is the default.