Skip to content

The platform for continuously improving AI agents.

8.7 KB
Raw Blame
import { useState } from "react";

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

import api from "@/client";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { DateTime } from "@/components/ui/datetime";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { SectionCard } from "@/components/ui/section-card";
import { errorMessage } from "@/lib/notify";
import type { TrainingAgent as Agent, OperationEnum, TrainingControl } from "@/openapi";

const OPERATIONS: Record<string, string> = {
  checkpoint: "Save checkpoint",
  finish: "Finish with best checkpoint",
  restore_checkpoint: "Recover checkpoint",
  set_clip_norm: "Change clip norm",
  set_learning_rate: "Change learning rate",
  stop: "Stop",
};

/** What a change did, in the trainer's words when it reported back. */
export function controlOutcome(control: TrainingControl): string {
  const result = (control.result ?? {}) as Record<string, unknown>;
  if (control.state === "applied")
    return control.step == null ? "Applied" : `Applied at step ${control.step}`;
  if (control.state === "rejected")
    return typeof result.error === "string" ? `Not applied: ${result.error}` : "Not applied";
  return control.state === "sent" ? "Sent to the trainer" : "Requested";
}

function controlValue(control: TrainingControl): string {
  const args = (control.arguments ?? {}) as Record<string, unknown>;
  if (typeof args.value === "number") return ` to ${args.value}`;
  if (typeof args.step === "number") return ` at step ${args.step}`;
  return "";
}

/** The training agent of one job: its reviews, the changes made to the run, and the same
 *  live controls for a person. */
export function TrainingAgent({ jobId, terminal }: { jobId: string; terminal: boolean }) {
  const client = useQueryClient();
  const [learningRate, setLearningRate] = useState("");
  const agent = useQuery({
    queryFn: () => api.finetuningJobs.finetuningJobsTrainingAgentRetrieve({ id: jobId }),
    queryKey: ["training-agent", jobId],
    refetchInterval: terminal ? false : 5000,
  });
  const control = useMutation({
    mutationFn: ({ operation, args }: { operation: OperationEnum; args?: object }) =>
      api.finetuningJobs.finetuningJobsTrainingControlsCreate({
        id: jobId,
        trainingControlRequestRequest: {
          arguments: args ?? {},
          operation,
          reason: "Requested from the Training job",
          requestKey: crypto.randomUUID(),
        },
      }),
    onSuccess: () => client.invalidateQueries({ queryKey: ["training-agent", jobId] }),
  });
  const data: Agent | undefined = agent.data;
  if (!data || (!data.limits && !data.reviews.length && !data.controls.length)) {
    return agent.error ? (
      <Alert variant="destructive">{errorMessage(agent.error, "Couldn't load the agent")}</Alert>
    ) : null;
  }
  const live = !terminal && !data.unavailable;
  const pending = data.controls.some((item) => item.state === "requested" || item.state === "sent");
  const busy = control.isPending || pending;
  const rate = Number(learningRate);
  const [low, high] = data.limits?.learningRate ?? [0, Number.POSITIVE_INFINITY];
  const latest = data.reviews.at(-1);
  return (
    <SectionCard
      contentClassName="space-y-4"
      headerEnd={
        <span className="text-xs text-muted-foreground">
          {terminal ? "ended" : (latest?.state ?? "watching")}
        </span>
      }
      title="Training agent"
    >
      {(agent.error || control.error) && (
        <Alert variant="destructive">
          {errorMessage(agent.error || control.error, "Couldn't update Training activity")}
        </Alert>
      )}
      <ol className="space-y-4">
        {data.reviews.map((review) => (
          <li className="space-y-1" key={review.id}>
            <div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
              <span>
                {review.reason === "setup"
                  ? "Recipe setup"
                  : `Development review${review.step == null ? "" : ` · step ${review.step}`}`}{" "}
                · {review.state}
              </span>
              <DateTime value={review.createdAt} />
            </div>
            {review.summary && (
              <p className="text-sm leading-relaxed whitespace-pre-line">{review.summary}</p>
            )}
            {review.error && <p className="text-xs text-error">{review.error}</p>}
          </li>
        ))}
      </ol>
      {!terminal && data.unavailable && (
        <p className="text-xs text-muted-foreground">{data.unavailable}</p>
      )}
      {!terminal && (
        <div className="flex flex-wrap gap-2">
          {live && (
            <>
              <Button
                disabled={busy}
                onClick={() => control.mutate({ operation: "checkpoint" })}
                size="sm"
                variant="secondary"
              >
                Save checkpoint
              </Button>
              <Button
                disabled={busy}
                onClick={() => control.mutate({ operation: "finish" })}
                size="sm"
                variant="secondary"
              >
                Finish with best checkpoint
              </Button>
            </>
          )}
          <Button
            disabled={control.isPending}
            onClick={() => control.mutate({ operation: "stop" })}
            size="sm"
            variant="secondary"
          >
            Stop
          </Button>
        </div>
      )}
      {live && (
        <details>
          <summary className="cursor-pointer text-xs text-muted-foreground">
            Adjust learning rate
          </summary>
          <div className="mt-3 flex flex-wrap items-end gap-2">
            <div className="space-y-1">
              <Label htmlFor={`learning-rate-${jobId}`}>Learning rate</Label>
              <Input
                id={`learning-rate-${jobId}`}
                max={high}
                min={low}
                onChange={(event) => setLearningRate(event.target.value)}
                placeholder={data.learningRate == null ? undefined : String(data.learningRate)}
                step="any"
                type="number"
                value={learningRate}
              />
            </div>
            <Button
              disabled={
                busy || !learningRate || !Number.isFinite(rate) || rate < low || rate > high
              }
              onClick={() =>
                control.mutate({ args: { value: rate }, operation: "set_learning_rate" })
              }
              size="sm"
              variant="secondary"
            >
              Apply at next step
            </Button>
          </div>
        </details>
      )}
      {live && data.checkpoints.length > 0 && (
        <details>
          <summary className="cursor-pointer text-xs text-muted-foreground">
            Recover checkpoint
          </summary>
          <ul className="mt-3 space-y-2 text-xs">
            {data.checkpoints.map((checkpoint) => (
              <li
                className="flex flex-wrap items-center justify-between gap-2"
                key={checkpoint.step}
              >
                <span>
                  Step {checkpoint.step}
                  {checkpoint.evalLoss == null ? "" : ` · development loss ${checkpoint.evalLoss}`}
                  {checkpoint.selected ? " · best" : ""}
                </span>
                <Button
                  disabled={busy}
                  onClick={() =>
                    control.mutate({
                      args: { step: checkpoint.step },
                      operation: "restore_checkpoint",
                    })
                  }
                  size="xs"
                  variant="secondary"
                >
                  Reload weights
                </Button>
              </li>
            ))}
          </ul>
        </details>
      )}
      {data.controls.length > 0 && (
        <ul className="space-y-3 border-t border-border/70 pt-3 text-xs">
          {data.controls.map((item) => (
            <li className="space-y-1" key={item.id}>
              <div className="flex flex-wrap justify-between gap-2">
                <span>
                  {OPERATIONS[item.operation] ?? item.operation}
                  {controlValue(item)}
                </span>
                <span className="text-muted-foreground">
                  {item.author === "agent" ? "agent" : (item.userEmail ?? "person")} ·{" "}
                  {controlOutcome(item)}
                </span>
              </div>
              {item.reason && <p className="text-muted-foreground">{item.reason}</p>}
            </li>
          ))}
        </ul>
      )}
    </SectionCard>
  );
}