|
| 1 | +# coding=utf-8 |
| 2 | +""" |
| 3 | + @project: MaxKB |
| 4 | + @Author:虎虎 |
| 5 | + @file: init_jinja.py |
| 6 | + @date:2025/12/1 17:16 |
| 7 | + @desc: |
| 8 | +""" |
| 9 | +from typing import Any |
| 10 | + |
| 11 | +from jinja2.sandbox import SandboxedEnvironment |
| 12 | +from langchain_core.prompts.string import DEFAULT_FORMATTER_MAPPING, _HAS_JINJA2 |
| 13 | + |
| 14 | + |
| 15 | +def jinja2_formatter(template: str, /, **kwargs: Any) -> str: |
| 16 | + """Format a template using jinja2. |
| 17 | +
|
| 18 | + *Security warning*: |
| 19 | + As of LangChain 0.0.329, this method uses Jinja2's |
| 20 | + SandboxedEnvironment by default. However, this sand-boxing should |
| 21 | + be treated as a best-effort approach rather than a guarantee of security. |
| 22 | + Do not accept jinja2 templates from untrusted sources as they may lead |
| 23 | + to arbitrary Python code execution. |
| 24 | +
|
| 25 | + https://jinja.palletsprojects.com/en/3.1.x/sandbox/ |
| 26 | +
|
| 27 | + Args: |
| 28 | + template: The template string. |
| 29 | + **kwargs: The variables to format the template with. |
| 30 | +
|
| 31 | + Returns: |
| 32 | + The formatted string. |
| 33 | +
|
| 34 | + Raises: |
| 35 | + ImportError: If jinja2 is not installed. |
| 36 | + """ |
| 37 | + if not _HAS_JINJA2: |
| 38 | + msg = ( |
| 39 | + "jinja2 not installed, which is needed to use the jinja2_formatter. " |
| 40 | + "Please install it with `pip install jinja2`." |
| 41 | + "Please be cautious when using jinja2 templates. " |
| 42 | + "Do not expand jinja2 templates using unverified or user-controlled " |
| 43 | + "inputs as that can result in arbitrary Python code execution." |
| 44 | + ) |
| 45 | + raise ImportError(msg) |
| 46 | + |
| 47 | + # Use a restricted sandbox that blocks ALL attribute/method access |
| 48 | + # Only simple variable lookups like {{variable}} are allowed |
| 49 | + # Attribute access like {{variable.attr}} or {{variable.method()}} is blocked |
| 50 | + return SandboxedEnvironment().from_string(template).render(**kwargs) |
| 51 | + |
| 52 | + |
| 53 | +def run(): |
| 54 | + DEFAULT_FORMATTER_MAPPING['jinja2'] = jinja2_formatter |
0 commit comments