langchain-ai/langchain · error · ImportError

jinja2 not installed, which is needed to use the jinja2_form

Error message

jinja2 not installed, which is needed to use the jinja2_formatter. Please install it with `pip install jinja2`.Please be cautious when using jinja2 templates. Do not expand jinja2 templates using unverified or user-controlled inputs as that can result in arbitrary Python code execution.

What it means

Raised by `jinja2_formatter` in `langchain_core.prompts.string` when a template with `template_format='jinja2'` must be rendered but the optional `jinja2` dependency is not installed. LangChain treats Jinja2 as an optional extra, so importing the formatter machinery succeeds but rendering fails with `ImportError` at call time. The message also warns that Jinja2 templates can execute arbitrary Python code if fed untrusted input — the sandboxed environment used here is best-effort only.

Source

Thrown at libs/core/langchain_core/prompts/string.py:65

    Args:
        template: The template string.
        **kwargs: The variables to format the template with.

    Returns:
        The formatted string.

    Raises:
        ImportError: If jinja2 is not installed.
    """
    if not _HAS_JINJA2:
        msg = (
            "jinja2 not installed, which is needed to use the jinja2_formatter. "
            "Please install it with `pip install jinja2`."
            "Please be cautious when using jinja2 templates. "
            "Do not expand jinja2 templates using unverified or user-controlled "
            "inputs as that can result in arbitrary Python code execution."
        )
        raise ImportError(msg)

    # Use Jinja2's SandboxedEnvironment which blocks access to dunder attributes
    # (e.g., __class__, __globals__) to prevent sandbox escapes.
    # Note: regular attribute access (e.g., {{obj.attr}}) and method calls are
    # still allowed. This is a best-effort measure — do not use with untrusted
    # templates.
    return SandboxedEnvironment().from_string(template).render(**kwargs)


def validate_jinja2(template: str, input_variables: list[str]) -> None:
    """Validate that the input variables are valid for the template.

    Issues a warning if missing or extra variables are found.

    Args:
        template: The template string.
        input_variables: The input variables.
    """

View on GitHub (pinned to e32fa9a52e)

Solutions

  1. Install the dependency: `pip install jinja2` (or `uv add jinja2` / add it to the project's dependencies)
  2. If Jinja2 features (loops, conditionals) are not needed, switch the template to the default f-string format: `template_format="f-string"` and use `{var}` placeholders
  3. Add a startup check like `import jinja2` in environments that use jinja2 templates so the failure surfaces at boot rather than mid-request

Example fix

# before
# environment lacks jinja2
p = PromptTemplate.from_template("{% for i in items %}{{ i }}{% endfor %}", template_format="jinja2")
p.format(items=[1, 2])  # ImportError: jinja2 not installed

# after
pip install jinja2
p.format(items=[1, 2])  # renders "12"
Defensive patterns

Strategy: validation

Validate before calling

def assert_jinja2_available() -> None:
    try:
        import jinja2  # noqa: F401
    except ImportError as e:
        msg = "jinja2 is required for jinja2 prompt templates: pip install jinja2"
        raise RuntimeError(msg) from e

Try / catch

try:
    out = jinja_prompt.format(**vars)
except ImportError:
    raise SystemExit("Missing dependency: run `pip install jinja2`") from None

Prevention

When it happens

Trigger: Creating `PromptTemplate.from_template(t, template_format="jinja2")` and calling `.format(...)` (or invoking a chain containing it) in an environment where `pip install jinja2` was never run. `_HAS_JINJA2` is False, so the `if not _HAS_JINJA2` guard raises immediately.

Common situations: Docker images or CI environments that install only `langchain-core` without extras; upgrading/migrating environments where jinja2 was previously pulled in transitively by another package and later dropped; local runs working but slim production images missing the dependency.

Related errors


AI-assisted analysis of langchain-ai/langchain@e32fa9a52e (2026-08-14). Data as JSON: /api/errors/f327f298aaab751c. Report an issue: GitHub.