graph.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. import { zodToJsonSchema } from "zod-to-json-schema";
  2. import { v4 as uuidv4, validate as isUuid } from "uuid";
  3. import { isRunnableInterface } from "./utils.js";
  4. import { drawMermaid, drawMermaidPng } from "./graph_mermaid.js";
  5. function nodeDataStr(id, data) {
  6. if (id !== undefined && !isUuid(id)) {
  7. return id;
  8. }
  9. else if (isRunnableInterface(data)) {
  10. try {
  11. let dataStr = data.getName();
  12. dataStr = dataStr.startsWith("Runnable")
  13. ? dataStr.slice("Runnable".length)
  14. : dataStr;
  15. return dataStr;
  16. }
  17. catch (error) {
  18. return data.getName();
  19. }
  20. }
  21. else {
  22. return data.name ?? "UnknownSchema";
  23. }
  24. }
  25. function nodeDataJson(node) {
  26. // if node.data implements Runnable
  27. if (isRunnableInterface(node.data)) {
  28. return {
  29. type: "runnable",
  30. data: {
  31. id: node.data.lc_id,
  32. name: node.data.getName(),
  33. },
  34. };
  35. }
  36. else {
  37. return {
  38. type: "schema",
  39. data: { ...zodToJsonSchema(node.data.schema), title: node.data.name },
  40. };
  41. }
  42. }
  43. export class Graph {
  44. constructor(params) {
  45. Object.defineProperty(this, "nodes", {
  46. enumerable: true,
  47. configurable: true,
  48. writable: true,
  49. value: {}
  50. });
  51. Object.defineProperty(this, "edges", {
  52. enumerable: true,
  53. configurable: true,
  54. writable: true,
  55. value: []
  56. });
  57. this.nodes = params?.nodes ?? this.nodes;
  58. this.edges = params?.edges ?? this.edges;
  59. }
  60. // Convert the graph to a JSON-serializable format.
  61. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  62. toJSON() {
  63. const stableNodeIds = {};
  64. Object.values(this.nodes).forEach((node, i) => {
  65. stableNodeIds[node.id] = isUuid(node.id) ? i : node.id;
  66. });
  67. return {
  68. nodes: Object.values(this.nodes).map((node) => ({
  69. id: stableNodeIds[node.id],
  70. ...nodeDataJson(node),
  71. })),
  72. edges: this.edges.map((edge) => {
  73. const item = {
  74. source: stableNodeIds[edge.source],
  75. target: stableNodeIds[edge.target],
  76. };
  77. if (typeof edge.data !== "undefined") {
  78. item.data = edge.data;
  79. }
  80. if (typeof edge.conditional !== "undefined") {
  81. item.conditional = edge.conditional;
  82. }
  83. return item;
  84. }),
  85. };
  86. }
  87. addNode(data, id,
  88. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  89. metadata) {
  90. if (id !== undefined && this.nodes[id] !== undefined) {
  91. throw new Error(`Node with id ${id} already exists`);
  92. }
  93. const nodeId = id ?? uuidv4();
  94. const node = {
  95. id: nodeId,
  96. data,
  97. name: nodeDataStr(id, data),
  98. metadata,
  99. };
  100. this.nodes[nodeId] = node;
  101. return node;
  102. }
  103. removeNode(node) {
  104. // Remove the node from the nodes map
  105. delete this.nodes[node.id];
  106. // Filter out edges connected to the node
  107. this.edges = this.edges.filter((edge) => edge.source !== node.id && edge.target !== node.id);
  108. }
  109. addEdge(source, target, data, conditional) {
  110. if (this.nodes[source.id] === undefined) {
  111. throw new Error(`Source node ${source.id} not in graph`);
  112. }
  113. if (this.nodes[target.id] === undefined) {
  114. throw new Error(`Target node ${target.id} not in graph`);
  115. }
  116. const edge = {
  117. source: source.id,
  118. target: target.id,
  119. data,
  120. conditional,
  121. };
  122. this.edges.push(edge);
  123. return edge;
  124. }
  125. firstNode() {
  126. return _firstNode(this);
  127. }
  128. lastNode() {
  129. return _lastNode(this);
  130. }
  131. /**
  132. * Add all nodes and edges from another graph.
  133. * Note this doesn't check for duplicates, nor does it connect the graphs.
  134. */
  135. extend(graph, prefix = "") {
  136. let finalPrefix = prefix;
  137. const nodeIds = Object.values(graph.nodes).map((node) => node.id);
  138. if (nodeIds.every(isUuid)) {
  139. finalPrefix = "";
  140. }
  141. const prefixed = (id) => {
  142. return finalPrefix ? `${finalPrefix}:${id}` : id;
  143. };
  144. Object.entries(graph.nodes).forEach(([key, value]) => {
  145. this.nodes[prefixed(key)] = { ...value, id: prefixed(key) };
  146. });
  147. const newEdges = graph.edges.map((edge) => {
  148. return {
  149. ...edge,
  150. source: prefixed(edge.source),
  151. target: prefixed(edge.target),
  152. };
  153. });
  154. // Add all edges from the other graph
  155. this.edges = [...this.edges, ...newEdges];
  156. const first = graph.firstNode();
  157. const last = graph.lastNode();
  158. return [
  159. first ? { id: prefixed(first.id), data: first.data } : undefined,
  160. last ? { id: prefixed(last.id), data: last.data } : undefined,
  161. ];
  162. }
  163. trimFirstNode() {
  164. const firstNode = this.firstNode();
  165. if (firstNode && _firstNode(this, [firstNode.id])) {
  166. this.removeNode(firstNode);
  167. }
  168. }
  169. trimLastNode() {
  170. const lastNode = this.lastNode();
  171. if (lastNode && _lastNode(this, [lastNode.id])) {
  172. this.removeNode(lastNode);
  173. }
  174. }
  175. /**
  176. * Return a new graph with all nodes re-identified,
  177. * using their unique, readable names where possible.
  178. */
  179. reid() {
  180. const nodeLabels = Object.fromEntries(Object.values(this.nodes).map((node) => [node.id, node.name]));
  181. const nodeLabelCounts = new Map();
  182. Object.values(nodeLabels).forEach((label) => {
  183. nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1);
  184. });
  185. const getNodeId = (nodeId) => {
  186. const label = nodeLabels[nodeId];
  187. if (isUuid(nodeId) && nodeLabelCounts.get(label) === 1) {
  188. return label;
  189. }
  190. else {
  191. return nodeId;
  192. }
  193. };
  194. return new Graph({
  195. nodes: Object.fromEntries(Object.entries(this.nodes).map(([id, node]) => [
  196. getNodeId(id),
  197. { ...node, id: getNodeId(id) },
  198. ])),
  199. edges: this.edges.map((edge) => ({
  200. ...edge,
  201. source: getNodeId(edge.source),
  202. target: getNodeId(edge.target),
  203. })),
  204. });
  205. }
  206. drawMermaid(params) {
  207. const { withStyles, curveStyle, nodeColors = {
  208. default: "fill:#f2f0ff,line-height:1.2",
  209. first: "fill-opacity:0",
  210. last: "fill:#bfb6fc",
  211. }, wrapLabelNWords, } = params ?? {};
  212. const graph = this.reid();
  213. const firstNode = graph.firstNode();
  214. const lastNode = graph.lastNode();
  215. return drawMermaid(graph.nodes, graph.edges, {
  216. firstNode: firstNode?.id,
  217. lastNode: lastNode?.id,
  218. withStyles,
  219. curveStyle,
  220. nodeColors,
  221. wrapLabelNWords,
  222. });
  223. }
  224. async drawMermaidPng(params) {
  225. const mermaidSyntax = this.drawMermaid(params);
  226. return drawMermaidPng(mermaidSyntax, {
  227. backgroundColor: params?.backgroundColor,
  228. });
  229. }
  230. }
  231. /**
  232. * Find the single node that is not a target of any edge.
  233. * Exclude nodes/sources with ids in the exclude list.
  234. * If there is no such node, or there are multiple, return undefined.
  235. * When drawing the graph, this node would be the origin.
  236. */
  237. function _firstNode(graph, exclude = []) {
  238. const targets = new Set(graph.edges
  239. .filter((edge) => !exclude.includes(edge.source))
  240. .map((edge) => edge.target));
  241. const found = [];
  242. for (const node of Object.values(graph.nodes)) {
  243. if (!exclude.includes(node.id) && !targets.has(node.id)) {
  244. found.push(node);
  245. }
  246. }
  247. return found.length === 1 ? found[0] : undefined;
  248. }
  249. /**
  250. * Find the single node that is not a source of any edge.
  251. * Exclude nodes/targets with ids in the exclude list.
  252. * If there is no such node, or there are multiple, return undefined.
  253. * When drawing the graph, this node would be the destination.
  254. */
  255. function _lastNode(graph, exclude = []) {
  256. const sources = new Set(graph.edges
  257. .filter((edge) => !exclude.includes(edge.target))
  258. .map((edge) => edge.source));
  259. const found = [];
  260. for (const node of Object.values(graph.nodes)) {
  261. if (!exclude.includes(node.id) && !sources.has(node.id)) {
  262. found.push(node);
  263. }
  264. }
  265. return found.length === 1 ? found[0] : undefined;
  266. }