chore(core): add ruff rule PLC0415 (#32351)

See https://docs.astral.sh/ruff/rules/import-outside-top-level/

Co-authored-by: Mason Daugherty <mason@langchain.dev>
This commit is contained in:
Christophe Bornet
2025-09-08 20:15:04 +02:00
committed by GitHub
parent 16420cad71
commit cc98fb9bee
49 changed files with 360 additions and 412 deletions

View File

@@ -88,7 +88,8 @@ class BaseMessagePromptTemplate(Serializable, ABC):
Returns:
Combined prompt template.
"""
from langchain_core.prompts.chat import ChatPromptTemplate
# Import locally to avoid circular import.
from langchain_core.prompts.chat import ChatPromptTemplate # noqa: PLC0415
prompt = ChatPromptTemplate(messages=[self])
return prompt + other

View File

@@ -15,6 +15,14 @@ from langchain_core.utils import get_colored_text, mustache
from langchain_core.utils.formatting import formatter
from langchain_core.utils.interactive_env import is_interactive_env
try:
from jinja2 import Environment, meta
from jinja2.sandbox import SandboxedEnvironment
_HAS_JINJA2 = True
except ImportError:
_HAS_JINJA2 = False
PromptTemplateFormat = Literal["f-string", "mustache", "jinja2"]
@@ -40,9 +48,7 @@ def jinja2_formatter(template: str, /, **kwargs: Any) -> str:
Raises:
ImportError: If jinja2 is not installed.
"""
try:
from jinja2.sandbox import SandboxedEnvironment
except ImportError as e:
if not _HAS_JINJA2:
msg = (
"jinja2 not installed, which is needed to use the jinja2_formatter. "
"Please install it with `pip install jinja2`."
@@ -50,7 +56,7 @@ def jinja2_formatter(template: str, /, **kwargs: Any) -> str:
"Do not expand jinja2 templates using unverified or user-controlled "
"inputs as that can result in arbitrary Python code execution."
)
raise ImportError(msg) from e
raise ImportError(msg)
# This uses a sandboxed environment to prevent arbitrary code execution.
# Jinja2 uses an opt-out rather than opt-in approach for sand-boxing.
@@ -88,14 +94,12 @@ def validate_jinja2(template: str, input_variables: list[str]) -> None:
def _get_jinja2_variables_from_template(template: str) -> set[str]:
try:
from jinja2 import Environment, meta
except ImportError as e:
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) from e
raise ImportError(msg)
env = Environment() # noqa: S701
ast = env.parse(template)
return meta.find_undeclared_variables(ast)