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.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.
| Pattern | Description |
|---|---|
email | Email addresses |
phoneNumber | Phone numbers |
ssn | Social Security Numbers |
creditCard | Credit 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. |
caSin | Canadian 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 theagentgateway 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.
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" EOFStart the agentgateway.
agentgateway -f config.yamlOpen http://localhost:15000/ui/llm/guardrails (LLM > Guardrails).
In the Request guards section, click Add guard, and configure the guard for the SSN keywords.
From the Guard type list, select Custom regex.
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.


- Reject request: Block the request and return the rejection response. This choice sets
In Custom regex patterns, enter
SSN. Click Add pattern, and enterSocial Security.In Rejection status, enter
400.In Rejection body, enter the following JSON.
{ "error": { "message": "Request rejected: Content contains sensitive information", "type": "invalid_request_error", "code": "content_policy_violation" } }

Click Add guard.
In the Request guards section, click Add guard again, and configure the guard for email addresses.
- From the Guard type list, select Built-in detectors.
- From the Action list, select Reject request.
- In Built-in detectors, make sure that only Email is selected.
- In Rejection status, enter
400. - In Rejection body, enter the following JSON.
{ "error": { "message": "Request blocked: Contains email address", "type": "invalid_request_error", "code": "pii_detected" } } - Click Add guard.
The Request guards section lists the two guards.


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.
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"}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" } }Send another request with an email address. The prompt guard blocks it by using the built-in
emailpattern.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.
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" EOFStart the agentgateway.
agentgateway -f config.yamlOpen http://localhost:15000/ui/llm/guardrails (LLM > Guardrails).
In the Response guards section, click Add guard.
From the Guard type list, select Built-in detectors.
From the Action list, select Mask matched text.
In Built-in detectors, select Phone, and clear Email.


Click Add guard.
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.
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.
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"}} EOFNote
Setting
scopereplaces the default. To keep the default content and add tool call arguments, list all four values. Userejectrather thanmaskfortoolInput, because masking tool call arguments can produce invalid JSON.Start the agentgateway with the new configuration.
agentgateway -f config-scope.yamlSend 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"}}