AI & LLM integration patterns
Call LLM APIs, structure prompts, parse responses, and ship AI features safely.
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.
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…
How to randomly assign a prompt variant to each key in Python
Randomly pick one variant from a list for each prompt key, useful for A/B testing message variations.
import random
def assign_prompt_variant(prompts: dict[str, list[str]]) -> dict[str, str]:
"""Assign a random prompt variant to each prompt key."""
return {key: random.choice(variants) for key, variants in prompts.items()}
if __name__ == "__main__":
prompt_bank = {
"greeting": ["Hello!", "Hi there…
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.