SamJoshua's picture
Chat Template Checker: CTT-Bench v1.0, runs in your browser
4a22613 verified
Raw History Blame Contribute Delete
10.4 kB
const $ = (id) => document.getElementById(id);
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
const EXAMPLES = ["zai-org/GLM-5.3", "MiniMaxAI/MiniMax-M2.5", "tencent/Hy3", "Qwen/Qwen2.5-7B-Instruct", "LiquidAI/LFM2.5-1.2B-Instruct", "swiss-ai/Apertus-8B-Instruct-2509"];
const SPECIAL = ["bos_token", "eos_token", "unk_token", "sep_token", "pad_token", "cls_token", "mask_token"];
const LB = await (await fetch("leaderboard_index.json")).json();
const HINTS = {
string_crash: "Template treats arguments as a dict and crashes on the OpenAI JSON string. Client fix: json.loads(tool_call['function']['arguments']) before apply_chat_template. Template fix: parse it when `arguments is string`.",
string_clear: "Template refuses JSON-string arguments with a clear error. Deserialize client-side: json.loads the arguments before templating.",
double: "The JSON string is pasted inside JSON, so the model sees escaped quotes. json.loads the arguments first, or emit strings raw in the template.",
dropped: "Rendered, but the argument values never reach the prompt. The template ignores this argument shape.",
raw_name: "Tool names are pasted verbatim, so a quote in a name can forge JSON. Validate names against ^[A-Za-z0-9_.-]{1,64}$ before templating, or render them with |tojson.",
dict_crash: "Template crashes on the documented dict format. Read the error: usually a field the template assumes is always present (e.g. tool description).",
};
const LABEL = { pass: "pass", fail_crash: "crash", fail_clear: "fail (clear error)", fail_double_encoded: "fail (double-encoded)", fail_dropped: "fail (values dropped)", fail_raw_name: "fail (raw name)" };
const hint = (r, strCases) => r.status === "pass" ? "" : r.status === "fail_raw_name" ? HINTS.raw_name : r.status === "fail_double_encoded" ? HINTS.double :
r.status === "fail_dropped" ? HINTS.dropped : strCases.includes(r.case_id) ? (r.status === "fail_clear" ? HINTS.string_clear : HINTS.string_crash) : HINTS.dict_crash;
let worker, pending = new Map(), seq = 0, isReady = false;
function startWorker() {
isReady = false; $("status").textContent = "Loading the in-browser Python runtime…";
worker = new Worker("worker.js");
worker.onmessage = (e) => {
if (e.data.type === "ready") { isReady = true; $("status").textContent = "Ready."; document.querySelectorAll("button.go").forEach((b) => (b.disabled = false)); window.__ready = true; }
else if (e.data.type === "initerror") $("status").textContent = "Could not start the runtime: " + e.data.error;
else { const p = pending.get(e.data.id); if (p) { pending.delete(e.data.id); p(e.data.data); } }
};
}
startWorker();
document.querySelectorAll("button.go").forEach((b) => (b.disabled = true));
function runTemplate(template, special) {
return new Promise((resolve) => {
if (template.length > 300000) return resolve({ ok: false, error: `Template is ${template.length.toLocaleString()} characters; the limit is 300,000.` });
const id = ++seq; const timer = setTimeout(() => { pending.delete(id); worker.terminate(); startWorker(); resolve({ ok: false, error: "Rendering took longer than 15s and was stopped." }); }, 15000);
pending.set(id, (d) => { clearTimeout(timer); resolve(d); });
worker.postMessage({ id, template, special });
});
}
const tokStr = (v) => (v && typeof v === "object" ? v.content : v);
async function hub(url) { const r = await fetch(url); return r; }
async function fetchTemplate(input) {
let id = (input || "").trim().replace(/^\/+|\/+$/g, "");
const m = id.match(/^https?:\/\/huggingface\.co\/([^/]+\/[^/?#]+)/); if (m) id = m[1];
if (!/^[A-Za-z0-9][\w.\-]{0,95}\/[\w.\-]{1,96}$/.test(id)) return { error: `'${id}' is not a Hub model id. Use the form org/name.` };
const r = await hub(`https://huggingface.co/api/models/${id}`);
if (r.status === 401 || r.status === 404) return { error: `No public model repo named ${id} (or it is private).` };
if (!r.ok) return { error: `Hub error: HTTP ${r.status}` };
const info = await r.json(); const files = new Set((info.siblings || []).map((s) => s.rfilename));
if (info.gated) return { error: "This repo is gated. Accept its terms on the Hub, then paste the template into the Raw template tab." };
const get = async (f) => { const x = await hub(`https://huggingface.co/${id}/resolve/main/${f}`); return x.ok ? await x.text() : null; };
const templates = {}, special = {}, sources = [];
try {
if (files.has("tokenizer_config.json")) {
const cfg = JSON.parse((await get("tokenizer_config.json")) || "{}");
for (const k of SPECIAL) { const s = tokStr(cfg[k]); if (typeof s === "string") special[k] = s; }
const ct = cfg.chat_template;
if (typeof ct === "string" && ct) { templates.default = ct; sources.push("tokenizer_config.json"); }
else if (Array.isArray(ct)) { for (const it of ct) if (it && it.name && it.template) templates[it.name] = it.template; if (ct.length) sources.push("tokenizer_config.json"); }
}
if (files.has("special_tokens_map.json")) {
const stm = JSON.parse((await get("special_tokens_map.json")) || "{}");
for (const k of SPECIAL) { const s = tokStr(stm[k]); if (typeof s === "string" && !(k in special)) special[k] = s; }
}
if (files.has("chat_template.json")) { const c = JSON.parse((await get("chat_template.json")) || "{}").chat_template; if (typeof c === "string" && c) { templates.default = c; sources.push("chat_template.json"); } }
if (files.has("chat_template.jinja")) { const t = await get("chat_template.jinja"); if (t) { templates.default = t; sources.push("chat_template.jinja"); } }
for (const f of [...files].sort()) if (f.startsWith("additional_chat_templates/") && f.endsWith(".jinja")) { const t = await get(f); if (t) { templates[f.split("/")[1].replace(/\.jinja$/, "")] = t; sources.push(f); } }
} catch (e) { return { error: "Could not parse the repo's template files: " + e.message }; }
const names = Object.keys(templates);
const tpl = templates.tool_use ?? templates.default ?? (names.length === 1 ? templates[names[0]] : null);
const used = templates.tool_use ? "tool_use" : templates.default ? "default" : names[0];
if (tpl == null) return { error: names.length ? `Several templates (${names.sort().join(", ")}) and no default.` : `${id} has no chat template.` };
return { id, template: tpl, special, source: sources.join(" + ") + (names.length > 1 ? ` (using '${used}')` : "") };
}
function render(res, repoId, src, t0) {
if (!res.ok) { $("out").innerHTML = `<div class="card err"><b>Could not check.</b>&nbsp;${esc(res.error)}</div>`; return; }
const cases = Object.fromEntries(res.rows.map((r) => [r.short, r.status]));
const score = res.rows.filter((r) => r.status === "pass").length, n = res.rows.length;
const strOk = ["string_args", "nested_string_args", "unicode_string_args"].every((k) => cases[k] === "pass");
let verdict = cases.dict_args !== "pass" ? "Crashes on the documented dict format, so tool calling is broken for every client."
: !strOk ? "Works with dict arguments but not with OpenAI-style JSON-string arguments. json.loads them before templating." : "Handles both dict and JSON-string arguments.";
if (cases.name_escape !== "pass") verdict += " Tool names are pasted unescaped.";
let lb = ""; const m = repoId && LB.models[repoId];
if (m) lb = `<div class="sub">Leaderboard run (${LB.measured}): <b>${m.score}/10</b>${m.sha1 === res.sha1 ? " with the same template." : ". The template has changed since then."}</div>`;
const color = score >= 9 ? "#16a34a" : score >= 5 ? "#d97706" : "#dc2626";
const rows = res.rows.map((r) => {
const what = r.rendered ? (r.detail || "") + (r.snippet ? " | " + r.snippet.replace(/\n/g, "⏎").slice(0, 220) : "") : (r.detail || "").slice(0, 300);
return `<tr><td>${esc(r.case_id.split("_")[0])} ${esc(r.title)}</td><td>${r.status === "pass" ? "✅" : r.status === "fail_crash" ? "💥" : "❌"} ${esc(LABEL[r.status] || r.status)}</td><td class="what">${esc(what)}</td><td>${esc(hint(r, res.string_cases))}</td></tr>`;
}).join("");
$("out").innerHTML = `<div class="card"><div class="score" style="color:${color}" id="score">${score}/${n}</div><div><div class="verdict">${esc(verdict)}</div>
<div class="sub">Source: ${esc(src)} · template sha1 ${res.sha1} · ${((performance.now() - t0) / 1000).toFixed(1)}s · jinja2 ${res.jinja2} (in-browser)</div>${lb}</div></div>
<table><thead><tr><th>Case</th><th>Result</th><th>What happened</th><th>Fix hint</th></tr></thead><tbody>${rows}</tbody></table>`;
}
async function checkRepo() {
const v = $("repo").value.trim(); if (!v) { $("out").innerHTML = `<div class="card err">Enter a model id, for example zai-org/GLM-5.3.</div>`; return; }
const t0 = performance.now(); $("status").textContent = "Fetching template…"; $("out").innerHTML = "";
let src; try { src = await fetchTemplate(v); } catch (e) { src = { error: "Network error: " + e.message }; }
if (src.error) { $("status").textContent = "Ready."; return render({ ok: false, error: src.error }); }
$("status").textContent = "Running 10 cases…"; const res = await runTemplate(src.template, src.special);
$("status").textContent = "Ready."; render(res, src.id, src.source, t0);
}
async function checkRaw() {
const t = $("raw").value.replace(/^\ufeff/, ""); if (!t.trim()) return render({ ok: false, error: "Paste a Jinja chat template first." });
const special = {}; if ($("bos").value) special.bos_token = $("bos").value; if ($("eos").value) special.eos_token = $("eos").value;
const t0 = performance.now(); $("status").textContent = "Running 10 cases…"; const res = await runTemplate(t, special); $("status").textContent = "Ready."; render(res, null, "pasted template", t0);
}
$("go").onclick = checkRepo; $("goraw").onclick = checkRaw; $("repo").addEventListener("keydown", (e) => e.key === "Enter" && checkRepo());
$("exs").innerHTML = EXAMPLES.map((x) => `<a data-x="${x}">${x}</a>`).join("");
$("exs").onclick = (e) => { if (e.target.dataset.x) { $("repo").value = e.target.dataset.x; } };
for (const [a, b, p, q] of [["t1", "t2", "p1", "p2"], ["t2", "t1", "p2", "p1"]]) $(a).onclick = () => { $(a).className = "on"; $(b).className = ""; $(p).hidden = false; $(q).hidden = true; };