How to Filter Toxic Keywords in Python
Filter toxic keywords from text by replacing each occurrence with asterisks, useful as a basic guardrail for LLM inputs.
Python code
23 linesTOXIC_KEYWORDS = ["insult", "threat", "hate", "violence", "spam"]
def guardrails_filter(text: str, keywords: list[str] | None = None) -> str:
"""Filter out toxic keywords from the given text.
Args:
text: The input text to filter.
keywords: Optional keyword list. Defaults to TOXIC_KEYWORDS.
Returns:
The filtered text with toxic keywords replaced by '*' characters.
"""
keywords = keywords or TOXIC_KEYWORDS
filtered_text = text
for keyword in keywords:
filtered_text = filtered_text.replace(keyword, "*" * len(keyword))
return filtered_text
if __name__ == "__main__":
sample_text = "This is a hate message and a threat to violence."
print(guardrails_filter(sample_text))
Output
This is a **** message and a ****** to ********.
How it works
The function iterates through a list of keywords and uses str.replace() to substitute each toxic word with asterisks of the same length. The optional keywords parameter defaults to a predefined list, letting you reuse the filter with custom lists. Because replace() handles substring matches, this approach works for any text where toxic terms appear as standalone or embedded words.
Common mistakes
- Replacing keywords with fixed-length asterisks instead of matching keyword length
- Forgetting that substring matching may filter non-toxic words containing the keyword
- Not handling case sensitivity — 'Hate' won't be caught by 'hate'
Variations
- Use regex with word boundaries to avoid partial-word matches
- Convert text and keywords to lowercase before filtering for case-insensitive matching
Real-world use cases
- Pre-processing user prompts before sending to an LLM API to block harmful or spammy content.
- Sanitizing chat messages in a moderation queue to strip offensive terms before display.
- Redacting sensitive or banned words in logs or analytics pipelines before storage.
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.