Skip to content

loader

loader

Template loader — dynamically construct BaseTool from TOML definitions.

Classes

ToolTemplate

ToolTemplate(template_data: Dict[str, Any])

Bases: BaseTool

A tool dynamically constructed from a TOML template definition.

Source code in src/openjarvis/tools/templates/loader.py
def __init__(self, template_data: Dict[str, Any]) -> None:
    self._data = template_data
    self.tool_id = template_data.get("name", "template")
    self._name = template_data.get("name", "template")
    self._description = template_data.get("description", "")
    self._parameters = template_data.get("parameters", {})
    self._action = template_data.get("action", {})

Functions

safe_eval_expr

safe_eval_expr(expr: str, names: Dict[str, Any]) -> Any

Safely evaluate a template python-action expression.

Parses expr and interprets it against the allowlist in :func:_eval_node. No eval/exec is used, and the only callables reachable are :data:_SAFE_EVAL_FUNCS plus the supplied names (the tool parameters). Raises ValueError / SyntaxError on anything unsafe.

Source code in src/openjarvis/tools/templates/loader.py
def safe_eval_expr(expr: str, names: Dict[str, Any]) -> Any:
    """Safely evaluate a template ``python``-action expression.

    Parses *expr* and interprets it against the allowlist in
    :func:`_eval_node`. No ``eval``/``exec`` is used, and the only callables
    reachable are :data:`_SAFE_EVAL_FUNCS` plus the supplied *names* (the tool
    parameters). Raises ``ValueError`` / ``SyntaxError`` on anything unsafe.
    """
    return _eval_node(ast.parse(expr, mode="eval"), names)

load_template

load_template(path: str | Path) -> ToolTemplate

Load a single tool template from a TOML file.

Source code in src/openjarvis/tools/templates/loader.py
def load_template(path: str | Path) -> ToolTemplate:
    """Load a single tool template from a TOML file."""
    path = Path(path)
    with open(path, "rb") as fh:
        data = tomllib.load(fh)
    tool_data = data.get("tool", data)
    return ToolTemplate(tool_data)

discover_templates

discover_templates(directory: Optional[str | Path] = None) -> List[ToolTemplate]

Discover all TOML templates in a directory.

Source code in src/openjarvis/tools/templates/loader.py
def discover_templates(
    directory: Optional[str | Path] = None,
) -> List[ToolTemplate]:
    """Discover all TOML templates in a directory."""
    if directory is None:
        directory = Path(__file__).parent / "builtin"
    directory = Path(directory)
    if not directory.exists():
        return []
    templates = []
    for path in sorted(directory.glob("*.toml")):
        try:
            templates.append(load_template(path))
        except Exception as exc:
            logger.debug("Skipping unparseable template %s: %s", path, exc)
    return templates