Prompt Template Manager v2.0

Prompt EngineeringReimagined.

The definitive toolkit for engineering complex, versioned, and reusable LLM prompts with native support for chat formats, model tags, and CLI workflows.

main.py
1from prompt_template_manager import PromptManager
2
3# Load sources with global context
4manager = PromptManager('prompts/', context={"user": "Dave"})
5
6# Get model-optimized prompt
7prompt = manager.get('review_code', model='gpt-4')
8
9# Resolve for chat completion
10messages = prompt.to_openai_messages({
11 "code": "print('hello world')"
12})

Chat & Messages Format

Native support for multi-turn chat prompts. Export directly to OpenAI or Anthropic message formats.

Model-Tagged Versions

Optimize prompts for specific models (gpt-4o, claude-3.5) and resolve the right one at runtime.

Developer CLI

Validate, list, and debug your prompt library directly from the terminal with the new ptm tool.

Advanced Versioning

Semantic versioning with fallback logic. Perfect for A/B testing or gradual prompt rollouts.

Recursive Composition

Build complex prompts from smaller, reusable components using recursive {include} directives.

Env Secret Injection

Securely inject environment secrets and session-wide variables into your prompts automatically.

Hot Reloading

Watch mode automatically reloads your prompt library in development when local files change.

Smart Suggestions

Actionable error messages with Levenshtein-based name suggestions for missing prompts.

Bulk YAML Loading

Load entire directories of YAML files with collision detection and deep validation.

Installation

Available on PyPI. Compatible with Python 3.9+ and all major LLM provider SDKs.

1. Core Installation

Installs only the essential library and the YAML parser. Ideal for production environments needing basic template loading.

Core Package

pip install prompt-template-manager

Basic template loading and formatting.

Deps: PyYAML

2. Feature-Specific Extras

Install specific groups of features to keep your environment lean.

watch

pip install "prompt-template-manager[watch]"

Enables Hot Reloading. Automatically reloads templates when you edit YAML files.

Deps: watchdog

tokenization

pip install "prompt-template-manager[tokenization]"

Enables OpenAI Token Estimation for .estimate_tokens(provider='openai').

Deps: tiktoken

anthropic

pip install "prompt-template-manager[anthropic]"

Enables Anthropic Token Estimation for .estimate_tokens(provider='anthropic').

Deps: anthropic

3. Combined Extras

"Meta" packages that install multiple features at once for the best experience.

all

pip install "prompt-template-manager[all]"

Installs all feature-specific extras (watch + tokenization + anthropic).

Quick Start

Go from zero to production-ready in minutes.

1. Define your prompts

prompts/analysis.yaml
1system_persona:
2 _default: helpful
3 helpful: "You are a helpful assistant."
4
5analyze_text:
6 _default: v1
7 v1:
8 - role: system
9 content: "{include system_persona}"
10 - role: user
11 content: "Summarize this: {text}"

2. Execute in Python

main.py
1from prompt_template_manager import PromptManager
2
3manager = PromptManager('prompts/')
4prompt = manager.get('analyze_text')
5
6# Native chat support
7messages = prompt.to_openai_messages({
8 "text": "LLMs are evolving."
9})

OpenAI Compatible Output

stdout
1[
2 {
3 "role": "system",
4 "content": "You are a helpful assistant."
5 },
6 {
7 "role": "user",
8 "content": "Summarize this: LLMs are evolving."
9 }
10]
API Reference

API Reference

Exhaustive technical specification for the prompt-template-manager. Built for deterministic integration into agentic workflows and complex LLM pipelines.

Evaluation Lifecycle

Execution is split into three distinct phases. Understanding exactly when resolution occurs is critical for managing environment secrets versus runtime data.

1

Load Time

PromptManager()

  • YAML parsing & validation
  • {env:VAR} resolution
  • Collision detection
2

Access Time

manager.get()

  • Fallback logic execution
  • Model-tag resolution
  • Cache lookup & instantiation
3

Format Time

prompt.format()

  • Recursive {include}
  • Variable {var} injection
  • Type coercion (Dict to JSON)

YAML Schema Specification

Reserved Keys

_defaultRequired for versioned prompts. A string pointer to the active version key.
_metaOptional key-value map for metadata. Values must be strings.

Resolution Logic

Resolving manager.get(name, model=M, version=V) follows this sequence:

1

Explicit Version

version="v2" | version=2

2

Model Match

model="gpt-4o"

3

Default Fallback

content[_default]

anatomy.yaml
1# 1. Simple mapping
2simple_task: "Write a summary of {text}"
3
4# 2. Managed versions
5complex_task:
6 _default: v2
7 _meta:
8 author: "Dave"
9 max_tokens: "4000"
10
11 v1: "Refactor: {code}"
12 v2: "Refactor {code} concisely."
13
14 # 3. Chat format
15 claude-3-opus:
16 - role: system
17 content: "You are an expert engineer."
18 - role: user
19 content: "Refactor: {code}"

Directives & Syntax

Recursive IncludesFormat Time

Compose templates using {include prompt_name}. Resolution is recursive and detects circular dependencies.

Incompatibility Rule

Includes are only supported for string-format prompts. You cannot include a chat-format prompt into another template.

Environment InjectionLoad Time

Inject environment variables using {env:VAR_NAME}. Resolved exactly once during initialization.

env_resolution.yaml
1system_prompt: "Active Env: {env:APP_ENV}" # Resolved at startup

Regex Specification

EntityPattern
Prompt Name^[a-zA-Z_][a-zA-Z0-9_]*$
Variables{([a-zA-Z][\w-]*[a-zA-Z0-9])}
Includes{include ([a-zA-Z][\w-]*[a-zA-Z0-9])}
Env Vars{env:([A-Z_][A-Z0-9_]*)}

PromptManager

__init__

Initializes the manager and recursively loads prompt sources from disk.

source_pathstr | Path

File path to .yaml or folder containing .yaml and .txt files.

contextdictOptional

Variables bound to every Prompt object returned by this manager.

watchboolOptional

Enables background thread to monitor file changes and trigger auto-reload.

1from prompt_template_manager import PromptManager
2
3manager = PromptManager(
4 source_path="./prompts/",
5 context={"user": "Dave"},
6 watch=True
7)

get()

Returns a resolved Prompt instance with automatic resolution.

namestr

Unique prompt key from YAML.

versionstr | intOptional

Exact version key. Integers are prefixed with 'v'.

modelstrOptional

Attempts model-specific resolution, fallback to _default.

1prompt = manager.get("auth_check", model="gpt-4o")

list()

Returns the complete library catalog.

Essential for building UI-based prompt explorers or static analysis tools.

1[{
2 "name": "greet",
3 "versions": ["v1", "gpt-4"],
4 "variables": ["user"],
5 "meta": {"author": "Marketing"}
6}]

reload()

Clears all caches and re-parses the source files.

No arguments. Re-scans source_path immediately.

1manager.reload()

watchdog

Internal file system observation interface.

Spawned automatically if watch=True is passed.

1manager.start_watching()

Prompt Instance

format()

Executes variable substitution and include resolution.

datadict

Mapping of variable keys to runtime values.

strictboolOptional

If True, raises Exception for missing keys. Default is True.

1prompt = manager.get("summarize")
2text = prompt.format({"text": "Hello world"})

partial()

Functional partial application of variables.

datadict

Subset of variables to bind permanently.

1bound = prompt.partial({"lang": "Python"})

to_openai_messages()

Ensures output is OpenAI chat completion compatible.

Wraps string-prompts into a 'user' message automatically.

1messages = prompt.to_openai_messages({"user": "Dave"})

to_anthropic_messages()

Formatted for the Anthropic Messages API.

Full Claude system-key separation coming in v2.1.
1payload = prompt.to_anthropic_messages({"user": "Dave"})

estimate_tokens()

Offline token counting using provider tokenizers.

providerstrOptional

'openai' or 'anthropic'.

modelstrOptional

Tokenizer target model.

1count = prompt.estimate_tokens(model="gpt-4o")

Inspection Methods

Access internal state and metadata.

get_variables()

Returns dict of all variable placeholders.

get_meta()

Returns the _meta dict.

introspection.py
1required = prompt.get_variables()
2metadata = prompt.get_meta()

CLI Tools

The library provides a CLI tool named ptm. You can use it to manage your prompts without writing any Python code.

ptm validate

Checks your prompt files for syntax errors, logical errors, and circular dependencies.

sourcestr

Path to a YAML file or directory of YAML files.

Scans the provided source. If there are circular includes (e.g., Prompt A includes Prompt B which includes Prompt A) or invalid YAML syntax, it will report the error.

1ptm validate ./prompts

ptm list

Displays a comprehensive inventory of all loaded prompts.

sourcestr

Path to a YAML file or directory of YAML files.

Outputs a JSON-formatted list of every prompt found in your source. It includes name, versions, variables, and metadata.

1ptm list prompts.yaml

ptm get

Renders the raw content of a specific prompt to your terminal.

sourcestr

Path to a YAML file or directory of YAML files.

prompt_namestr

Name of the prompt to fetch.

--versionstrOptional

Specific version number.

--modelstrOptional

Specific model tag.

Fetches the specific version of a prompt and prints it. Useful for quickly checking content without opening YAML files.

1ptm get prompts.yaml summarizer --model gpt-4

Exception Matrix

ExceptionContextRoot Cause
FileNotFoundError__init__Path source_path not found.
ValueError__init__Invalid YAML or missing {env:VAR}.
KeyErrorget()Prompt name or version key not found.
ImportErrorformat()Circular {include} detected.

Method Summary Tables

PromptManager

MethodReturnsPhase
__init__()NoneLoad
get()PromptAccess
list()list[dict]N/A

Prompt Instance

MethodReturnsPhase
format()str | listFormat
to_openai_messages()list[dict]Format