Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 3 min read

How to Redact PII Before Sending Data to Hosted LLMs

Every time your application sends a prompt to a hosted LLM provider, data leaves your network. If that prompt contains names, email addresses, social security numbers, or account IDs, sensitive customer information is no

Every time your application sends a prompt to a hosted LLM provider, data leaves your network. If that prompt contains names, email addresses, social security numbers, or account IDs, sensitive customer information is now sitting on third-party servers.

Relying solely on model providers' privacy policies isn't a compliance strategy. Security must be handled inside your own application boundary before the first API request is ever dispatched.

Why Static Masking Fails

When developers first approach PII masking, they often reach for simple string replacements:

Input: "Can you update the billing address for Jane Doe at [email protected]?"
Masked: "Can you update the billing address for [REDACTED] at [REDACTED]?"

This approach creates significant operational problems:

  1. Loss of Relational Context: If a prompt contains two different people or accounts, turning both into [REDACTED] destroys the relationships between entities. The LLM can no longer distinguish who did what.
  2. Irreversible Outputs: Because [REDACTED] is non-unique, your system cannot programmatically restore the real values when the model returns a response.

Consistent Token Mapping

A far better approach is reversible tokenization. Replace sensitive items with consistent, entity-aware placeholders such as <CUSTOMER_001> or <EMAIL_001>.

Your backend keeps an isolated, short-lived lookup table that maps each real value to its assigned token. The LLM processes the prompt using the tokens, maintains full logical context, and returns a response containing those same tokens. Before sending the output back to the user, your backend swaps the real data back in.

Here is a practical Python implementation using regex-based pattern matching and a stateful mapping dictionary:

import re

class PIIRedactor:
    def __init__(self):
        self.val_to_token = {}
        self.token_to_val = {}
        self.counters = {}

    def _generate_token(self, value: str, entity_type: str) -> str:
        if value in self.val_to_token:
            return self.val_to_token[value]

        count = self.counters.get(entity_type, 0) + 1
        self.counters[entity_type] = count
        token = f"<{entity_type}_{count:03d}>"

        self.val_to_token[value] = token
        self.token_to_val[token] = value
        return token

    def redact(self, text: str) -> str:
        # Define regex patterns for target PII
        email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
        phone_pattern = r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b'

        text = re.sub(email_pattern, lambda m: self._generate_token(m.group(0), "EMAIL"), text)
        text = re.sub(phone_pattern, lambda m: self._generate_token(m.group(0), "PHONE"), text)
        return text

    def restore(self, text: str) -> str:
        for token, original_val in self.token_to_val.items():
            text = text.replace(token, original_val)
        return text

You can test this flow to verify that entity relationships stay intact:

redactor = PIIRedactor()

raw_user_input = "Contact Alice at [email protected] or Bob at [email protected]."
safe_prompt = redactor.redact(raw_user_input)

print(safe_prompt)
# Output: Contact Alice at <EMAIL_001> or Bob at <EMAIL_002>.

# Simulate sending safe_prompt to an LLM:
llm_response = "I will send an update to <EMAIL_001> first, then follow up with <EMAIL_002>."

final_output = redactor.restore(llm_response)
print(final_output)
# Output: I will send an update to [email protected] first, then follow up with [email protected].

The RAG Pipeline Trap

A major vulnerability in LLM architecture happens inside Retrieval-Augmented Generation (RAG) pipelines.

Teams often set up redaction middleware right at the API gateway to scrub incoming user queries. However, they forget about the context fetched from internal vector databases or search indices. Support tickets, CRM notes, and database records retrieved during search frequently contain unmasked PII.

If you sanitize the user query but inject raw retrieved documents into the system prompt, the PII still leaks directly to the LLM.

To fix this, execute redaction at the prompt assembly stage, right after retrieval:

def assemble_rag_prompt(user_query: str, retrieved_docs: list[str], redactor: PIIRedactor) -> str:
    # 1. Redact the user input
    clean_query = redactor.redact(user_query)

    # 2. Redact retrieved knowledge chunks before prompt injection
    clean_docs = [redactor.redact(doc) for doc in retrieved_docs]

    context_str = "\n".join(clean_docs)

    return f"""
    Context:
    {context_str}

    User Question:
    {clean_query}
    """

By standardizing this flow, neither input queries nor background context can expose sensitive data to external endpoints.

Summary

Security in AI systems should never be an afterthought. By adopting consistent token mapping and enforcing redaction after document retrieval in RAG systems, you protect sensitive enterprise data without compromising model intelligence.

About me

Tanmay builds AI agents and automation for businesses and is open to freelance projects. Invite readers to connect on LinkedIn.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.