File size: 2,442 Bytes
fbf3c28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""
id: compose
title: Plan Composer
author: admin
description: Execute a multi-step plan across tools (YAML or JSON).
version: 0.1.0
license: Proprietary
"""

import json
from typing import Any, Dict


class Tools:
    def run(self, plan: str, variables_json: str = "{}") -> Dict[str, Any]:
        """
        Execute a plan (YAML or JSON). Each step: {tool: id, func: name, args: {...}}
        variables_json: JSON dict for ${var} substitution in args.
        """
        import re
        from open_webui.utils.plugin import load_tool_module_by_id

        try:
            import yaml  # type: ignore

            try_yaml = True
        except Exception:
            try_yaml = False
        # Parse plan
        try:
            steps = yaml.safe_load(plan) if try_yaml else json.loads(plan)
        except Exception:
            steps = json.loads(plan)  # fallback
        if isinstance(steps, dict) and "steps" in steps:
            steps = steps["steps"]
        assert isinstance(steps, list), "plan must be a list of steps"
        vars = json.loads(variables_json) if variables_json else {}

        def subst(obj):
            if isinstance(obj, str):
                return re.sub(
                    r"\$\{([A-Za-z0-9_]+)\}",
                    lambda m: str(vars.get(m.group(1), m.group(0))),
                    obj,
                )
            if isinstance(obj, dict):
                return {k: subst(v) for k, v in obj.items()}
            if isinstance(obj, list):
                return [subst(x) for x in obj]
            return obj

        results = []
        for i, step in enumerate(steps, 1):
            tool_id = step.get("tool")
            func = step.get("func")
            args = subst(step.get("args", {}))
            if not tool_id or not func:
                results.append({"step": i, "error": "missing tool or func"})
                continue
            try:
                mod, _fm = load_tool_module_by_id(tool_id)
                callable = getattr(mod, func)
                out = callable(**args) if callable else {"error": "func not found"}
                results.append(
                    {"step": i, "tool": tool_id, "func": func, "result": out}
                )
            except Exception as e:
                results.append(
                    {"step": i, "tool": tool_id, "func": func, "error": str(e)}
                )
        return {"ok": True, "results": results}