tfrere's picture
tfrere HF Staff
Cursor
feat(embeds): shared Embed.mount runtime, checker, gallery and evals
4e112fd
Raw History Blame Contribute Delete
16.1 kB
#!/usr/bin/env tsx
// Run the Embed Studio agent on the eval cases (evals/embeds/cases.json) the
// way the editor does - same system prompt, same tools, same data files - then
// render every result through the embed checker.
//
// npm run eval:embeds # every case, default model
// npm run eval:embeds -- scaling-law messy-data # some cases
// npm run eval:embeds -- --model Qwen/Qwen3-Coder-480B-A35B-Instruct --label qwen-coder
// npm run eval:embeds -- --max-steps 12 --concurrency 3
// npm run eval:embeds -- --label qwen-coder --recheck # re-run the checker only
// npm run eval:embeds -- --label opus --model claude-opus --import
// # check charts produced elsewhere: <case>/embed.html (+ reply.txt) in the label dir
//
// Auth: HF_TOKEN from the shell, else the `hf auth login` token. backend/.env
// is deliberately not loaded.
//
// Results land in .embed-evals/<label>/<case>/: embed.html, preview.html (open
// it in a browser), trace.json, screenshots. Compare two runs with
// `npm run eval:compare -- <labelA> <labelB>`.
import { createHash } from "node:crypto";
import { existsSync, readFileSync } from "node:fs";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { stepCountIs, streamText, tool, type Tool } from "ai";
import { buildEmbedSystemPrompt, type EmbedChatContext } from "../src/agent/embed-chat.js";
import type { DataFileMeta } from "../src/agent/embed-system-prompt.js";
import { embedTools } from "../src/agent/embed-tools.js";
import { createProvider, DEFAULT_MODEL } from "../src/agent/stream-handler.js";
import { buildEmbedSrcdoc } from "../src/shared/embed-doc.js";
import { extFromName, inferDataShape } from "../../frontend/src/utils/data-files.js";
import { backendDir, checkOne, launchBrowser, reportStatus, type Report } from "./embed-check/check.js";
import { BUILTIN_EMBEDS } from "./embed-check/registry.js";
const EVAL_DIR = join(backendDir, "evals/embeds");
// Same limits as executeToolCall in frontend/src/hooks/useEmbedChat.ts.
const MAX_EMBED_SIZE = 512_000;
const MAX_DATA_INLINE = 120_000;
interface EvalCase {
id: string;
prompt: string;
files: string[];
start?: string;
banner?: boolean;
watch: string[];
success: string;
}
interface Options {
ids: string[];
model: string;
label: string;
maxSteps: number;
concurrency: number;
recheck: boolean;
import: boolean;
}
function parseArgs(argv: string[]): Options {
const model = process.env.HF_INFERENCE_MODEL || DEFAULT_MODEL;
const opts: Options = { ids: [], model, label: "", maxSteps: 12, concurrency: 3, recheck: false, import: false };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === "--recheck") opts.recheck = true;
else if (a === "--import") opts.import = true;
else if (a === "--model") opts.model = argv[++i];
else if (a === "--label") opts.label = argv[++i];
else if (a === "--max-steps") opts.maxSteps = Number(argv[++i]);
else if (a === "--concurrency") opts.concurrency = Math.max(1, Number(argv[++i]));
else opts.ids.push(a);
}
if (!opts.label) {
const stamp = new Date().toISOString().slice(0, 16).replace(/[-:T]/g, "");
opts.label = `${opts.model.split("/").pop()!.replace(/[^a-zA-Z0-9.-]+/g, "-")}-${stamp}`;
}
return opts;
}
function hfToken(): string {
if (process.env.HF_TOKEN) return process.env.HF_TOKEN;
const file = join(process.env.HF_HOME || join(homedir(), ".cache/huggingface"), "token");
if (existsSync(file)) return readFileSync(file, "utf8").trim();
throw new Error("No HF token: export HF_TOKEN or run `hf auth login`.");
}
function slugify(raw: string): string {
const base = raw
.toLowerCase()
.replace(/\.html?$/i, "")
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 60);
return base || "chart";
}
interface DataFile extends DataFileMeta {
content: string;
}
async function loadDataFiles(names: string[]): Promise<DataFile[]> {
return Promise.all(names.map(async (name) => {
const content = await readFile(join(EVAL_DIR, "data", name), "utf8");
const ext = extFromName(name);
return { name, ext, size: Buffer.byteLength(content), content, ...inferDataShape(ext, content) };
}));
}
interface StepTrace {
text: string;
finishReason: string;
toolCalls: { tool: string; input: Record<string, unknown>; output: string }[];
}
interface CaseResult {
id: string;
src: string;
html: string | null;
reply: string;
steps: StepTrace[];
seconds: number;
usage: { inputTokens?: number; outputTokens?: number };
error?: string;
}
function describeError(err: unknown): string {
const body = (err as { responseBody?: string }).responseBody;
return (err instanceof Error ? err.message : String(err)) + (body ? `: ${body.slice(0, 400)}` : "");
}
function summarizeInput(input: Record<string, unknown>): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(input ?? {})) {
out[k] = typeof v === "string" && v.length > 200 ? `<${v.length} chars>` : v;
}
return out;
}
async function runCase(c: EvalCase, opts: Options, token: string): Promise<CaseResult> {
const files = await loadDataFiles(c.files);
const embeds = new Map<string, string>();
const isBanner = Boolean(c.banner);
let src = isBanner ? "banner.html" : "d3-chart-eval0.html";
if (c.start) {
const seed = BUILTIN_EMBEDS.find((e) => e.name === c.start);
if (!seed) throw new Error(`${c.id}: unknown start embed ${c.start}`);
src = `${c.start}.html`;
embeds.set(src, seed.html);
}
const context = (): EmbedChatContext => ({
embedHtml: embeds.get(src),
isBanner,
isScratch: !isBanner && !embeds.get(src) && /^d3-chart-[a-z0-9]+\.html$/i.test(src),
dataFiles: files.map(({ content: _content, ...meta }) => meta),
theme: "light",
});
const execute = (name: string, input: Record<string, any>): string => {
switch (name) {
case "createEmbed": {
const html = String(input.html ?? "").trim();
if (!html) return "ERROR: html cannot be empty";
if (html.length > MAX_EMBED_SIZE) return `ERROR: chart too large (${html.length} bytes, max ${MAX_EMBED_SIZE}). Simplify the code.`;
let renamed = "";
if (input.filename && !isBanner) {
const target = `${slugify(input.filename)}.html`;
if (target !== src) {
embeds.delete(src);
src = target;
renamed = ` [renamed to ${target}]`;
}
}
embeds.set(src, html);
return `chart created (${html.split("\n").length} lines, ${html.length} chars)${input.title ? ` - "${input.title}"` : ""}${renamed}`;
}
case "patchEmbed": {
const current = embeds.get(src);
if (!current) return "ERROR: no chart exists yet. Use createEmbed first.";
if (!input.search) return "ERROR: search block cannot be empty";
if (!current.includes(input.search)) return "ERROR: search block not found in current chart. Call readEmbed to see the exact current content, then retry.";
const patched = current.replace(input.search, input.replace ?? "");
if (patched.length > MAX_EMBED_SIZE) return `ERROR: patch would exceed size limit (${patched.length} bytes, max ${MAX_EMBED_SIZE}).`;
embeds.set(src, patched);
return "patch applied successfully";
}
case "readEmbed":
return embeds.get(src) ?? "(no chart yet)";
case "listDataFiles":
if (!files.length) return "(no data files attached)";
return files.map((f) => {
const cols = f.columns?.length ? ` columns=[${f.columns.join(", ")}]` : "";
const rows = f.rowCount !== undefined ? ` rows=${f.rowCount}` : "";
return `- ${f.name} (${f.ext}, ${f.size} bytes)${rows}${cols}`;
}).join("\n");
case "readDataFile": {
const file = files.find((f) => f.name === input.name);
if (!file) return `ERROR: data file "${input.name}" not found`;
if (file.content.length <= MAX_DATA_INLINE) return file.content;
return file.content.slice(0, MAX_DATA_INLINE) +
`\n\n[TRUNCATED - full file is ${file.content.length} chars, showing first ${MAX_DATA_INLINE}]`;
}
default:
return `Unknown tool: ${name}`;
}
};
const tools = Object.fromEntries(
Object.entries(embedTools).map(([name, t]) => [
name,
tool({ ...(t as Tool), execute: async (input: Record<string, unknown>) => execute(name, input) } as Tool),
]),
);
const started = Date.now();
const result: CaseResult = { id: c.id, src, html: null, reply: "", steps: [], seconds: 0, usage: {} };
try {
// Streamed like the editor: a long non-streamed generation hits gateway timeouts.
const out = streamText({
model: createProvider(token).chatModel(opts.model),
system: buildEmbedSystemPrompt(context()),
// Like the editor: refresh the chart in the prompt and drop past reasoning
// parts, which some providers reject (see stripReasoningParts).
prepareStep: ({ messages }) => ({
system: buildEmbedSystemPrompt(context()),
messages: messages.map((m) =>
m.role === "assistant" && Array.isArray(m.content)
? { ...m, content: m.content.filter((p) => p.type !== "reasoning") }
: m,
),
}),
messages: [{ role: "user", content: c.prompt }],
tools,
stopWhen: stepCountIs(opts.maxSteps),
onStepFinish: (s) => {
result.steps.push({
text: s.text,
finishReason: s.finishReason,
toolCalls: s.toolCalls.map((call) => {
const res = s.toolResults.find((r) => r.toolCallId === call.toolCallId);
const output = typeof res?.output === "string" ? res.output : JSON.stringify(res?.output ?? null);
return { tool: call.toolName, input: summarizeInput(call.input as Record<string, unknown>), output: output.slice(0, 300) };
}),
});
},
onError: ({ error }) => { result.error ??= describeError(error); },
});
await out.consumeStream({ onError: (error) => { result.error ??= describeError(error); } });
if (!result.error) {
result.reply = await out.text;
const usage = await out.totalUsage;
result.usage = { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens };
}
} catch (err) {
result.error ??= describeError(err);
}
result.seconds = Math.round((Date.now() - started) / 1000);
result.src = src;
result.html = embeds.get(src) ?? null;
return result;
}
async function pool<T, R>(items: T[], size: number, fn: (item: T) => Promise<R>): Promise<R[]> {
const results: R[] = new Array(items.length);
let next = 0;
await Promise.all(Array.from({ length: Math.min(size, items.length) }, async () => {
while (next < items.length) {
const i = next++;
results[i] = await fn(items[i]);
}
}));
return results;
}
const opts = parseArgs(process.argv.slice(2));
const allCases = JSON.parse(await readFile(join(EVAL_DIR, "cases.json"), "utf8")) as EvalCase[];
let cases = opts.ids.length ? allCases.filter((c) => opts.ids.includes(c.id)) : allCases;
if (!cases.length) {
console.error(`No case matches ${opts.ids.join(", ")}. Known: ${allCases.map((c) => c.id).join(", ")}`);
process.exit(2);
}
const runDir = resolve(backendDir, ".embed-evals", opts.label);
await mkdir(runDir, { recursive: true });
const previousRun = existsSync(join(runDir, "run.json"))
? JSON.parse(await readFile(join(runDir, "run.json"), "utf8")) as { model: string; promptHash: string; summary: { id: string }[] }
: null;
let results: CaseResult[];
let promptHash: string;
if (opts.import) {
promptHash = createHash("sha256").update(buildEmbedSystemPrompt({})).digest("hex").slice(0, 12);
cases = cases.filter((c) => existsSync(join(runDir, c.id, "embed.html")));
results = await Promise.all(cases.map(async (c) => {
const replyFile = join(runDir, c.id, "reply.txt");
return {
id: c.id, src: `${c.id}.html`, seconds: 0, usage: {},
html: await readFile(join(runDir, c.id, "embed.html"), "utf8"),
reply: existsSync(replyFile) ? (await readFile(replyFile, "utf8")).trim() : "",
// The external harness was handed every attached file up front.
steps: [{ text: "", finishReason: "imported", toolCalls: c.files.map((name) => ({ tool: "readDataFile", input: { name }, output: "" })) }],
};
}));
console.log(`import label=${opts.label} model=${opts.model} cases=${cases.length}`);
} else if (opts.recheck) {
if (!previousRun) {
console.error(`--recheck needs an existing run in ${runDir}`);
process.exit(2);
}
opts.model = previousRun.model;
promptHash = previousRun.promptHash;
cases = cases.filter((c) => existsSync(join(runDir, c.id, "trace.json")));
results = await Promise.all(cases.map(async (c) => {
const trace = JSON.parse(await readFile(join(runDir, c.id, "trace.json"), "utf8"));
const htmlFile = join(runDir, c.id, "embed.html");
return { ...trace, html: existsSync(htmlFile) ? await readFile(htmlFile, "utf8") : null } as CaseResult;
}));
console.log(`recheck label=${opts.label} cases=${cases.length}`);
} else {
const token = hfToken();
promptHash = createHash("sha256").update(buildEmbedSystemPrompt({})).digest("hex").slice(0, 12);
console.log(`model=${opts.model} label=${opts.label} prompt=${promptHash} cases=${cases.length}`);
results = await pool(cases, opts.concurrency, async (c) => {
const r = await runCase(c, opts, token);
const calls = r.steps.flatMap((s) => s.toolCalls.map((t) => t.tool));
console.log(` ${c.id}: ${r.error ? `error (${r.error.slice(0, 120)})` : r.html ? "chart" : "no chart"} in ${r.seconds}s, ${r.steps.length} steps [${calls.join(", ")}]`);
return r;
});
}
const browser = await launchBrowser();
const summary: Record<string, unknown>[] = [];
try {
for (const [i, r] of results.entries()) {
const c = cases[i];
const dir = join(runDir, c.id);
await mkdir(dir, { recursive: true });
let report: Report | null = null;
if (r.html) {
await writeFile(join(dir, "embed.html"), r.html);
const preview = buildEmbedSrcdoc(r.html, { isDark: false, fullBleed: Boolean(c.banner) })
.replace("</head>", "<style>html { background: var(--page-bg); }</style></head>");
await writeFile(join(dir, "preview.html"), preview);
report = await checkOne(browser, { name: c.id, html: r.html, banner: Boolean(c.banner) }, { widths: [360, 760], out: runDir });
}
await writeFile(join(dir, "trace.json"), JSON.stringify({ case: c, ...r, html: undefined, check: report }, null, 2));
const status = r.error ? "ERROR" : report ? reportStatus(report) : "NO CHART";
const toolCalls = r.steps.reduce((n, s) => n + s.toolCalls.length, 0);
const read = new Set(r.steps.flatMap((s) => s.toolCalls.filter((t) => t.tool === "readDataFile").map((t) => t.input.name)));
const unread = c.files.filter((f) => !read.has(f));
summary.push({ id: c.id, status, fails: report?.fails.length ?? 0, warns: report?.warns.length ?? 0, unreadFiles: unread.length, toolCalls, seconds: r.seconds, chars: r.html?.length ?? 0 });
}
} finally {
await browser.close();
}
// Partial runs and rechecks keep the other cases of the same label.
const kept = (previousRun?.summary ?? []).filter((s) => !summary.some((n) => n.id === s.id));
const merged = allCases.map((c) => [...kept, ...summary].find((s) => s.id === c.id)).filter(Boolean);
await writeFile(join(runDir, "run.json"), JSON.stringify({ model: opts.model, promptHash, date: new Date().toISOString(), maxSteps: opts.maxSteps, summary: merged }, null, 2));
console.log("");
console.table(summary);
console.log(`\nResults: ${runDir.replace(`${backendDir}/`, "")}`);