graph.cjs 9.0 KB

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