AI & LLM integration patterns
Call LLM APIs, structure prompts, parse responses, and ship AI features safely.
How to Accumulate Streamed Tokens into a Final String in Python
Accumulate a stream of tokens into a single final string by concatenating each token in sequence.
def accumulate_tokens(tokens):
"""Accumulate a stream of tokens into a single final string."""
result = ""
for token in tokens:
result += token
return result
if __name__ == "__main__":
token_stream = ["Hello", ", ", "world", "!", " This ", "is ", "accumulated."]
final_string = accumul…
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 Render a Jinja-like Template from a Dict in Python
Replace {{placeholders}} in a string using values from a Python dict with a simple regex-based template renderer.
import re
def render_template(template, context):
pattern = re.compile(r"\{\{\s*(\w+)\s*\}\}")
def replace(match):
key = match.group(1)
return str(context.get(key, ""))
return pattern.sub(replace, template)
if __name__ == "__main__":
template = "Hello {{name}}, you have {{count}} new …
Serialize and Format Data for LLM Prompts in Python
Use dataclasses and the json module to convert Python objects to JSON strings, parse them back, and format structured data into prompt-friendly text for LLM calls.
import json
from dataclasses import dataclass, asdict
@dataclass
class Recipe:
"""Simple data model to represent a recipe."""
name: str
cuisine: str
prep_minutes: int
def to_json(recipe: Recipe) -> str:
"""Serialize a Recipe to a JSON string."""
return json.dumps(asdict(recipe), indent=2)
…
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.