AI & LLM integration patterns
Call LLM APIs, structure prompts, parse responses, and ship AI features safely.
Cache LLM Completions by Hashing the Prompt in Python
A simple in-memory cache that stores LLM completions keyed by a SHA-256 hash of the prompt to avoid recomputing identical requests.
import hashlib
import json
class PromptCache:
def __init__(self):
self.cache = {}
def _hash_prompt(self, prompt: str) -> str:
return hashlib.sha256(prompt.encode("utf-8")).hexdigest()
def get(self, prompt: str) -> str | None:
key = self._hash_prompt(prompt)
return self.ca…
How to Build an In-Memory Vector Store in Python
Build a lightweight in-memory vector store using a Python dict and cosine similarity for fast nearest-neighbor searches.
import math
from typing import Dict, List, Optional
class InMemoryVectorStore:
def __init__(self) -> None:
self.vectors: Dict[str, List[float]] = {}
self.index: Dict[str, List[str]] = {} # query -> list of ids sorted by similarity
def add(self, vector_id: str, vector: List[float]) -> None:
…
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.