Metadata-Version: 2.4
Name: md-tmpl
Version: 0.10.9
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Rust
Classifier: Topic :: Text Processing :: Markup
Classifier: Typing :: Typed
Requires-Dist: flatbuffers>=25.12
Summary: Strongly-typed template engine for LLM prompts
Keywords: template,prompt,llm,ai,typed
License: Apache-2.0 OR MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Documentation, https://github.com/domenukk/md-tmpl/blob/main/crates/md-tmpl-python/README.md
Project-URL: Homepage, https://github.com/domenukk/md-tmpl
Project-URL: Repository, https://github.com/domenukk/md-tmpl

# md-tmpl

Typed prompt templates for LLMs.

```python
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:

<!-- prettier-ignore -->
```markdown
---
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/>

```bash
pip install md-tmpl
```

<details>
<summary>Development installation (building from source)</summary>

Requires a Rust toolchain and [maturin](https://github.com/PyO3/maturin):

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

</details>

## Generated Types

### `template()` — the recommended API

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

```python
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

```python
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:

```python
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:

```python
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:

```python
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 %}`:

<!-- prettier-ignore -->
```markdown
---
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

```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+)

```python
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:

```python
from md_tmpl import variant

@variant
class NeedsChanges:
    reason: str

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

## Features

### Typed Lists

```python
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

```python
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.

```python
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:

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

### Caching

```python
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`:

```python
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](../../SPEC.md#host-sanitization-primitives)** for the full host primitive reference.

### Errors

```python
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:

```python
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](../../benchmarks/python/bench_templates.py)):

| 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 |

```bash
just bench-python          # run comparison benchmarks
just bench-update-python   # run + update these tables
```

## Full Reference

See **[SPEC.md](../../SPEC.md)** for the complete syntax reference.

## License

Apache-2.0 OR MIT

