Skip to content

prompt_template

This module provides utilities for managing and rendering string templates that use double braces {{}} to denote placeholders for variables. It includes a PromptTemplate class for creating, managing, and rendering these templates, along with functions to check if a template is fully filled and to perform the rendering.

Templates are strings that use double curly braces to enclose variable names, e.g., {{variable}}, which can be dynamically replaced with actual values.

Classes:

Name Description
PromptTemplate

Encapsulates template management and rendering.

Raises:

Type Description
PromptTemplateError

Custom exception for handling template errors.

Functions:

Name Description
render_prompt

str, **variables) -> str: Renders a template with variables.

is_prompt_fully_filled

str) -> bool: Checks if a template has unfilled placeholders.

find_unfilled_variables

str) -> list[str]: Finds and returns the list of unfilled variable names in a template string.

PromptTemplate

A class for managing and rendering templates with placeholders.

These templates are strings that use double curly braces {{}} to denote variable names, which are intended to be replaced by actual values when the template is rendered. Example of a template: "Hello, {{ name }}!"

Attributes:

Name Type Description
prompt_template str

The current state of the template string, initially set with placeholders.

prompt str

Returns the fully filled template if all placeholders have been replaced, otherwise raises PromptTemplateError.

unfilled_variables list[str]

Returns the list of unfilled variable names.

Methods:

Name Description
load_template

str) -> PromptTemplate: Class method to create a new instance with the specified template.

render

Renders the template with provided variables and updates the instance. This method replaces placeholders in the format {{ variable }} with values from variables.

prompt

Returns the fully filled template or raises an error if unfilled placeholders remain. This method is used to retrieve the final rendered string if it is fully filled.

is_fully_filled

Checks if the template has any unfilled placeholders. This method determines whether all placeholders have been replaced.

Source code in src/agere/utils/prompt_template.py
class PromptTemplate:
    """A class for managing and rendering templates with placeholders.

    These templates are strings that use double curly braces `{{}}` to denote variable names,
    which are intended to be replaced by actual values when the template is rendered.
    Example of a template: "Hello, {{ name }}!"

    Attributes:
        prompt_template (str):
            The current state of the template string, initially set with placeholders.
        prompt (str):
            Returns the fully filled template if all placeholders have been replaced, otherwise raises PromptTemplateError.
        unfilled_variables (list[str]): 
            Returns the list of unfilled variable names.

    Methods:
        load_template(prompt_template: str) -> PromptTemplate:
            Class method to create a new instance with the specified template.
        render(**variables) -> Self:
            Renders the template with provided variables and updates the instance.
            This method replaces placeholders in the format `{{ variable }}` with values from `variables`.
        prompt() -> str:
            Returns the fully filled template or raises an error if unfilled placeholders remain.
            This method is used to retrieve the final rendered string if it is fully filled.
        is_fully_filled() -> bool:
            Checks if the template has any unfilled placeholders. This method determines whether all
            placeholders have been replaced.
    """

    def __init__(self, prompt_template: str):
        """
        Initializes a new instance of PromptTemplate with a prompt template string.

        Args:
            prompt_template (str): The initial template string with placeholders.
        """
        self.prompt_template = prompt_template

    @classmethod
    def load_template(cls, prompt_template: str) -> PromptTemplate:
        """
        Class method to create a new instance of PromptTemplate from a given template string.

        Args:
            prompt_template (str): The template string to initialize the template.

        Returns:
            PromptTemplate: A new instance of PromptTemplate initialized with the specified template.
        """
        return PromptTemplate(prompt_template)

    def render(self, **variables) -> Self:
        """
        Renders the template with provided variables and updates the instance. This method replaces
        placeholders in the format `{{ variable }}` with values from `variables`. It allows for chainable 
        method calls, enabling a fluent interface pattern.

        Args:
            **variables:
                Arbitrary keyword arguments where the key is the placeholder variable name and 
                the value is the replacement value.

        Returns:
            PromptTemplate: The instance itself with updated template, allowing for method chaining.

        Example of usage:
            template = PromptTemplate("Hello, {{ name }}! Today is {{ day }}.")
            template.render(name="Alice").render(day="Wednesday")
        """
        prompt_template = render_prompt(self.prompt_template, **variables)
        self.prompt_template = prompt_template
        return self

    @property
    def prompt(self) -> str:
        """
        Returns the fully filled template if all placeholders have been replaced, otherwise raises an PromptTemplateError.

        Returns:
            str: The fully filled template string.

        Raises:
            PromptTemplateError: If the template contains unfilled placeholders.
        """
        if not self.is_fully_filled():
            raise PromptTemplateError("The prompt template is not fully filled.")
        return self.prompt_template

    @property
    def unfilled_variables(self) -> list[str]:
        """Returns the list of unfilled variable names.

        Returns:
            list: The list of unfilled variable names.
        """
        return find_unfilled_variables(self.prompt_template)

    def is_fully_filled(self) -> bool:
        """
        Checks if the template has any unfilled placeholders remaining.

        Returns:
            bool: True if no placeholders remain unfilled, False otherwise.
        """
        return is_prompt_fully_filled(self.prompt_template)

    def __str__(self) -> str:
        """
        Returns the string representation of the current template, which may or may not be fully filled.

        Returns:
            str: The current state of the template string.
        """
        return self.prompt_template

prompt: str property

Returns the fully filled template if all placeholders have been replaced, otherwise raises an PromptTemplateError.

Returns:

Name Type Description
str str

The fully filled template string.

Raises:

Type Description
PromptTemplateError

If the template contains unfilled placeholders.

unfilled_variables: list[str] property

Returns the list of unfilled variable names.

Returns:

Name Type Description
list list[str]

The list of unfilled variable names.

__init__(prompt_template)

Initializes a new instance of PromptTemplate with a prompt template string.

Parameters:

Name Type Description Default
prompt_template str

The initial template string with placeholders.

required
Source code in src/agere/utils/prompt_template.py
def __init__(self, prompt_template: str):
    """
    Initializes a new instance of PromptTemplate with a prompt template string.

    Args:
        prompt_template (str): The initial template string with placeholders.
    """
    self.prompt_template = prompt_template

__str__()

Returns the string representation of the current template, which may or may not be fully filled.

Returns:

Name Type Description
str str

The current state of the template string.

Source code in src/agere/utils/prompt_template.py
def __str__(self) -> str:
    """
    Returns the string representation of the current template, which may or may not be fully filled.

    Returns:
        str: The current state of the template string.
    """
    return self.prompt_template

is_fully_filled()

Checks if the template has any unfilled placeholders remaining.

Returns:

Name Type Description
bool bool

True if no placeholders remain unfilled, False otherwise.

Source code in src/agere/utils/prompt_template.py
def is_fully_filled(self) -> bool:
    """
    Checks if the template has any unfilled placeholders remaining.

    Returns:
        bool: True if no placeholders remain unfilled, False otherwise.
    """
    return is_prompt_fully_filled(self.prompt_template)

load_template(prompt_template) classmethod

Class method to create a new instance of PromptTemplate from a given template string.

Parameters:

Name Type Description Default
prompt_template str

The template string to initialize the template.

required

Returns:

Name Type Description
PromptTemplate PromptTemplate

A new instance of PromptTemplate initialized with the specified template.

Source code in src/agere/utils/prompt_template.py
@classmethod
def load_template(cls, prompt_template: str) -> PromptTemplate:
    """
    Class method to create a new instance of PromptTemplate from a given template string.

    Args:
        prompt_template (str): The template string to initialize the template.

    Returns:
        PromptTemplate: A new instance of PromptTemplate initialized with the specified template.
    """
    return PromptTemplate(prompt_template)

render(**variables)

Renders the template with provided variables and updates the instance. This method replaces placeholders in the format {{ variable }} with values from variables. It allows for chainable method calls, enabling a fluent interface pattern.

Parameters:

Name Type Description Default
**variables

Arbitrary keyword arguments where the key is the placeholder variable name and the value is the replacement value.

{}

Returns:

Name Type Description
PromptTemplate Self

The instance itself with updated template, allowing for method chaining.

Example of usage

template = PromptTemplate("Hello, {{ name }}! Today is {{ day }}.") template.render(name="Alice").render(day="Wednesday")

Source code in src/agere/utils/prompt_template.py
def render(self, **variables) -> Self:
    """
    Renders the template with provided variables and updates the instance. This method replaces
    placeholders in the format `{{ variable }}` with values from `variables`. It allows for chainable 
    method calls, enabling a fluent interface pattern.

    Args:
        **variables:
            Arbitrary keyword arguments where the key is the placeholder variable name and 
            the value is the replacement value.

    Returns:
        PromptTemplate: The instance itself with updated template, allowing for method chaining.

    Example of usage:
        template = PromptTemplate("Hello, {{ name }}! Today is {{ day }}.")
        template.render(name="Alice").render(day="Wednesday")
    """
    prompt_template = render_prompt(self.prompt_template, **variables)
    self.prompt_template = prompt_template
    return self

PromptTemplateError

Bases: AgereUtilsError

Raised when encountering an error related to the prompt template.

Source code in src/agere/utils/prompt_template.py
class PromptTemplateError(AgereUtilsError):
    """Raised when encountering an error related to the prompt template."""

find_unfilled_variables(prompt_template)

Finds and returns the list of unfilled variable names in a template string.

Parameters:

Name Type Description Default
prompt_template str

The template string to check.

required

Returns:

Name Type Description
list list[str]

The list of unfilled variable names.

Source code in src/agere/utils/prompt_template.py
def find_unfilled_variables(prompt_template: str) -> list[str]:
    """
    Finds and returns the list of unfilled variable names in a template string.

    Args:
        prompt_template (str): The template string to check.

    Returns:
        list: The list of unfilled variable names.
    """
    pattern = re.compile(r"\{\{\s*(\w+)\s*\}\}")
    unfilled_variables = pattern.findall(prompt_template)

    return unfilled_variables

is_prompt_fully_filled(prompt)

Checks if a template string contains any unfilled placeholders.

Parameters:

Name Type Description Default
prompt str

The template string to check.

required

Returns:

Name Type Description
bool bool

True if no unfilled placeholders are found, False otherwise.

Source code in src/agere/utils/prompt_template.py
def is_prompt_fully_filled(prompt: str) -> bool:
    """
    Checks if a template string contains any unfilled placeholders.

    Args:
        prompt (str): The template string to check.

    Returns:
        bool: True if no unfilled placeholders are found, False otherwise.
    """
    if find_unfilled_variables(prompt):
        return False
    return True

render_prompt(prompt_template, **variables)

Renders a template string by replacing placeholders formatted as {{ variable }} with values provided in the variables keyword arguments.

Parameters:

Name Type Description Default
prompt_template str

The template string containing placeholders.

required
**variables

Arbitrary keyword arguments where the key is the placeholder variable name and the value is the replacement value.

{}

Returns:

Name Type Description
str str

The template string with placeholders replaced by actual values.

Source code in src/agere/utils/prompt_template.py
def render_prompt(prompt_template: str, **variables) -> str:
    """
    Renders a template string by replacing placeholders formatted as `{{ variable }}`
    with values provided in the variables keyword arguments.

    Args:
        prompt_template (str): The template string containing placeholders.
        **variables:
            Arbitrary keyword arguments where the key is the placeholder variable
            name and the value is the replacement value.

    Returns:
        str: The template string with placeholders replaced by actual values.
    """
    pattern = re.compile(r"\{\{\s*(\w+)\s*\}\}")

    def replace_func(match):
        key = match.group(1)
        return str(variables.get(key, match.group(0)))

    prompt = pattern.sub(replace_func, prompt_template)

    return prompt