Skip to content

pandas_utils

langroid/utils/pandas_utils.py

UnsafeCommandError

Bases: ValueError

Raised when a command string violates security policy.

CommandValidator(df_name='df')

Bases: NodeVisitor

AST walker that enforces the security policy.

Source code in langroid/utils/pandas_utils.py
def __init__(self, df_name: str = "df"):
    self.df_name = df_name
    self.depth = 0
    self.chain = 0

sanitize_command(expr, df_name='df')

Validate expr; return it unchanged if it passes all rules, else raise UnsafeCommandError with the first violation encountered.

Source code in langroid/utils/pandas_utils.py
def sanitize_command(expr: str, df_name: str = "df") -> str:
    """
    Validate *expr*; return it unchanged if it passes all rules,
    else raise UnsafeCommandError with the first violation encountered.
    """
    tree = ast.parse(expr, mode="eval")
    CommandValidator(df_name).visit(tree)
    return expr

safe_eval_globals(local_vars)

Return a globals dict for :func:eval with __builtins__ restricted to a safe read-only set, so that LLM-generated expressions cannot reach __import__, eval, exec, open, etc. via Python's implicit builtin injection.

Parameters:

Name Type Description Default
local_vars Dict[str, Any]

User-provided variables to expose to the eval'd expression (e.g. {"df": <DataFrame>}).

required

Returns:

Type Description
Dict[str, Any]

A new dict suitable as the globals argument of eval().

Source code in langroid/utils/pandas_utils.py
def safe_eval_globals(local_vars: Dict[str, Any]) -> Dict[str, Any]:
    """Return a globals dict for :func:`eval` with ``__builtins__`` restricted
    to a safe read-only set, so that LLM-generated expressions cannot reach
    ``__import__``, ``eval``, ``exec``, ``open``, etc. via Python's implicit
    builtin injection.

    Args:
        local_vars: User-provided variables to expose to the eval'd
            expression (e.g. ``{"df": <DataFrame>}``).

    Returns:
        A new dict suitable as the ``globals`` argument of ``eval()``.
    """
    return {**local_vars, "__builtins__": _SAFE_BUILTINS}