hbllmutils.template
Jinja2 template utilities for prompt rendering and environment configuration.
This module provides a comprehensive set of tools for working with Jinja2 templates, including automatic text decoding, environment configuration with Python builtins, and a flexible prompt template system. It serves as the main entry point for the template package, exposing key functionality for template rendering and processing.
The module contains the following main components:
auto_decode()- Automatic text decoding with support for various encodingsadd_builtins_to_env()- Mount Python built-in functions to Jinja2 environmentsadd_settings_for_env()- Add custom settings and filters to Jinja2 environmentscreate_env()- Create fully configured Jinja2 environmentsPromptTemplate- Flexible template class for rendering promptsQuickPromptTemplate- Enhanced template with custom environment preprocessingquick_render()- Convenience function for quick template file renderingBaseMatcher- Base class for file pattern matching with type extractionBaseMatcherPair- Base class for grouping related matchers
Note
This package requires Jinja2 and provides enhanced functionality beyond standard Jinja2 templates, including Python builtin integration and automatic encoding detection.
Warning
When using strict_undefined mode (default), ensure all template variables are provided during rendering to avoid UndefinedError exceptions.
Example:
>>> from hbllmutils.template import PromptTemplate, auto_decode, create_env
>>>
>>> # Create and render a simple template
>>> template = PromptTemplate("Hello {{ name }}!")
>>> result = template.render(name="World")
>>> print(result)
Hello World!
>>>
>>> # Auto decode bytes with unknown encoding
>>> text = auto_decode(b'\xe4\xb8\xad\xe6\x96\x87')
>>> print(text)
中文
>>>
>>> # Create enhanced Jinja2 environment
>>> env = create_env()
>>> template = env.from_string("{{ items | len }}")
>>> template.render(items=[1, 2, 3])
'3'
>>>
>>> # Quick render from file
>>> from hbllmutils.template import quick_render
>>> result = quick_render("template.txt", name="Alice", age=30)