0PricingLogin
AI Prompt Engineering · Lesson

Input Sanitization Strategies

Escaping, filtering, and validating user input before prompt construction.

The Role of Input Sanitization

Input sanitization is the practice of processing user-provided text before it enters the prompt to reduce its ability to override instructions. It is the first layer of defense in a multi-layer injection defense strategy.

Sanitization cannot stop all attacks — a determined attacker can always find novel phrasings. But it efficiently blocks the majority of opportunistic injection attempts.

Keyword Detection

The simplest sanitization: scan input for known injection keywords and block or flag the request. Maintain a list of high-signal phrases commonly used in injection attempts.

import re

INJECTION_KEYWORDS = [
    'ignore previous instructions',
    'ignore all instructions',
    'disregard your instructions',
    'forget your role',
    'you are now',
    'act as if you are',
    'new persona',
    'admin mode',
    'developer mode',
    'unlock mode',
    'repeat your system prompt',
    'what were your instructions',
]

def contains_injection_keyword(text):
    text_lower = text.lower()
    for keyword in INJECTION_KEYWORDS:
        if keyword in text_lower:
            return True, keyword
    return False, None

flagged, kw = contains_injection_keyword(user_input)
if flagged:
    return 'I cannot process this request.', 400

All lessons in this course

  1. How Prompt Injection Works
  2. Types of Injection Attacks
  3. Input Sanitization Strategies
  4. Building Injection-Resistant Prompts
← Back to AI Prompt Engineering