Model picker
Point at a model and the same answer streams at that model's own speed, with what one task costs on it. You feel fast and slow instead of reading a spec table.
npx shadcn@latest add https://captain-ui.vercel.app/r/model-picker.jsonBalanced
0.0 s to answer$0.072 per review
"use client";
// Captain UI · Model picker, MIT. Hover or focus a model and a sample answer streams at that model's own speed, so you feel the difference before you pick.
import { motion, useReducedMotion } from "motion/react";
import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react";
import { EASE, cx } from "@/registry/captain/ui/captain";
import { Icon } from "@/registry/captain/ui/icons";
export type PickerModel = {
id: string;
name: string;
/** Output tokens per second. */
tps: number;
/** Time to first token, ms. */
ttft: number;
/** US dollars per million input and output tokens. */
input: number;
output: number;
};
type ModelPickerProps = {
models: PickerModel[];
value?: string;
defaultValue?: string;
onValueChange?: (id: string) => void;
/** The answer every model streams, so only the speed differs. */
sample: string;
/** The task the cost is quoted for, in tokens. */
task: { label: string; input: number; output: number };
"aria-label"?: string;
className?: string;
};
const TOKENS_PER_WORD = 1.3;
const money = (n: number) => (n === 0 ? "Free" : n < 0.1 ? `$${n.toFixed(3)}` : `$${n.toFixed(2)}`);
export const costPerTask = (m: PickerModel, t: { input: number; output: number }) => (t.input * m.input + t.output * m.output) / 1e6;
export function ModelPicker({ models, value, defaultValue, onValueChange, sample, task, className, ...rest }: ModelPickerProps) {
const [inner, setInner] = useState(defaultValue ?? models[0]?.id ?? "");
const picked = value ?? inner;
const [preview, setPreview] = useState<string | null>(null);
const shownId = preview ?? picked;
const shown = models.find((m) => m.id === shownId) ?? models[0];
const words = sample.split(/(\s+)/).filter(Boolean);
const [count, setCount] = useState(0);
const [elapsed, setElapsed] = useState(0);
const [run, setRun] = useState(0); // bump to replay
const opts = useRef<Array<HTMLButtonElement | null>>([]);
const reduce = useReducedMotion();
const id = useId();
// Stream words at tokens-per-second, after the model's time to first token.
useEffect(() => {
if (!shown) return;
const perWord = (1000 * TOKENS_PER_WORD) / shown.tps;
const total = shown.ttft + perWord * words.filter((w) => w.trim()).length;
if (reduce) {
setCount(words.length);
setElapsed(total);
return;
}
setCount(0);
setElapsed(0);
const t0 = performance.now();
let raf = 0;
const tick = () => {
const t = performance.now() - t0;
const spoken = Math.max(0, Math.floor((t - shown.ttft) / perWord) + 1);
let n = 0;
let seen = 0;
while (n < words.length && seen < spoken) {
if (words[n]?.trim()) seen++;
n++;
}
setCount(t < shown.ttft ? 0 : n);
setElapsed(Math.min(t, total));
if (t < total) raf = requestAnimationFrame(tick);
else setCount(words.length);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [shownId, run, sample, reduce]);
const select = (m: PickerModel) => {
if (value === undefined) setInner(m.id);
onValueChange?.(m.id);
};
const key = (e: KeyboardEvent<HTMLButtonElement>, i: number) => {
const n = models.length;
const to = e.key === "ArrowDown" ? (i + 1) % n : e.key === "ArrowUp" ? (i - 1 + n) % n : e.key === "Home" ? 0 : e.key === "End" ? n - 1 : -1;
if (to < 0) return;
e.preventDefault();
opts.current[to]?.focus();
};
const streaming = count < words.length;
return (
<div className={cx("raised grid overflow-hidden rounded-shell sm:grid-cols-[minmax(0,15rem)_minmax(0,1fr)]", className)}>
<div
role="listbox"
aria-label={rest["aria-label"] ?? "Model"}
aria-orientation="vertical"
className="flex flex-col gap-0.5 p-2"
onPointerLeave={() => setPreview(null)}
>
{models.map((m, i) => {
const on = m.id === picked;
return (
<button
key={m.id}
ref={(el) => {
opts.current[i] = el;
}}
type="button"
role="option"
aria-selected={on}
aria-describedby={`${id}-preview`}
tabIndex={on ? 0 : -1}
onPointerEnter={() => setPreview(m.id)}
onFocus={() => setPreview(m.id)}
onBlur={() => setPreview(null)}
onClick={() => select(m)}
onKeyDown={(e) => key(e, i)}
className={cx(
"pressable relative flex h-12 items-center gap-3 rounded-inner px-3 text-left transition-colors duration-150",
on ? "well" : "hover:bg-hover focus-visible:bg-hover",
)}
>
<span className="min-w-0 flex-1">
<span className="block truncate text-[13.5px] font-medium text-ink">{m.name}</span>
<span className="tnum block text-[12px] text-ink-3">{m.tps} tokens a second</span>
</span>
<span className="tnum shrink-0 text-[12.5px] text-ink-2">{money(costPerTask(m, task))}</span>
<span className={cx("w-4 shrink-0 text-ink", on ? "opacity-100" : "opacity-0")}>
<Icon name="check" size={16} />
</span>
</button>
);
})}
</div>
<div id={`${id}-preview`} className="flex min-h-[220px] flex-col bg-band p-5" aria-live="off">
<div className="flex items-baseline justify-between gap-3 text-[12.5px]">
<span className="font-medium text-ink">{shown?.name}</span>
<button
type="button"
onClick={() => setRun((r) => r + 1)}
className="pressable relative -m-1 flex items-center gap-1 rounded-[6px] p-1 text-ink-3 transition-colors duration-150 before:absolute before:-inset-2 before:content-[''] hover:text-ink focus-visible:bg-hover"
aria-label="Replay"
>
<Icon name="replay" size={14} />
</button>
</div>
<p className="mt-3 flex-1 text-[14px] leading-relaxed text-ink">
{words.slice(0, count).map((w, i) => (
<motion.span key={`${shownId}-${run}-${i}`} initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 0.18, ease: EASE }}>
{w}
</motion.span>
))}
{streaming ? <span aria-hidden className="ml-px inline-block h-[1.05em] w-[2px] translate-y-[3px] bg-accent" /> : null}
</p>
<p className="tnum mt-4 flex justify-between gap-4 text-[12.5px] text-ink-2">
<span>
<span className="text-ink">{(elapsed / 1000).toFixed(1)} s</span> to answer
</span>
<span>
<span className="text-ink">{shown ? money(costPerTask(shown, task)) : ""}</span> per {task.label}
</span>
</p>
</div>
</div>
);
}Usage
import { ModelPicker } from "@/components/ui/model-picker"
<ModelPicker
models={[{ id: "fast", name: "Fast", tps: 160, ttft: 250, input: 0.8, output: 4 }]}
sample="Store event.id before charging and return 200 if you have seen it."
task={{ label: "review", input: 18000, output: 1200 }}
/>Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| models | { id; name; tps; ttft; input; output }[] | tps is output tokens a second, ttft the wait for the first token in ms, input and output are $ per million tokens. | |
| sample | string | The answer every model streams, so only the speed differs. | |
| task | { label: string; input: number; output: number } | The job the cost is quoted for, in tokens, e.g. one review. | |
| value | string | Controlled model id. | |
| defaultValue | string | models[0].id | Initial model when uncontrolled. |
| onValueChange | (id: string) => void | Called when a model is picked. |
Keyboard
- ↑ ↓
- Move between models; the preview follows focus
- Enter / Space
- Pick the focused model
Accessibility
- role=listbox with role=option and aria-selected; arrows move focus, Enter picks.
- The preview is linked to each option with aria-describedby, and is not a live region, so it never talks over the user.
- Reduced motion shows the whole answer at once, with the time it would take.