{"record":{"id":"f327f298aaab751c","repo":"langchain-ai/langchain","slug":"jinja2-not-installed-which-is-needed-to-use-the-j","errorCode":null,"errorMessage":"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.","messagePattern":"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\\.","errorType":"exception","errorClass":"ImportError","httpStatus":null,"severity":"error","filePath":"libs/core/langchain_core/prompts/string.py","lineNumber":65,"sourceCode":"    Args:\n        template: The template string.\n        **kwargs: The variables to format the template with.\n\n    Returns:\n        The formatted string.\n\n    Raises:\n        ImportError: If jinja2 is not installed.\n    \"\"\"\n    if not _HAS_JINJA2:\n        msg = (\n            \"jinja2 not installed, which is needed to use the jinja2_formatter. \"\n            \"Please install it with `pip install jinja2`.\"\n            \"Please be cautious when using jinja2 templates. \"\n            \"Do not expand jinja2 templates using unverified or user-controlled \"\n            \"inputs as that can result in arbitrary Python code execution.\"\n        )\n        raise ImportError(msg)\n\n    # Use Jinja2's SandboxedEnvironment which blocks access to dunder attributes\n    # (e.g., __class__, __globals__) to prevent sandbox escapes.\n    # Note: regular attribute access (e.g., {{obj.attr}}) and method calls are\n    # still allowed. This is a best-effort measure — do not use with untrusted\n    # templates.\n    return SandboxedEnvironment().from_string(template).render(**kwargs)\n\n\ndef validate_jinja2(template: str, input_variables: list[str]) -> None:\n    \"\"\"Validate that the input variables are valid for the template.\n\n    Issues a warning if missing or extra variables are found.\n\n    Args:\n        template: The template string.\n        input_variables: The input variables.\n    \"\"\"","sourceCodeStart":47,"sourceCodeEnd":83,"githubUrl":"https://github.com/langchain-ai/langchain/blob/e32fa9a52eab3b61ad7a45399bfde59b3e580fc4/libs/core/langchain_core/prompts/string.py#L47-L83","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Install the dependency: `pip install jinja2` (or `uv add jinja2` / add it to the project's dependencies)","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","Add a startup check like `import jinja2` in environments that use jinja2 templates so the failure surfaces at boot rather than mid-request"],"exampleFix":"# before\n# environment lacks jinja2\np = PromptTemplate.from_template(\"{% for i in items %}{{ i }}{% endfor %}\", template_format=\"jinja2\")\np.format(items=[1, 2])  # ImportError: jinja2 not installed\n\n# after\npip install jinja2\np.format(items=[1, 2])  # renders \"12\"","handlingStrategy":"validation","validationCode":"def assert_jinja2_available() -> None:\n    try:\n        import jinja2  # noqa: F401\n    except ImportError as e:\n        msg = \"jinja2 is required for jinja2 prompt templates: pip install jinja2\"\n        raise RuntimeError(msg) from e","typeGuard":null,"tryCatchPattern":"try:\n    out = jinja_prompt.format(**vars)\nexcept ImportError:\n    raise SystemExit(\"Missing dependency: run `pip install jinja2`\") from None","preventionTips":["Declare jinja2 in project dependencies whenever any prompt uses template_format='jinja2'","Add a boot-time `import jinja2` check in services using jinja templates","Never render jinja2 templates from untrusted input (arbitrary code execution risk, sandbox is best-effort)"],"tags":["prompts","jinja2","importerror","dependencies","optional-deps"],"backgroundTag":null,"analyzedSha":"e32fa9a52eab3b61ad7a45399bfde59b3e580fc4","analyzedAt":"2026-08-14T18:42:09.092Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}