toolrouter / web /index.html
stanley-nv's picture
Upload model
b2607a3 verified
Raw History Blame Contribute Delete
17.1 kB
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ToolRouter playground</title>
<style>
:root { --bg:#f6f7fb; --card:#fff; --ink:#1b1f2a; --muted:#667085; --line:#e4e7ee; --accent:#4f46e5; --good:#12805c; --mid:#b45309; --bad:#b42318; --bar:#c7d2fe; }
@media (prefers-color-scheme: dark) { :root { --bg:#0f1220; --card:#171a2b; --ink:#e8eaf3; --muted:#98a2b3; --line:#2a2f45; --accent:#818cf8; --good:#34d399; --mid:#fbbf24; --bad:#f87171; --bar:#3730a3; } }
* { box-sizing: border-box; }
body { margin:0; font:15px/1.45 system-ui,-apple-system,Segoe UI,Roboto,sans-serif; background:var(--bg); color:var(--ink); }
header { padding:22px 24px 8px; max-width:1200px; margin:0 auto; }
h1 { margin:0 0 4px; font-size:24px; } header p { margin:0; color:var(--muted); max-width:900px; }
main { max-width:1200px; margin:0 auto; padding:12px 24px 40px; display:grid; grid-template-columns:minmax(0,3fr) minmax(0,2fr); gap:18px; }
@media (max-width: 900px) { main { grid-template-columns:1fr; } }
.card { background:var(--card); border:1px solid var(--line); border-radius:12px; padding:16px; }
.card h2 { margin:0 0 10px; font-size:15px; text-transform:uppercase; letter-spacing:.04em; color:var(--muted); }
label { font-size:13px; color:var(--muted); display:block; margin-bottom:4px; }
input, textarea, select, button { font:inherit; color:inherit; }
input[type=text], textarea, select { width:100%; padding:8px 10px; border:1px solid var(--line); border-radius:8px; background:var(--bg); }
textarea { resize:vertical; min-height:38px; }
button { padding:8px 14px; border:1px solid var(--line); border-radius:8px; background:var(--card); cursor:pointer; }
button:hover { border-color:var(--accent); } button.primary { background:var(--accent); border-color:var(--accent); color:#fff; font-weight:600; }
button:disabled { opacity:.5; cursor:not-allowed; }
table { width:100%; border-collapse:collapse; } th { text-align:left; font-size:12px; color:var(--muted); font-weight:600; padding:0 6px 6px; }
td { padding:3px 4px; vertical-align:top; } td.name { width:26%; } td.desc { width:44%; } td.ex { width:26%; } td.del { width:4%; }
td.del button { padding:4px 8px; border-color:transparent; color:var(--muted); }
.row { display:flex; gap:10px; align-items:center; flex-wrap:wrap; } .grow { flex:1; min-width:180px; }
.chips { display:flex; flex-wrap:wrap; gap:6px; margin-top:10px; } .chip { font-size:12.5px; padding:4px 10px; border-radius:999px; background:var(--bg); border:1px solid var(--line); cursor:pointer; }
.chip:hover { border-color:var(--accent); }
.result { display:none; } .result.show { display:block; }
.pick { font-size:26px; font-weight:700; word-break:break-all; } .meta { color:var(--muted); font-size:13px; margin-top:2px; }
.badge { display:inline-block; padding:2px 10px; border-radius:999px; font-weight:600; font-size:13px; color:#fff; vertical-align:middle; }
.warn { margin-top:8px; padding:8px 10px; border-radius:8px; background:rgba(180,83,9,.12); color:var(--mid); font-size:13px; }
.err { margin-top:8px; padding:8px 10px; border-radius:8px; background:rgba(180,35,24,.12); color:var(--bad); font-size:13px; display:none; }
.bars { margin-top:12px; } .bar { display:grid; grid-template-columns:minmax(80px,32%) 1fr 56px; align-items:center; gap:8px; margin:5px 0; font-size:13.5px; }
.bar .track { height:14px; background:var(--bg); border-radius:7px; overflow:hidden; border:1px solid var(--line); } .bar .fill { height:100%; background:var(--bar); }
.bar.top .fill { background:var(--accent); } .bar .lab { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } .bar .val { text-align:right; font-variant-numeric:tabular-nums; color:var(--muted); }
details { margin-top:12px; } summary { cursor:pointer; color:var(--muted); font-size:13px; }
pre { margin:8px 0 0; padding:10px; background:var(--bg); border:1px solid var(--line); border-radius:8px; overflow:auto; font-size:12.5px; max-height:300px; }
.small { font-size:12.5px; color:var(--muted); } .progress { height:6px; background:var(--line); border-radius:3px; overflow:hidden; margin-top:6px; } .progress > div { height:100%; width:0; background:var(--accent); transition:width .2s; }
footer { max-width:1200px; margin:0 auto; padding:0 24px 30px; color:var(--muted); font-size:12.5px; } a { color:var(--accent); }
</style>
</head>
<body>
<header>
<h1>🧭 ToolRouter playground</h1>
<p>Define <b>your own tools</b> (name + description, optionally example queries), type a query, and see which tool a tiny router picks. The model (7.7&nbsp;MB, downloaded once from the model repo) runs <b>in your browser</b> — nothing you type is sent anywhere. Input and output use a structured <code>choice</code> format.</p>
</header>
<main>
<section class="card">
<h2>1 · Tools</h2>
<div class="row"><div class="grow"><label for="preset">Start from a preset</label><select id="preset"></select></div>
<div style="align-self:flex-end"><button id="addRow">+ Add tool</button></div></div>
<table id="tools" style="margin-top:10px"><thead><tr><th>Tool name</th><th>Description</th><th>Example queries (optional, “;” separated)</th><th></th></tr></thead><tbody></tbody></table>
<details><summary>Edit as JSON</summary>
<p class="small">Either <code>{"tool_name": "description"}</code> or <code>{"tool_name": {"description": "…", "examples": ["…"]}}</code></p>
<textarea id="json" rows="9" spellcheck="false" style="font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12.5px"></textarea>
<div class="row" style="margin-top:8px"><button id="jsonToTable">JSON → table</button><button id="tableToJson">table → JSON</button></div></details>
<p class="small" style="margin-bottom:0">Tips: specific descriptions beat short ones · add example queries to sharpen a tool · works best with ≤ 10 tools.</p>
</section>
<section class="card">
<h2>2 · Query</h2>
<label for="query">User query</label>
<textarea id="query" rows="2" placeholder="e.g. how is Google trading today"></textarea>
<div class="row" style="margin-top:10px"><button class="primary" id="go" disabled>Route</button><span id="status" class="small">loading model…</span></div>
<div class="progress" id="prog"><div></div></div>
<div class="err" id="err"></div>
<div class="chips" id="chips"></div>
<div class="result" id="result">
<hr style="border:none;border-top:1px solid var(--line);margin:16px 0">
<div class="pick" id="pick"></div><div class="meta" id="meta"></div><div class="warn" id="warn" style="display:none"></div>
<div class="bars" id="bars"></div>
<details><summary>request / response</summary><pre id="req"></pre><pre id="resp"></pre></details>
</div>
</section>
</main>
<footer>Model: <a href="https://huggingface.co/stanley-nv/toolrouter">stanley-nv/toolrouter</a> · data: <a href="https://huggingface.co/datasets/stanley-nv/tool-routing-data">stanley-nv/tool-routing-data</a> · backbone: potion-base-8M (MIT) · small test sets written by LLMs; expect lower accuracy on real traffic.</footer>
<script type="module">
import { ToolRouter } from "./toolrouter.js";
const DEFAULT7 = {wiki:"Encyclopedic, stable facts: definitions, history, people, places, science concepts.", websearch:"Live or commercial web info: prices, reviews, products, how-tos, scores, directions.",
weather:"Weather conditions or forecasts for a place and time.", news:"Recent news, headlines, breaking events and updates on a topic.", files:"Reading, finding, creating or editing local files and folders.",
shell:"Running terminal commands: git, installs, processes, system status, builds.", other:"No tool needed: chit-chat, math, writing, translation, coding help, advice."};
const PRESETS = {
"Smart assistant": {stock_quotes:"Real-time share prices, tickers and market indices from stock exchanges.", smart_home:"Control lights, thermostat, locks, cameras and other connected home devices.",
calendar:"Read, create and move meetings and appointments on the user's calendar.", food_delivery:"Order meals and groceries for delivery from restaurants and stores.",
flight_search:"Search airlines for flights, fares and schedules between airports.", translator:"Translate words, sentences and documents from one language to another.",
git_helper:"Run git operations: commit, push, pull, branches, diffs and history of the repository.", other:"No tool needed: chit-chat, writing, math, advice and general questions."},
"7 priority tools": DEFAULT7,
"Business ops": {crm_lookup:"Find customers, accounts, contacts and deal status in the CRM.", invoice_manager:"Create, send and track invoices, payments and overdue balances.",
hr_portal:"Request leave, view payslips and look up company HR policies.", expense_reports:"Submit and approve expense claims, receipts and reimbursements.",
meeting_scheduler:"Find free time and book meetings with colleagues and rooms.", other:"No tool needed: general questions and writing help."},
"Dev & IT": {log_search:"Search application and server logs for errors, stack traces and request ids.", ci_pipeline:"Trigger, monitor and retry CI/CD builds, tests and deployments.",
cloud_console:"Start, stop and inspect cloud virtual machines, disks and costs.", pager_oncall:"Page the on-call engineer and manage incidents and alerts.",
code_search:"Search the source code repositories for functions, symbols and usages.", other:"No tool needed: explanations, code writing and general questions."},
"Tools with examples": {bank:{description:"Banking access.", examples:["how much money do I have","show my last transactions"]},
calendar:{description:"Calendar access.", examples:["what meetings do I have today","move my 3pm to Friday"]}, other:"No tool needed."},
};
const EXAMPLES = [["Smart assistant","how is Google trading today"],["Smart assistant","turn off the living room lights"],["Smart assistant","commit my changes and push"],["Smart assistant","order me a pizza for tonight"],
["7 priority tools","will it rain in Hanoi tomorrow"],["7 priority tools","kill the process on port 8080"],["7 priority tools","any news on the Fed rate decision"],["7 priority tools","open config.yaml and show me the port"],
["Dev & IT","why did the deploy fail at 3am"],["Business ops","reimburse my taxi receipt from Monday"],["Tools with examples","what's my balance"]];
const $ = (id) => document.getElementById(id), tbody = $("tools").querySelector("tbody");
let router = null;
const autosize = (el) => { el.style.height = "auto"; el.style.height = Math.max(el.scrollHeight + 2, 40) + "px"; };
function addRow(name = "", desc = "", ex = "") {
const tr = document.createElement("tr");
tr.innerHTML = `<td class="name"><input type="text" placeholder="tool_name" aria-label="tool name"></td><td class="desc"><textarea rows="1" placeholder="what the tool does" aria-label="description" style="overflow:hidden"></textarea></td>
<td class="ex"><textarea rows="1" placeholder="optional" aria-label="example queries" style="overflow:hidden"></textarea></td><td class="del"><button title="remove tool" aria-label="remove tool">✕</button></td>`;
tr.querySelector("input").value = name; const [d, e] = tr.querySelectorAll("textarea"); d.value = desc; e.value = ex;
tr.querySelector("button").onclick = () => { tr.remove(); save(); }; tr.querySelectorAll("input,textarea").forEach((el) => el.addEventListener("input", save));
tr.querySelectorAll("textarea").forEach((el) => el.addEventListener("input", () => autosize(el))); tbody.appendChild(tr); tr.querySelectorAll("textarea").forEach(autosize);
}
function setTools(crit) {
tbody.innerHTML = "";
for (const [n, v] of Object.entries(crit)) v && typeof v === "object" ? addRow(n, v.description || "", (v.examples || []).join("; ")) : addRow(n, String(v), "");
$("json").value = JSON.stringify(crit, null, 2); save();
}
function getTools() {
const crit = {}, seen = new Set();
for (const tr of tbody.querySelectorAll("tr")) {
const name = tr.querySelector("input").value.trim(); if (!name) continue;
if (seen.has(name)) throw new Error(`Duplicate tool name: "${name}"`); seen.add(name);
const [d, e] = tr.querySelectorAll("textarea"), ex = e.value.split(";").map((s) => s.trim()).filter(Boolean);
crit[name] = ex.length ? {description: d.value.trim(), examples: ex} : d.value.trim();
}
if (!Object.keys(crit).length) throw new Error("Add at least one tool (a row with a name).");
return crit;
}
function save() { try { localStorage.setItem("toolrouter.tools", JSON.stringify(getTools())); } catch (_) {} }
function showErr(msg) { const e = $("err"); e.textContent = msg || ""; e.style.display = msg ? "block" : "none"; }
function route() {
showErr("");
try {
const q = $("query").value.trim(); if (!q) throw new Error("Type a query first.");
const crit = getTools(), req = {state: q, questions: {tool: {type: "choice", instructions: "Pick the single best tool.", criteria: crit}}};
const t0 = performance.now(), resp = router.handle(req), ms = performance.now() - t0, a = resp.answers.tool;
$("pick").textContent = "→ " + a.choice; const c = a.confidence;
$("meta").innerHTML = `confidence <span class="badge" style="background:${c >= .8 ? "var(--good)" : c >= .5 ? "var(--mid)" : "var(--bad)"}">${c.toFixed(2)}</span> · ${ms.toFixed(1)} ms · ${Object.keys(crit).length} tools`;
const w = $("warn"); w.style.display = c < .8 ? "block" : "none"; w.textContent = "Low confidence — add a clearer description or example queries to the tool, or fall back to a larger model.";
$("bars").innerHTML = Object.entries(a.probabilities).sort((x, y) => y[1] - x[1]).map(([n, p], i) =>
`<div class="bar ${i === 0 ? "top" : ""}"><span class="lab" title="${n.replace(/"/g, "&quot;")}"></span><span class="track"><span class="fill" style="display:block;width:${(p * 100).toFixed(1)}%"></span></span><span class="val">${(p * 100).toFixed(1)}%</span></div>`).join("");
[...$("bars").querySelectorAll(".lab")].forEach((el, i) => el.textContent = Object.entries(a.probabilities).sort((x, y) => y[1] - x[1])[i][0]);
$("req").textContent = "request\n" + JSON.stringify(req, null, 2); $("resp").textContent = "response\n" + JSON.stringify(resp, null, 2); $("result").classList.add("show");
} catch (e) { showErr(e.message); }
}
for (const k of Object.keys(PRESETS)) $("preset").add(new Option(k, k));
$("preset").onchange = () => setTools(PRESETS[$("preset").value]);
$("addRow").onclick = () => addRow();
$("jsonToTable").onclick = () => { try { const c = JSON.parse($("json").value); if (!c || typeof c !== "object" || Array.isArray(c) || !Object.keys(c).length) throw new Error('JSON must be an object like {"tool_name": "description"}'); showErr(""); setTools(c); } catch (e) { showErr("Invalid JSON: " + e.message); } };
$("tableToJson").onclick = () => { try { $("json").value = JSON.stringify(getTools(), null, 2); showErr(""); } catch (e) { showErr(e.message); } };
$("go").onclick = route; $("query").addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); if (!$("go").disabled) route(); } });
$("chips").innerHTML = ""; for (const [p, q] of EXAMPLES) { const b = document.createElement("span"); b.className = "chip"; b.textContent = q; b.title = "preset: " + p;
b.onclick = () => { $("preset").value = p; setTools(PRESETS[p]); $("query").value = q; if (router) route(); }; $("chips").appendChild(b); }
let initial = PRESETS["Smart assistant"]; $("preset").value = "Smart assistant";
try { const s = JSON.parse(localStorage.getItem("toolrouter.tools") || "null"); if (s && Object.keys(s).length) initial = s; } catch (_) {}
setTools(initial);
try {
const HUB_URL = "https://huggingface.co/stanley-nv/toolrouter/resolve/main/web/model.bin"; // single source of truth: the model repo
const onHub = /(\.hf\.space|huggingface\.co)$/.test(location.hostname);
const sources = onHub ? [HUB_URL] : ["model.bin", HUB_URL]; // local dev: use a local export if present
const progress = (got, total) => { $("prog").firstElementChild.style.width = total ? (100 * got / total).toFixed(0) + "%" : "50%"; $("status").textContent = `loading model… ${(got / 1e6).toFixed(1)}${total ? " / " + (total / 1e6).toFixed(1) : ""} MB`; };
let lastErr; for (const u of sources) { try { router = await ToolRouter.load(u, progress); break; } catch (e) { lastErr = e; } }
if (!router) throw lastErr;
$("status").textContent = "model ready (runs locally in your browser)"; $("prog").style.display = "none"; $("go").disabled = false;
window.__router = router; // for tests / console experiments
} catch (e) { $("status").textContent = "model failed to load"; showErr(String(e.message || e)); }
</script>
</body>
</html>