Skip to content
Source
Sign inSign up
samwillis/neonbricks
Open History to see the last commit

benchmark-ai.ts

170 lines5.4 KB

1import { randomUUID } from "node:crypto";
2import { mkdir, writeFile } from "node:fs/promises";
3import { pool } from "../src/server/db";
4import { AI_BUILDER_VERSION } from "../src/server/ai";
5​
6// Fixed, inspectable cases. Every request uses Neon's Gateway spending policy,
7// authentication, validation and acceptance path. Never retry a failed case here.
8const cases = [
9 {
10 id: "lookout",
11 prompt: "A little forest lookout with a red roof",
12 },
13 {
14 id: "cabin",
15 prompt:
16 "A cosy woodland cabin with a red pitched roof, an open doorway, a chimney and a pine tree beside it.",
17 },
18 {
19 id: "rover",
20 prompt:
21 "A yellow exploration rover with four chunky wheels, real axles, a cockpit, headlights and an antenna. A static model.",
22 },
23 {
24 id: "castle",
25 prompt:
26 "A small medieval castle gatehouse with two towers, crenellations, an arched gateway and a bridge over blue water.",
27 },
28 {
29 id: "dinosaur",
30 prompt:
31 "A friendly green long-neck dinosaur with four legs, a long tail, a cream belly and a small head with eyes.",
32 },
33 {
34 id: "treehouse",
35 prompt:
36 "A little treehouse in a broad green tree, with a wooden balcony, a red roof and steps leading up to it.",
37 },
38 {
39 id: "windmill",
40 prompt:
41 "A little Dutch windmill with a cream tower, a red roof, four blades forming a cross and a garden. A static brick model.",
42 },
43];
44const chosen = (
45 process.env.AI_BENCH_CASES || cases.map((c) => c.id).join(",")
46).split(",");
47if (!chosen.every((id) => cases.some((c) => c.id === id)))
48 throw new Error("Unknown benchmark case");
49const selected = cases.filter((c) => chosen.includes(c.id));
50const label = process.env.AI_BENCH_LABEL || "current";
51if (!/^[a-zA-Z0-9_-]{1,50}$/.test(label)) throw new Error("Invalid label");
52const base = (process.env.TEST_API_URL || process.env.VITE_API_URL!).replace(
53 /\/$/,
54 "",
55);
56async function api(token: string, path: string, body?: unknown) {
57 const response = await fetch(`${base}/api${path}`, {
58 method: body === undefined ? "GET" : "POST",
59 headers: {
60 "Content-Type": "application/json",
61 ...(token ? { Authorization: `Bearer ${token}` } : {}),
62 },
63 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
64 signal: AbortSignal.timeout(240_000),
65 cache: "no-store",
66 });
67 const result = await response.json();
68 if (!response.ok) throw new Error(`${response.status}: ${result.error}`);
69 return result;
71await mkdir(`artifacts/ai-benchmark-${label}`, { recursive: true });
72const health = await api("", `/health?rollout=${Date.now()}`);
73if (health.aiBuilder !== AI_BUILDER_VERSION) {
74 await pool.end();
75 throw new Error(
76 "The deployed AI builder is not this version yet. Wait for rollout before benchmarking.",
77 );
79const results: Record<string, unknown>[] = [];
80async function run(test: (typeof cases)[number]) {
81 const id = randomUUID();
82 const session = await api("", "/session", {
83 name: "AI benchmark",
84 color: "#289b74",
85 });
86 const config = await api(session.token, `/ai/config?rollout=${Date.now()}`);
87 const expectedModel = process.env.AI_BENCH_MODEL || "gpt-5-4";
88 if (config.model !== expectedModel || config.version !== AI_BUILDER_VERSION) {
89 throw new Error(
90 `Expected ${expectedModel} on ${AI_BUILDER_VERSION}; rollout still serves ${config.model || "unknown"}. No build reserved.`,
91 );
92 }
93 const started = performance.now();
94 let result: Record<string, unknown>;
95 try {
96 await api(session.token, "/ai/generations", { id, prompt: test.prompt });
97 const built = await api(session.token, `/ai/generations/${id}/run`, {});
98 const elapsedMs = Math.round(performance.now() - started);
99 const stats = (
100 await pool.query(
101 "SELECT model,attempt,input_tokens,output_tokens,issues,error,blueprint,design,attempts FROM ai_generations WHERE id=$1",
102 [id],
103 )
104 ).rows[0];
105 let slug: string | null = null;
106 if (built.status === "ready")
107 slug = (await api(session.token, `/ai/generations/${id}/accept`, {}))
108 .slug;
109 result = {
110 case: test.id,
111 prompt: test.prompt,
112 id,
113 status: built.status,
114 elapsedMs,
115 parts: built.parts.length,
116 slug,
117 ...stats,
118 };
119 } catch (error) {
120 result = {
121 case: test.id,
122 prompt: test.prompt,
123 id,
124 status: "request_failed",
125 elapsedMs: Math.round(performance.now() - started),
126 error: (error as Error).message,
127 };
128 }
129 results.push(result);
130 await writeFile(
131 `artifacts/ai-benchmark-${label}/${test.id}.json`,
132 JSON.stringify(result, null, 2),
133 );
134 console.log(
135 JSON.stringify({
136 ...result,
137 blueprint: undefined,
138 design: undefined,
139 attempts: undefined,
140 }),
141 );
143try {
144 // At most two paid builds at once, matching the application's global cap.
145 const pending = [...selected];
146 await Promise.all(
147 Array.from({ length: Math.min(2, pending.length) }, async () => {
148 while (pending.length) await run(pending.shift()!);
149 }),
150 );
151 const summary = {
152 label,
153 successes: results.filter((r) => r.status === "ready").length,
154 total: results.length,
155 results: results.map(({ blueprint, design, attempts, ...r }) => r),
156 };
157 await writeFile(
158 `artifacts/ai-benchmark-${label}/summary.json`,
159 JSON.stringify(summary, null, 2),
160 );
161 console.log(
162 JSON.stringify({
163 label,
164 successes: summary.successes,
165 total: summary.total,
166 }),
167 );
168} finally {
169 await pool.end();