Skip to content

The platform for continuously improving AI agents.

11.1 KB
Raw Blame
import type { EditorBlock } from "./canvas-document";
import type { ExperimentDocument, NodeReceipt } from "./document";
import { objectValue } from "./node-summary";

const label = (key: string) =>
  ({
    batch_size: "Batch size",
    context_length: "Context",
    learning_rate: "Learning rate",
    lora_r: "LoRA rank",
    lr: "Learning rate",
    max_steps: "Steps",
    max_tokens: "Max tokens",
    method: "Method",
    metrics: "Metrics",
    n_epochs: "Epochs",
    num_train_epochs: "Epochs",
    seed: "Seed",
    temperature: "Temperature",
    warmup_ratio: "Warmup",
  })[key] ?? key.replaceAll("_", " ");
const scalar = (value: unknown): value is string | number | boolean =>
  ["string", "number", "boolean"].includes(typeof value);
export function nodeFacts(block: EditorBlock): [string, string][] {
  const config = objectValue(block.parameters),
    args = objectValue(block.arguments);
  const recipe = { ...args, ...config };
  const keys: Record<string, string[]> = {
    check_data: ["minimum_rows"],
    compare: ["metrics", "selection_metric", "direction", "method"],
    evaluate: ["method", "metrics", "judge", "threshold"],
    export_data: ["format"],
    inference: ["max_tokens", "enable_thinking"],
    ingest: ["connector", "max_pages"],
    model: ["quantization", "context_length", "precision", "revision"],
    performance: ["sample_size", "repetitions", "concurrency", "questions_per_request"],
    predict: ["temperature", "max_tokens", "batch_size", "seed"],
    publish: ["execution_seconds", "ttl_seconds", "max_requests"],
    trace_dataset: ["name", "intent"],
    train: [
      "method",
      "n_epochs",
      "num_train_epochs",
      "max_steps",
      "learning_rate",
      "lr",
      "batch_size",
      "context_length",
      "lora_r",
      "warmup_ratio",
      "weight_decay",
      "feature_columns",
    ],
  };
  const values = { ...recipe };
  for (const key of [
    "hyperparameters",
    "training",
    "recipe",
    "parameters",
    "config",
    "kwargs",
    "arguments",
    "workload",
  ])
    if (recipe[key] && typeof recipe[key] === "object" && !Array.isArray(recipe[key]))
      Object.assign(values, recipe[key]);
  if (block.kind === "train") Object.assign(values, trainingOverrides(block));
  return (keys[block.kind] ?? [])
    .flatMap((key): [string, string][] => {
      const value = values[key];
      if (key === "feature_columns" && Array.isArray(value))
        return [["Features", String(value.length)]];
      if (Array.isArray(value) && value.every(scalar)) return [[label(key), value.join(", ")]];
      return scalar(value) ? [[label(key), String(value)]] : [];
    })
    .slice(0, 8);
}

export const trainingFields = [
  { key: "n_epochs", label: "Epochs", min: 1, step: 1 },
  { key: "learning_rate", label: "Learning rate", min: 0.000000001, step: "any" },
  { key: "batch_size", label: "Batch size", min: 1, step: 1 },
  { key: "context_length", label: "Context length", min: 1, step: 1 },
] as const;

// A Train node starts a training campaign: `run` holds the start_finetune arguments every
// run shares, `trials` the most runs.
function campaignArguments(block: EditorBlock) {
  return objectValue(JSON.stringify(objectValue(block.arguments).arguments));
}

export function trainingOverrides(block: EditorBlock): Record<string, unknown> {
  const run = objectValue(JSON.stringify(campaignArguments(block).run));
  return objectValue(JSON.stringify(run.hyperparameters));
}

export function setTrainingOverride(block: EditorBlock, key: string, value: number | undefined) {
  const args = campaignArguments(block);
  const run = objectValue(JSON.stringify(args.run));
  const hyperparameters = { ...trainingOverrides(block) };
  if (value === undefined) delete hyperparameters[key];
  else hyperparameters[key] = value;
  return {
    ...block,
    arguments: JSON.stringify(
      {
        ...objectValue(block.arguments),
        arguments: { ...args, run: { ...run, hyperparameters } },
        operation: "create",
      },
      null,
      2
    ),
    tool: "training",
  };
}

export function nodeInputs(document: ExperimentDocument, id: string) {
  return document.edges
    .filter((edge) => edge.target === id)
    .map((edge) => ({
      id: edge.source,
      output: edge.output,
      port: edge.input,
      title: document.nodes.find((node) => node.id === edge.source)?.title ?? edge.source,
    }));
}

interface ModelCandidate {
  id: string;
  title: string;
  model?: string;
  nodeId?: string;
  kind?: string;
  baseline?: boolean;
  job?: string;
}

export function modelCandidates(document: ExperimentDocument, id: string) {
  const visit = (key: string, seen: Set<string>): ModelCandidate[] => {
    if (seen.has(key)) return [];
    const next = new Set(seen).add(key);
    const node = document.nodes.find((item) => item.id === key);
    if (!node) return [];
    const incoming = document.edges.filter((edge) => edge.target === key);
    const modelEdges = incoming.filter((edge) => edge.input === "model");
    const parents = (
      modelEdges.length
        ? modelEdges
        : incoming.filter((edge) => ["predictions", "scores", "baseline"].includes(edge.input))
    ).flatMap((edge) => visit(edge.source, next));
    const selection = node.config.model;
    const own =
      typeof selection === "string"
        ? selection
        : selection &&
            typeof selection === "object" &&
            "model" in selection &&
            typeof selection.model === "string"
          ? selection.model
          : undefined;
    if (node.kind === "model" || node.kind === "train") {
      const checkpoint = node.config._checkpoint as { job?: string; model?: string } | undefined;
      return [
        {
          id: node.id,
          job: checkpoint?.job,
          model: checkpoint?.model ?? own ?? parents[0]?.model,
          title: node.title,
          ...(node.kind === "train" || checkpoint?.job ? { kind: "trained" } : {}),
        },
      ];
    }
    if (node.operation?.tool === "benchmark") {
      const settings = { ...node.operation.arguments, ...node.config };
      const participants = Array.isArray(settings.participants) ? settings.participants : [];
      const checkpoints = parents.filter((parent) => parent.kind === "trained");
      let connected = checkpoints;
      const selected = participants.flatMap((participant): ModelCandidate[] => {
        if (!participant || typeof participant !== "object" || typeof participant.key !== "string")
          return [];
        const bound =
          participant.kind === "trained"
            ? checkpoints.find((candidate) => !participant.job || candidate.job === participant.job)
            : undefined;
        if (bound) connected = connected.filter((candidate) => candidate.id !== bound.id);
        return [
          {
            baseline: participant.key === settings.baseline,
            id: `${node.id}:${participant.key}`,
            job: participant.job ?? bound?.job,
            kind: participant.kind,
            model:
              bound?.model ??
              (typeof participant.model === "string" ? participant.model : undefined),
            nodeId: bound ? (bound.nodeId ?? bound.id) : node.id,
            title:
              typeof participant.name === "string"
                ? participant.name
                : (bound?.title ??
                  (typeof participant.model === "string"
                    ? participant.model
                    : "New OpenRouter model")),
          },
        ];
      });
      return [...connected, ...selected];
    }
    if (own) return [{ id: node.id, model: own, title: node.title }];
    return parents;
  };
  return [...new Map(visit(id, new Set()).map((model) => [model.id, model])).values()];
}
export function evaluationContext(document: ExperimentDocument, id: string) {
  const node = document.nodes.find((node) => node.id === id);
  const settings = { ...node?.operation?.arguments, ...node?.config };
  const dataEdges = (target: string) =>
    document.edges.filter((edge) => edge.target === target && edge.input === "data");
  let edges = dataEdges(id);
  if (!edges.length)
    edges = document.edges
      .filter((edge) => edge.target === id && edge.input === "predictions")
      .flatMap((edge) => dataEdges(edge.source));
  const datasets = edges.map((edge) => ({
    id: edge.source,
    partition: edge.output,
    title: document.nodes.find((node) => node.id === edge.source)?.title ?? edge.source,
  }));
  const evaluation =
    settings.evaluation_set ??
    settings.eval_set ??
    settings.evaluation_set_id ??
    settings.eval_set_id;
  return { datasets, evaluation: typeof evaluation === "string" ? evaluation : undefined };
}
export function outputFacts(receipt?: NodeReceipt): [string, string][] {
  if (!receipt?.current) return [];
  const facts: [string, string][] = [];
  for (const [port, output] of Object.entries(receipt.outputs)) {
    for (const [key, value] of Object.entries(output)) {
      if (
        [
          "accuracy",
          "loss",
          "score",
          "f1",
          "auc",
          "perplexity",
          "latency_ms",
          "endpoint",
          "status",
        ].includes(key) &&
        scalar(value)
      )
        facts.push([label(key), String(value)]);
      if (key === "metrics" && value && typeof value === "object" && !Array.isArray(value))
        for (const [name, metric] of Object.entries(value))
          if (typeof metric === "number") facts.push([label(name), String(metric)]);
    }
    if (output.checkpoint?.step != null)
      facts.push(["Checkpoint", `Step ${output.checkpoint.step}`]);
    if (output.selected && typeof output.selected === "object" && "value" in output.selected) {
      const value = output.selected.value;
      if (typeof value === "number" && Number.isFinite(value))
        facts.push([
          "Selected score",
          value.toLocaleString(undefined, { maximumFractionDigits: 4 }),
        ]);
    }
    if (Array.isArray(output.reports) && output.reports.length)
      facts.push(["Results", String(output.reports.length)]);
    if (!facts.length && output.artifact) facts.push([port, "Artifact retained"]);
  }
  return facts.slice(0, 8);
}

export function trainingWork(receipt?: NodeReceipt): { campaign: string; job: string } | undefined {
  if (!receipt) return;
  const model = receipt.current ? receipt.outputs.model : undefined;
  if (typeof model?.campaign === "string" && typeof model.job === "string")
    return { campaign: model.campaign, job: model.job };
  // The campaign as it starts: `{ campaign: { id, trials: [{ job }] } }`; its newest run trains.
  const result =
    receipt.result && typeof receipt.result === "object" && "campaign" in receipt.result
      ? receipt.result.campaign
      : undefined;
  if (!result || typeof result !== "object") return;
  const campaign = "id" in result && typeof result.id === "string" ? result.id : undefined;
  const trials = "trials" in result && Array.isArray(result.trials) ? result.trials : [];
  const job = trials
    .map((trial) => (trial && typeof trial === "object" && "job" in trial ? trial.job : undefined))
    .filter((id): id is string => typeof id === "string")
    .at(-1);
  if (campaign && job) return { campaign, job };
}