Component · New
Model arena
One prompt, several models, answers streaming side by side with live timings and a winner.
Waiting for a prompt.
Waiting for a prompt.
Waiting for a prompt.
Simulated answers on a timer. No model is called.
Usage
<ModelArena
models={[
{ id: "claude", name: "Claude Sonnet", provider: "Anthropic" },
{ id: "gpt", name: "GPT", provider: "OpenAI" },
]}
// Any async iterable of text works: a fetch stream, an SDK stream, a generator.
respond={async function* (model, prompt, signal) {
const response = await fetch(`/api/chat?model=${model.id}`, { method: "POST", body: prompt, signal });
const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader();
for (;;) {
const { value, done } = await reader.read();
if (done) return;
yield value;
}
}}
/>Source
Copy both files into your project. The component has no dependencies beyond React.
"use client";
import { useEffect, useRef, useState, type FormEvent } from "react";
import styles from "./model-arena.module.css";
export type ArenaModel = { id: string; name: string; provider: string; color?: string };
type RunState = {
text: string;
status: "idle" | "waiting" | "streaming" | "done" | "stopped" | "error";
startedAt: number;
firstAt: number | null;
endedAt: number | null;
chunks: number;
};
type ModelArenaProps = {
models: ArenaModel[];
/** Return the model's answer as a stream of text chunks. Stop when the signal aborts. */
respond: (model: ArenaModel, prompt: string, signal: AbortSignal) => AsyncIterable<string>;
defaultPrompt?: string;
/** Start a run as soon as the arena mounts. */
autoRun?: boolean;
};
const idle: RunState = { text: "", status: "idle", startedAt: 0, firstAt: null, endedAt: null, chunks: 0 };
function seconds(ms: number) {
return `${(ms / 1000).toFixed(1)}s`;
}
export function ModelArena({ models, respond, defaultPrompt = "", autoRun = false }: ModelArenaProps) {
const [prompt, setPrompt] = useState(defaultPrompt);
const [runs, setRuns] = useState<Record<string, RunState>>({});
const [now, setNow] = useState(0);
const controller = useRef<AbortController | null>(null);
const states = models.map((model) => runs[model.id] ?? idle);
const running = states.some((run) => run.status === "waiting" || run.status === "streaming");
// A clock for the live timers, only while something is streaming.
useEffect(() => {
if (!running) return;
const id = window.setInterval(() => setNow(performance.now()), 100);
return () => window.clearInterval(id);
}, [running]);
useEffect(() => {
if (autoRun && defaultPrompt) start(defaultPrompt);
return () => controller.current?.abort();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
function start(question: string) {
controller.current?.abort();
const current = new AbortController();
controller.current = current;
const startedAt = performance.now();
setNow(startedAt);
setRuns(Object.fromEntries(models.map((model) => [model.id, { ...idle, status: "waiting", startedAt }])));
// Writes from an older run are dropped once a newer one has started.
const patch = (id: string, change: (run: RunState) => RunState) => {
if (controller.current !== current) return;
setRuns((all) => (all[id] ? { ...all, [id]: change(all[id]) } : all));
};
for (const model of models) {
(async () => {
try {
for await (const chunk of respond(model, question, current.signal)) {
if (current.signal.aborted) break;
patch(model.id, (run) => ({
...run,
text: run.text + chunk,
status: "streaming",
firstAt: run.firstAt ?? performance.now(),
chunks: run.chunks + 1,
}));
}
patch(model.id, (run) => ({ ...run, status: "done", endedAt: performance.now() }));
} catch {
patch(model.id, (run) => ({ ...run, status: "error", endedAt: performance.now() }));
}
})();
}
}
function stop() {
const current = controller.current;
if (!current) return;
const endedAt = performance.now();
setRuns((all) =>
Object.fromEntries(
Object.entries(all).map(([id, run]) => [
id,
run.status === "waiting" || run.status === "streaming" ? { ...run, status: "stopped", endedAt } : run,
]),
),
);
controller.current = null;
current.abort();
}
function onSubmit(event: FormEvent) {
event.preventDefault();
if (running) stop();
else if (prompt.trim()) start(prompt.trim());
}
const finished = states.filter((run) => run.status === "done");
const fastest =
!running && finished.length > 1
? models[states.indexOf(finished.reduce((a, b) => ((a.endedAt ?? 0) - a.startedAt < (b.endedAt ?? 0) - b.startedAt ? a : b)))]?.id
: null;
return (
<div className={styles.arena}>
<form className={styles.ask} onSubmit={onSubmit}>
<input
value={prompt}
placeholder="Ask every model the same thing"
aria-label="Prompt"
onChange={(event) => setPrompt(event.target.value)}
/>
<button type="submit" data-running={running ? "true" : "false"} disabled={!running && !prompt.trim()}>
{running ? "Stop" : "Run"}
</button>
</form>
<div className={styles.grid} style={{ gridTemplateColumns: `repeat(${models.length}, minmax(0, 1fr))` }}>
{models.map((model, index) => {
const run = states[index];
const end = run.endedAt ?? now;
const elapsed = Math.max(0, end - run.startedAt);
const rate = run.firstAt && end > run.firstAt ? Math.round((run.chunks / (end - run.firstAt)) * 1000) : 0;
const live = run.status === "streaming";
return (
<section key={model.id} className={styles.lane} data-status={run.status} aria-label={model.name}>
<header>
<span className={styles.dot} style={{ background: model.color }} />
<strong>{model.name}</strong>
{fastest === model.id ? <span className={styles.badge}>Fastest</span> : null}
<span className={styles.provider}>{model.provider}</span>
</header>
<p className={styles.text}>
{run.status === "idle" ? <span className={styles.quiet}>Waiting for a prompt.</span> : null}
{run.status === "waiting" ? (
<span className={styles.thinking} aria-label="Thinking">
<i />
<i />
<i />
</span>
) : null}
{run.status === "error" ? <span className={styles.quiet}>This model failed to answer.</span> : null}
{run.text}
{live ? <span className={styles.caret} aria-hidden="true" /> : null}
</p>
<footer>
<span>{run.status === "idle" ? "—" : seconds(elapsed)}</span>
<span>{run.firstAt ? `first word ${seconds(run.firstAt - run.startedAt)}` : " "}</span>
<span>{rate ? `${rate} words/s` : " "}</span>
</footer>
</section>
);
})}
</div>
</div>
);
}