> ## Documentation Index
> Fetch the complete documentation index at: https://docs.promptguard.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Redact PII in a RAG pipeline

> Redact sensitive data from user queries and retrieved documents before they reach the LLM

This example shows how to build a Retrieval-Augmented Generation (RAG) system that redacts PII from both the user's query and the retrieved documents before they reach the LLM.

**Prefer to watch?** This page as a silent, step-by-step video:

**Tutorial 06** ·  · a silent follow-along of this page. Pressing
play loads the video from YouTube.
Watch on YouTube

## Overview

RAG systems often process sensitive documents (HR records, customer data, legal contracts). This example demonstrates:

* Redacting PII from the user's query and the retrieved documents in the LLM call
* Scanning the LLM's answer before it reaches the user
* Maintaining answer quality while protecting data

## Architecture

```mermaid theme={"system"}
graph LR
    A[User Query] --> C[Vector Search]
    C --> D[Retrieved Docs]
    A --> E[PromptGuard]
    D --> E
    E -->|Redact PII| F[LLM]
    F --> G[Response]
    G --> P[PromptGuard]
    P -->|Scan response| H[User]
```

`promptguard.init()` patches the LLM call, so PromptGuard scans the query and the retrieved documents together when they are sent to the model. The vector search itself runs in your process and is not scanned: the raw query is embedded and compared locally, and never reaches the LLM unredacted.

## Implementation

### Setup

```bash theme={"system"}
# Installs the latest release of each
pip install promptguard-sdk openai chromadb
```

### Basic RAG with Protection

```python theme={"system"}
import promptguard
from openai import OpenAI
import chromadb

# Initialize PromptGuard with response scanning.
# The API key is read from the PROMPTGUARD_API_KEY environment variable.
promptguard.init(
    mode="enforce",
    scan_responses=True,
)

# Initialize clients
openai_client = OpenAI()
chroma_client = chromadb.Client()
collection = chroma_client.get_or_create_collection("documents")

# Load your documents. Chroma embeds them with its default model, locally.
collection.add(
    ids=["hr-001", "hr-002"],
    documents=[
        "John Smith, Senior Engineer. Salary: $145,000. Contact: john.smith@company.com, (555) 123-4567.",
        "Jane Doe, Product Manager. Benefits: dental, vision, 401(k) match. SSN on file: 123-45-6789.",
    ],
)

def secure_rag_query(user_query: str) -> str:
    # Step 1: Retrieve relevant documents (local, not scanned)
    results = collection.query(
        query_texts=[user_query],
        n_results=5
    )

    # Step 2: Build context from retrieved docs
    context = "\n\n".join(results["documents"][0])

    # Step 3: LLM call - PromptGuard scans the query and the context, and redacts PII
    response = openai_client.chat.completions.create(
        model="gpt-5-nano",
        messages=[
            {
                "role": "system",
                "content": f"Answer based on this context:\n\n{context}"
            },
            {
                "role": "user",
                "content": user_query
            }
        ]
    )

    return response.choices[0].message.content

# Example usage
answer = secure_rag_query("What's the salary for employee John Smith?")
print(answer)
```

### With LangChain

`RetrievalQA` is gone from LangChain 1.x, so build the chain with LCEL. The inline `PromptGuardRunnable` sits between the retriever and the prompt: on a redact decision it passes the redacted context on, and on a block it raises `PromptGuardBlockedError`.

```bash theme={"system"}
pip install "promptguard-sdk[langchain]>=2.4.0" "langchain-core>=1.6,<2" "langchain-openai>=1.7,<2" "langchain-chroma>=1,<2"
```

```python theme={"system"}
from langchain_chroma import Chroma
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI, OpenAIEmbeddings

from promptguard.integrations.langchain import PromptGuardRunnable

vectorstore = Chroma(embedding_function=OpenAIEmbeddings())
retriever = vectorstore.as_retriever()

guard = PromptGuardRunnable().as_runnable()  # reads PROMPTGUARD_API_KEY


def format_docs(docs) -> str:
    return "\n\n".join(doc.page_content for doc in docs)


prompt = ChatPromptTemplate.from_template(
    "Answer based on this context:\n\n{context}\n\nQuestion: {question}"
)

qa_chain = (
    {
        "context": retriever | format_docs | guard,  # redact PII in retrieved documents
        "question": guard,  # and in the question
    }
    | prompt
    | ChatOpenAI(model="gpt-5-nano")
    | StrOutputParser()
)

answer = qa_chain.invoke("What benefits does Jane Doe have?")
```

## PII Types Detected

| Type | Example | Redacted As |
| - | - | - |
| Email | [john@company.com](mailto:john@company.com) | `[EMAIL_REDACTED]` |
| Phone | (555) 123-4567 | `[PHONE_REDACTED]` |
| SSN | 123-45-6789 | `[SSN_REDACTED]` |
| Credit Card | 4532-1234-5678-9012 | `[CARD_REDACTED]` |

These are a few of the types PromptGuard redacts. The full list, including country-specific identifiers, is in [PII and sensitive data protection](https://docs.promptguard.co/security/threat-detection.md#pii-and-sensitive-data-protection).

## Next Steps

> [card] [Data Privacy Example](https://docs.promptguard.co/cookbooks/data-privacy.md)
>
> More data protection patterns

> [card] [Threat Detection](https://docs.promptguard.co/security/threat-detection.md)
>
> Understand detection capabilities


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.