Input validation and sanitization help make sure the data going into a machine learning system is safe and correct. This stops errors and keeps the system working well.
Input validation and sanitization in Agentic AI
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Agentic AI
def validate_input(data): # Check if data meets rules if not isinstance(data, str): raise ValueError('Input must be a string') if len(data) == 0: raise ValueError('Input cannot be empty') return data def sanitize_input(data): # Remove unwanted characters clean_data = data.strip().lower() return clean_data
Validation checks if input is the right type and format.
Sanitization cleans the input to remove or fix bad parts.
Examples
Agentic AI
validate_input('Hello World')Agentic AI
sanitize_input(' Hello World! ')Agentic AI
validate_input(123)Sample Model
This program checks a list of inputs. It validates each input to be a non-empty string, then cleans it by trimming spaces and making it lowercase. It prints the cleaned input or an error message.
Agentic AI
def validate_input(data): if not isinstance(data, str): raise ValueError('Input must be a string') if len(data) == 0: raise ValueError('Input cannot be empty') return data def sanitize_input(data): clean_data = data.strip().lower() return clean_data # Example usage inputs = [' Hello AI ', '', 42, 'Goodbye!'] for i, item in enumerate(inputs): try: valid = validate_input(item) clean = sanitize_input(valid) print(f'Input {i}: Valid and sanitized -> "{clean}"') except ValueError as e: print(f'Input {i}: Error - {e}')
Important Notes
Always validate before sanitizing to catch wrong data early.
Sanitization depends on your use case; for example, removing HTML tags if needed.
Good input handling improves model reliability and security.
Summary
Input validation checks if data is the right type and format.
Input sanitization cleans data to remove unwanted parts.
Both steps help keep machine learning systems safe and working well.
Practice
1. What is the main purpose of
input validation in machine learning systems?easy
Solution
Step 1: Understand input validation
Input validation means checking if the data is the right type and format before using it.Step 2: Differentiate from sanitization
Input sanitization cleans data, but validation focuses on correctness and format.Final Answer:
To check if the input data is the correct type and format -> Option CQuick Check:
Input validation = Check data type and format [OK]
Hint: Validation means checking data type and format [OK]
Common Mistakes:
- Confusing validation with sanitization
- Thinking validation trains the model
- Assuming validation stores data
2. Which of the following is the correct way to validate that an input is a positive integer in Python?
easy
Solution
Step 1: Check type correctly
Useisinstance(input_value, int)to check if input is an integer.Step 2: Check positivity
Ensure the integer is greater than zero withinput_value > 0.Final Answer:
if isinstance(input_value, int) and input_value > 0: -> Option AQuick Check:
Use isinstance and > 0 for positive integer check [OK]
Hint: Use isinstance() to check type, then compare value [OK]
Common Mistakes:
- Using type() == 'int' (wrong syntax)
- Calling isdigit() on non-string input
- Skipping type check before comparison
3. Given the code below, what will be the output?
def sanitize_input(text):
return text.strip().lower()
user_input = ' Hello World! '
cleaned = sanitize_input(user_input)
print(cleaned)medium
Solution
Step 1: Understand strip()
Thestrip()method removes spaces from the start and end of the string.Step 2: Understand lower()
Thelower()method converts all letters to lowercase.Final Answer:
hello world! -> Option DQuick Check:
strip + lower = 'hello world!' [OK]
Hint: strip removes spaces, lower makes all letters small [OK]
Common Mistakes:
- Ignoring strip() effect on spaces
- Confusing lower() with upper()
- Expecting original casing in output
4. Identify the error in this input validation code snippet:
def validate_age(age):
if age.isdigit() and age > 0:
return True
else:
return Falsemedium
Solution
Step 1: Check isdigit() usage
isdigit() works on strings, so age should be a string here.Step 2: Identify type mismatch in comparison
Comparingage > 0compares string to int, which causes error.Final Answer:
Comparing string with integer using > operator -> Option AQuick Check:
String > int comparison causes error [OK]
Hint: Check types before comparing values [OK]
Common Mistakes:
- Assuming isdigit() converts type
- Ignoring type mismatch in comparisons
- Thinking function name affects validation
5. You receive user data as a list of strings representing ages:
['25', ' 30', 'twenty', '40', '']. Which code snippet correctly validates and sanitizes this data to keep only valid positive integers?hard
Solution
Step 1: Sanitize input by stripping spaces
Useage.strip()to remove spaces before validation.Step 2: Validate with isdigit() and positive check
Check if stripped string is digits only and convert to int to check > 0.Step 3: Convert valid strings to integers
Useint(age.strip())to convert valid strings to integers.Final Answer:
valid_ages = [int(age.strip()) for age in ages if age.strip().isdigit() and int(age.strip()) > 0] -> Option BQuick Check:
Strip spaces, check digits, convert to int > 0 [OK]
Hint: Strip spaces before isdigit(), then convert and check > 0 [OK]
Common Mistakes:
- Not stripping spaces before validation
- Comparing strings directly to numbers
- Including empty or non-digit strings
