AI & LLM integration patterns
Call LLM APIs, structure prompts, parse responses, and ship AI features safely.
How to Parse JSON from LLM Model Output Fence in Python
Extract and parse a JSON object from a language model's output that may be wrapped in triple-backtick fences with an optional language tag.
import json
import re
def parse_json_from_fence(text):
"""
Extract JSON object from a model output that may be wrapped in
triple-backtick fences with optional language tag.
"""
# Match content inside
How to Validate JSON Output Against a Dict Schema in Python
Validate JSON-like data against a simple dict schema with type checking and descriptive error messages using only the Python standard library.
from typing import Dict, Any, List, Union
def validate_json(data: Any, schema: Dict[str, str]) -> List[str]:
"""
Validate JSON-like data against a simple dict schema.
Schema format: {field_name: expected_type} where type is one of:
'str', 'int', 'float', 'bool', 'list', 'dict', 'any'
Returns list …
How to Validate LLM Output in Python
A beginner-friendly DataValidator class that checks required fields and type constraints on LLM-generated or user JSON data.
import json
from typing import Any, Dict, List, Optional
class DataValidator:
"""Simple helper for validating LLM-generated or user data."""
def __init__(self, required_fields: List[str], schema: Optional[Dict[str, str]] = None):
self.required_fields = required_fields
self.schema = schema or…
How to compute exact match metric in Python
Computes the exact match (EM) metric for LLM outputs by normalizing text and comparing predictions against references.
def compute_exact_match(predictions, references):
def normalize(text):
import re
text = text.lower().strip()
text = re.sub(r'\b(a|an|the)\b', ' ', text)
text = re.sub(r'[^a-z0-9\s]', '', text)
text = ' '.join(text.split())
return text
matches = sum(1 for pred, r…
How to parse JSON in Python: A Beginner's Guide with Code Examples
This guide shows you how to parse JSON data in Python step by step, with practical code examples and expected outputs.
import json
from typing import Any, Dict, List, Optional
class DataHelper:
"""Beginner-friendly helper for common AI/LLM data tasks."""
def __init__(self, data: Optional[Dict[str, Any]] = None):
self.data = data or {}
def to_prompt(self, template: str) -> str:
"""Format a prompt…
JSON Mode Prompt Schema Output in Python
Extract a user object to JSON with explicit schema keys, ready for LLM JSON-mode prompts.
import json
from typing import Any, Dict
def extract_user_as_json(user: Dict[str, Any]) -> str:
"""Extract a user object and return it as JSON using explicit schema keys."""
schema_fields = ("id", "name", "email", "is_active")
user_subset = {key: user[key] for key in schema_fields if key in user}
ret…
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.