init_template.py 1.8 KB

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