Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 | 1x 1x 1x 1x 1x | /**
* Quick try — the Compare scratchpad.
*
* Send one prompt to several models/agents at once and read the answers
* side by side, with latency, tokens, and an optional grade. This is the
* first thing to reach for when trying out a prompt, and "Save as
* evaluation" turns a promising comparison into a repeatable one — keeping
* the results just read as the evaluation's first run. The backend holds the
* comparison under an id for a day; nothing appears in any list until saved.
*/
import { Modal, ModalActions } from "@/components/detail";
import { CreateButton } from "@/components/collection";
import { Agent } from "@/objects/Agent";
import {
CaseExpectation,
Comparison,
ComparisonResult,
EvaluationScorer,
EvaluationTarget,
} from "@/objects/Evaluation";
import { Model } from "@/objects/Model";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { errorDetail } from "@/util/apiError";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
Columns3,
Loader2,
Play,
Plus,
Save,
Trash2,
Wand2,
} from "lucide-react";
import React, { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
ErrorNote,
Field,
PassBadge,
ScoreBadge,
ScorerPicker,
SectionCard,
TargetPicker,
experimentHref,
formatDuration,
formatTokens,
inputCls,
parseLines,
targetLabel,
} from "./components";
// Matches the backend's cap on POST /evaluations/compare.
const MAX_TARGETS = 6;
/** A target row in the comparison form, with a stable key for React. */
interface TargetSlot {
key: string;
target: EvaluationTarget | null;
}
const newSlot = (target: EvaluationTarget | null = null): TargetSlot => ({
key: Math.random().toString(36).slice(2),
target,
});
// ─── Save-as-evaluation modal ─────────────────────────────────────────────────
/**
* Turn the comparison just run into a saved evaluation.
*
* One request naming the comparison. The backend derives everything else
* from what actually ran — the prompt as a one-case dataset, the scorer, one
* variant per target with the system prompt it used — and adopts the
* comparison's results as the evaluation's first run, in a single
* transaction. Deriving it server-side rather than sending the form back is
* what makes the saved evaluation describe the results it holds, whatever
* the form says now.
*/
const SaveModal: React.FC<{
comparisonId: string;
targetCount: number;
onClose: () => void;
}> = ({ comparisonId, targetCount, onClose }) => {
const { getApiHandler } = useApiHandler();
const queryClient = useQueryClient();
const navigate = useNavigate();
const [name, setName] = useState("");
const [error, setError] = useState<string | null>(null);
const save = useMutation({
mutationFn: async () => {
const experiment =
await getApiHandler().evaluation_router.createExperiment({
name: name.trim(),
description: "Saved from Quick try.",
comparison_id: comparisonId,
});
if (!experiment) throw new Error("Could not save this comparison.");
return experiment;
},
onSuccess: (experiment) => {
void queryClient.invalidateQueries({
queryKey: [QUERY_KEYS.GET.EXPERIMENTS],
});
navigate(experimentHref(experiment.id));
},
onError: (e) => setError(errorDetail(e, "Could not save this comparison.")),
});
return (
<Modal
title="Save as an experiment"
icon={Save}
size="md"
busy={save.isPending}
onClose={onClose}
description={
<>
Creates a dataset with this prompt as its first case, and an
experiment on it with {targetCount}{" "}
{targetCount === 1 ? "variant" : "variants"} and these results as its
first run — so you can re-run it, add more cases, and optimise it.
</>
}
footer={
<ModalActions
onCancel={onClose}
onConfirm={() => {
setError(null);
save.mutate();
}}
confirmLabel="Save"
icon={Save}
loading={save.isPending}
disabled={!name.trim()}
/>
}
>
<Field label="Name">
<input
autoFocus
className={inputCls}
placeholder="e.g. Support triage prompt — model shootout"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</Field>
{error && (
<div className="mt-3">
<ErrorNote message={error} />
</div>
)}
</Modal>
);
};
// ─── Result column ────────────────────────────────────────────────────────────
const ResultColumn: React.FC<{
result: ComparisonResult;
/** The best score in this comparison, to mark the winner. */
best: number | null;
}> = ({ result, best }) => {
const isWinner =
typeof result.score === "number" && best !== null && result.score >= best;
return (
<div
className={`flex flex-col rounded-xl border bg-white dark:bg-gray-800 overflow-hidden ${
isWinner
? "border-green-300 dark:border-green-700 ring-1 ring-green-200 dark:ring-green-800"
: "border-gray-200 dark:border-gray-700"
}`}
>
<div className="flex items-center justify-between gap-2 px-4 py-2.5 border-b border-gray-100 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/60">
<span className="text-xs font-semibold text-gray-700 dark:text-gray-300 truncate">
{targetLabel(result.target)}
</span>
<div className="flex items-center gap-1.5 shrink-0">
{result.passed !== null && <PassBadge passed={result.passed} />}
<ScoreBadge value={result.score} />
</div>
</div>
<div className="px-4 py-3 flex-1 min-h-[8rem]">
{result.error ? (
<ErrorNote message={result.error} />
) : (
<p className="text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap leading-relaxed break-words">
{result.output || (
<span className="italic text-gray-400">(empty response)</span>
)}
</p>
)}
</div>
{result.score_reason && (
<div className="px-4 pb-3">
<p className="text-xs italic text-gray-400 dark:text-gray-500">
{result.score_reason}
</p>
</div>
)}
<div className="flex items-center gap-3 px-4 py-2 border-t border-gray-100 dark:border-gray-700 text-[10px] text-gray-400 dark:text-gray-500 tabular-nums">
<span>{formatDuration(result.latency_ms)}</span>
<span>{formatTokens(result.total_tokens)} tok</span>
<span className="truncate">
{formatTokens(result.input_tokens)} in /{" "}
{formatTokens(result.output_tokens)} out
</span>
</div>
</div>
);
};
// ─── Main ─────────────────────────────────────────────────────────────────────
const Compare: React.FC = () => {
const { getApiHandler } = useApiHandler();
const [prompt, setPrompt] = useState("");
const [systemPrompt, setSystemPrompt] = useState("");
const [expectedOutput, setExpectedOutput] = useState("");
// The question's label, as a dataset case carries it — saving this
// comparison puts it on the new dataset's case, never on the scorer.
const [criteria, setCriteria] = useState("");
const [mustContain, setMustContain] = useState("");
const [mustNotContain, setMustNotContain] = useState("");
const [scorer, setScorer] = useState<EvaluationScorer>("manual");
const [scorerConfig, setScorerConfig] = useState<Record<string, unknown>>({});
const [judge, setJudge] = useState<EvaluationTarget | null>(null);
const [slots, setSlots] = useState<TargetSlot[]>([newSlot(), newSlot()]);
const [showGrading, setShowGrading] = useState(false);
const [showSave, setShowSave] = useState(false);
const [error, setError] = useState<string | null>(null);
// The last comparison, with the inputs it was run from. Results stay on
// screen while the form is edited, but saving is only offered for the run
// that produced them — the backend saves what ran, not what the form says.
const [comparison, setComparison] = useState<{
id: string | null;
results: ComparisonResult[];
signature: string;
} | null>(null);
const results = comparison?.results ?? null;
const { data: models = [] } = useQuery<Model[]>({
queryKey: [QUERY_KEYS.GET.MODELS],
queryFn: () => getApiHandler().model_router.list() as Promise<Model[]>,
});
const { data: agents = [] } = useQuery<Agent[]>({
queryKey: [QUERY_KEYS.GET.AGENTS],
queryFn: () =>
getApiHandler().agent_router.list(undefined) as Promise<Agent[]>,
});
const chosen = useMemo(
() => slots.map((s) => s.target).filter((t): t is EvaluationTarget => !!t),
[slots],
);
const request = useMemo(() => {
const expectation: CaseExpectation = {};
const must = parseLines(mustContain);
const mustNot = parseLines(mustNotContain);
if (must.length) expectation.must_contain = must;
if (mustNot.length) expectation.must_not_contain = mustNot;
return {
prompt,
targets: chosen,
system_prompt: systemPrompt,
expected_output: expectedOutput.trim() || null,
// One criterion per line, so the judge marks each.
criteria: parseLines(criteria).length
? parseLines(criteria).map((text) => ({ text, gate: false }))
: null,
expectation: Object.keys(expectation).length ? expectation : null,
scorer: scorer === "manual" ? null : scorer,
scorer_config: scorerConfig,
judge,
};
}, [
prompt,
chosen,
systemPrompt,
expectedOutput,
criteria,
mustContain,
mustNotContain,
scorer,
scorerConfig,
judge,
]);
const signature = JSON.stringify(request);
const run = useMutation({
mutationFn: () => getApiHandler().evaluation_router.compare(request),
onSuccess: (data: Comparison) => {
setComparison({
id: data.comparison_id,
results: data.results,
signature,
});
setError(null);
},
onError: (e) => {
setComparison(null);
setError(errorDetail(e, "The comparison failed."));
},
});
// Saving names the comparison that ran; if the form has moved on since,
// what would be saved is not what is on screen, so say so instead.
const stale = !!comparison && comparison.signature !== signature;
const canSave = !!comparison?.id && !stale;
const canRun = prompt.trim().length > 0 && chosen.length > 0;
const bestScore = useMemo(() => {
const scores = (results ?? [])
.map((r) => r.score)
.filter((s): s is number => typeof s === "number");
return scores.length ? Math.max(...scores) : null;
}, [results]);
return (
<div className="space-y-4">
{showSave && comparison?.id && (
<SaveModal
comparisonId={comparison.id}
targetCount={comparison.results.length}
onClose={() => setShowSave(false)}
/>
)}
<p className="text-sm text-gray-500 dark:text-gray-400">
Send one prompt to several models or agents at once and read the answers
side by side. Save a comparison to keep it as an experiment, results
included; otherwise it is gone in a day.
</p>
<SectionCard icon={Wand2} title="Prompt">
<div className="space-y-3">
<Field label="System prompt" hint="optional — shared by every target">
<textarea
rows={3}
className={`${inputCls} resize-y font-mono`}
placeholder="You are a support triage assistant…"
value={systemPrompt}
onChange={(e) => setSystemPrompt(e.target.value)}
/>
</Field>
<Field label="User prompt">
<textarea
rows={4}
className={`${inputCls} resize-y`}
placeholder="The message you want every target to answer…"
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
/>
</Field>
<button
type="button"
onClick={() => setShowGrading((v) => !v)}
className="text-xs text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 transition-colors"
>
{showGrading ? "Hide" : "Add"} an expected answer and grade the
outputs
</button>
{showGrading && (
<div className="space-y-3 rounded-lg border border-gray-100 dark:border-gray-700 p-4">
<Field
label="Criteria"
hint="what a good answer must do, one per line — the LLM judge marks each"
>
<textarea
rows={2}
className={`${inputCls} resize-y`}
value={criteria}
onChange={(e) => setCriteria(e.target.value)}
/>
</Field>
<Field label="Expected output" hint="optional reference answer">
<textarea
rows={2}
className={`${inputCls} resize-y`}
value={expectedOutput}
onChange={(e) => setExpectedOutput(e.target.value)}
/>
</Field>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<Field label="Must contain" hint="one per line — Text checks">
<textarea
rows={2}
className={`${inputCls} resize-y font-mono text-xs`}
value={mustContain}
onChange={(e) => setMustContain(e.target.value)}
/>
</Field>
<Field
label="Must not contain"
hint="one per line — Text checks"
>
<textarea
rows={2}
className={`${inputCls} resize-y font-mono text-xs`}
value={mustNotContain}
onChange={(e) => setMustNotContain(e.target.value)}
/>
</Field>
</div>
<ScorerPicker
scorer={scorer}
config={scorerConfig}
onChange={(kind, config) => {
setScorer(kind);
setScorerConfig(config);
}}
judge={judge}
onJudgeChange={setJudge}
/>
</div>
)}
</div>
</SectionCard>
<SectionCard
icon={Columns3}
title="Targets"
subtitle={`${chosen.length}/${MAX_TARGETS}`}
action={
slots.length < MAX_TARGETS && (
<button
onClick={() => setSlots((s) => [...s, newSlot()])}
className="flex items-center gap-1 text-xs px-2.5 py-1.5 rounded-lg border border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
>
<Plus className="size-3.5" />
Add
</button>
)
}
>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{slots.map((slot, index) => (
<div
key={slot.key}
className="rounded-lg border border-gray-100 dark:border-gray-700 p-3 space-y-2"
>
<div className="flex items-center justify-between">
<span className="text-[10px] uppercase tracking-wide font-medium text-gray-400 dark:text-gray-500">
Target {index + 1}
</span>
{slots.length > 1 && (
<button
onClick={() =>
setSlots((s) => s.filter((x) => x.key !== slot.key))
}
className="text-gray-300 dark:text-gray-600 hover:text-red-500 dark:hover:text-red-400 transition-colors"
>
<Trash2 className="size-3.5" />
</button>
)}
</div>
<TargetPicker
value={slot.target}
onChange={(target) =>
setSlots((s) =>
s.map((x) => (x.key === slot.key ? { ...x, target } : x)),
)
}
models={models}
agents={agents}
/>
</div>
))}
</div>
</SectionCard>
{error && <ErrorNote message={error} />}
<div className="flex items-center gap-2">
<button
disabled={!canRun || run.isPending}
onClick={() => run.mutate()}
className="flex items-center gap-1.5 px-4 py-2 rounded-lg bg-gray-900 dark:bg-white text-white dark:text-gray-900 text-sm font-medium hover:opacity-80 transition-opacity disabled:opacity-40"
>
{run.isPending ? (
<Loader2 className="size-3.5 animate-spin" />
) : (
<Play className="size-3.5" />
)}
{run.isPending ? "Running…" : `Run on ${chosen.length || "…"}`}
</button>
{results && (
<CreateButton
label="Save as experiment"
onClick={() => setShowSave(true)}
disabled={!canSave}
/>
)}
{results && stale && (
<span className="text-xs text-amber-600 dark:text-amber-400">
Inputs changed since this run — run again to save.
</span>
)}
{results && !stale && !comparison?.id && (
<span className="text-xs text-gray-400 dark:text-gray-500">
This comparison was not recorded, so it cannot be saved.
</span>
)}
</div>
{results && (
<div
className={`grid gap-4 ${
results.length > 2
? "sm:grid-cols-2 xl:grid-cols-3"
: "sm:grid-cols-2"
}`}
>
{results.map((result, index) => (
<ResultColumn
key={`${targetLabel(result.target)}-${index}`}
result={result}
best={bestScore}
/>
))}
</div>
)}
</div>
);
};
export default Compare;
|