Skip to content
Help guide the future of agentgateway — Take the survey

Regex filters

Verified : Automated tests passed for: Configuration files: The configuration files on this page were checked against their schema. End-to-end run: Every step ran in a fresh test environment and the results were checked.
Page as Markdown

Match and redact prompt content with custom regex patterns or agentgateway’s built-in PII detectors.

Use custom regex patterns and built-in PII detectors to filter LLM requests and responses.

About regex prompt templating

Regex-based prompt guards let you inspect LLM requests and responses against custom regex patterns or built-in PII detectors. Use the reject action to block a request or a response that matches a pattern. Use the mask action to replace the matched text with a placeholder instead. In a request, the LLM provider receives the placeholder. In a response, the client receives the placeholder.

Built-in prompt guard patterns

Agentgateway includes the following built-in patterns for common PII types that you can reference in your prompt guards.

PatternDescription
emailEmail addresses
phoneNumberPhone numbers
ssnSocial Security Numbers
creditCardCredit card numbers that pass the Luhn checksum. Digit groups can be separated by spaces or hyphens. The checksum runs before the guard action, so a number that fails it is not masked, rejected, or audited.
caSinCanadian Social Insurance Numbers

Custom regex patterns

Use custom patterns to match credentials, secrets, or application-specific sensitive data.

llm:
  models:
  - name: "*"
    provider: openAI
    params:
      model: gpt-4o-mini
      apiKey: "$OPENAI_API_KEY"
    guardrails:
      request:
      - regex:
          action: reject
          rules:
          - pattern: "password[=:]\\s*\\S+"
          - pattern: "api[_-]?key[=:]\\s*\\S+"
          - pattern: "secret[=:]\\s*\\S+"
        rejection:
          status: 400
          headers:
            set:
              content-type: "application/json"
          body: |
            {
              "error": {
                "message": "Request contains credentials",
                "type": "invalid_request_error",
                "code": "credentials_detected"
              }
            }

Before you begin

Install the agentgateway binary.

PII detection

The following example rejects requests that contain PII data, such as Social Security Numbers (using a custom keyword pattern) or email addresses (using the built-in email pattern). When a request is blocked, agentgateway returns a custom error response.

The UI saves the guards in llm.policies.guardrails, which applies to all LLM models. The Config file tab adds the same guards to a single model instead. The UI form sets the rejection status and body, but not the rejection headers. To set a header such as content-type, use the Config file tab.

  1. Create a configuration file with an LLM model, but no guardrails. You add the guardrails in the UI.

    cat <<'EOF' > config.yaml
    # yaml-language-server: $schema=https://agentgateway.dev/schema/config
    llm:
      models:
      - name: "*"
        provider: openAI
        params:
          model: gpt-4o-mini
          apiKey: "$OPENAI_API_KEY"
    EOF
  2. Start the agentgateway.

    agentgateway -f config.yaml
  3. Open http://localhost:15000/ui/llm/guardrails (LLM > Guardrails).

  4. In the Request guards section, click Add guard, and configure the guard for the SSN keywords.

    1. From the Guard type list, select Custom regex.

    2. From the Action list, select Reject request. The Action list has the following choices.

      • Reject request: Block the request and return the rejection response. This choice sets action: reject.
      • Mask matched text: Replace the matched content and continue. This choice sets action: mask.
      • Audit: Record the match and forward the content unchanged. This choice sets action: audit. For more information, see Audit mode.
      Add request guard drawer for a Custom regex guard with the Action list open, showing Reject request, Mask matched text, and Audit
      Add request guard drawer for a Custom regex guard with the Action list open, showing Reject request, Mask matched text, and Audit
    3. In Custom regex patterns, enter SSN. Click Add pattern, and enter Social Security.

    4. In Rejection status, enter 400.

    5. In Rejection body, enter the following JSON.

      {
        "error": {
          "message": "Request rejected: Content contains sensitive information",
          "type": "invalid_request_error",
          "code": "content_policy_violation"
        }
      }
      Add request guard drawer with the SSN and Social Security patterns, the Reject request action, the 400 rejection status, and the rejection body
      Add request guard drawer with the SSN and Social Security patterns, the Reject request action, the 400 rejection status, and the rejection body
    6. Click Add guard.

  5. In the Request guards section, click Add guard again, and configure the guard for email addresses.

    1. From the Guard type list, select Built-in detectors.
    2. From the Action list, select Reject request.
    3. In Built-in detectors, make sure that only Email is selected.
    4. In Rejection status, enter 400.
    5. In Rejection body, enter the following JSON.
      {
        "error": {
          "message": "Request blocked: Contains email address",
          "type": "invalid_request_error",
          "code": "pii_detected"
        }
      }
    6. Click Add guard.

    The Request guards section lists the two guards.

    LLM Guardrails page with a Custom regex guard and a Built-in detectors guard in the Request guards section, both rejecting with 400
    LLM Guardrails page with a Custom regex guard and a Built-in detectors guard in the Request guards section, both rejecting with 400
  6. Click Save guardrails.

Whether the UI can save depends on your storage mode. For more information, see Save changes from the UI.

Verify the PII guards

Send requests to your LLM provider to verify that the guards block PII.

  1. In a new terminal, send a request to your LLM provider. Verify that the request succeeds.

    curl http://localhost:4000/v1/chat/completions \
      -H "Content-Type: application/json" \
      -d '{
        "model": "gpt-4o-mini",
        "messages": [{"role": "user", "content": "Hello, how are you?"}]
      }'

    Example output:

    :0},"prompt_tokens_details":{"cached_tokens":0,
    "audio_tokens":0}},"choices":[{"message":
    {"content":"Hello! I'm just a program, but I'm here and 
    ready to help you. How can I assist you today?",
    "role":"assistant","refusal":null,"annotations":[]},
    "index":0,"logprobs":null,"finish_reason":"stop"}],
    "id":"chatcmpl-DHwlvtADPu5ZFznynSpmSjXL4B6W3",
    "object":"chat.completion",
    "service_tier":"default",
    "system_fingerprint":"fp_a1ddba3226"}
    
  2. Send a request containing the SSN keyword. The prompt guard blocks the request and returns your custom error response.

    curl http://localhost:4000/v1/chat/completions \
      -H "Content-Type: application/json" \
      -d '{
        "model": "gpt-4o-mini",
        "messages": [{"role": "user", "content": "My SSN is 123-45-6789"}]
      }'

    Example output:

    {
      "error": {
        "message": "Request rejected: Content contains sensitive information",
        "type": "invalid_request_error",
        "code": "content_policy_violation"
      }
    }
    
  3. Send another request with an email address. The prompt guard blocks it by using the built-in email pattern.

    curl http://localhost:4000/v1/chat/completions \
      -H "Content-Type: application/json" \
      -d '{
        "model": "gpt-4o-mini",
        "messages": [{"role": "user", "content": "Contact me at test@example.com"}]
      }'

    Example output:

    {
      "error": {
        "message": "Request blocked: Contains email address",
        "type": "invalid_request_error",
        "code": "pii_detected"
      }
    }
    

Mask PII in responses

You can also filter LLM responses to redact sensitive data before it reaches the client. When a match is found, agentgateway replaces built-in pattern matches with <ENTITY_TYPE> (for example, <CREDIT_CARD>) and custom pattern matches with <masked>. The following example masks phone numbers in responses.

Warning

Masking applies only to a buffered response. When the client sets "stream": true, the LLM response is streamed, and agentgateway cannot rewrite content that is already on its way to the client. A response guard that uses action: mask passes the matched content through unmodified, and the client receives no error. To protect a streamed response, use action: reject and set streaming: Enabled. For more information, see Streaming guardrails.

The UI saves the guard in llm.policies.guardrails, which applies to all LLM models. The Config file tab adds the same guard to a single model instead.

  1. Create a configuration file with an LLM model, but no guardrails. You add the guardrails in the UI.

    cat <<'EOF' > config.yaml
    # yaml-language-server: $schema=https://agentgateway.dev/schema/config
    llm:
      models:
      - name: "*"
        provider: openAI
        params:
          model: gpt-4o-mini
          apiKey: "$OPENAI_API_KEY"
    EOF
  2. Start the agentgateway.

    agentgateway -f config.yaml
  3. Open http://localhost:15000/ui/llm/guardrails (LLM > Guardrails).

  4. In the Response guards section, click Add guard.

    1. From the Guard type list, select Built-in detectors.

    2. From the Action list, select Mask matched text.

    3. In Built-in detectors, select Phone, and clear Email.

      Add response guard drawer with Built-in detectors, the Mask matched text action, and only the Phone detector selected
      Add response guard drawer with Built-in detectors, the Mask matched text action, and only the Phone detector selected
    4. Click Add guard.

  5. Click Save guardrails.

Whether the UI can save depends on your storage mode. For more information, see Save changes from the UI.

Verify the phone number masking

Send a request to your LLM provider to verify that the guard masks phone numbers in the response.

  1. In a new terminal, send a request to your LLM provider with a phone number and verify that the number is masked in your response.

    curl http://localhost:4000/v1/chat/completions \
      -H "Content-Type: application/json" \
      -d '{
        "model": "gpt-4o-mini",
        "messages": [{"role": "user", "content": "What number is 919 222 1111?"}]
      }'

    Example output:

    {"model":"gpt-4o-mini-2024-07-18","usage":
    {"prompt_tokens":18,"completion_tokens":57,
    "total_tokens":75,"completion_tokens_details":
    {"reasoning_tokens":0,"audio_tokens":0,
    "accepted_prediction_tokens":0,
    "rejected_prediction_tokens":0},"prompt_tokens_details":
    {"cached_tokens":0,"audio_tokens":0}},"choices":
    [{"message":{"content":"The number <PHONE_NUMBER>appears 
    to be a phone number in the United States. The area code
    919 serves parts of North Carolina, including cities 
    like Raleigh and Durham. If you have a specific 
    question or need more information regarding this 
    number, please let me know!","role":"assistant",
    "refusal":null,"annotations":[]},"index":0,
    "logprobs":null,"finish_reason":"stop"}],
    "id":"chatcmpl-DHxEv3O5VOQPCmIVPruRiToal0rIe","object":"chat.completion","created":1773171665,
    "service_tier":"default",
    "system_fingerprint":"fp_a1ddba3226"}%    
    

Scan tool call arguments

By default, a request guard reads the system prompt, regular message text, and tool call results. Tool call arguments are not scanned. The following example adds toolInput to scope so that the guard also rejects PII in tool call arguments.

For what each scope value covers and the limits on the field, see Guard scope.

  1. Create a configuration that rejects a request when the system prompt, messages, tool call results, or tool call arguments contain a Social Security number.

    cat <<'EOF' > config-scope.yaml
    # yaml-language-server: $schema=https://agentgateway.dev/schema/config
    llm:
      models:
      - name: "*"
        provider: openAI
        params:
          model: gpt-4o-mini
          apiKey: "$OPENAI_API_KEY"
        guardrails:
          request:
          - scope: [systemPrompt, messages, toolOutput, toolInput]
            regex:
              action: reject
              rules:
              - builtin: ssn
            rejection:
              status: 400
              body: |
                {"error": {"message": "Request contains PII", "code": "pii_detected"}}
    EOF

    Note

    Setting scope replaces the default. To keep the default content and add tool call arguments, list all four values. Use reject rather than mask for toolInput, because masking tool call arguments can produce invalid JSON.

  2. Start the agentgateway with the new configuration.

    agentgateway -f config-scope.yaml
  3. Send a request whose tool call arguments contain a Social Security number. The guard rejects it before the request reaches the provider.

    curl -s http://localhost:4000/v1/chat/completions \
    --header 'Content-Type: application/json' \
    --data '{
      "model": "gpt-4o-mini",
      "messages": [
        {"role": "user", "content": "look up my record"},
        {"role": "assistant", "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "lookup", "arguments": "{\"ssn\": \"123-45-6789\"}"}}]},
        {"role": "tool", "tool_call_id": "c1", "content": "record found"}
      ]
    }' | jq .

    Example output:

    {"error": {"message": "Request contains PII", "code": "pii_detected"}}
    
Was this page helpful?
Agentgateway assistant

Ask me anything about agentgateway configuration, features, or usage.

Note: AI-generated content might contain errors; please verify and test all returned information.

Tip: one topic per conversation gives the best results. Use the + button in the chat header to start a new conversation.

Switching topics? Starting a new conversation improves accuracy.
↑↓ navigate ↵ select esc dismiss

What could be improved?

Your feedback helps us improve assistant answers and identify docs gaps we should fix.

Need more help? Join us on Discord: https://discord.gg/y9efgEmppm

Want to use your own agent? Add the Solo MCP server to query our docs directly. Get started here: https://search.solo.io/.