polanon
English | Polski
Reversible PII masking for LLM calls, Polish-first. Mask personal data before a prompt leaves your network, send only tokens to the model, and put the originals back into its answer, even while it streams. Pure Python: the standard library is the whole core.
Without writing code, with the gateway in Docker. Claude Code, n8n, Open WebUI, LibreChat, Hermes Agent and any other tool that speaks the OpenAI or Anthropic API keep working as they did, and every call is masked before it leaves:
export POLANON_UPSTREAM_KEY=sk-... # your provider's key
export POLANON_GATEWAY_KEY=$(openssl rand -hex 16) # the key your tools will send
docker run --rm -p 127.0.0.1:8787:8787 -e POLANON_UPSTREAM_KEY -e POLANON_GATEWAY_KEY \
ghcr.io/boromat/polanon-gateway:0.4 --upstream https://api.openai.com/v1
Then give the tool http://127.0.0.1:8787/v1 as its base URL and the value of
POLANON_GATEWAY_KEY as its API key. One gateway serves one provider: for Claude Code start
another with --upstream https://api.anthropic.com/v1, an Anthropic key and
-p 127.0.0.1:8788:8787, then run
ANTHROPIC_BASE_URL=http://127.0.0.1:8788 ANTHROPIC_API_KEY=$POLANON_GATEWAY_KEY claude. Every
tool, the gateway without Docker, and what it does with a call are in
the gateway's section.
In Python, in your own code: mask a text, send it, restore the answer.
pip install polanon
from polanon import Anonymizer, default_guards
anonymizer = Anonymizer(default_guards(with_ner=False))
result = anonymizer.anonymize_sync(
"Proszę o korektę faktury dla Jana Kowalskiego, PESEL 50810112354, "
"konto PL61109010140000071219812874, mail jan.kowalski@example.com."
)
print(result.anonymized)
# Proszę o korektę faktury dla <OSOBA_1>, PESEL <PESEL_1>, konto <IBAN_1>, mail <EMAIL_1>.
answer = "Korekta dla <OSOBA_1> (PESEL <PESEL_1>) jest gotowa." # what the model replied
print(Anonymizer.restore(answer, result.mapping))
# Korekta dla Jana Kowalskiego (PESEL 50810112354) jest gotowa.
The model only ever sees <OSOBA_1>. The mapping that turns it back into a name never leaves your
process. anonymize_sync works in scripts, Django and Flask views, Celery tasks and notebooks; in
async code, await anonymizer.anonymize(...) does the same work in a worker thread.
Why another PII library
General-purpose tools are built around English. Polish data needs three things they do not do out of the box:
- Checksums. A PESEL, NIP, REGON, ID card number, IBAN or payment card is validated, not just pattern-matched: the checksum rejects most random digit strings (for a PESEL, together with the birth date, about 98% of them), while a valid number always passes. KRS numbers, which have no public checksum, and passports are recognised next to their label as well. Eleven digits right after the word PESEL are masked even with a typo in them.
- Seven grammatical cases. "Jan Kowalski", "Jana Kowalskiego" and "z Janem Kowalskim" are the same person. Polish first names are recognised in every case, in lowercase and typed without Polish letters, together with the surname that agrees with them, without any language model.
- Polish model labels. Polish spaCy models tag people as
persName, notPERSON. A pipeline configured for English labels finds no names at all, and says nothing about it.
It also reads foreign invoices: EU, UK and Swiss VAT numbers, company register numbers, Bankgiro, Plusgiro and sort codes, international phone numbers, street addresses and postcodes.
How it compares
| polanon | Presidio | pii-veil | piimask | |
|---|---|---|---|---|
| Restores the model's answer | Yes, from stable tokens such as <OSOBA_1>, also while it streams |
Not built in: its deanonymizer decrypts spans at known positions; its docs include a sample that restores an LLM answer | Yes, from stable tokens and a saved mapping | Yes, from stable tokens |
| Polish identifiers with a checksum | PESEL, NIP, REGON, ID card, IBAN, payment cards | PESEL; IBAN and payment cards in general | PESEL, NIP, REGON, IBAN, payment cards; ID card and passport by pattern only | None; IBAN and payment cards in general |
| Polish names in every grammatical case | For listed first names and the surnames that agree with them, without a language model; spaCy adds the rest | With a Polish spaCy model and its persName label mapped |
Not detected | Not detected; its README suggests adding an NER model |
| What the core needs | Nothing beyond the standard library | spaCy, numpy, pydantic and a few more; a language model only for names and places | pii-core and typer | Nothing beyond the standard library |
| On Polish data neither was tuned on (OpenPII, KPWr) | 72% of 5,255 values masked whole with pl_core_news_md, 306 false alarms; 90% of people in real text |
66%, 2,641 false alarms; 90% of people (presidio-analyzer 2.2.366, same model) | Not measured | Not measured |
| On polanon's own sample documents, tuned on | 99% fully masked with pl_core_news_md, 93% with rules alone |
67% with the same model | Not measured | Not measured |
| License | MIT | MIT | Apache-2.0 | MIT |
Compared from each project's own documentation and source on 3 November 2026; measured on 17
November 2026. Only Presidio was run, with the scripts in benchmarks/. polanon's own thirteen
documents are not neutral ground: its author wrote them and tuned its rules on them, and Presidio
had only the Polish model, also for the three invoices from abroad. The Polish rows of ai4privacy's
OpenPII and CLARIN-PL's KPWr are: polanon was never tuned on the parts measured, and on them the
gap narrows to five points and eight times fewer false alarms, with a tie on people, where the same
spaCy model does the work. Presidio wins on random codes written without a label, which it reads
with low-score patterns that also mark product codes and order numbers. Each has its place:
Presidio for many languages, structured data and its Azure integration; pii-veil for Polish
identifiers under Apache-2.0 when names do not matter; piimask for language-neutral identifiers
(e-mail, phone numbers, payment cards, IBAN, IP addresses, URLs) and US social security numbers,
with fake-value, hashing and partial strategies and an encrypted vault. polanon is for Polish text
on its way to a model, where the names in it
and the restored answer matter as much as the numbers.
Install
| You want | Install |
|---|---|
| Identifiers, contacts, secrets, Polish names, companies by legal form | pip install polanon |
| Also places, and names and organisations no rule can see | pip install "polanon[ner]" then python -m spacy download pl_core_news_md |
| The stage-2 judges (a local Ollama model, or a remote one) | pip install "polanon[judge]" |
| Components for Haystack 3 pipelines | pip install "polanon[haystack]" |
| A gateway for tools that use the OpenAI API | pip install "polanon[gateway]" |
| The gateway as a Docker image, with the spaCy model inside | docker pull ghcr.io/boromat/polanon-gateway:0.4 |
Then use default_guards() with the model, or default_guards(with_ner=False) without it.
Another spaCy model is one argument away: default_guards(spacy_model="pl_core_news_lg").
Package names copied from pip work too (pl-core-news-lg). A local model directory can be passed
as a path; it must contain meta.json and config.cfg. Missing packages or model directories are
reported when the guards are built, while the model itself loads on first use.
An installed model package takes priority over a local path with the same name.
From the command line
Text comes from the arguments, from a file with --file, or from standard input. Masked text goes
to stdout and the mapping to stderr, or to a file with --mapping:
polanon --version # print the installed version
polanon "Jan Kowalski, PESEL 50810112354"
polanon --file umowa.txt --ner --mapping mapping.json > masked.txt
cat umowa.txt | polanon --ner > masked.txt 2> mapping.json
polanon --restore --mapping mapping.json --file answer.txt # the model's answer, restored
polanon --json "Jan Kowalski, PESEL 50810112354" # {"text": "...", "mapping": {...}}
--restore puts the originals back into masked text, such as the model's answer, with the mapping
--mapping wrote, a person named in another case included; a token the mapping does not hold
stays as it is. --json writes one JSON object to stdout instead, for a script: the text, and the
mapping unless --mapping takes it.
A non-zero exit status means something went wrong and stderr says what. --file reads the file's
bytes itself and tells UTF-8, UTF-16 (what Windows PowerShell 5.1 writes with >) and cp1250
apart; text it cannot decode for certain is refused rather than masked half-blind. --ner --paranoid masks every name the model finds, also in English prose and code, as
mode="paranoid" does.
On Windows, prefer --file and --mapping to pipes and redirection. Windows PowerShell 5.1
re-encodes text piped into a program as ASCII, so Polish letters arrive as ? and a garbled name
is not recognised, and its 2> wraps stderr in error records. If you do pipe, run
$OutputEncoding = [System.Text.UTF8Encoding]::new($false) first; in cmd.exe, run chcp 65001.
Streaming
A provider streams arbitrary fragments, so <OSOBA_1> can arrive as <OSO and BA_1>. The
restorer holds back anything that could still grow into a token:
restorer = Anonymizer.stream_restorer(result.mapping)
for chunk in stream: # "Dzień dobry <OSO", "BA_1>, PESEL <PESEL", "_1> zweryfikowany."
print(restorer.feed(chunk), end="")
print(restorer.flush())
# Dzień dobry Jana Kowalskiego, PESEL 50810112354 zweryfikowany.
With Claude, GPT or a local model
Mask before the call, restore while the answer streams. With the Anthropic SDK:
import anthropic
from polanon import Anonymizer, default_guards
anonymizer = Anonymizer(default_guards(with_ner=False))
masked = anonymizer.anonymize_sync(question)
restorer = Anonymizer.stream_restorer(masked.mapping)
with anthropic.Anthropic().messages.stream(
model="claude-opus-5-5",
max_tokens=64000,
system="Personal data is replaced by tokens such as <OSOBA_1>. Copy a token exactly as written.",
messages=[{"role": "user", "content": masked.anonymized}],
) as stream:
for text in stream.text_stream:
print(restorer.feed(text), end="")
print(restorer.flush())
Telling the model what the tokens are keeps it from rewriting them. The
examples go further:
openai_chat.py does the same for any OpenAI-compatible endpoint (OpenAI, OpenRouter, Azure, vLLM,
a local Ollama), and anthropic_chat.py holds a conversation whose history keeps masked text only,
so an answer restored for the reader is never sent back in the clear. Both are tested in CI against
the real SDKs, offline.
A chat turn with tools
A turn of a chat with tools sends more than the question: the history, and the result of every tool
the model calls. anonymizer.turn() masks all of it with one mapping, puts the originals back into
the tool arguments and the answer, and refuses instead of sending anything it could not mask:
import json
import anthropic
from polanon import Anonymizer, MaskingUnavailableError, default_guards, token_instructions
anonymizer = Anonymizer(default_guards(with_ner=False))
client = anthropic.Anthropic()
def chat(history: list[dict], clients: list[str]) -> None:
"""One turn. `history` ends with the question; SYSTEM, TOOLS and run_tool are your own."""
try:
turn = anonymizer.turn(known=clients, unknown_blocks="drop")
messages = turn.mask_messages(history)
while True:
restorer = turn.stream_restorer()
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=64000,
system=SYSTEM + "\n\n" + token_instructions("en"),
tools=TOOLS,
messages=messages,
) as stream:
for text in stream.text_stream:
print(restorer.feed(text), end="")
response = stream.get_final_message()
print(restorer.flush())
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
return
results = []
for block in response.content:
if block.type == "tool_use":
result = run_tool(block.name, turn.restore_data(block.input))
masked = json.dumps(turn.mask_data(result, default=str), ensure_ascii=False)
results.append(
{"type": "tool_result", "tool_use_id": block.id, "content": masked}
)
messages.append({"role": "user", "content": results})
except MaskingUnavailableError:
print("Masking is on but not working, so nothing more was sent to the model.")
turn.stream_restorer() puts the originals back as each response streams in, also a token cut
between two events, as in Streaming. The tests run this example as written here
against the real anthropic SDK, offline, so it cannot drift from the library.
A turn or the lower API. Take a turn whenever a model gets a list of messages, with tools or
without: it keeps one mapping for all of them, masks a value found in a later message in the
earlier ones too, and refuses on any failure, all of which you would otherwise write yourself. Call
anonymize_sync(), Anonymizer.restore() and StreamRestorer directly for a single text, such as
a document or a prompt you build yourself, when you need the spans of the result, or when the
stage-2 judge must run, which a turn does not take.
One mapping for the turn. A client in the history, in the question and in a tool result is the
same <FIRMA_1>. To keep the tokens from one turn to the next, start the next one with
anonymizer.turn(mapping=turn.mapping).
What mask_messages masks. Messages in the Anthropic or the OpenAI format: their text, the
input of tool_use, tool results and the arguments of tool_calls, with JSON kept valid and ids
and tool names left alone. A value recognised only in the question is masked where it stood earlier
in the history, unrecognised. A block nothing can mask, such as an image or a model's signed
reasoning, is refused, or left out with unknown_blocks="drop". mask_data masks the strings in a
value; keys and numbers stay as they are, so keep personal data in string values, and an object
such as a date needs default=str.
Values you already know. known= takes what you know is sensitive, such as your clients' names
from the database. They are masked wherever they appear, also when they are on the allowlist.
History kept with the real values. A turn reads a token in its input as its own masked text,
as in a model's answer sent back with the next call. An application that keeps the conversation
with real values and starts a turn per request passes plain_input=True: token-shaped text in its
input, left from an earlier request or typed by a user, is then written [FIRMA_1] and never
restored as whoever this turn gave <FIRMA_1>.
Refusing instead of leaking. Whatever fails while masking raises MaskingUnavailableError, and
nothing half masked comes back. default_guards() raises NerModelUnavailableError, which is one,
when spaCy or the model is missing, and ner_available() tells a settings page whether they are
installed. Once the answer is in, turn.unknown_tokens(answer) lists the tokens the model made up,
and turn.sweep(restored) also looks for personal data the answer added.
Masking for RAG and search indexes
Tokens numbered per call mean nothing outside their conversation: a contract masked for a search
index and a question masked a week later can each call a different person <OSOBA_1>, and the
search finds nothing. Give the anonymizer a secret key and every token is computed instead, from
HMAC-SHA256 of the value under the key: the same in every document, every process and every
question, with no shared state. "Jan Kowalski", "Jana Kowalskiego" and "z Janem Kowalskim" get one
token, and so does a NIP with its dashes or without them.
import os
from polanon import Anonymizer, InMemoryMappingStore, Pseudonyms, default_guards, stored_mapping
key = bytes.fromhex(os.environ["POLANON_KEY"]) # 32 random bytes per company, from a secret store
store = InMemoryMappingStore() # in production, an encrypted table of yours, apart from the index
pseudonyms = Pseudonyms(key, collisions=store.collisions)
anonymizer = Anonymizer(default_guards(with_ner=False), pseudonyms=pseudonyms)
document = anonymizer.index_chunks(
[
"Umowę z Firmą Kot Sp. z o.o. podpisał Jan Kowalski.",
"Pełnomocnikiem Jana Kowalskiego jest Anna Nowak, tel. 600 100 200.",
],
store,
)
for text in document.texts: # tokens only: these go to the embedder and the index
index.add(text, embed(text)) # index and embed are your own
question = anonymizer.mask_query("Kto jest pełnomocnikiem Jana Kowalskiego?", store)
passages = index.search(embed(question.anonymized)) # the question has the passages' tokens
mapping = question.mapping | stored_mapping(store, question.anonymized, *passages)
restorer = Anonymizer.stream_restorer(mapping) # restores the answer, as in Streaming
The tests run this example as written here, with a stand-in index and embedder. Each part:
Nothing in the index names a value. document.texts holds tokens where the values were; what
each token stands for goes to the store. Never copy a mapping into a passage's metadata, which is
stored and searched with it. document.mappings[i] restores passage i exactly as it was written,
"Jana Kowalskiego" in the genitive; keep it with the passage, encrypted, outside the index.
A store of your own. MappingStore has two methods: get(tokens) and add(entries), which
stores only the tokens it does not hold yet, atomically per token, as a unique key on the token
does. It returns what it already holds for the others. Encrypt StoredValue.value, which is the
personal data; its fingerprint names nothing without the key. Keep store.collisions next to it
and pass it to every Pseudonyms: it holds tokens and fingerprints, nothing else.
Which form a name comes back in. One token stands for "Jan Kowalski" and "Jana Kowalskiego". The store keeps the nominative, because the model writes the token in a sentence of its own, and "Umowę podpisał Jana Kowalskiego" would be wrong whichever document came first. A passage restored with its own mapping keeps the case it was written in.
Names the store already holds. A surname on its own, as in "Co podpisał Kowalczyk?", is a name
no rule reads. index_chunks stores the surname of every person whose first name the rules know,
next to the full name, and mask_query and index_chunks look up every run of up to four words in
the store and mask the ones it holds a token for. A question then gets the surname's token, and a
surname masked in one document stays masked in the next. A surname in a case the rules cannot
read, "Koziołowi" or "Kozła" after "Adam Kozieł", is looked up by the nominatives it may come from,
masked as well, and given the surname's token: the store tells "Kozieł" from "Kozioł", which no
rule can. Where it holds both, or where the text or the conversation names another person the
word is a case of, such as "Jan Kozioł", the word keeps the token its own spelling gives. Pass
lookup=False for a store too slow for that.
The key. At least 32 random bytes, one key per company and a scope= per index that must not be
linked to another. Keep it in a secret manager, out of the index, the code and the logs;
Pseudonyms never shows, pickles or copies it. A new key, scope or number of digits changes every
token, so the index has to be built again: store pseudonyms.settings with the index and compare
them at startup. To erase a person, delete the passages holding pseudonyms.token(name, "PERSON"),
and those holding the surname's token where nobody else with that surname is indexed. Deleting the
store's entries alone does not unlink them, since the key turns a guess back into the token.
Collisions. Twelve digits make two values of one type share a token with a chance of about 1 in 20,000 at 10,000 values, and 1 in 200 at 100,000. Wherever two such values meet, in the store or in one text, the one that came second gets four digits more.
Limits. A name the rules cannot decline, such as a rare first name or "Jana Krawca" from "Jan Krawiec", and a company name in another case, "Firmą Kot" beside "Firma Kot", keep a token per form, which costs a missed search but leaks nothing. A word alone in lowercase is never looked up in the store. And one token everywhere is the point and the price: whoever reads many masked passages can tell which of them are about the same person. The threat model says what that means.
With Haystack
pip install "polanon[haystack]" adds components that put the masking into a
Haystack 3 pipeline. The key is read from POLANON_KEY, 32
random bytes in hexadecimal:
from haystack import Pipeline
from haystack.components.preprocessors import DocumentSplitter
from haystack.components.writers import DocumentWriter
from polanon import InMemoryMappingStore
from polanon.integrations.haystack import (
PolanonDocumentMasker,
PolanonQueryMasker,
PolanonRestorer,
PolanonStreamRestorer,
)
mappings = InMemoryMappingStore() # in production, an encrypted table of yours
indexing = Pipeline()
indexing.add_component("mask", PolanonDocumentMasker(store=mappings))
indexing.add_component("split", DocumentSplitter(split_by="period"))
indexing.add_component("embed", document_embedder) # any embedder: it gets masked text
indexing.add_component("write", DocumentWriter(document_store))
indexing.connect("mask", "split")
indexing.connect("split", "embed")
indexing.connect("embed", "write")
asking = Pipeline() # with an embedder, a retriever, a prompt builder and a generator of yours
asking.add_component("mask", PolanonQueryMasker(store=mappings)) # first
asking.add_component("restore", PolanonRestorer(store=mappings)) # after the generator
asking.connect("mask.query", "embed.text")
asking.connect("mask.query", "prompt.query")
asking.connect("retrieve.documents", "restore.documents")
asking.connect("llm.replies", "restore.replies")
asking.connect("mask.mapping", "restore.mapping")
stream = PolanonStreamRestorer(mappings, on_text=lambda text: print(text, end=""))
asking.run({"mask": {"query": question, "stream": stream}, "llm": {"streaming_callback": stream}})
examples/haystack_rag.py
is the whole of it, offline, with Haystack's stand-in embedder and generator, and the tests run it.
examples/haystack_openai.py
is the same with OpenAI's embedder and model: it is paid, so the tests only build it.
Mask first. The document masker comes before the splitter, so a whole document is read and a
company or an address is masked where it stands: cut at full stops first, "Firmą Kot Sp. z o.o."
fell apart and went out unmasked. Passages that come split already are masked together when they
name one source in source_id, parent_id or __parent_id. Split by word, sentence, period or
passage: a splitter that counts characters cuts tokens in two, and a half matches nothing.
Nothing in the document store names a value. The masked documents are new ones: tokens in the
content and in every string of meta, nested keys and the members of sets included. A document's
id is a plain SHA-256 of its text, so every string of meta shaped like one, which is what
splitters write there, points to the masked twin of its document or becomes a keyed fingerprint.
An id Haystack computed is computed again from the masked document; one you chose is masked like
text and kept, so upserts and deleting by id still work. What the tokens stand for goes to the
mapping store only, never into meta. A document with
a blob or an embedding is refused, since both were made from the original. The tests check every
document in the store, and the file it saves, for each original value.
The answer, for the reader. PolanonQueryMasker sends the masked question to the embedder and
the prompt builder, and its mapping to PolanonRestorer, which restores the replies and the
documents found. Its documents are for display only: never write them to a store or send them to a
model. PolanonStreamRestorer restores a streamed answer as the generator's streaming_callback;
with Pipeline.stream(), feed it the chunks instead: stream.feed(chunk.content). Values you know
are sensitive, such as client names, go in at run time, {"mask": {"known": clients}}, so they
never end up in a saved pipeline.
The detectors. Both maskers use the rules alone unless given with_ner=True, and then
spacy_model, mode and ml_filter work as they do in default_guards:
PolanonDocumentMasker(store=mappings, with_ner=True, mode="paranoid").
Saving a pipeline. The key is a Haystack Secret, and a saved pipeline holds the name of its
variable only. A mapping store is saved through its own to_dict, which should say where it
connects and never what it holds; InMemoryMappingStore has none, so a pipeline with it is built
in code. Haystack 3 loads classes from its own modules only, so allow this one and your store's:
Pipeline.loads(text, allowed_modules=["polanon.integrations.haystack", "myapp.vault"]).
Keep content tracing off. With HAYSTACK_CONTENT_TRACING_ENABLED, Haystack records what every
component receives, and the masker receives the originals. A run that fails keeps its inputs in
the error's snapshot, written to disk with HAYSTACK_PIPELINE_SNAPSHOT_SAVE_ENABLED. Both are off
by default.
Haystack's own telemetry is on by default. Haystack reports how its pipelines are used to its
own servers unless HAYSTACK_TELEMETRY_ENABLED=False is set; polanon sends nothing. Where nothing
but the masked calls should leave the machine, set it.
A gateway for any OpenAI-compatible tool
Tools such as Hermes Agent, n8n, Open WebUI or LibreChat talk to a model through the OpenAI API.
polanon-gateway stands between such a tool and the provider, on the machine of whoever runs it:
every message is masked before it leaves, and the answer comes back with the original values,
streamed or not, tool calls included.
pip install "polanon[gateway,ner]"
python -m spacy download pl_core_news_md
polanon-gateway --upstream https://api.openai.com/v1
Then point the tool's base URL at http://127.0.0.1:8787/v1 and keep its API key: the gateway
passes it on to the provider. A local model works the same way, --upstream http://localhost:11434/v1 for Ollama.
Or in Docker, with the spaCy model inside, on Intel and ARM machines alike:
docker run --rm -p 127.0.0.1:8787:8787 -e POLANON_UPSTREAM_KEY -e POLANON_GATEWAY_KEY \
ghcr.io/boromat/polanon-gateway:0.4 --upstream https://api.openai.com/v1
Inside a container the gateway listens on every interface, so it starts only with
POLANON_GATEWAY_KEY, the key every tool then sends as its API key, and needs
POLANON_UPSTREAM_KEY, the provider's key it sends on instead. -p 127.0.0.1:8787:8787
keeps the port on this machine. Every option of polanon-gateway goes after the image's
name. A model on the same machine, such as Ollama, is --upstream http://host.docker.internal:11434/v1, on Linux with --add-host=host.docker.internal:host-gateway.
The image is tagged with the version, such as 0.4.3, the minor version, 0.4, and latest.
| Tool | Where the base URL goes |
|---|---|
| Hermes Agent | base_url of the model or of a named provider in config.yaml |
| n8n | the Base URL of the OpenAI credential |
| Open WebUI | the URL of an OpenAI API connection; a team already on it can start both with deploy/open-webui, and one choosing a chat now has PolGate |
| LibreChat | the baseURL of a custom endpoint in librechat.yaml |
| an app on Anthropic's SDK, Claude Code | base_url, or ANTHROPIC_BASE_URL, as http://127.0.0.1:8787 |
A tool that speaks Anthropic's Messages API needs a gateway of its own, started with
--upstream https://api.anthropic.com/v1; its key, sent as x-api-key or as a bearer token, is
passed on as the OpenAI key is, and a base URL ending in /v1 works for it too.
What it does with a call:
- It serves
/v1/chat/completions, the Responses API,/v1/responses, and Anthropic's Messages API,/v1/messages, streamed or not, with/v1/messages/count_tokens,/v1/embeddingsand/v1/models, and refuses every other endpoint, so nothing it cannot mask leaves as it came. - With the Messages API the system prompt, the messages, the tools and the metadata are masked, and the note about tokens joins the system prompt. A thinking block passes as the model wrote it, from masked text: the provider checks its signature. The last check still searches it.
- With the Responses API the whole conversation comes with every call, as Hermes Agent sends it
with
store: false. A call that leaves it at the provider, withprevious_response_idorconversation, or asks for abackgroundresponse to fetch later, would bring back tokens no one can restore, and is refused. Encrypted reasoning passes as it is: the provider sealed it from masked text. - Every message, tool result and earlier tool call is masked, and so is the prose of the tools and
of an answer format: descriptions, titles and example values. Tool names, types and parameter
names stay, so the tools keep working. A participant's
nameis left out. - An image, a file or audio cannot be masked, so the call is refused;
--drop-unsupportedleaves such content out and sends the rest, and--pass-unsupportedsends it to the provider as it is, unmasked, with a file's name, for an operator who wants the model to see it. - Before anything leaves, the payload is searched once more for every original value, and the call is refused if one is still there. Names from code the masking leaves as they are, such as field names, ids and tools' names, are not searched.
- A note telling the model what the tokens are joins the system message:
--instructions en, ornoneto leave it out. --paranoidmasks every name the spaCy model finds, asmode="paranoid"does. By default what it finds in English prose, code and identifiers is left out, since an agent's prompt, tools and logs are full of English words the Polish model takes for names.--allow NAME, given as many times as needed, and--allow-file PATH, a file with one name per line, leave readable the names the model has to see as they are, such as the assistant's own and the company it speaks for; a person named so stays readable too. Everything else in the prompt is masked as before.--pii-maplets a client that keeps its own records, an audit or a store of mappings, ask for the call's mapping: with"return_pii_map": truein the request, the answer carries"return_pii_map": {"<OSOBA_1>": "Jan Kowalski"}, and a stream carries it in its last event. The provider never sees the field. Without the switch such a request is refused.- It keeps nothing on disk. A tool sends the whole conversation with every call, and each call is
masked and restored on its own. With
POLANON_KEYset to 64 hexadecimal characters, a person keeps one token in every call and in every grammatical case.
By default the gateway masks one call at a time, in its own process: the spaCy model is not
shared safely between threads, and Python runs one thread of a process at a time anyway. With
the default guards 100 KB takes about 3 s to mask, so a second tool waits for the first.
--workers N masks N calls at once, each in a process of its own with its own copy of the model,
on as many cores, while the gateway's own process keeps serving, streaming and restoring; on a
machine with 16 threads four calls at once took as long as one. More workers than cores gain
nothing.
Each worker holds its own spaCy model: with pl_core_news_md about 330 MB for every worker,
while the gateway's own process then loads no model and stays near 55 MB. One process takes
about 340 MB, --workers 2 about 710 MB and --workers 4 about 1.4 GB. In Docker the option goes after the image's name, and a
memory limit such as docker run --memory has to leave room for every worker. The workers load
the model before the gateway accepts calls, and stop with it. A call goes to a worker and comes
back masked, with its mapping, through a pipe on the same machine, and the worker forgets the
values once the call is masked. Each worker reads POLANON_KEY from the environment it inherits,
so stable tokens are the same whichever worker masked a call. A worker that stops, killed for
lack of memory say, fails only the call it was masking, which may be what took the memory: it is
refused with a 503 and nothing is sent, the error OpenAI's and Anthropic's SDKs send again. A new
worker takes its place at once, and the calls waiting for a worker, or sent to one that stopped
before it began them, go to the others or to the new one. Ctrl+C, Ctrl+Break and the SIGTERM
systemd sends every process of a service reach the workers too: they ignore them, and the
gateway finishes the calls it is masking before it stops them.
Keys stay with whoever runs the gateway, and come from the environment only. By default the
tool's own key is passed on; POLANON_UPSTREAM_KEY sends another one instead, as a bearer
token or, to Anthropic, as x-api-key. The gateway listens on 127.0.0.1. To reach it from
another machine, set --host and POLANON_GATEWAY_KEY, which every client must then send,
as a bearer token or as x-api-key: without the key it refuses to start. The log names the path, the
status, the time and how many values of each type were masked, never a value.
There is no hosted service: the gateway runs where it is installed, and whoever runs it answers for that machine, its keys and the provider the calls go to. The threat model says what the gateway protects and what it does not.
What it detects
Checksum-validated Polish identifiers (PESEL, NIP, REGON, ID card, IBAN, payment cards), KRS numbers
next to their label, e-mail addresses and phone numbers, street addresses, postcodes and the town
after one, links to a person's profile (LinkedIn, GitHub, GitHub Pages, GitLab, social media) up to the handle, IPv4
and IPv6, MAC addresses, vehicle registrations after their label ("nr rej."), VINs, passport
numbers, driving licence numbers after their label, birth dates, API keys, tokens and passwords, Polish first names with their surnames, and
company names anchored on a legal form ("Sp. z o.o.", "S.A.", "Ltd", "GmbH"). Once a person or a
profile link is masked, the surname or the handle alone is masked wherever it appears in the same
text: "Kowalski" after "Jan Kowalski", in another case too, "Lisowi" after "Katarzyna Lis",
"Dudzie" after "Anna Duda" and "Koziołowi" or "Kozła" after "Adam Kozieł", and "jkowalski" in a
JSON field after "github.com/jkowalski". A case whose stem changes, "Kozła" or "Dudzie", is
masked as a whole word where its capital tells a name: inside a sentence and not in a place's
name, so "Zimą jest zimno" and "w Zielonej Górze" stay after "Jan Zima" and "Michał Góra".
With the ner extra, a spaCy model adds the places outside an address or a form field and the
names nothing else marks. An optional second stage lets a small local model review the masked
text for what still identifies someone
by context. Other dates are recognised too, but left readable unless you ask for them.
Text copied from PDFs, Word or macOS is read as a person would read it: letters written as a base letter plus an accent, no-break spaces and en dashes inside numbers, and invisible zero-width characters do not hide a value. The mapping keeps each value as it was first written.
On the annotated sample documents in the repository, the rules alone fully mask 93% of the
values and the rules with pl_core_news_md mask 99%, with nothing left half-masked. Thirteen short
documents are a regression check, not a research benchmark: see the
benchmark notes for what is
missed and why, and for Presidio on them with the same model: 67% fully masked, 77% at its
most lenient. Eight invented calls of an AI agent, with its English prompt,
its tools and their JSON, code, logs, a lease and mail in three languages, measure what an
agent's traffic costs: with pl_core_news_md, 2 of the 250 marked occurrences reach the model,
and 5 of 316 uses of a token hide nothing, a word the model could not read. The model's answers
to them come back with every token restored, as text, as a response and as a stream, and 39 of
their 40 lines read exactly as a person would write them.
Worth knowing
Tokens are stable per conversation, not global, unless you give a key, as for a search index. Pass the mapping from the latest result to the next call: the same value keeps the same token, and a token is never reused for another value. The mapping you pass in is read, not changed, so keep the one each result returns:
mapping = result.mapping
second = anonymizer.anonymize_sync("Ten sam PESEL 50810112354", mapping)
second.anonymized # "Ten sam PESEL <PESEL_1>"
mapping = second.mapping # everything so far, for the next turn
A token restores the form it replaced, unless the model names a case. Masking happens on the
text as written, so a name masked in the genitive comes back in the genitive. The model may write
the case its own sentence needs after a colon, and a person's name comes back declined:
Szanowny Panie <OSOBA_1:wołacz> gives "Szanowny Panie Janie Kowalski" where the text said "Jana
Kowalskiego". token_instructions("pl") asks for it, and every restore understands it, streams and
the gateway included. Declined are names of one or two words the rules read for sure: a listed
first name and a surname such as Kowalski, Nowak, Bednarek, Mickiewicz or Duda. A surname alone
that may be a man's or a woman's, a foreign name, a company and a place come back as written, and
the case is dropped. The other cases of a person who already has a token keep the person's
number and carry their case: after "Jan Kowalski", "Janowi Kowalskiemu" goes out as
<OSOBA_1:celownik>, so the model sees one person, and restoring declines the name back into
exactly the form the text wrote. A form that declining does not give back letter for letter, such
as one in capitals, keeps a token of its own, and a stable token from a key carries no case.
CASED_TOKEN_PATTERN matches a token with a case or without. Spellings that differ only in letter
case, in the kind of whitespace (a no-break space, a line break, a run of spaces) or in invisible
characters are the same value, and so are an identifier's groups written apart or together: they
share its token, and restore writes the spelling seen first. Passwords and custom types are the
exception, since two passwords that differ in case are two passwords, and a password never shares
a token with a name that reads alike. A one-word name found in all lowercase keeps a token of its
own too, for the reason below.
Every occurrence of a masked value is masked, also where no detector would recognise it on its own: as written, in capitals, across a line break, with a zero-width character in it, with Cyrillic or Greek letters that look Latin in it, with its groups spaced differently, and around whatever a detector found inside it. Three exceptions keep ordinary words readable. A capitalised one-word name is not matched in all lowercase, because Zima, Kot and Wilk are surnames and "zima" is winter; identifiers such as a VIN or an e-mail address are matched in any case. A value shorter than four letters is not matched inside a longer word, so "Jan" leaves "Janusz" alone; a surname of three letters is matched with a case ending glued on, "Lisowi" or "Lisem" for Lis, and "Lista" stays. A number shorter than six digits, such as a PIN, is not matched inside a longer number, a date, a time or an amount: "15.04.2025", "2024-2025", "2025,50" and "20250" stay readable when the PIN is 2025, while "w 2025 roku" and "PIN/PUK 2025/36912874" do not.
A token you write stays yours. A placeholder such as <PESEL_1> in your own text is never handed
to real data. It joins the mapping as standing for itself, so the reservation holds in later turns
too.
The mapping is the sensitive half. result.anonymized holds a token for everything the
detectors found, and only what they missed in the clear; result.mapping is the key that undoes
it. Store the mapping the way you would store the original document.
Replaying a conversation? mask_known_values(text, mapping) masks every value a mapping already
holds in text that was masked earlier, such as history sent again after a new value got its token.
The same call checks a payload before it leaves: mask_known_values(payload, mapping) == payload
means no value the mapping holds is left where the library would mask it. For a whole request
body, leaked_tokens(body, mapping) names the tokens whose values would still go out, never the
values, so the result may be logged; the gateway runs it on every call.
Words of your own. In-house names no rule can know, such as a project codename or a client, go on a denylist and are masked wherever they appear, in any case and across line breaks:
guards = default_guards(denylist=["Projekt Wichura", "Zakład Nowak"], with_ner=False)
A company listed with its legal form, "Siłownia Testowa Sp. z o.o.", is found without it too when two words or more are left, written as on the list or in capitals, and a listed number of nine digits or more, such as a NIP, however its digits are grouped.
Checking the answer. After restoring, anonymizer.sweep(restored, mapping) reports tokens the
model invented and personal data its answer added: report.is_clean, or report.unknown_tokens
and report.new_spans to look at.
Choosing what to mask
Anonymizer(guards) masks DEFAULT_ENABLED: every type in ENTITY_TYPES except DATE, because a
date rarely identifies anyone and masking every deadline leaves the model unable to answer. A birth
date does identify someone, so a date after "ur.", "data urodzenia", "DOB" or "geb." is its own
type, BIRTH_DATE, and stays masked. Pass enabled to choose for yourself:
from polanon import DEFAULT_ENABLED, ENTITY_TYPES, Anonymizer, default_guards
guards = default_guards(with_ner=False)
Anonymizer(guards, enabled=DEFAULT_ENABLED | {"DATE"}) # dates too
Anonymizer(guards, enabled={"PESEL", "NIP", "IBAN"}) # identifiers only
list(ENTITY_TYPES) # every name you can use
A name that is neither built in nor declared in a guard's entity_types raises ValueError, so a
typo such as "PERSONS" cannot quietly switch masking off.
With the spaCy model, mode sets how much of what it reads as a name is masked. The Polish model
takes English words for names, and an AI agent's prompt, tools, code and logs are full of them:
"return", "message" or a button's "Uncheck" become tokens the model cannot read. The default,
mode="normal", leaves out what the model finds in English prose, in code and identifiers, and a
place written in lowercase; the price is a name opening an English sentence, or "jadę do gdyni",
which go out as written. mode="paranoid" masks all of it:
guards = default_guards(mode="paranoid")
On the calls of an AI agent in benchmarks/, "normal" lets 2 of 250 marked occurrences through,
and 2% of the token uses hide nothing; "paranoid" lets 1 through, a name in Cyrillic no guard
finds, and more than half of the token uses hide nothing. The rules are the same in both, so without the model
the mode changes nothing.
In the normal mode, an ML filter drops more of what the model reads as a name: a logistic
regression that weighs the span, its words and the words around it, their vectors and what the
rules found there, fitted on public Polish data. It masks the same values whole on every
benchmark and leaves about a quarter fewer spans that hide nothing: on a part of OpenPII held out
until it was done, 400 instead of 539. It adds about half a millisecond to a text the model takes
twelve to read, and it learns nothing from the texts it masks: it ships as fixed weights. Its
weights read the vectors of pl_core_news_md, so with another spaCy model the hand-written
filters decide alone. It is on by default; the
benchmark notes
tell how it was fitted and measured, and this leaves the decision to the hand-written filters:
guards = default_guards(ml_filter=False)
A second opinion: the judge
Rules and a language model miss what identifies someone only by context: "the finance director of the only steelworks in town". A judge is a small model that reads the masked text after stage 1 and flags such fragments. Run it locally with Ollama, so the review never leaves your network:
import asyncio
from polanon import Anonymizer, JudgeError, default_guards
from polanon.judge import OllamaJudge
anonymizer = Anonymizer(
default_guards(),
judge=OllamaJudge(model="qwen2.5:1.5b"),
judge_fallback="block", # refuse to go on if the judge is down
)
async def main(text: str) -> None:
try:
result = await anonymizer.anonymize(text)
except JudgeError:
... # the judge was down, and "block" means nothing goes out
asyncio.run(main("..."))
It needs pip install "polanon[ner,judge]", the spaCy model, a running Ollama and
ollama pull qwen2.5:1.5b. With judge_fallback="send_stage1" the call goes on when the judge
is down, and result.judge_failed says that stage 1 went out alone.
Judges are asynchronous, so anonymize_sync refuses an anonymizer that has one. RemoteJudge asks an
OpenAI-compatible endpoint instead; the masked text then leaves your network, which makes it a
testing aid rather than a privacy control.
Names that should stay readable
A language model flags "Facebook" or "Google Ads" as an organisation, which masks the very thing a question is about. Pass an allowlist and those detections are dropped before tokens are assigned:
from polanon import WELL_KNOWN_NAMES, Allowlist, Anonymizer, default_guards
anonymizer = Anonymizer(default_guards(), allowlist=Allowlist(WELL_KNOWN_NAMES))
WELL_KNOWN_NAMES holds platforms and office tools, public institutions and filing programs
such as ZUS, Płatnik, NFZ and KSeF, and the models and tools an AI agent names, such as
OpenRouter, DeepSeek and Home Assistant with its "HA", and hardware such as Dell or Roborock.
A one-word name also matches its Polish case forms
("Facebooku", "Canvie", "ZUS-ie"). Only detections of names are dropped, and only when every word in them is on the list; identifiers, the denylist and
values a conversation has already masked stay masked.
The pieces
| Module | What it is for |
|---|---|
guards/ |
deterministic detectors. Each returns Spans in original-text coordinates |
pipeline.py |
runs the guards in a thread, resolves overlaps, assigns stable tokens |
policy.py |
the entity taxonomy and the token naming (<OSOBA_1>, <PESEL_1>) |
judge/ |
the optional second stage: a model reviews the masked text for what still identifies |
stream_restore.py |
puts originals back into a streamed reply without splitting a token |
turn.py |
masks everything one call to a model sends, with one mapping, and restores what it gets back |
pseudonyms.py |
computes stable tokens from a secret key, the same in every document and process |
index.py |
masks documents and questions for a search index, with the store of what tokens hide |
integrations/haystack.py |
Haystack components that mask documents and questions and restore answers |
gateway/ |
a gateway compatible with the OpenAI API, run on the operator's own machine |
output_sweep.py |
flags invented tokens and personal data the answer introduced |
Adding a detector
Subclass Guard, return spans in original-text coordinates and respect the enabled set. A type of
your own goes in entity_types, which turns it on by default; it becomes the label of its tokens,
so it is written in uppercase letters and underscores:
import re
from polanon import Anonymizer, Guard, Span, default_guards
class EmployeeIdGuard(Guard):
name = "employee_id"
entity_types = frozenset({"EMPLOYEE_ID"})
def detect(self, text: str, enabled: set[str]) -> list[Span]:
if "EMPLOYEE_ID" not in enabled:
return []
return [
Span(m.start(), m.end(), "EMPLOYEE_ID", 1.0, self.name)
for m in re.finditer(r"\bEMP-\d{5}\b", text)
]
anonymizer = Anonymizer([*default_guards(with_ner=False), EmployeeIdGuard()])
anonymizer.anonymize_sync("Wniosek EMP-11111").anonymized # "Wniosek <EMPLOYEE_ID_1>"
The score decides who wins where detections overlap: 1.0 for a value a checksum, a label or an
official format vouches for, 0.85 for a statistical guess; the judge's findings score 0.5. A Polish
name with its surname scores 0.9 and a first name alone 0.8, so a guess of a place wins over it. A
secret is masked whole, with whatever was detected inside it. A span outside the text, a type
spelled any other way, or one spelled like a built-in token label (OSOBA, DATA) raises
ValueError naming your guard.
Before you rely on it
Masking is pseudonymisation, not anonymisation in the legal sense, and no detector catches everything. The threat model says what is covered, what is not, and what stays your application's job, starting with keeping the mapping safe.
polanon was built as the masking engine of PolGate, a self-hosted hub that lets a team use Claude or GPT on real documents without sending personal data to the provider. The library knows nothing about it, with no HTTP, no database and no settings, and a test fails if it ever starts to.
Used by
PolGate is a self-hosted company chat for Claude and GPT built on polanon: every message and uploaded document is masked on the server before it reaches the model, and the answer streams back with the originals in place. It adds what a team needs around the library: an encrypted vault for the mapping, retention that deletes, an audit log of types and counts, and an admin panel for the policy, including the allowlist and denylist.
PolCV writes CVs for Polish job postings and can mask the candidate's name, contact details and company names with polanon before any text reaches the model, then put them back into the answer. It adds a guard of its own for what the profile already knows, such as a LinkedIn link with the name in it, as Adding a detector describes. polanon stays optional there: the app installs it on request, talks to it through a small JSON-lines bridge, and sends nothing at all while masking is on but polanon is not working.
Written about
- unknowNews, Jakub Mrugalski's newsletter, 13 November 2026: "polanon - zamaskuj polskie dane osobowe przed wysłaniem ich do LLM-a".
- blog.prokulski.science, Łukasz Prokulski's weekly review, 16 November 2026: how polanon masks PESEL, NIP and IBAN reversibly, names in every case, before a text reaches a language model.
Contributing
Bug reports, missed values and new detectors are welcome: see CONTRIBUTING.md. A way to get an original value past the masking is a security report, made privately as SECURITY.md describes.
MIT licensed.
Metadata
Release files for polanon 0.4.3
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 |
|---|---|---|---|---|
| polanon-0.4.3.tar.gz | 567.2 kB | With provenance | Details for polanon-0.4.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| polanon-0.4.3-py3-none-any.whl | Python 3 | none | any | Details for polanon-0.4.3-py3-none-any.whl |
Total release size: 826.0 kB
Release files / polanon-0.4.3.tar.gz
| Download URL | polanon-0.4.3.tar.gz |
|---|---|
| Size | 567.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
bb5b8487f988313c4d2491dd8ed13b9b25382acb24d883331a3e3a55e454a530
|
|
BLAKE2b-256 checksum How to use checksums |
05cdbd698bdecf485538f327fa82facbbc5833f8f14c788c0885d623550c0a12
|
| 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 22, 2026.
Transparency logRelease files / polanon-0.4.3-py3-none-any.whl
| Download URL | polanon-0.4.3-py3-none-any.whl |
|---|---|
| Size | 258.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
1bf6910a93991f1c3f7234179ab3950660aa75747d242e76da251c36a1078e86
|
|
BLAKE2b-256 checksum How to use checksums |
19ef136092a6fe7fd1a70899b66a1d20a774726f1dba6492192dbcab8e66d029
|
| 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 22, 2026.
Transparency logSecurity for polanon 0.4.3
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 polanon-0.4.3.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 22, 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.