Skip to main content

A lightweight Python library for managing, versioning, and composing reusable prompt templates.

Project description

Prompt Template Manager (v2.0)

PyPI version License: MIT Python Versions Coverage Status

Prompt Template Manager is a definitive Python toolkit for engineering complex, versioned, and reusable LLM prompts. It transforms prompts from static strings into managed assets that can be composed, versioned for specific models, and hot-reloaded in production.


📖 Table of Contents


⚡ Quick Start

1. Define prompts.yaml

system_persona:
  _default: helpful
  helpful: "You are a helpful assistant."

analyze_text:
  _default: v1
  v1: |
    {include system_persona}
    Summarize this: {text}

2. Run in Python

from prompt_template_manager import PromptManager

# Load and fetch
manager = PromptManager("prompts.yaml")
prompt = manager.get("analyze_text")

# Format and print
print(prompt.format({"text": "LLMs are evolving."}))

💾 Installation

# Core library (PyYAML only)
pip install prompt-template-manager

# All features (Watchdog, Tiktoken, Anthropic SDK)
pip install "prompt-template-manager[all]"

1. Configuration Architecture

The YAML Schema

The core of the library is the YAML configuration. A file can contain multiple prompts, each identified by a unique key.

Simple (Static) Prompt

Best for snippets that never change.

footer: "End of prompt. Response required."

Versioned Prompt (Standard)

Required for prompts that evolve or require metadata.

task_generator:
  _default: v2
  _meta:
    description: "Generates code tasks"
    author: "Dave"
  v1: "Task: {task}"
  v2: "Revised Task: {task}. Be concise."

Prompt Versioning

You can use standard version keys (v1, v2) or Model Tags to optimize for specific LLMs.

summarizer:
  _default: gpt-4
  gpt-4: "Summarize: {text}"
  claude-3: "Please summarize: {text}"
  llama-3: "Summ: {text}"

Chat/Messages Format

Prompts can be defined as a list of role-content pairs.

code_review:
  _default: v1
  v1:
    - role: system
      content: "You are a senior dev."
    - role: user
      content: "Check this {language} code:\n{code}"

Metadata (_meta)

Metadata is a key-value store (Strings only) for tracking prompt provenance.

my_prompt:
  _default: v1
  _meta:
    max_tokens: "500"
    temperature: "0.7"
  v1: "..."

2. Template Logic & Substitution

Variable Resolution ({var})

Any text in curly braces that isn't a reserved tag (include or env) is a variable.

Mode Usage Behavior on Missing Variable
Strict p.format(data, strict=True) Raises ValueError listing missing keys.
Non-Strict p.format(data, strict=False) Leaves the placeholder as-is (e.g., {missing_var}).

Recursive Includes ({include})

Inject one prompt into another. If the included prompt is versioned, its _default version is used.

persona: "You are an AI."
task: "{include persona} Solve: {problem}"

Note: Circular references will raise an ImportError.

Environment Variables ({env:VAR})

Resolved at load time (when PromptManager is initialized).

  • Success: Replaces tag with os.environ[VAR].
  • Failure: Raises ValueError at load time if the variable is not set.
system_warning: "Running in {env:ENVIRONMENT} mode."

Global Context

Inject variables into every prompt managed by a specific PromptManager.

manager = PromptManager("prompts.yaml", context={"app_id": "PTM-001"})
# Every prompt in this manager now knows {app_id}

3. API Reference: PromptManager

PromptManager is thread-safe for reading (.get()) after initialization.

Initialization & Loading

def __init__(
    self, 
    source_path: str | Path, 
    context: dict[str, Any] | None = None, 
    watch: bool = False
) -> None
  • source_path: File or directory. If a directory, all .yaml/.yml files are loaded.
  • Collision Rule: If multiple files define the same prompt name, PromptManager raises a ValueError during initialization to prevent ambiguous resolution.

Hot Reloading (Watch Mode)

Requires watchdog. Automatically reloads the library when source files change.

manager = PromptManager("prompts.yaml", watch=True)

Retrieving Prompts (.get)

def get(
    self, 
    name: str, 
    version: int | str | None = None, 
    model: str | None = None
) -> Prompt
  • Raises KeyError if not found, providing Levenshtein-based suggestions (e.g., "Did you mean 'summarize'?").

Cataloging (.list)

def list(self) -> list[dict[str, Any]]

Returns a list of dictionaries describing every loaded prompt, its versions, and required variables.


4. API Reference: Prompt

Formatting & Substitution

def format(
    self, 
    data: dict[str, Any], 
    strict: bool = True
) -> str | list[dict[str, str]]

Returns a string for text prompts, or a list of messages for chat prompts.

Partial Application

def partial(self, data: dict[str, Any]) -> Prompt

Fill some variables now, returning a new Prompt object for the remaining variables.

Token Estimation

def estimate_tokens(
    self, 
    provider: str = "openai", 
    model: str = "gpt-4"
) -> int

Requires tiktoken (OpenAI) or anthropic SDK. Raises ImportError if missing.

SDK Compatibility

def to_openai_messages(self, data: dict[str, Any]) -> list[dict[str, str]]
def to_anthropic_messages(self, data: dict[str, Any]) -> list[dict[str, str]]

5. Advanced Patterns

Few-Shot Prompting

Use includes to manage your example bank separately from your task logic.

YAML:

# examples.yaml
sentiment_examples: |
  Text: "I love this!" | Sentiment: Positive
  Text: "This is bad." | Sentiment: Negative

# classifier.yaml
classify_task: |
  {include sentiment_examples}
  Text: "{input_text}" | Sentiment:

Model Migration / A/B Testing

# Easily switch between model-optimized versions
p_gpt = manager.get("task", model="gpt-4")
p_claude = manager.get("task", model="claude-3")

6. CLI Documentation

validate

Recursively checks all YAML files in a directory for syntax, type errors, and circular includes.

ptm validate ./prompts

list

Prints a human-readable table of prompts, versions, and variables.

ptm list prompts.yaml

get

Renders a prompt to STDOUT.

ptm get prompts.yaml my_prompt --version v1

7. Performance & Best Practices

  1. Include Caching: PromptManager uses an internal LRU cache for resolved includes. Deeply nested templates resolve in constant time after the first access.
  2. Directory Loading: We recommend a "One Domain per File" approach:
    • prompts/auth_flow.yaml
    • prompts/data_extraction.yaml
  3. Environment Isolation: Use {env:VAR} for instructions that vary by deployment (e.g., {env:LLM_SAFETY_LEVEL}).

Created by Dave Manufor — 2026

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

prompt_template_manager-2.0.0.tar.gz (25.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

prompt_template_manager-2.0.0-py3-none-any.whl (15.2 kB view details)

Uploaded Python 3

File details

Details for the file prompt_template_manager-2.0.0.tar.gz.

File metadata

  • Download URL: prompt_template_manager-2.0.0.tar.gz
  • Upload date:
  • Size: 25.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.9

File hashes

Hashes for prompt_template_manager-2.0.0.tar.gz
Algorithm Hash digest
SHA256 c9c51ba3c976e02943d7a9809ff29b149740d2f430adbf40fef796e4369b0edc
MD5 cab12eddc533c9e36208dfe13f0c8eb2
BLAKE2b-256 38036d86b1b344b54d41746c85ece5f69440202f3aadd57243ec4d3b376bb10a

See more details on using hashes here.

File details

Details for the file prompt_template_manager-2.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for prompt_template_manager-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ffe6670813e1cfe130709d5787ddc761c9586d440ddbc967c6ddc7a8e34b5d25
MD5 7463fd5fa5313b97505c21f11a77be69
BLAKE2b-256 28c3ce7121d7d5f47b3d59b58c591f635072fc4007c15e4de0b25e5371c1a23e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page