AI & LLM integration patterns
Call LLM APIs, structure prompts, parse responses, and ship AI features safely.
How to Detect Prompt Injection in Python
Implements a regex-based heuristic in Python to flag common prompt injection attempts before sending input to an LLM.
import re
def contains_prompt_injection(user_input: str) -> bool:
# Directives to ignore previous instructions or act as system
ignore_patterns = [
r"\bignore\s+(all\s+)?previous\s+instructions\b",
r"\bdisregard\s+(all\s+)?previous\s+instructions\b",
r"\bdon'?t\s+follow\s+(any\s+)?inst…
How to Redact Emails and Phones Before Sending to an LLM in Python
This code uses regular expressions to replace email addresses and US phone numbers with [EMAIL] and [PHONE] placeholders before any LLM processing.
import re
def redact_pii(text: str) -> str:
# Replace email addresses with [EMAIL]
text = re.sub(r'[\w.+-]+@[\w-]+\.[\w.-]+', '[EMAIL]', text)
# Replace phone numbers (US format) with [PHONE]
text = re.sub(r'\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}', '[PHONE]', text)
return text
if __name__ == "__main…
Browse by section
Each section groups closely related Python snippets.
AI & LLM integration patterns — Python code examples
What you will find here
This page collects ai & llm integration patterns snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.