Skip to main content

A simple but robust zero-dependency library for creating prompt templates

Project description

Prompt Template

This is a lightweight zero-dependency Python library for managing LLM prompt template. Its modelled on the stdlib string.Template but with more robust features.

Features

- Template validation
- Support for nested braces and JSON structures
- Automatic value serialization
- Incremental template population
- Clear error messages with detailed context
- Type hints for better IDE support
- Extensible design

Installation

Install using pip:

```bash
pip install prompt-template
```

Usage

Basic Usage

```python
from prompt_template import PromptTemplate

# Create a template
template = PromptTemplate("Hello ${name}! Welcome to ${location}.")

# Render the template
result = template.to_string(name="Alice", location="Wonderland")
print(result)  # Hello Alice! Welcome to Wonderland.
```

Working with JSON Templates

```python
template = PromptTemplate("""
{
    "user": "${username}",
    "settings": {
        "theme": "${theme}",
        "notifications": ${notifications}
    }
}
""")

# Values are automatically serialized
result = template.to_string(
    username="john_doe",
    theme="dark",
    notifications={"email": True, "push": False}
)
```

Incremental Template Population

You can populate template values incrementally using the substitute method:

```python
# Start with a base template
base = PromptTemplate("The ${animal} jumped over the ${obstacle} in ${location}.")

# Partially populate values
partial = base.substitute(animal="fox", obstacle="fence")

# Complete the template later
final = partial.to_string(location="garden")
print(final)  # The fox jumped over the fence in garden.
```

Validation Features

The library includes built-in validation to catch common issues:

```python
# Missing variables raise MissingTemplateValuesError
template = PromptTemplate("Hello ${name}!")
try:
    template.to_string()  # Raises MissingTemplateValuesError
except MissingTemplateValuesError as e:
    print(f"Missing values: {e.missing_values}")

# Invalid keys raise InvalidTemplateKeysError
try:
    template.to_string(name="World", invalid_key="value")  # Raises InvalidTemplateKeysError
except InvalidTemplateKeysError as e:
    print(f"Invalid keys: {e.invalid_keys}")
```

Automatic Value Serialization

The library handles various Python types automatically:

```python
from uuid import UUID
from decimal import Decimal

template = PromptTemplate("ID: ${id}, Amount: ${amount}, Data: ${data}")
result = template.to_string(
    id=UUID("550e8400-e29b-41d4-a716-446655440000"),
    amount=Decimal("45.67"),
    data={"key": "value"}
)
```

Custom Serialization

You can customize how values are serialized by subclassing PromptTemplate:

```python
from datetime import datetime
import json

class CustomTemplate(PromptTemplate):
    @staticmethod
    def serializer(value: Any) -> str:
        if isinstance(value, datetime):
            return value.isoformat()
        return json.dumps(value, default=str)

# Use custom serialization
template = CustomTemplate("Time: ${current_time}, Data: ${data}")
result = template.to_string(
    current_time=datetime.now(),
    data={"complex": "object"}
)
```

Error Handling

The library provides specific exception classes for different error cases:

  • TemplateError: Base exception for all template-related errors
  • InvalidTemplateKeysError: Raised when invalid keys are provided
  • MissingTemplateValuesError: Raised when required template values are missing
  • TemplateSerializationError: Raised when value serialization fails

License

MIT License

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-1.0.0.tar.gz (32.5 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-1.0.0-py3-none-any.whl (5.8 kB view details)

Uploaded Python 3

File details

Details for the file prompt_template-1.0.0.tar.gz.

File metadata

  • Download URL: prompt_template-1.0.0.tar.gz
  • Upload date:
  • Size: 32.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.0.1 CPython/3.12.8

File hashes

Hashes for prompt_template-1.0.0.tar.gz
Algorithm Hash digest
SHA256 b3a7e93572e59c04494d07ed8a62b1f51033860dc887915a06c8909c76023347
MD5 3d6a6c2688aaf33a90c8b6523c617f56
BLAKE2b-256 28c8fe9b8150f7c3dae22d08b3b4c8981cfc10817cba10976f4564f3aad00189

See more details on using hashes here.

Provenance

The following attestation bundles were made for prompt_template-1.0.0.tar.gz:

Publisher: release.yaml on Goldziher/prompt-template

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file prompt_template-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for prompt_template-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d7f0b79175abba9cf99735924b23fa3090a2073d7d2d1ec9095185cbb20b5771
MD5 a63831b1b45b8325e5e41ade35a98555
BLAKE2b-256 6fc42aeeb0ffe3ad33a89b343055fcc7ca9d7d5f958df539f02130bfe579ec31

See more details on using hashes here.

Provenance

The following attestation bundles were made for prompt_template-1.0.0-py3-none-any.whl:

Publisher: release.yaml on Goldziher/prompt-template

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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