Reference library

AI & LLM integration patterns

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

8 matches
AI & LLM integration patterns medium

Circuit Breaker Pattern in Python for LLM API Calls

Implements a circuit breaker class that wraps LLM client calls to fail fast when the service is degrading, then recover automatically after a timeout.

circuit-breaker llm resilience
Python
import time

class CircuitBreaker:
    def __init__(self, failure_threshold=3, recovery_timeout=5):
        self.failure_threshold = failure_threshold
        self.recovery_timeout = recovery_timeout
        self.failure_count = 0
        self.state = "closed"
        self.last_failure_time = None

    def call(self, …
14 0 Open
AI & LLM integration patterns easy

How to Build a System-User-Assistant Message List in Python

Use dataclasses to model a chat conversation and build the system/user/assistant message list expected by LLM APIs.

llm dataclass openai
Python
from dataclasses import dataclass, field
from typing import List


@dataclass
class Message:
    role: str
    content: str


@dataclass
class Conversation:
    messages: List[Message] = field(default_factory=list)

    def add_system(self, content: str) -> None:
        self.messages.append(Message(role="system", con…
12 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 an LLM Response in Python

This code parses a JSON string from an LLM response, stripping code fences and handling common issues like whitespace, returning a Python dictionary.

llm json parsing
Python
import json
from typing import Any, Dict, List


def parse_llm_response(response: str) -> Dict[str, Any]:
    """Parse a JSON string from an LLM response, handling common edge cases."""
    # Remove code fences if present
    cleaned = response.strip()
    if cleaned.startswith("
13 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 build a function calling schema dict in Python

Build an OpenAI-compatible function calling schema dictionary with a helper function that takes name, description, parameters, and required fields.

llm-api function-calling schema
Python
import json
from typing import Dict, Any, List, Optional


def build_function_schema(
    name: str,
    description: str,
    parameters: Optional[Dict[str, Any]] = None,
    required: Optional[List[str]] = None
) -> Dict[str, Any]:
    """Build an OpenAI-compatible function calling schema dictionary."""
    schema: …
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
AI & LLM integration patterns medium

Track GitHub Repository Growth in Python

A Python dashboard that fetches and displays GitHub repository statistics including stars, forks, creation date, and recent star activity using the GitHub API.

github api requests
Python
import requests
import json
from datetime import datetime, timedelta

def track_repo_growth(owner, repo):
    url = f"https://api.github.com/repos/{owner}/{repo}"
    headers = {"Accept": "application/vnd.github.v3+json"}
    response = requests.get(url, headers=headers)
    data = response.json()
    
    name = data…
43 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.