AI & LLM integration patterns
Call LLM APIs, structure prompts, parse responses, and ship AI features safely.
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.
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, …
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.
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…
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.
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…
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.
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…
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.