Reference library

AI & LLM integration patterns

Call LLM APIs, structure prompts, parse responses, and ship AI features safely.

6 matches
AI & LLM integration patterns easy

How to Build a Simple Semantic Cache for Similar Prompts in Python

Mock a semantic cache that finds the closest matching prompt using word-overlap similarity and returns cached results above a threshold.

semantic cache prompt matching llm
Python
prompt_cache = [
    "What is the capital of France?",
    "How does recursion work?",
    "Best practices for Python logging?",
    "Explain binary search in one line.",
    "How to reverse a string in Python?"
]

def normalize(text):
    return " ".join(text.lower().split())

def similarity(a, b):
    a_words = set(…
14 0 Open
AI & LLM integration patterns easy

How to Compute a Mock BLEU Score with n-gram Overlap in Python

Evaluate text similarity with a simplified BLEU score using word-level n-gram precision and a brevity penalty.

bleu n-grams text evaluation
Python
from collections import Counter

def bleu_score(reference, candidate, n=2):
    """
    Compute a simplified BLEU score with n-gram precision and brevity penalty.
    Mock demo using word-level n-grams.
    """
    ref_tokens = reference.lower().split()
    cand_tokens = candidate.lower().split()
    
    # Compute n-…
12 0 Open
AI & LLM integration patterns easy

How to Create a Mock LLM Judge Rubric Score in Python

Scores a response against a rubric by counting keyword matches, returning total, percentage, and per-criterion feedback.

llm evaluation rubric
Python
def judge_score(response, rubric):
    """Mock LLM judge that scores a response against a rubric."""
    total = 0
    max_total = 0
    feedback = []

    for criterion, rubric_item in rubric.items():
        max_points = rubric_item["max"]
        description = rubric_item["description"]

        # Simple mock scori…
15 0 Open
AI & LLM integration patterns easy

How to Filter Blocked Words in Python

Scans input text against a moderation blocklist, returning blocked terms and their counts.

moderation blocklist security
Python
MODERATION_BLOCKLIST = {"spam", "scam", "fraud", "phishing", "malware", "abuse"}

def scan_text(text: str) -> dict:
    normalized = text.lower()
    words = normalized.replace(".", " ").replace(",", " ").replace("!", " ").replace("?", " ").split()
    
    found_terms = []
    for word in words:
        if word in MO…
12 0 Open
AI & LLM integration patterns easy

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.

guardrails text-filtering llm-safety
Python
TOXIC_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.

…
12 0 Open
AI & LLM integration patterns easy

How to build a mock RAG pipeline in Python

Build a minimal Retrieval-Augmented Generation pipeline that retrieves the best-matching document by keyword overlap and generates a template-based answer.

rag llm retrieval
Python
def simple_rag_pipeline(question, documents):
    """
    A minimal mock RAG pipeline: retrieve relevant context, then generate an answer.
    """
    # Step 1: Retrieve — mock retrieval by simple keyword scoring
    scores = []
    for doc in documents:
        doc_words = set(doc.lower().split())
        question_wo…
14 0 Open

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.