Reference library

AI & LLM integration patterns

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

12 matches
AI & LLM integration patterns easy

How to Batch Embed a List of Strings in Python

Batch embed a list of strings into deterministic pseudo-random vectors using a mock encoder class.

embedding batch-processing mock-encoder
Python
class MockEncoder:
    def __init__(self, dim=8, seed=42):
        self.dim = dim
        self.seed = seed

    def embed(self, text):
        # Deterministic pseudo-random embedding based on text content
        hash_val = hash(text)
        import random
        rng = random.Random(hash_val + self.seed)
        retu…
12 0 Open
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 Create a Mock Text Embedding with Hash in Python

Generate deterministic mock text embeddings using SHA-256 hashing and numpy, producing normalized vectors for similarity testing without an LLM.

embeddings hashing numpy
Python
import hashlib
import numpy as np

def mock_embed(text: str, dim: int = 10, seed: int = 42) -> np.ndarray:
    """Generate a deterministic mock embedding using a hash function.
    
    Args:
        text: Input text to embed
        dim: Dimension of the output vector
        seed: Seed for reproducibility
    
    R…
13 0 Open
AI & LLM integration patterns easy

How to Mock OpenAI Tool Call Messages in Python

Create an assistant message with a function tool call in OpenAI's chat format, useful for testing and mocking.

openai tool-calls mock
Python
from openai import OpenAI


def mock_tool_call(tool_name: str, arguments: dict) -> dict:
    """Simulate a tool call message in OpenAI style."""
    return {
        "role": "assistant",
        "content": None,
        "tool_calls": [
            {
                "id": "call_" + "a1b2c3d4e5f6",
                "type…
14 0 Open
AI & LLM integration patterns easy

How to Mock an LLM Client in Python

Create a simple mock LLM client that returns a canned completion for testing or development without a real API.

llm mock testing
Python
from dataclasses import dataclass


@dataclass
class MockLLMClient:
    canned_response: str = "This is a canned completion."

    def complete(self, prompt: str) -> str:
        return f"{self.canned_response} [to: {prompt[:20]}]"


if __name__ == "__main__":
    client = MockLLMClient()
    result = client.complete(…
16 0 Open
AI & LLM integration patterns easy

How to Parse Chat Completion JSON in Python

Parse a mock OpenAI chat completion JSON response into a clean dictionary with content, finish reason, and model.

json openai chat-completion
Python
import json

def parse_chat_response(raw: str) -> dict:
    data = json.loads(raw)
    choice = data["choices"][0]
    return {
        "content": choice["message"]["content"],
        "finish_reason": choice["finish_reason"],
        "model": data["model"],
    }

if __name__ == "__main__":
    mock_response = '''
  …
14 0 Open
AI & LLM integration patterns medium

How to Retry LLM Calls on Rate Limit Errors in Python

Implement a retry mechanism with exponential backoff for LLM API calls that raises a custom RateLimitError, using a mock function to demonstrate the pattern.

llm retry rate-limit
Python
import time
import random


def mock_llm_call():
    """Simulates an LLM API call that may raise a rate limit error."""
    if random.random() < 0.4:  # 40% chance of rate limit
        raise RateLimitError("Rate limit exceeded. Try again later.")
    return {"response": "Hello world from mock LLM"}


class RateLimitE…
16 0 Open
AI & LLM integration patterns easy

How to Stream Tokens from a Mock LLM in Python

Simulate real-time LLM streaming by yielding tokens one at a time with a delay, making it easy to test streaming UIs.

generator llm streaming
Python
import time
from typing import Generator


def stream_tokens(text: str, delay: float = 0.05) -> Generator[str, None, None]:
    """Simulate an LLM streaming tokens word by word."""
    for word in text.split():
        yield word
        time.sleep(delay)


if __name__ == "__main__":
    sample = "Hello world! This is…
15 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
AI & LLM integration patterns medium

How to implement exponential backoff for LLM API calls in Python

A decorator that retries flaky LLM API calls with exponential delay, using a mock client to demonstrate the pattern.

exponential-backoff retries llm
Python
import time
import random

class MockLLM:
    def call(self, prompt):
        if random.random() < 0.7:  # 70% chance of transient failure
            raise ConnectionError("API unavailable")
        return f"LLM response for: {prompt}"

def with_exponential_backoff(max_retries=5, base_delay=0.1):
    def decorator(fu…
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.