Skip to main content

md-tmpl

Typed prompt templates for LLMs.

from md_tmpl import template

# Load a template — enums and typed classes are generated automatically
review = template("prompts/code_review.tmpl.md")

output = review.render(
    reviewer="Alice",
    items=[
        review.CodeReviewItemsItem(file="main.py", status=review.Status.Approved),
        review.CodeReviewItemsItem(
            file="lib.py",
            status=review.Status.NeedsChanges(reason="missing tests"),
        ),
    ],
)

# Pattern-match on the generated enum (Python 3.10+)
match review.Status.NeedsChanges(reason="missing tests"):
    case review.Status.Approved:
        print("Ship it!")
    case review.Status.NeedsChanges(reason=r):
        print(f"Please fix: {r}")
    case review.Status.Rejected:
        print("Back to the drawing board")

The template file is plain Markdown with YAML frontmatter:

---
types:
  - Status = enum(Approved, NeedsChanges(reason = str), Rejected)

params:
  - reviewer = str
  - items = list(file = str, status = Status)
---

Review by {{ reviewer }}:

> {% for item in items %}

- **{{ item.file }}** — {% match item.status %}{% case Approved %}✅{% case NeedsChanges %}needs changes: {{ item.status.reason }}{% case Rejected %}❌{% /match %}

> {% /for %}

Installation

Available on PyPI: https://pypi.org/project/md-tmpl/

pip install md-tmpl
Development installation (building from source)

Requires a Rust toolchain and maturin:

pip install maturin
cd crates/md-tmpl-python
maturin develop

Generated Types

template() loads a .tmpl.md file and auto-generates Python classes for every enum, struct, and list-item type declared in the frontmatter:

from md_tmpl import template

tmpl = template("prompts/task_list.tmpl.md")

# Generated types are attributes on the returned object:
tmpl.Priority.High       # unit enum variant (sentinel, no parens)
tmpl.Priority.Medium
tmpl.Priority.Low

output = tmpl.render(
    tasks=[
        {"title": "Fix bug", "priority": tmpl.Priority.High},
        {"title": "Add tests", "priority": tmpl.Priority.Medium},
    ],
)

Generated class names use PascalCase: list param tasks on task_list → class TaskListTasksItem, type alias Priority → class Priority.

Type Mapping

Frontmatter Type Python Equivalent
str str (sanitized by default)
trusted str str (emitted verbatim)
int int
int(lo..=hi) / int(lo..hi) int (range-checked at runtime)
int enum(8, 16, ...) Literal[8, 16, ...] (domain-checked)
float float
float(lo..=hi) / float(lo..hi) float (finite & range-checked)
bool bool
list(field = type, ...) list[GeneratedClass]
list(type) list[PythonType] (e.g. list[str])
struct(field = type, ...) GeneratedClass
enum(Variant, ...) GeneratedEnumClass
option(type) Optional[PythonType] (PythonType | None)
tmpl(...) Template object or callable

load_types() — load types without a template object

from md_tmpl import load_types

types = load_types("prompts/review.tmpl.md")
Status = types.Status

# Or pick specific types:
types = load_types("prompts/review.tmpl.md", pick=["Status"])

generate_types_source() — static type stubs for mypy / pyright

Generate .py files with @dataclass classes so type checkers catch errors at analysis time:

from md_tmpl import generate_types_source

source = generate_types_source("prompts/greeting.tmpl.md")
with open("greeting_types.py", "w") as f:
    f.write(source)

Use the generated class like a normal dataclass:

from greeting_types import Greeting

# mypy / pyright catch missing or mistyped fields here:
params = Greeting(name="world", count=1, items=[])
output = params.render()   # → "Hello world! Count: 1. Items: "

Import Hook

Use templates as regular Python modules:

from md_tmpl import md_tmpl_import_hook

md_tmpl_import_hook()

from prompts.code_review import CodeReview, Status

output = CodeReview(
    reviewer="Alice",
    items=[...],
).render()

Enum Dispatch

Define enums in frontmatter and branch on them with {% match %}:

---
params:
  - status = enum(Done(summary = str), InProgress, Blocked)
---

> {% match status %}
> {% case Done %}

✅ Completed: {{ status.summary }}

> {% case InProgress %}

🔄 Still in progress.

> {% case Blocked %}

❌ Blocked.

> {% /match %}

Accessing status.summary outside {% case Done %} is a template error.

Variants — define enums in Python

from md_tmpl import Variants

class Status(Variants):
    Approved = ()                    # unit variant (sentinel)
    Rejected = ()
    NeedsChanges = {"reason": str}   # struct variant (callable)

Status.Approved                          # no parens
Status.NeedsChanges(reason="fix tests")  # keyword constructor

Pattern Matching (Python 3.10+)

def handle_review(status):
    match status:
        case Status.Approved:
            return "Ship it!"
        case Status.NeedsChanges(reason=r):
            return f"Please fix: {r}"
        case Status.Rejected:
            return "Back to the drawing board"

@variant decorator

Turn a class with annotations into a matchable variant:

from md_tmpl import variant

@variant
class NeedsChanges:
    reason: str

v = NeedsChanges(reason="fix tests")
assert v.reason == "fix tests"

Features

Typed Lists

from md_tmpl import Template

tmpl = Template.from_source("""\
---
params:
  - tasks = list(title = str, priority = str)
---
> {% for task in tasks %}

- **{{ task.title }}** ({{ task.priority }})

> {% /for %}
""")

output = tmpl.render(tasks=[
    {"title": "Write documentation", "priority": "High"},
    {"title": "Add unit tests",      "priority": "Medium"},
])

Defaults

Parameters can declare defaults in the frontmatter. Call render_empty() on templates where every parameter has a default.

Filters

Filter Example
upper {{ name | upper }}
lower {{ name | lower }}
trim {{ name | trim }}
fixed(N) {{ score | fixed(2) }}
join(sep) {{ tags | join(", ") }}
limit(N) {{ items | limit(3) }}
truncate(N, [m]) {{ text | truncate(1024) }} (middle-out string/list truncation)
add(N) {{ count | add(1) }}
sub(N) {{ count | sub(1) }}
escape_xml {{ val | escape_xml }} (alias: xml)
escape_json {{ val | escape_json }} (escape JSON string body)
json([N]) {{ val | json }} or {{ val | json(2) }} (serialize value to JSON)
sanitize {{ val | sanitize }} or {{ val | sanitize("tag") }}
sanitize_tokens {{ val | sanitize_tokens }} or {{ val | sanitize_tokens("tag") }}
fence(lang) {{ code | fence("python") }}
quarantine(tag) {{ untrusted | quarantine }} or {{ untrusted | quarantine("tag") }}
unsafe_trust {{ raw_fragment | unsafe_trust }}

Built-in Functions

Function Example
idx(binding) {{ idx(item) }} — 0-based loop index
len(expr) {{ len(items) }} — list or string length
kind(expr) {{ kind(status) }} — enum variant name
kinds(type) {{ kinds(Status) }} — list of enum variant names
has(expr) {{ has(field) }} — true if option(T) is present
unsafe_trust(expr) {{ unsafe_trust(raw_fragment) }} — emit string verbatim

Includes

Templates can include other templates with {% include "path.tmpl.md" %}.

Constants

tmpl = Template.from_source("""\
---
consts:
  - MAX_RETRIES = int := 3
  - MODEL = str := "gemini-3.5-flash"

params:
  - query = str
---
{{ query }}""")

constants = tmpl.consts()  # {"MAX_RETRIES": 3, "MODEL": "gemini-3.5-flash"}

Environment Variables

Inject values at compile time from the build environment using env: declarations. Env vars are resolved once when the template is compiled and behave like constants at render time.

tmpl = Template.from_source_with_env("""\
---
params:
  - name = str
env:
  - MODEL = str
  - MAX_TOKENS = int := 4096
---
Hello {{ name }}! Using {{ MODEL }} (max {{ MAX_TOKENS }} tokens).""",
    {"MODEL": "gemini-2.0-flash"},
)

output = tmpl.render(name="Alice")
# → "Hello Alice! Using gemini-2.0-flash (max 4096 tokens)."

Or use from_source_with_options() to combine env with other compile options:

tmpl = Template.from_source_with_options(
    source,
    base_dir="/path/to/prompts",
    env={"MODEL": "gemini-2.0-flash"},
)

Caching

from md_tmpl import TemplateCache

cache = TemplateCache()
tmpl = cache.load("prompts/greeting.tmpl.md")
output = tmpl.render(name="cached", count=1, items=[])

# Cache-aware rendering (resolves {% include %} through cache):
output = tmpl.render_cached(cache, name="world", count=1, items=[])

cache.template_count()  # number of cached templates
cache.clear()           # invalidate all entries

API Reference

Template

Method / Constructor Description
Template.from_file(path) Load and parse a .tmpl.md file
Template.from_source(source) Parse a template from an inline string
Template.from_source_with_env(source, env) Parse with compile-time environment variables
Template.from_source_with_options(source, …) Parse with base_dir, env, and allow_unused
tmpl.render(**kwargs) Render with keyword arguments (type-checked)
tmpl.render_dict(params, allow_extra=…) Render from a dict; allow_extra=True skips extras
tmpl.render_empty() Render a template with only defaults (no user args)
tmpl.declarations() Return [(name, type_str), …] for all params
tmpl.consts() Return {name: value, …} for constants
tmpl.test_matrix_len() Number of compile-time verified test-matrix: points
tmpl.render_test_point(index) Render the index-th verification point
tmpl.validate_declarations_against(…) Raise DeclarationsMutatedError if declarations changed
tmpl.validate_against_template(expected) Raise DeclarationsMutatedError if template contract diverged

Host Sanitization Primitives

Standalone sanitization, escaping, quarantine, and truncation functions are exported from md_tmpl:

from md_tmpl import (
    has_invisible_chars,
    strip_invisible,
    escape_xml,
    escape_json,
    sanitize_tokens,
    sanitize_role_tokens,
    sanitize,
    sanitize_block,
    quarantine_untrusted,
    truncate_middle,
    truncate_middle_list,
)

See SPEC.md for the full host primitive reference.

Errors

from md_tmpl import (
    TemplateError,             # base class
    TemplateSyntaxError,       # invalid template syntax
    MissingParamsError,        # required parameters not provided
    TypeMismatchError,         # value type doesn't match declaration
    ExtraParamsError,          # undeclared parameters passed
    UndefinedVariableError,    # undeclared variable referenced
    UnknownFilterError,        # unknown filter name
    IncludeNotFoundError,      # missing included template file
    DeclarationsMutatedError,  # hot-reload declaration/sanitization mismatch
    TemplatePanicError,        # {% panic(...) %} directive triggered
    AssertionFailedError,      # {% assert COND : "msg" %} failed (.condition, .assertion_message)
    TemplateArithmeticError,   # checked arithmetic overflow, div/0, or non-finite float
)

Wrong types produce clear errors:

tmpl.render(count="not an int")
# ValueError: type mismatch for 'count': expected int, got str

Extra parameters are rejected by default — pass allow_extra=True to opt out.

Performance

3–7× faster than Jinja2 for rendering (and 30–60× faster on cold parse), backed by a native-speed engine.

Render Time (pre-parsed template + data)

10,000 iterations, best of 5 runs (source):

Scenario md-tmpl Jinja2 Mako Chevron Django string.Template
simple 0.89 µs 🏆 6.47 µs 6.61 µs 7.21 µs 8.15 µs 1.61 µs
loop 1.90 µs 🏆 9.85 µs 6.87 µs 22.00 µs 48.85 µs N/A
conditional 0.95 µs 🏆 6.55 µs 6.44 µs N/A 16.39 µs N/A
hero 7.14 µs 🏆 24.01 µs 9.40 µs N/A 241.84 µs N/A

Parse Time (source → template object)

Note: Chevron has no pre-compilation API (compile() only wraps the source string in a closure and re-tokenizes on every render() call), and string.Template only supports flat $var interpolation.

Scenario md-tmpl Jinja2 Mako Chevron Django string.Template
simple 6.51 µs 309.70 µs 402.10 µs 0.13 µs 🏆 19.22 µs 0.22 µs
loop 10.93 µs 547.34 µs 515.37 µs 0.13 µs 🏆 42.80 µs N/A
conditional 10.98 µs 🏆 662.34 µs 572.74 µs N/A 76.48 µs N/A
hero 43.93 µs 🏆 2.23 ms 1.42 ms N/A 233.71 µs N/A

End-to-End (parse + render)

Scenario md-tmpl Jinja2 Mako Chevron Django str.Template
simple 7.81 µs 344.91 µs 468.01 µs 7.23 µs 41.16 µs 1.89 µs 🏆
loop 13.80 µs 🏆 580.56 µs 561.72 µs 21.71 µs 105.54 µs N/A
conditional 12.79 µs 🏆 695.79 µs 604.91 µs N/A 103.81 µs N/A
hero 56.11 µs 🏆 2.29 ms 1.46 ms N/A 501.31 µs N/A
just bench-python          # run comparison benchmarks
just bench-update-python   # run + update these tables

Full Reference

See SPEC.md for the complete syntax reference.

License

Apache-2.0 OR MIT

Metadata

Release files for md-tmpl 0.10.9

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for md-tmpl 0.10.9
File Size Uploaded Provenance Actions
md_tmpl-0.10.9.tar.gz 627.7 kB Without provenance Details for md_tmpl-0.10.9.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for md-tmpl 0.10.9
File Interpreter ABI Platform Actions
md_tmpl-0.10.9-cp314-cp314-manylinux_2_34_x86_64.whl CPython 3.14 CPython 3.14 Linux glibc 2.34+ x86-64 Details for md_tmpl-0.10.9-cp314-cp314-manylinux_2_34_x86_64.whl

Total release size: 1.7 MB

Release files / md_tmpl-0.10.9.tar.gz

Download URL md_tmpl-0.10.9.tar.gz
Size 627.7 kB
Tags Source
SHA-256 checksum
How to use checksums
7707598306d6f6308a3da89759baa858c5e0f3489e001ce2db86fca2765d483a
BLAKE2b-256 checksum
How to use checksums
c79f99d818f0fad000f71b38d25f975429daa93f536a1a8101727894b06aaa44
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.14.1

Release files / md_tmpl-0.10.9-cp314-cp314-manylinux_2_34_x86_64.whl

Download URL md_tmpl-0.10.9-cp314-cp314-manylinux_2_34_x86_64.whl
Size 1.1 MB
Tags CPython 3.14 Linux glibc 2.34+ x86-64
SHA-256 checksum
How to use checksums
94981b783ec3da49b93397fea5c060741feb0183ab571e679a16e085e3014e9a
BLAKE2b-256 checksum
How to use checksums
8a578e82b295a46bb055191262372084500752d1a25e70b245edc0a2a25aa4ba
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.14.1

Security for md-tmpl 0.10.9

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page