File size: 4,637 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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
import os
import sqlite3
import json
import time
import re
import inspect
import importlib.util
import sys
from pathlib import Path
DB_PATH = os.environ.get(
"WEBUI_DB", "/data/adaptai/migrate/vast/workspace-vast1-2/webui/webui.db"
)
REPO_ROOT = Path(os.environ.get("OUI_MAX_ROOT", "/data/adaptai/projects/oui-max"))
TOOLS_DIR = REPO_ROOT / "tools"
FUNCS_DIR = REPO_ROOT / "functions"
front_re = re.compile(r'^"""\n(.*?)\n"""', re.S)
def parse_frontmatter(text: str) -> dict:
m = front_re.search(text)
fm = {}
if not m:
return fm
for line in m.group(1).splitlines():
if ":" in line:
k, v = line.split(":", 1)
fm[k.strip()] = v.strip()
return fm
def make_specs_from_tools_class(module) -> list:
specs = []
if not hasattr(module, "Tools"):
return specs
cls = getattr(module, "Tools")
for name, func in inspect.getmembers(cls, predicate=inspect.isfunction):
if name.startswith("_"):
continue
sig = inspect.signature(func)
props = {}
req = []
for pname, p in sig.parameters.items():
if pname == "self":
continue
props[pname] = {"type": "string"}
if p.default is inspect._empty:
req.append(pname)
specs.append(
{
"name": name,
"description": func.__doc__.strip() if func.__doc__ else name,
"parameters": {
"type": "object",
"properties": props,
**({"required": req} if req else {}),
},
}
)
return specs
def load_module_from_path(path: Path):
spec = importlib.util.spec_from_file_location(path.stem, str(path))
mod = importlib.util.module_from_spec(spec)
assert spec and spec.loader
spec.loader.exec_module(mod)
return mod
def upsert_tool(cur, admin_id, tool_id, name, content, specs, meta):
now = int(time.time())
row = cur.execute("SELECT id FROM tool WHERE id=?", (tool_id,)).fetchone()
if row:
cur.execute(
"UPDATE tool SET user_id=?, name=?, content=?, specs=?, meta=?, updated_at=? WHERE id=?",
(
admin_id,
name,
content,
json.dumps(specs),
json.dumps(meta),
now,
tool_id,
),
)
else:
cur.execute(
"INSERT INTO tool(id,user_id,name,content,specs,meta,created_at,updated_at,valves,access_control) VALUES(?,?,?,?,?,?,?,?,NULL,NULL)",
(
tool_id,
admin_id,
name,
content,
json.dumps(specs),
json.dumps(meta),
now,
now,
),
)
def main():
if not Path(DB_PATH).exists():
print("DB not found:", DB_PATH)
sys.exit(1)
con = sqlite3.connect(DB_PATH)
cur = con.cursor()
admin = cur.execute(
"SELECT id FROM user ORDER BY created_at ASC LIMIT 1"
).fetchone()
admin_id = admin[0] if admin else None
# ensure tables exist
try:
cur.execute("SELECT 1 FROM tool LIMIT 1")
cur.execute("SELECT 1 FROM function LIMIT 1")
except Exception as e:
print("DB schema missing:", e)
con.close()
sys.exit(1)
# Clear existing tools/functions for clean slate
cur.execute("DELETE FROM tool")
cur.execute("DELETE FROM function")
# Seed tools (skip private/underscore files)
for path in sorted(TOOLS_DIR.glob("*.py")):
if path.name.startswith("_"):
# Skip internal modules not intended for Open WebUI Tools
continue
text = path.read_text()
fm = parse_frontmatter(text)
tool_id = fm.get("id") or path.stem
name = fm.get("title") or path.stem
meta = {
"description": fm.get("description", ""),
"manifest": {"version": fm.get("version", "")},
}
mod = load_module_from_path(path)
specs = make_specs_from_tools_class(mod)
if not specs:
# Only register tools that expose a Tools class with callable methods
print("skip: no Tools class for", tool_id)
continue
upsert_tool(cur, admin_id, tool_id, name, text, specs, meta)
print("seeded tool:", tool_id)
# Functions seeding placeholder (none by default)
con.commit()
con.close()
print("seeding complete")
if __name__ == "__main__":
main()
|