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 errorsInvalidTemplateKeysError: Raised when invalid keys are providedMissingTemplateValuesError: Raised when required template values are missingTemplateSerializationError: 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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b3a7e93572e59c04494d07ed8a62b1f51033860dc887915a06c8909c76023347
|
|
| MD5 |
3d6a6c2688aaf33a90c8b6523c617f56
|
|
| BLAKE2b-256 |
28c8fe9b8150f7c3dae22d08b3b4c8981cfc10817cba10976f4564f3aad00189
|
Provenance
The following attestation bundles were made for prompt_template-1.0.0.tar.gz:
Publisher:
release.yaml on Goldziher/prompt-template
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
prompt_template-1.0.0.tar.gz -
Subject digest:
b3a7e93572e59c04494d07ed8a62b1f51033860dc887915a06c8909c76023347 - Sigstore transparency entry: 162505474
- Sigstore integration time:
-
Permalink:
Goldziher/prompt-template@478453b760132bda172d9bbac9d5b718fe45316a -
Branch / Tag:
refs/tags/v1.0.0 - Owner: https://github.com/Goldziher
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yaml@478453b760132bda172d9bbac9d5b718fe45316a -
Trigger Event:
release
-
Statement type:
File details
Details for the file prompt_template-1.0.0-py3-none-any.whl.
File metadata
- Download URL: prompt_template-1.0.0-py3-none-any.whl
- Upload date:
- Size: 5.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.0.1 CPython/3.12.8
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d7f0b79175abba9cf99735924b23fa3090a2073d7d2d1ec9095185cbb20b5771
|
|
| MD5 |
a63831b1b45b8325e5e41ade35a98555
|
|
| BLAKE2b-256 |
6fc42aeeb0ffe3ad33a89b343055fcc7ca9d7d5f958df539f02130bfe579ec31
|
Provenance
The following attestation bundles were made for prompt_template-1.0.0-py3-none-any.whl:
Publisher:
release.yaml on Goldziher/prompt-template
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
prompt_template-1.0.0-py3-none-any.whl -
Subject digest:
d7f0b79175abba9cf99735924b23fa3090a2073d7d2d1ec9095185cbb20b5771 - Sigstore transparency entry: 162505476
- Sigstore integration time:
-
Permalink:
Goldziher/prompt-template@478453b760132bda172d9bbac9d5b718fe45316a -
Branch / Tag:
refs/tags/v1.0.0 - Owner: https://github.com/Goldziher
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yaml@478453b760132bda172d9bbac9d5b718fe45316a -
Trigger Event:
release
-
Statement type: