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 Parse JSON from LLM Model Output Fence in Python
Extract and parse a JSON object from a language model's output that may be wrapped in triple-backtick fences with an optional language tag.
import json
import re
def parse_json_from_fence(text):
"""
Extract JSON object from a model output that may be wrapped in
triple-backtick fences with optional language tag.
"""
# Match content inside
How to Render a Jinja-like Template from a Dict in Python
Replace {{placeholders}} in a string using values from a Python dict with a simple regex-based template renderer.
import re
def render_template(template, context):
pattern = re.compile(r"\{\{\s*(\w+)\s*\}\}")
def replace(match):
key = match.group(1)
return str(context.get(key, ""))
return pattern.sub(replace, template)
if __name__ == "__main__":
template = "Hello {{name}}, you have {{count}} new …
Parse ReAct Logs into Thought Action Observation Steps in Python
Parse a ReAct agent's textual log into structured steps with thought, action, and observation using regex and named tuples.
import re
from collections import namedtuple
ReActStep = namedtuple("ReActStep", ["thought", "action", "observation"])
def parse_react_log(log: str) -> list[ReActStep]:
"""Parse a ReAct log into structured thought/action/observation steps."""
pattern = re.compile(
r"Thought:\s*(?P<thought>.+?)\s*"
…
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.