Reference library

AI & LLM integration patterns

Call LLM APIs, structure prompts, parse responses, and ship AI features safely.

11 matches
AI & LLM integration patterns easy

How to Append Few-Shot Examples to a Prompt in Python

This code builds a complete LLM prompt by appending few-shot examples in alternating user/assistant format using a simple loop.

prompt-engineering few-shot llm
Python
def append_few_shot_examples(prompt: str, examples: list[tuple[str, str]], separator: str = "\n\n") -> str:
    """Append few-shot examples to a prompt in alternating user/assistant format."""
    full_prompt = prompt
    for user_input, assistant_output in examples:
        full_prompt = f"{full_prompt}{separator}Use…
15 0 Open
AI & LLM integration patterns easy

How to Build a Prompt Template with Variable Slots in Python

Create a reusable LLM prompt template with named variable slots using Python's string.Template class and fill them with render() calls.

llm prompt-engineering templates
Python
from string import Template


class PromptTemplate:
    def __init__(self, template_text):
        self.template = Template(template_text)

    def render(self, **kwargs):
        return self.template.substitute(**kwargs)


if __name__ == "__main__":
    template = PromptTemplate(
        "You are a helpful assistant …
14 0 Open
AI & LLM integration patterns easy

How to Build a Simple Semantic Cache for Similar Prompts in Python

Mock a semantic cache that finds the closest matching prompt using word-overlap similarity and returns cached results above a threshold.

semantic cache prompt matching llm
Python
prompt_cache = [
    "What is the capital of France?",
    "How does recursion work?",
    "Best practices for Python logging?",
    "Explain binary search in one line.",
    "How to reverse a string in Python?"
]

def normalize(text):
    return " ".join(text.lower().split())

def similarity(a, b):
    a_words = set(…
14 0 Open
AI & LLM integration patterns easy

How to Build a System-User-Assistant Message List in Python

Use dataclasses to model a chat conversation and build the system/user/assistant message list expected by LLM APIs.

llm dataclass openai
Python
from dataclasses import dataclass, field
from typing import List


@dataclass
class Message:
    role: str
    content: str


@dataclass
class Conversation:
    messages: List[Message] = field(default_factory=list)

    def add_system(self, content: str) -> None:
        self.messages.append(Message(role="system", con…
13 0 Open
AI & LLM integration patterns easy

How to Build a Zero-Shot Classification Prompt in Python

Creates a prompt for zero-shot text classification by pairing input text with candidate labels and a hypothesis template.

zero-shot prompt classification
Python
from typing import Dict, List


def build_zero_shot_prompt(
    text: str,
    candidate_labels: List[str],
    hypothesis_template: str = "This is about {}.",
) -> Dict[str, List[str]]:
    """Build a prompt ready for zero-shot classification."""
    return {
        "sequences": text,
        "candidate_labels": can…
13 0 Open
AI & LLM integration patterns easy

How to Build an Agent Loop with Plan, Act, Observe in Python

Implements a simple plan-act-observe loop that an AI agent uses to iteratively complete a task in an environment while storing observations in memory.

agents loop llm
Python
class Agent:
    def __init__(self, name):
        self.name = name
        self.memory = {}

    def plan(self, task):
        return f"Plan for {task}: step 1, step 2, step 3"

    def act(self, plan, environment):
        return f"Executing {plan} in {environment}"

    def observe(self, action_result):
        sel…
17 0 Open
AI & LLM integration patterns easy

How to Build an Entity Memory Dict to Store Facts in Python

Store and recall facts about entities using nested dictionaries with remember, recall, and forget functions in Python.

memory dict nested-dict
Python
facts = {}

def remember(entity, attribute, value):
    if entity not in facts:
        facts[entity] = {}
    facts[entity][attribute] = value

def recall(entity, attribute):
    return facts.get(entity, {}).get(attribute, None)

def forget(entity, attribute=None):
    if attribute is None:
        facts.pop(entity, …
12 0 Open
AI & LLM integration patterns easy

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.

vector-store cosine-similarity embeddings
Python
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:
…
12 0 Open
AI & LLM integration patterns easy

How to build a function calling schema dict in Python

Build an OpenAI-compatible function calling schema dictionary with a helper function that takes name, description, parameters, and required fields.

llm-api function-calling schema
Python
import json
from typing import Dict, Any, List, Optional


def build_function_schema(
    name: str,
    description: str,
    parameters: Optional[Dict[str, Any]] = None,
    required: Optional[List[str]] = None
) -> Dict[str, Any]:
    """Build an OpenAI-compatible function calling schema dictionary."""
    schema: …
14 0 Open
AI & LLM integration patterns easy

How to build a mock RAG pipeline in Python

Build a minimal Retrieval-Augmented Generation pipeline that retrieves the best-matching document by keyword overlap and generates a template-based answer.

rag llm retrieval
Python
def simple_rag_pipeline(question, documents):
    """
    A minimal mock RAG pipeline: retrieve relevant context, then generate an answer.
    """
    # Step 1: Retrieve — mock retrieval by simple keyword scoring
    scores = []
    for doc in documents:
        doc_words = set(doc.lower().split())
        question_wo…
14 0 Open
AI & LLM integration patterns easy

Prepare LLM prompt data with a Python helper class

A beginner-friendly Python class that collects records, converts them to JSON, and produces a quick summary for building LLM prompt context.

llm json prompt-engineering
Python
import json
from typing import Any, Dict, List

class DataHelper:
    """Simple helper to prepare data for LLM prompts."""
    
    def __init__(self):
        self.data = []
    
    def add(self, item: Dict[str, Any]) -> "DataHelper":
        self.data.append(item)
        return self
    
    def to_json(self) -> s…
16 0 Open

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.