Skip to main content
Browse docs

Response Rewriter

The response-rewriter policy modifies AI provider responses before they are returned to the caller, enabling disclaimer injection, content redaction, and regex-based text transformations while optionally preserving JSON structure.

Use this page when

  • You need to append disclaimers, redact brand names, or transform AI responses before they reach callers.
  • You are injecting compliance disclaimers conditionally (e.g., financial disclaimer only when "investment" appears).
  • You want regex-based response transformations while preserving JSON structure.

Primary audience

  • Primary: AI Agents, Technical Engineers
  • Secondary: Technical Leaders

Configuration

policy:
response-rewriter:
preserve_structure: true
rules:
- name: add-disclaimer
pattern: "$"
replacement: |2-


---
_This response was generated by AI and may contain errors._
position: append
- name: redact-competitor-names
pattern: '\b(CompetitorA|CompetitorB|CompetitorC)\b'
replacement: "[COMPETITOR]"
position: replace
pack:
name: response-rewriter-example-1
version: 1.0.0
enabled: true
policies:
chain:
- response-rewriter

Fields

FieldTypeDescriptionDefault
preserve_structureboolPreserve JSON structure in responses. When enabled, rewrite rules are applied only to string-valued text fields, leaving JSON keys, numbers, and booleans untouched.true
rulesRewriteRule[]Ordered list of regex-based rewrite rules applied to response content. Rules execute in declaration order.[]
rules[].namestringRequired. Unique identifier for the rule, used in audit logs.--
rules[].patternstringRegular expression pattern to match in the response content. Supports capture groups.--
rules[].replacementstringReplacement string. Use $1, $2, etc. to reference capture groups from the pattern.--
rules[].positionstringHow the replacement is applied: "replace" substitutes the match, "prepend" inserts before the match, "append" inserts after the match."replace"
rules[].conditionstringOptional substring guard. The rule only applies if this substring is present in the response content.--

Use Cases

Adding Compliance Disclaimers to Responses

Append a compliance disclaimer to every AI response in a regulated environment.

pack:
name: "compliance-disclaimers"
version: "0.1.0"
enabled: true

policies:
chain:
- safety-filter
- response-rewriter
- audit-logger

policy:
safety-filter:
action: "block"

response-rewriter:
preserve_structure: true
rules:
- name: "general-disclaimer"
pattern: "$"
replacement: '\n\n_Disclaimer: This AI-generated response is for informational purposes only and does not constitute professional advice._'
position: "append"
- name: "financial-disclaimer"
pattern: "$"
replacement: '\n_This is not financial advice. Consult a qualified financial advisor._'
position: "append"
condition: "investment"

audit-logger:
retention_days: 365

Redacting Brand Names

Replace competitor or internal brand names in responses with generic placeholders.

pack:
name: "brand-redaction"
version: "0.1.0"
enabled: true

policies:
chain:
- response-rewriter

policy:
response-rewriter:
preserve_structure: true
rules:
- name: "redact-competitors"
pattern: '\b(Acme Corp|Globex|Initech|Umbrella Corp)\b'
replacement: "[THIRD_PARTY]"
position: "replace"
- name: "redact-internal-codenames"
pattern: '\b(Project (Phoenix|Titan|Orion))\b'
replacement: "[INTERNAL_PROJECT]"
position: "replace"

Injecting Safety Warnings

Prepend a safety warning to responses that mention dangerous activities.

pack:
name: "safety-warnings"
version: "0.1.0"
enabled: true

policies:
chain:
- response-rewriter
- audit-logger

policy:
response-rewriter:
preserve_structure: false
rules:
- name: "chemical-warning"
pattern: "^"
replacement: '[WARN] SAFETY WARNING: The following information involves hazardous materials. Follow all applicable safety regulations.\n\n'
position: "prepend"
condition: "chemical"
- name: "electrical-warning"
pattern: "^"
replacement: '[WARN] SAFETY WARNING: Electrical work should only be performed by qualified professionals.\n\n'
position: "prepend"
condition: "voltage"

audit-logger:
retention_days: 90

How It Works

  1. Response interception -- The gateway intercepts the response from the upstream AI provider before returning it to the caller.
  2. Structure detection -- If preserve_structure is enabled, the gateway identifies the response format (JSON, streaming SSE, plain text) and extracts text fields for rule application.
  3. Rule evaluation -- Rules execute sequentially in declaration order. Each rule's condition (if set) is checked first; if the substring is not present in the response content, the rule is skipped.
  4. Pattern matching and replacement -- The pattern regex is applied to the extracted text content. Matches are processed according to position: "replace" substitutes, "prepend" inserts before, "append" inserts after.
  5. Structure reassembly -- When preserve_structure is enabled, modified text fields are placed back into the original response structure, preserving JSON formatting, streaming chunk boundaries, and metadata.

Best Practices

  • Keep preserve_structure enabled for API consumers. Disabling it on JSON responses can break downstream parsers that depend on the response schema.
  • Place response-rewriter after content-filtering policies. Apply safety filters and content checks first, then rewrite the approved response. This avoids rewriting content that would have been blocked.
  • Use condition guards for context-specific disclaimers. Adding financial disclaimers only when the response mentions investment topics reduces noise and improves user experience.
  • Avoid overlapping patterns. If multiple rules can match the same text, ensure they are ordered so earlier rules do not create text that triggers later rules unintentionally.
  • Test with streaming responses. Regex patterns that span chunk boundaries may not match in streaming mode. Prefer patterns that match within a single text segment.

For AI systems

  • Canonical terms: Keeptrusts, response-rewriter, preserve_structure, rules, pattern, replacement, position, condition, append, replace, prepend
  • Config/command names: policy.response-rewriter, preserve_structure, rules[], rules[].pattern (regex), rules[].replacement, rules[].position (replace/prepend/append), rules[].condition
  • Best next pages: Request Rewriter, Financial Compliance, Safety Filter

For engineers

  • Prerequisites: Regex patterns for content to transform. Disclaimer text approved by compliance. Understanding of JSON structure preservation requirements.
  • Validation: Send a request that generates a response containing your target patterns and verify transformations. Test preserve_structure: true with JSON responses to confirm keys/numbers are untouched.
  • Key commands: kt policy lint, kt gateway run, kt events tail

For leaders

  • Governance: Response rewriting ensures every AI output includes required disclaimers and excludes sensitive brand/competitor references — enforced at the infrastructure layer.
  • Cost: Local regex processing with no external calls. Negligible per-request overhead.
  • Rollout: Start with universal disclaimers (append to all responses). Add conditional rules (disclaimer only when specific keywords appear) as you refine requirements.

Next steps