Skip to content

The platform for continuously improving AI agents.

5.7 KB
Raw Blame
import { BLOCKS, type ExperimentBlock, type ExperimentDocument } from "./document";

export interface EditorBlock extends Omit<ExperimentBlock, "config" | "operation"> {
  parameters: string;
  tool: string;
  arguments: string;
}
export function toEditorBlock(block: ExperimentBlock): EditorBlock {
  return {
    ...block,
    arguments: JSON.stringify(block.operation?.arguments ?? {}, null, 2),
    parameters: JSON.stringify(block.config, null, 2),
    tool: block.operation?.tool ?? "",
  };
}
export function fromEditorBlock(block: EditorBlock): ExperimentBlock {
  const config: unknown = JSON.parse(block.parameters);
  const args: unknown = JSON.parse(block.arguments);
  if (
    !config ||
    typeof config !== "object" ||
    Array.isArray(config) ||
    !args ||
    typeof args !== "object" ||
    Array.isArray(args)
  )
    throw new Error(`${block.title}: parameters and arguments must be JSON objects`);
  const { parameters: _, arguments: __, tool, ...rest } = block;
  return {
    ...rest,
    config: config as Record<string, unknown>,
    operation: tool ? { arguments: args as Record<string, unknown>, tool } : null,
  };
}

export function blockPorts(
  node: ExperimentBlock,
  direction: "inputs" | "outputs"
): Record<string, string> {
  if (node.kind === "component") {
    const ports = node.config.ports as Record<string, Record<string, string>> | undefined;
    return ports?.[direction] ?? {};
  }
  return BLOCKS[node.kind][direction === "inputs" ? "inputTypes" : "outputTypes"];
}

export function inputBindings(document: ExperimentDocument, id: string) {
  const node = document.nodes.find((item) => item.id === id);
  if (!node) return [];
  return Object.keys(blockPorts(node, "inputs")).map((port) => ({
    many: (BLOCKS[node.kind].many as readonly string[]).includes(port),
    options: availableBindings(document, id, port),
    port,
    values: document.edges
      .filter((edge) => edge.target === id && edge.input === port)
      .map((edge) => `${edge.source}:${edge.output}`),
  }));
}

export function bindInput(
  document: ExperimentDocument,
  id: string,
  input: string,
  value: string,
  previous = ""
): ExperimentDocument {
  const binding = inputBindings(document, id).find((item) => item.port === input);
  const option = binding?.options.find((item) => `${item.source}:${item.output}` === value);
  const edges = document.edges.filter(
    (edge) =>
      edge.target !== id ||
      edge.input !== input ||
      (binding?.many && `${edge.source}:${edge.output}` !== previous)
  );
  if (
    option &&
    !edges.some(
      (edge) =>
        edge.target === id &&
        edge.input === input &&
        edge.source === option.source &&
        edge.output === option.output
    )
  ) {
    edges.push({ input, output: option.output, source: option.source, target: id });
  }
  return {
    ...document,
    edges,
    nodes: document.nodes.map((node) => {
      if (node.id !== id || !option) return node;
      if (input === "suite" && node.operation?.tool === "benchmark") {
        const { eval_set: _, suite: __, ...args } = node.operation.arguments;
        return { ...node, operation: { ...node.operation, arguments: args } };
      }
      if (input !== "model") return node;
      const { model: _, ...config } = node.config;
      return { ...node, config };
    }),
  };
}

export function removeNode(document: ExperimentDocument, id: string): ExperimentDocument {
  return {
    ...document,
    edges: document.edges.filter((edge) => edge.source !== id && edge.target !== id),
    nodes: document.nodes.filter((node) => node.id !== id),
    ...(document.outputs && {
      outputs: Object.fromEntries(
        Object.entries(document.outputs).filter(([, output]) => output.node !== id)
      ),
    }),
  };
}

export function recipeAt(
  document: ExperimentDocument,
  path: string[]
): ExperimentDocument | undefined {
  if (!path.length) return document;
  const group = document.nodes.find((node) => node.id === path[0] && node.kind === "map");
  const recipe = group?.config.recipe as ExperimentDocument | undefined;
  return recipe ? recipeAt(recipe, path.slice(1)) : undefined;
}

export function replaceRecipe(
  document: ExperimentDocument,
  path: string[],
  recipe: ExperimentDocument
): ExperimentDocument {
  if (!path.length) return recipe;
  return {
    ...document,
    nodes: document.nodes.map((node) =>
      node.id === path[0] && node.kind === "map" && node.config.recipe
        ? {
            ...node,
            config: {
              ...node.config,
              recipe: replaceRecipe(
                node.config.recipe as ExperimentDocument,
                path.slice(1),
                recipe
              ),
            },
          }
        : node
    ),
  };
}

export function availableBindings(document: ExperimentDocument, target: string, input: string) {
  const targetNode = document.nodes.find((node) => node.id === target);
  const inputType = targetNode ? blockPorts(targetNode, "inputs")[input] : undefined;
  const benchmarkModel = targetNode?.operation?.tool === "benchmark" && input === "model";
  const downstream = new Set([target]);
  const visit = (id: string) => {
    for (const edge of document.edges.filter((edge) => edge.source === id)) {
      if (!downstream.has(edge.target)) {
        downstream.add(edge.target);
        visit(edge.target);
      }
    }
  };
  visit(target);
  return document.nodes
    .filter(
      (node) =>
        !downstream.has(node.id) &&
        (!benchmarkModel || node.kind !== "model" || !!node.config._checkpoint)
    )
    .flatMap((node) =>
      Object.keys(blockPorts(node, "outputs"))
        .filter((port) => blockPorts(node, "outputs")[port] === inputType)
        .map((output) => ({ label: `${node.title} · ${output}`, output, source: node.id }))
    );
}