# 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
Raw data
{
"_id": null,
"home_page": null,
"name": "prompt-template",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": null,
"keywords": "ai, llm, prompt-engineering, prompt-template, templating",
"author": null,
"author_email": "Na'aman Hirschfeld <nhirschfed@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/f7/bd/e0613d2c76458960c75ad1c308144196955f83721f86a8644c9661a5ac49/prompt_template-1.0.1.tar.gz",
"platform": null,
"description": "# Prompt Template\n\nThis is a lightweight zero-dependency Python library for managing LLM prompt template. Its modelled on the stdlib `string.Template` but with more robust features.\n\n## Features\n\n- Template validation\n- Support for nested braces and JSON structures\n- Automatic value serialization\n- Incremental template population\n- Clear error messages with detailed context\n- Type hints for better IDE support\n- Extensible design\n\n## Installation\n\nInstall using pip:\n\n```bash\npip install prompt-template\n```\n\n## Usage\n\n### Basic Usage\n\n```python\nfrom prompt_template import PromptTemplate\n\n# Create a template\ntemplate = PromptTemplate(\"Hello ${name}! Welcome to ${location}.\")\n\n# Render the template\nresult = template.to_string(name=\"Alice\", location=\"Wonderland\")\nprint(result) # Hello Alice! Welcome to Wonderland.\n```\n\n### Working with JSON Templates\n\n```python\ntemplate = PromptTemplate(\"\"\"\n{\n \"user\": \"${username}\",\n \"settings\": {\n \"theme\": \"${theme}\",\n \"notifications\": ${notifications}\n }\n}\n\"\"\")\n\n# Values are automatically serialized\nresult = template.to_string(\n username=\"john_doe\",\n theme=\"dark\",\n notifications={\"email\": True, \"push\": False}\n)\n```\n\n### Incremental Template Population\n\nYou can populate template values incrementally using the `substitute` method:\n\n```python\n# Start with a base template\nbase = PromptTemplate(\"The ${animal} jumped over the ${obstacle} in ${location}.\")\n\n# Partially populate values\npartial = base.substitute(animal=\"fox\", obstacle=\"fence\")\n\n# Complete the template later\nfinal = partial.to_string(location=\"garden\")\nprint(final) # The fox jumped over the fence in garden.\n```\n\n### Validation Features\n\nThe library includes built-in validation to catch common issues:\n\n```python\n# Missing variables raise MissingTemplateValuesError\ntemplate = PromptTemplate(\"Hello ${name}!\")\ntry:\n template.to_string() # Raises MissingTemplateValuesError\nexcept MissingTemplateValuesError as e:\n print(f\"Missing values: {e.missing_values}\")\n\n# Invalid keys raise InvalidTemplateKeysError\ntry:\n template.to_string(name=\"World\", invalid_key=\"value\") # Raises InvalidTemplateKeysError\nexcept InvalidTemplateKeysError as e:\n print(f\"Invalid keys: {e.invalid_keys}\")\n```\n\n### Automatic Value Serialization\n\nThe library handles various Python types automatically:\n\n```python\nfrom uuid import UUID\nfrom decimal import Decimal\n\ntemplate = PromptTemplate(\"ID: ${id}, Amount: ${amount}, Data: ${data}\")\nresult = template.to_string(\n id=UUID(\"550e8400-e29b-41d4-a716-446655440000\"),\n amount=Decimal(\"45.67\"),\n data={\"key\": \"value\"}\n)\n```\n\n### Custom Serialization\n\nYou can customize how values are serialized by subclassing `PromptTemplate`:\n\n```python\nfrom datetime import datetime\nimport json\n\nclass CustomTemplate(PromptTemplate):\n @staticmethod\n def serializer(value: Any) -> str:\n if isinstance(value, datetime):\n return value.isoformat()\n return json.dumps(value, default=str)\n\n# Use custom serialization\ntemplate = CustomTemplate(\"Time: ${current_time}, Data: ${data}\")\nresult = template.to_string(\n current_time=datetime.now(),\n data={\"complex\": \"object\"}\n)\n```\n\n## Error Handling\n\nThe library provides specific exception classes for different error cases:\n\n- `TemplateError`: Base exception for all template-related errors\n- `InvalidTemplateKeysError`: Raised when invalid keys are provided\n- `MissingTemplateValuesError`: Raised when required template values are missing\n- `TemplateSerializationError`: Raised when value serialization fails\n\n## License\n\nMIT License\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "A simple but robust zero-dependency library for creating prompt templates",
"version": "1.0.1",
"project_urls": {
"homepage": "https://github.com/Goldziher/prompt-template"
},
"split_keywords": [
"ai",
" llm",
" prompt-engineering",
" prompt-template",
" templating"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "53edc85a05997a97e1dd9f4db163aba8d706a38360187c3181f29ea62d62a7e2",
"md5": "220431d4c866047dae07dfe2c698c24d",
"sha256": "311781098ca48511e1b87f1f29adc1ef48c7ac4a73fe127cc25b3d4f96d4f7cf"
},
"downloads": -1,
"filename": "prompt_template-1.0.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "220431d4c866047dae07dfe2c698c24d",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9",
"size": 6580,
"upload_time": "2025-01-15T10:06:53",
"upload_time_iso_8601": "2025-01-15T10:06:53.824098Z",
"url": "https://files.pythonhosted.org/packages/53/ed/c85a05997a97e1dd9f4db163aba8d706a38360187c3181f29ea62d62a7e2/prompt_template-1.0.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "f7bde0613d2c76458960c75ad1c308144196955f83721f86a8644c9661a5ac49",
"md5": "f9c854abca79a1fa92bfbe44311a8538",
"sha256": "99066919d5b2633c9fe37ff25aef5b10da27ea9bf82f6dbb300043d32b253f37"
},
"downloads": -1,
"filename": "prompt_template-1.0.1.tar.gz",
"has_sig": false,
"md5_digest": "f9c854abca79a1fa92bfbe44311a8538",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9",
"size": 33197,
"upload_time": "2025-01-15T10:06:56",
"upload_time_iso_8601": "2025-01-15T10:06:56.266633Z",
"url": "https://files.pythonhosted.org/packages/f7/bd/e0613d2c76458960c75ad1c308144196955f83721f86a8644c9661a5ac49/prompt_template-1.0.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-01-15 10:06:56",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "Goldziher",
"github_project": "prompt-template",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "prompt-template"
}