hbllmutils.template.render
Jinja2-based prompt template module for rendering text templates.
This module provides a flexible prompt template system built on top of Jinja2, allowing users to create, load, and render text templates with variable substitution. It supports loading templates from files with automatic encoding detection and provides hooks for environment customization.
PromptTemplate
- class hbllmutils.template.render.PromptTemplate(template_text: str, strict_undefined: bool = True)[source]
A template class for rendering prompts using Jinja2 templating engine.
This class wraps Jinja2 functionality to provide a simple interface for creating and rendering text templates with variable substitution.
- Parameters:
template_text (str) – The Jinja2 template string to use for rendering.
strict_undefined (bool) – Whether to raise errors on undefined variables. Defaults to True.
- Example::
>>> template = PromptTemplate("Hello, {{ name }}!") >>> template.render(name="World") 'Hello, World!'
- __init__(template_text: str, strict_undefined: bool = True)[source]
Initialize a PromptTemplate with the given template text.
- Parameters:
template_text (str) – The Jinja2 template string.
strict_undefined (bool) – Whether to raise errors on undefined variables. Defaults to True.
- classmethod from_file(template_file)[source]
Create a PromptTemplate instance from a template file.
This method reads a template file with automatic encoding detection and creates a PromptTemplate instance from its content.
- Parameters:
template_file (str or pathlib.Path) – Path to the template file (string or Path object).
- Returns:
A new PromptTemplate instance created from the file content.
- Return type:
- Example::
>>> template = PromptTemplate.from_file("templates/greeting.txt") >>> template.render(name="Bob") 'Hello, Bob!'
- render(**kwargs) str[source]
Render the template with the provided keyword arguments.
- Parameters:
kwargs – Variable names and their values to substitute in the template.
- Returns:
The rendered template string.
- Return type:
str
- Example::
>>> template = PromptTemplate("Hello, {{ name }}! You are {{ age }} years old.") >>> template.render(name="Alice", age=30) 'Hello, Alice! You are 30 years old.'