|
|
""" |
|
|
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 |
|
|
|
|
|
try_yaml = True |
|
|
except Exception: |
|
|
try_yaml = False |
|
|
|
|
|
try: |
|
|
steps = yaml.safe_load(plan) if try_yaml else json.loads(plan) |
|
|
except Exception: |
|
|
steps = json.loads(plan) |
|
|
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} |
|
|
|