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`.

What it means

Raised by `_get_jinja2_variables_from_template` in `langchain_core.prompts.string` when LangChain needs to statically parse a Jinja2 template to discover its variables (e.g. in `get_template_variables` or when a `PromptTemplate` with `template_format='jinja2'` infers its `input_variables`) but the optional `jinja2` package is absent. Unlike the formatter variant (which fires at render time), this fires at template-construction/inspection time because parsing the AST requires the library.

Source

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

    warning_message = ""
    if missing_variables:
        warning_message += f"Missing variables: {missing_variables} "

    if extra_variables:
        warning_message += f"Extra variables: {extra_variables}"

    if warning_message:
        warnings.warn(warning_message.strip(), stacklevel=7)


def _get_jinja2_variables_from_template(template: str) -> set[str]:
    if not _HAS_JINJA2:
        msg = (
            "jinja2 not installed, which is needed to use the jinja2_formatter. "
            "Please install it with `pip install jinja2`."
        )
        raise ImportError(msg)
    env = SandboxedEnvironment()
    ast = env.parse(template)
    return meta.find_undeclared_variables(ast)


def mustache_formatter(template: str, /, **kwargs: Any) -> str:
    """Format a template using mustache.

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

    Returns:
        The formatted string.
    """
    return mustache.render(template, kwargs)

View on GitHub (pinned to e32fa9a52e)

Solutions

  1. Install jinja2: `pip install jinja2` (or add it to the dependency list for any service using jinja2-format prompts)
  2. Pass `input_variables` explicitly if you only need to construct the object — but note formatting will still need jinja2, so installing it is the real fix
  3. If the template does not need Jinja2 control flow, rewrite it as an f-string template (`{var}`) which needs no extra dependency

Example fix

# before
# jinja2 not installed
vars_ = get_template_variables("{{ name }} is {{ age }}", "jinja2")  # ImportError

# after
pip install jinja2
vars_ = get_template_variables("{{ name }} is {{ age }}", "jinja2")  # ['age', 'name']
Defensive patterns

Strategy: validation

Validate before calling

def assert_jinja2_available() -> None:
    try:
        import jinja2  # noqa: F401
    except ImportError as e:
        msg = "jinja2 required to infer variables from jinja2 templates"
        raise RuntimeError(msg) from e

assert_jinja2_available()  # before PromptTemplate.from_template(t, template_format="jinja2")

Try / catch

try:
    p = PromptTemplate.from_template(t, template_format="jinja2")
except ImportError:
    raise SystemExit("pip install jinja2") from None

Prevention

When it happens

Trigger: `PromptTemplate.from_template(t, template_format="jinja2")` without explicit `input_variables` in an environment lacking jinja2 — variable inference calls this helper and hits the `_HAS_JINJA2` guard. Also `get_template_variables(t, "jinja2")` directly.

Common situations: Fresh installs of `langchain-core` alone (jinja2 is not a hard dependency); CI pipelines that trim requirements files; sharing code across teams where one environment has jinja2 and a minimal deployment environment does not.

Related errors


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