Redact PII before it reaches an LLM
Send user messages to ChatGPT, Claude, Gemini or a local model without sending the user's personal data, and still give a personal answer back.
Why redact personal data before calling an LLM?
Prompts you send to a hosted model leave your servers, may be logged by the provider and can end up in your own logs and traces. Redacting first keeps Aadhaar numbers, phone numbers and names out of all of them, which is what India's DPDP Act and most security reviews expect.
How do I redact a prompt and restore the answer?
Call detect() on the prompt, send redacted to the model, then call restore() on the answer with the redactionMap. Keep the map on your server.
import { Piilite } from "piilite";
const shield = new Piilite({ preset: "dpdp" });
const { redacted, redactionMap } = shield.detect(userMessage);
// "Hi, I am [NAME_1], my number is [PHONE_IN_1]. Change my plan."
const answer = await callYourModel(redacted);
// "Sure [NAME_1], I have updated the plan for [PHONE_IN_1]."
const reply = shield.restore(answer, redactionMap);
// "Sure Rahul Sharma, I have updated the plan for 9123456780."How do I mask a RAG question, its passages and the history together?
Use a session. Every text shares one set of placeholders, and once a name is found anywhere, other mentions of it are masked too, even a bare lowercase first name in the question with no clue around it.
const session = shield.session();
const [q, ...context] = session.redactAll([question, ...passages, history]);
// "what did rahul approve?" -> "what did [NAME_1] approve?"
// "Approved by Rahul Sharma" -> "Approved by [NAME_1]"
const answer = await callYourModel(q, context);
const reply = session.restore(answer); // "Rahul Sharma approved ..."Masking a question with 8 passages of about 900 characters and 2 KB of history takes about 8 ms (p95 13 ms) on a 4-core server, and restoring the answer under 1 ms, so it can run on the request thread.
What if the model changes the placeholders?
restore() is fuzzy by default: it also restores placeholders a model rewrote, such as [NAME 1], [name_1], NAME_1 or [ NAME-1 ]. Pass { fuzzy: false } for exact matching only.
Spellings of one value share a placeholder (“rahul sharma” and “Rahul Sharma”, or 9123456780 and +91 91234 56780), and restore uses the best-capitalised spelling. Set matchCase: true to keep spellings apart. If your output may contain words like EMAIL_1 on purpose, use { fuzzy: "brackets" }.
How do I restore placeholders in a streamed answer?
Use restoreStream(). It holds back any text that could be the start of a placeholder until the next chunk arrives, so users never see half of “[NAME_1]”, in any form the model writes it.
for await (const piece of session.restoreStream(modelTextStream)) res.write(piece);
// or push / end yourself
const r = session.createRestoreStream();
onToken((t) => res.write(r.push(t)));
onDone(() => res.end(r.end()));How do I redact streaming LLM output?
Use redactStream() on any async iterable of text chunks. piilite holds back a short tail of text, so a value split across two chunks is never emitted half-redacted.
for await (const piece of shield.redactStream(modelTextStream)) {
process.stdout.write(piece);
}
// manual control
const stream = shield.createStream();
socket.on("data", (chunk) => send(stream.push(chunk)));
socket.on("end", () => send(stream.end()));
// Web Streams (fetch, Deno, edge runtimes)
response.body.pipeThrough(new TextDecoderStream()).pipeThrough(shield.transformStream());How do I redact a whole chat history or tool result?
Use redactObject(). It redacts every string in an object or array and gives the same value the same placeholder everywhere, so the model can still follow the conversation.
const { value, redactionMap } = shield.redactObject(
{ messages, toolResult },
{ skipKeys: ["id", "role"] }
);How do I add PII redaction to an Express API?
Add piiliteMiddleware() after express.json(). It redacts req.body before your handlers run and keeps the originals on req.pii.
import express from "express";
import { piiliteMiddleware } from "piilite/express";
const app = express();
app.use(express.json(), piiliteMiddleware({ preset: "dpdp" }));
app.post("/chat", async (req, res) => {
const answer = await callYourModel(req.body.message); // already redacted
res.json({ answer: req.pii.restore(answer) });
});
// reject requests that contain secrets with HTTP 422
app.use("/logs", piiliteMiddleware({ preset: "secrets", block: true }));How do I warn users before they send personal data?
Use the usePIIDetector React hook to check a message as the user types and show a warning or a redacted preview.
import { usePIIDetector } from "piilite/react";
function ChatInput({ text }) {
const { hasPII, redacted } = usePIIDetector(text);
return hasPII ? <p>This message contains personal data: {redacted}</p> : null;
}Best practices
- Redact model output too before you log or store it.
- Keep the
redactionMapon the server, never in logs, analytics or the client. - Use
maskmode for display only; it keeps the last digits and is not anonymisation. - Use
onDetectto count what was redacted for audits, without storing the values.
Last updated ยท piilite 0.3.0