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 Estimate Token Count in Python
Estimates tokens in a text string using a whitespace and punctuation heuristic without external libraries.
def estimate_tokens(text: str) -> int:
"""Estimate token count using whitespace and punctuation heuristics."""
if not text:
return 0
words = text.split()
total_punctuation = sum(1 for char in text if char in ".,!?;:")
special_tokens = sum(1 for char in text if char in "\n\t")
# Rough …
How to Repair Malformed JSON Braces Heuristically in Python
Heuristically fix malformed JSON by balancing braces and quotes, using a stack-based approach to add missing closing characters.
import json
import re
def repair_json(text: str) -> str:
"""Heuristically repair malformed JSON by balancing braces and quotes."""
# Trim whitespace and handle leading/trailing garbage
text = text.strip()
# Remove common non-JSON decorations
text = re.sub(r'^(
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.