adaptai / projects /oui-max /scripts /seed_openwebui.py
ADAPT-Chase's picture
Add files using upload-large-folder tool
fbf3c28 verified
Raw History Blame Contribute Delete
4.64 kB
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()