Skip to content

Jinja2Config

Base classes

Name Children Inherits
ConfigModel
llmling.config.base
Base class for all LLMling configuration models.

⋔ Inheritance diagram

graph TD
  3992295014["models.Jinja2Config"]
  2455074328["base.ConfigModel"]
  330168112["schema.Schema"]
  3879467795["main.BaseModel"]
  2751680898["builtins.object"]
  2455074328 --> 3992295014
  330168112 --> 2455074328
  3879467795 --> 330168112
  2751680898 --> 3879467795

🛈 DocStrings

Bases: ConfigModel

Configuration for Jinja2 environment.

See: https://jinja.palletsprojects.com/en/3.1.x/api/#jinja2.Environment

Source code in src/llmling/config/models.py
class Jinja2Config(ConfigModel):
    """Configuration for Jinja2 environment.

    See: https://jinja.palletsprojects.com/en/3.1.x/api/#jinja2.Environment
    """

    block_start_string: str = "{%"
    """String denoting the beginning of a block (default: '{%')."""

    block_end_string: str = "%}"
    """String denoting the end of a block (default: '%}')."""

    variable_start_string: str = "{{"
    """String denoting the beginning of a variable (default: '{{')."""

    variable_end_string: str = "}}"
    """String denoting the end of a variable (default: '}}')."""

    comment_start_string: str = "{#"
    """String denoting the beginning of a comment (default: '{#')."""

    comment_end_string: str = "#}"
    """String denoting the end of a comment (default: '#}')."""

    line_statement_prefix: str | None = None
    """Prefix that begins a line-based statement (e.g., '#' for line statements)."""

    line_comment_prefix: str | None = None
    """Prefix that begins a line-based comment."""

    trim_blocks: bool = False
    """Remove first newline after a block (affects whitespace control)."""

    lstrip_blocks: bool = False
    """Remove leading spaces and tabs from the start of a line to a block."""

    newline_sequence: Literal["\n", "\r\n", "\r"] = "\n"
    """Sequence that starts a newline (default: '\n')."""

    keep_trailing_newline: bool = False
    """Preserve the trailing newline when rendering templates."""

    extensions: list[str] = Field(default_factory=list)
    """List of Jinja2 extensions to load (e.g., 'jinja2.ext.do')."""

    undefined: Literal["default", "strict", "debug", "chainable"] = "default"
    """Behavior when accessing undefined variables (default, strict, debug, chainable)."""

    filters: dict[str, str] = Field(default_factory=dict)
    """Custom filters as mapping of names to import paths."""

    tests: dict[str, str] = Field(default_factory=dict)
    """Custom tests as mapping of names to import paths."""

    globals: dict[str, Any] = Field(default_factory=dict)
    """Global variables available to all templates."""

    def create_environment_kwargs(self) -> dict[str, Any]:
        """Convert config to Jinja2 environment kwargs.

        Creates a dictionary of kwargs for jinja2.Environment with proper
        conversion of special values.

        Returns:
            Dict of kwargs for jinja2.Environment constructor

        Raises:
            ValueError: If filter or test imports fail
        """
        import jinja2

        # Start with basic string/bool config items
        kwargs = self.model_dump(exclude={"undefined", "filters", "tests"})

        # Convert undefined to proper class
        kwargs["undefined"] = {
            "default": jinja2.Undefined,
            "strict": jinja2.StrictUndefined,
            "debug": jinja2.DebugUndefined,
            "chainable": jinja2.ChainableUndefined,
        }[self.undefined]

        try:
            # Import filters and tests (must be callables)
            filters = {name: import_callable(path) for name, path in self.filters.items()}
            kwargs["filters"] = filters
            tests = {name: import_callable(path) for name, path in self.tests.items()}
            kwargs["tests"] = tests
        except Exception as exc:
            msg = f"Failed to import Jinja2 filters/tests: {exc}"
            raise ValueError(msg) from exc

        return kwargs

block_end_string class-attribute instance-attribute

block_end_string: str = '%}'

String denoting the end of a block (default: '%}').

block_start_string class-attribute instance-attribute

block_start_string: str = '{%'

String denoting the beginning of a block (default: '{%').

comment_end_string class-attribute instance-attribute

comment_end_string: str = '#}'

String denoting the end of a comment (default: '#}').

comment_start_string class-attribute instance-attribute

comment_start_string: str = '{#'

String denoting the beginning of a comment (default: '{#').

extensions class-attribute instance-attribute

extensions: list[str] = Field(default_factory=list)

List of Jinja2 extensions to load (e.g., 'jinja2.ext.do').

filters class-attribute instance-attribute

filters: dict[str, str] = Field(default_factory=dict)

Custom filters as mapping of names to import paths.

globals class-attribute instance-attribute

globals: dict[str, Any] = Field(default_factory=dict)

Global variables available to all templates.

keep_trailing_newline class-attribute instance-attribute

keep_trailing_newline: bool = False

Preserve the trailing newline when rendering templates.

line_comment_prefix class-attribute instance-attribute

line_comment_prefix: str | None = None

Prefix that begins a line-based comment.

line_statement_prefix class-attribute instance-attribute

line_statement_prefix: str | None = None

Prefix that begins a line-based statement (e.g., '#' for line statements).

lstrip_blocks class-attribute instance-attribute

lstrip_blocks: bool = False

Remove leading spaces and tabs from the start of a line to a block.

newline_sequence class-attribute instance-attribute

newline_sequence: Literal['\n', '\r\n', '\r'] = '\n'

Sequence that starts a newline (default: ' ').

tests class-attribute instance-attribute

tests: dict[str, str] = Field(default_factory=dict)

Custom tests as mapping of names to import paths.

trim_blocks class-attribute instance-attribute

trim_blocks: bool = False

Remove first newline after a block (affects whitespace control).

undefined class-attribute instance-attribute

undefined: Literal['default', 'strict', 'debug', 'chainable'] = 'default'

Behavior when accessing undefined variables (default, strict, debug, chainable).

variable_end_string class-attribute instance-attribute

variable_end_string: str = '}}'

String denoting the end of a variable (default: '}}').

variable_start_string class-attribute instance-attribute

variable_start_string: str = '{{'

String denoting the beginning of a variable (default: '{{').

create_environment_kwargs

create_environment_kwargs() -> dict[str, Any]

Convert config to Jinja2 environment kwargs.

Creates a dictionary of kwargs for jinja2.Environment with proper conversion of special values.

Returns:

Type Description
dict[str, Any]

Dict of kwargs for jinja2.Environment constructor

Raises:

Type Description
ValueError

If filter or test imports fail

Source code in src/llmling/config/models.py
def create_environment_kwargs(self) -> dict[str, Any]:
    """Convert config to Jinja2 environment kwargs.

    Creates a dictionary of kwargs for jinja2.Environment with proper
    conversion of special values.

    Returns:
        Dict of kwargs for jinja2.Environment constructor

    Raises:
        ValueError: If filter or test imports fail
    """
    import jinja2

    # Start with basic string/bool config items
    kwargs = self.model_dump(exclude={"undefined", "filters", "tests"})

    # Convert undefined to proper class
    kwargs["undefined"] = {
        "default": jinja2.Undefined,
        "strict": jinja2.StrictUndefined,
        "debug": jinja2.DebugUndefined,
        "chainable": jinja2.ChainableUndefined,
    }[self.undefined]

    try:
        # Import filters and tests (must be callables)
        filters = {name: import_callable(path) for name, path in self.filters.items()}
        kwargs["filters"] = filters
        tests = {name: import_callable(path) for name, path in self.tests.items()}
        kwargs["tests"] = tests
    except Exception as exc:
        msg = f"Failed to import Jinja2 filters/tests: {exc}"
        raise ValueError(msg) from exc

    return kwargs

:fa-brands-github: Show source on GitHub