hbllmutils.template.render
Jinja2-based prompt template rendering module.
This module provides a flexible and powerful prompt template system built on top of the Jinja2 templating engine. It enables users to create, load, and render text templates with variable substitution, supporting both string-based templates and file-based templates with automatic encoding detection.
The module contains the following main components:
PromptTemplate- Main template class for rendering prompts with Jinja2
Key Features:
Variable substitution using Jinja2 syntax
Automatic encoding detection for template files
Customizable Jinja2 environment preprocessing
Strict undefined variable handling (configurable)
Support for loading templates from files or strings
Note
This module requires the Jinja2 templating engine and uses automatic encoding detection for file-based templates.
Example:
>>> from hbllmutils.template.render import PromptTemplate
>>>
>>> # Create template from string
>>> template = PromptTemplate("Hello, {{ name }}!")
>>> result = template.render(name="World")
>>> print(result)
Hello, World!
>>>
>>> # Create template from file
>>> template = PromptTemplate.from_file("templates/greeting.txt")
>>> result = template.render(name="Alice", greeting="Hi")
>>> print(result)
PromptTemplate
- class hbllmutils.template.render.PromptTemplate(template_text: str, strict_undefined: bool = True)[source]
A template class for rendering prompts using the Jinja2 templating engine.
This class provides a high-level interface for working with Jinja2 templates, wrapping the template creation and rendering process. It supports variable substitution, custom environment preprocessing, and strict undefined variable handling to catch template errors early.
The class can be instantiated directly with a template string or created from a file using the
from_file()class method. The Jinja2 environment can be customized by overriding the_preprocess_env()method in subclasses.- Parameters:
template_text (str) – The Jinja2 template string to use for rendering
strict_undefined (bool, optional) – Whether to raise errors on undefined variables. When True, uses StrictUndefined to catch template errors. Defaults to True.
- Variables:
_template (jinja2.Template) – The compiled Jinja2 template object
Note
By default, this class uses strict undefined variable handling, which means that attempting to render a template with missing variables will raise an error. Set strict_undefined=False to allow undefined variables.
Warning
When strict_undefined is False, undefined variables will be silently ignored in the rendered output, which may lead to unexpected results.
Example:
>>> # Basic usage with string template >>> template = PromptTemplate("Hello, {{ name }}!") >>> result = template.render(name="World") >>> print(result) Hello, World! >>> # Template with multiple variables >>> template = PromptTemplate( ... "{{ greeting }}, {{ name }}! You are {{ age }} years old." ... ) >>> result = template.render(greeting="Hi", name="Alice", age=30) >>> print(result) Hi, Alice! You are 30 years old. >>> # Using non-strict mode >>> template = PromptTemplate( ... "Hello, {{ name }}!", ... strict_undefined=False ... ) >>> result = template.render() # Missing 'name' variable >>> print(result) Hello, !
- __init__(template_text: str, strict_undefined: bool = True)[source]
Initialize a PromptTemplate with the given template text.
Creates a new Jinja2 environment, preprocesses it using the
_preprocess_env()hook, and compiles the template string.- Parameters:
template_text (str) – The Jinja2 template string containing variables in {{ variable }} format
strict_undefined (bool, optional) – Whether to raise errors on undefined variables. When True, accessing undefined variables will raise jinja2.UndefinedError. Defaults to True.
- Raises:
jinja2.TemplateSyntaxError – If the template string contains invalid Jinja2 syntax
Example:
>>> template = PromptTemplate("Hello, {{ name }}!") >>> print(template._template) <Template memory:...> >>> # Template with control structures >>> template = PromptTemplate(''' ... {% for item in items %} ... - {{ item }} ... {% endfor %} ... ''')
- classmethod from_file(template_file: str | Path, **params: Any) PromptTemplate[source]
Create a PromptTemplate instance from a template file.
Reads a template file with automatic encoding detection and creates a PromptTemplate instance from its content. This method uses the
auto_decode()function to handle various text encodings automatically, making it suitable for templates in different languages and encoding formats.- Parameters:
template_file (str or pathlib.Path) – Path to the template file. Can be a string path or a pathlib.Path object.
params – Additional keyword arguments to pass to the PromptTemplate constructor (e.g., strict_undefined=False)
- Returns:
A new PromptTemplate instance created from the file content
- Return type:
- Raises:
FileNotFoundError – If the template file does not exist
UnicodeDecodeError – If the file cannot be decoded with any supported encoding
jinja2.TemplateSyntaxError – If the file contains invalid Jinja2 syntax
Note
This method automatically detects the file encoding using chardet and tries multiple encoding strategies to successfully read the file.
Example:
>>> # Load template from file >>> template = PromptTemplate.from_file("templates/greeting.txt") >>> result = template.render(name="Bob") >>> print(result) Hello, Bob! >>> # Load with custom parameters >>> template = PromptTemplate.from_file( ... "templates/greeting.txt", ... strict_undefined=False ... ) >>> result = template.render() # Missing variables allowed >>> # Using pathlib.Path >>> from pathlib import Path >>> template_path = Path("templates") / "greeting.txt" >>> template = PromptTemplate.from_file(template_path)
- render(**kwargs: Any) str[source]
Render the template with the provided keyword arguments.
Substitutes all template variables with the provided values and returns the rendered string. Variables should be passed as keyword arguments matching the variable names in the template.
- Parameters:
kwargs – Variable names and their values to substitute in the template. Keys should match the variable names used in the template (e.g., {{ name }} expects a ‘name’ keyword argument).
- Returns:
The rendered template string with all variables substituted
- Return type:
str
- Raises:
jinja2.UndefinedError – If strict_undefined is True and a required variable is missing from kwargs
jinja2.TemplateError – If an error occurs during template rendering
Example:
>>> template = PromptTemplate("Hello, {{ name }}!") >>> result = template.render(name="Alice") >>> print(result) Hello, Alice! >>> # Multiple variables >>> template = PromptTemplate( ... "{{ greeting }}, {{ name }}! You are {{ age }} years old." ... ) >>> result = template.render(greeting="Hi", name="Bob", age=25) >>> print(result) Hi, Bob! You are 25 years old. >>> # With control structures >>> template = PromptTemplate(''' ... Items: ... {% for item in items %} ... - {{ item }} ... {% endfor %} ... ''') >>> result = template.render(items=["apple", "banana", "cherry"]) >>> print(result) Items: - apple - banana - cherry