惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

MongoDB | Blog
MongoDB | Blog
AI
AI
B
Blog RSS Feed
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
Threatpost
I
Intezer
P
Proofpoint News Feed
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Scott Helme
Scott Helme
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Threat Research - Cisco Blogs
Google DeepMind News
Google DeepMind News
GbyAI
GbyAI
H
Hackread – Cybersecurity News, Data Breaches, AI and More
S
Schneier on Security
Webroot Blog
Webroot Blog
Recorded Future
Recorded Future
aimingoo的专栏
aimingoo的专栏
L
Lohrmann on Cybersecurity
Simon Willison's Weblog
Simon Willison's Weblog
MyScale Blog
MyScale Blog
Project Zero
Project Zero
L
LangChain Blog
B
Blog
D
DataBreaches.Net
Microsoft Security Blog
Microsoft Security Blog
F
Fortinet All Blogs
美团技术团队
Engineering at Meta
Engineering at Meta
Cisco Talos Blog
Cisco Talos Blog
D
Docker
WordPress大学
WordPress大学
人人都是产品经理
人人都是产品经理
S
Security Affairs
Attack and Defense Labs
Attack and Defense Labs
N
News | PayPal Newsroom
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
量子位
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
W
WeLiveSecurity
V2EX - 技术
V2EX - 技术
TaoSecurity Blog
TaoSecurity Blog
博客园 - Franky
P
Proofpoint News Feed
Jina AI
Jina AI
Google DeepMind News
Google DeepMind News
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
雷峰网
雷峰网
The Hacker News
The Hacker News
G
GRAHAM CLULEY

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Presidio as an LLM Guardrail
Brian Spann · 2026-06-12 · via DEV Community

Every previous part of this series has been building toward this one. You can detect PII. You can anonymize it with the right operator for each entity type. You can build custom recognizers for your organization's specific data patterns. Now we put it all together into the architecture that matters most in 2026: a PII guardrail that sits between your users and your LLM.

The problem is straightforward. Users type personal information into prompts. Support agents paste customer records into chat interfaces. Developers pipe production data into debugging workflows. All of that PII flows to your model provider's API endpoint. Even if the provider says they don't train on your data, the information still transits their infrastructure. For regulated industries, that transit itself can be a compliance violation.

The PII Proxy Pattern

The solution is a proxy that intercepts every LLM request, scrubs PII from the prompt, forwards the clean version, and then restores the PII in the response.

The flow looks like this:

  1. User sends a prompt containing PII
  2. Proxy detects and encrypts all PII entities
  3. Clean prompt (with encrypted tokens) goes to the LLM
  4. LLM responds using the encrypted tokens
  5. Proxy decrypts the tokens in the response, restoring original PII
  6. User sees a response with their real data intact

The user never notices the proxy exists. The LLM never sees the real PII. The encryption key stays on your infrastructure.

Building the Proxy in Python

from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine, DeanonymizeEngine
from presidio_anonymizer.entities import OperatorConfig
import openai

# Initialize Presidio engines
analyzer = AnalyzerEngine()
anonymizer = AnonymizerEngine()
deanonymizer = DeanonymizeEngine()

ENCRYPTION_KEY = "WmZq4t7w!z%C*F-J"  # In production, pull from Key Vault

def scrub_prompt(text: str) -> tuple:
    """Detect and encrypt PII in the prompt."""
    results = analyzer.analyze(text=text, language="en")

    if not results:
        return text, None

    anonymized = anonymizer.anonymize(
        text=text,
        analyzer_results=results,
        operators={
            "DEFAULT": OperatorConfig("encrypt", {"key": ENCRYPTION_KEY})
        }
    )

    return anonymized.text, anonymized.items

def restore_response(text: str, items: list) -> str:
    """Decrypt PII tokens in the LLM response."""
    if not items:
        return text

    deanonymized = deanonymizer.deanonymize(
        text=text,
        entities=items,
        operators={
            "DEFAULT": OperatorConfig("decrypt", {"key": ENCRYPTION_KEY})
        }
    )

    return deanonymized.text

def chat_with_guardrail(user_message: str) -> str:
    """Send a message to the LLM with PII protection."""
    # Step 1: Scrub
    clean_prompt, pii_items = scrub_prompt(user_message)

    # Step 2: Send to LLM
    client = openai.AzureOpenAI(
        azure_endpoint="https://your-endpoint.openai.azure.com/",
        api_key="your-api-key",
        api_version="2024-02-01"
    )

    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": clean_prompt}]
    )

    llm_response = response.choices[0].message.content

    # Step 3: Restore
    final_response = restore_response(llm_response, pii_items)

    return final_response

Test it:

user_input = """
Summarize this customer case: John Smith (john.smith@acme.com, 
SSN 123-45-6789) reported unauthorized charges on his Visa 
ending 4242. He can be reached at 206-555-0147.
"""

response = chat_with_guardrail(user_input)
print(response)

What the LLM sees: encrypted tokens where the PII was. What the user sees: a response with their real customer data. The LLM processes the request without ever handling the actual PII.

Moving the Guardrail into Azure API Management

The Python proxy works, but it lives inside one application. Every team that wants the same protection has to wire in the same code and keep it current. A guardrail belongs at the edge, where every model call already passes through. On Azure, that edge is API Management.

Put APIM in front of Azure OpenAI and point your applications at the APIM endpoint instead of the model endpoint. Now APIM is the one place that sees every prompt and every completion. An inbound policy scrubs PII out of the prompt before it reaches the model. An outbound policy restores it on the way back, so the caller still gets their real values. You can run either direction on its own, or both.

The flow with APIM:

  1. App calls the APIM endpoint with a prompt containing PII
  2. Inbound policy sends the prompt to Presidio, which encrypts the PII entities
  3. APIM stashes the entity map in a context variable and forwards the scrubbed prompt to Azure OpenAI
  4. Azure OpenAI responds, echoing back the encrypted tokens
  5. Outbound policy sends the response plus the saved entity map to Presidio to decrypt
  6. APIM returns the restored response to the app

The model never sees real PII. The encryption key and the entity map never leave your APIM instance and its backend. No application code changes.

In this setup Presidio sits behind two small endpoints, /deidentify and /reidentify, that wrap the analyzer and anonymizer (a thin container that encrypts on the way in, decrypts on the way out, with the key pulled from Key Vault). The APIM policy calls them with send-request:

<policies>
  <inbound>
    <base />
    <!-- Pull the user's prompt out of the chat completion body -->
    <set-variable name="userPrompt"
      value="@(context.Request.Body.As<JObject>(preserveContent: true)["messages"].Last["content"].ToString())" />

    <!-- De-identify: send the prompt to Presidio before the model sees it -->
    <send-request mode="new" response-variable-name="deidentified" timeout="10">
      <set-url>https://presidio.internal/deidentify</set-url>
      <set-method>POST</set-method>
      <set-header name="Content-Type" exists-action="override">
        <value>application/json</value>
      </set-header>
      <set-body>@(new JObject(new JProperty("text", (string)context.Variables["userPrompt"])).ToString())</set-body>
    </send-request>

    <!-- Save the entity map so the outbound step can re-identify -->
    <set-variable name="entityMap"
      value="@(((IResponse)context.Variables["deidentified"]).Body.As<JObject>()["entities"].ToString())" />

    <!-- Swap the scrubbed prompt back into the request before it hits the model -->
    <set-body>@{
      var body = context.Request.Body.As<JObject>();
      var clean = ((IResponse)context.Variables["deidentified"]).Body.As<JObject>()["text"].ToString();
      body["messages"].Last["content"] = clean;
      return body.ToString();
    }</set-body>
  </inbound>

  <backend>
    <base />
  </backend>

  <outbound>
    <base />
    <!-- Re-identify: decrypt the PII back into the model's response -->
    <send-request mode="new" response-variable-name="reidentified" timeout="10">
      <set-url>https://presidio.internal/reidentify</set-url>
      <set-method>POST</set-method>
      <set-header name="Content-Type" exists-action="override">
        <value>application/json</value>
      </set-header>
      <set-body>@{
        var resp = context.Response.Body.As<JObject>(preserveContent: true);
        var content = resp["choices"][0]["message"]["content"].ToString();
        return new JObject(
          new JProperty("text", content),
          new JProperty("entities", JArray.Parse((string)context.Variables["entityMap"]))
        ).ToString();
      }</set-body>
    </send-request>

    <set-body>@{
      var resp = context.Response.Body.As<JObject>();
      var restored = ((IResponse)context.Variables["reidentified"]).Body.As<JObject>()["text"].ToString();
      resp["choices"][0]["message"]["content"] = restored;
      return resp.ToString();
    }</set-body>
  </outbound>

  <on-error>
    <base />
  </on-error>
</policies>

With this policy in place, every application pointed at the APIM endpoint gets PII protection without changing a line of its own code. The inbound and outbound blocks are independent: scrub on the way in only, restore on the way out only, or both, depending on whether you need the real values back in the response.

Two decisions shape the setup:

Reversibility. The policy above uses Presidio's encrypt operator so the outbound step can decrypt. If you only need to keep PII away from the model and never need it back, switch the wrapper to replace and drop the outbound policy. It's simpler and there's no key to manage.

Where Presidio runs. The send-request calls point at an internal Presidio endpoint. Keep it on the same VNet as APIM so prompts never touch the public internet. The next section covers those deployment options.

Deploying on Azure

For production, you need Presidio running as a service, not embedded in your application code. Here are the deployment options on Azure, from the quickest to stand up to the most production-ready.

Azure App Service

The fastest path to production. Deploy the Presidio Docker containers to App Service with minimal configuration.

# Create a resource group
az group create --name rg-presidio --location eastus

# Create an App Service plan
az appservice plan create \
  --name presidio-plan \
  --resource-group rg-presidio \
  --is-linux \
  --sku B2

# Deploy the analyzer
az webapp create \
  --name presidio-analyzer-prod \
  --resource-group rg-presidio \
  --plan presidio-plan \
  --deployment-container-image-name mcr.microsoft.com/presidio-analyzer:latest

# Deploy the anonymizer
az webapp create \
  --name presidio-anonymizer-prod \
  --resource-group rg-presidio \
  --plan presidio-plan \
  --deployment-container-image-name mcr.microsoft.com/presidio-anonymizer:latest

Azure Container Apps

For more control over scaling, networking, and multi-container deployments:

# Create an ACA environment
az containerapp env create \
  --name presidio-env \
  --resource-group rg-presidio \
  --location eastus

# Deploy analyzer
az containerapp create \
  --name presidio-analyzer \
  --resource-group rg-presidio \
  --environment presidio-env \
  --image mcr.microsoft.com/presidio-analyzer:latest \
  --target-port 3000 \
  --ingress internal \
  --min-replicas 1 \
  --max-replicas 10

# Deploy anonymizer
az containerapp create \
  --name presidio-anonymizer \
  --resource-group rg-presidio \
  --environment presidio-env \
  --image mcr.microsoft.com/presidio-anonymizer:latest \
  --target-port 3000 \
  --ingress internal \
  --min-replicas 1 \
  --max-replicas 10

Using --ingress internal means the Presidio services aren't exposed to the internet. Only other services in the same ACA environment (or VNet) can reach them. Your /deidentify and /reidentify wrapper sits in the same environment and calls the analyzer and anonymizer over the internal network, and APIM calls the wrapper the same way.

Kubernetes

For enterprise deployments with existing AKS clusters, Presidio publishes Helm charts. The setup is more involved but gives you full control over resource limits, HPA scaling, pod affinity, and network policies.

Production Hardening

Logging and Monitoring

Log every detection for audit trails, but never log the actual PII values. Log the entity types, confidence scores, and positions.

import logging

logger = logging.getLogger("presidio-guardrail")

def scrub_with_logging(text: str, request_id: str) -> tuple:
    results = analyzer.analyze(text=text, language="en")

    # Log detection summary (not the actual PII)
    for r in results:
        logger.info(
            f"request={request_id} "
            f"entity_type={r.entity_type} "
            f"score={r.score:.2f} "
            f"start={r.start} end={r.end}"
        )

    logger.info(f"request={request_id} total_entities={len(results)}")

    anonymized = anonymizer.anonymize(
        text=text,
        analyzer_results=results,
        operators={"DEFAULT": OperatorConfig("encrypt", {"key": ENCRYPTION_KEY})}
    )

    return anonymized.text, anonymized.items

False Positive Handling

Presidio will occasionally flag non-PII as PII. A city name like "Jordan" might be detected as a person name. A product SKU might match a phone number pattern. For production systems, build a feedback mechanism:

# Maintain an allow list of known false positives
FALSE_POSITIVE_ALLOWLIST = {
    "PERSON": ["Jordan", "Phoenix", "Austin"],  # Cities that are also names
    "PHONE_NUMBER": ["555-0100"],  # Known test number
}

def filter_false_positives(text: str, results: list) -> list:
    filtered = []
    for r in results:
        value = text[r.start:r.end].strip()
        allowlist = FALSE_POSITIVE_ALLOWLIST.get(r.entity_type, [])
        if value not in allowlist:
            filtered.append(r)
    return filtered

Performance Considerations

Presidio's analyzer is CPU-intensive, especially with the large spaCy model. For high-throughput workloads:

Keep the analyzer engine warm. Initializing AnalyzerEngine() loads the NLP model, which takes a few seconds. Do it once at startup, not per request.

Set a score threshold. Processing low-confidence detections wastes CPU cycles and increases false positives. Start with 0.5 and adjust based on your accuracy requirements.

Use the right NLP model size. en_core_web_lg is more accurate but slower. en_core_web_sm is faster but misses more entities. Profile your specific workload to find the right tradeoff.

Cache recognizer results for repeated text. If the same support template gets processed thousands of times, cache the detection results and only run the anonymizer.

When the guardrail runs inside APIM, two more things matter. Set a sane timeout on the send-request calls so a slow Presidio response can't hang the whole model call, and decide how to fail. Failing closed (block the request if Presidio is unreachable) protects PII at the cost of availability. Failing open does the reverse. For regulated workloads, fail closed and put Presidio behind enough replicas that it rarely comes to that.

Series Wrap-Up

Over these five parts we've gone from zero to a production-ready PII detection and anonymization pipeline. You can install and run Presidio, detect PII in text, images, and structured data, build custom recognizers for your organization's specific patterns, choose the right anonymization strategy for each use case, and deploy Presidio as an LLM guardrail at the APIM edge that keeps sensitive data off third-party infrastructure.

The framework is actively maintained, the Docker images are production-ready, and the extensibility model (custom recognizers, custom operators, external NLP services) means it adapts to whatever compliance requirements your organization throws at it.


This is Part 5 of the Hands-On Microsoft Presidio series. I write about PII detection, AI infrastructure, and building with Claude Code on Dev.to.