@alpic80/rivet-core 1.19.1-aidon.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (381) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +176 -0
  3. package/dist/cjs/bundle.cjs +18915 -0
  4. package/dist/cjs/bundle.cjs.map +7 -0
  5. package/dist/esm/api/createProcessor.js +131 -0
  6. package/dist/esm/api/streaming.js +116 -0
  7. package/dist/esm/exports.js +32 -0
  8. package/dist/esm/index.js +2 -0
  9. package/dist/esm/integrations/AudioProvider.js +1 -0
  10. package/dist/esm/integrations/DatasetProvider.js +92 -0
  11. package/dist/esm/integrations/EmbeddingGenerator.js +1 -0
  12. package/dist/esm/integrations/GptTokenizerTokenizer.js +65 -0
  13. package/dist/esm/integrations/LLMProvider.js +1 -0
  14. package/dist/esm/integrations/Tokenizer.js +1 -0
  15. package/dist/esm/integrations/VectorDatabase.js +1 -0
  16. package/dist/esm/integrations/enableIntegrations.js +3 -0
  17. package/dist/esm/integrations/integrations.js +19 -0
  18. package/dist/esm/integrations/openai/OpenAIEmbeddingGenerator.js +23 -0
  19. package/dist/esm/model/DataValue.js +176 -0
  20. package/dist/esm/model/Dataset.js +1 -0
  21. package/dist/esm/model/EditorDefinition.js +1 -0
  22. package/dist/esm/model/GraphProcessor.js +1198 -0
  23. package/dist/esm/model/NodeBase.js +1 -0
  24. package/dist/esm/model/NodeBodySpec.js +1 -0
  25. package/dist/esm/model/NodeDefinition.js +12 -0
  26. package/dist/esm/model/NodeGraph.js +14 -0
  27. package/dist/esm/model/NodeImpl.js +49 -0
  28. package/dist/esm/model/NodeRegistration.js +144 -0
  29. package/dist/esm/model/Nodes.js +227 -0
  30. package/dist/esm/model/PluginLoadSpec.js +1 -0
  31. package/dist/esm/model/ProcessContext.js +1 -0
  32. package/dist/esm/model/Project.js +2 -0
  33. package/dist/esm/model/RivetPlugin.js +1 -0
  34. package/dist/esm/model/RivetUIContext.js +1 -0
  35. package/dist/esm/model/Settings.js +1 -0
  36. package/dist/esm/model/nodes/AbortGraphNode.js +100 -0
  37. package/dist/esm/model/nodes/AppendToDatasetNode.js +115 -0
  38. package/dist/esm/model/nodes/ArrayNode.js +144 -0
  39. package/dist/esm/model/nodes/AssembleMessageNode.js +199 -0
  40. package/dist/esm/model/nodes/AssemblePromptNode.js +129 -0
  41. package/dist/esm/model/nodes/AudioNode.js +101 -0
  42. package/dist/esm/model/nodes/BooleanNode.js +74 -0
  43. package/dist/esm/model/nodes/CallGraphNode.js +136 -0
  44. package/dist/esm/model/nodes/ChatNode.js +964 -0
  45. package/dist/esm/model/nodes/ChunkNode.js +166 -0
  46. package/dist/esm/model/nodes/CoalesceNode.js +104 -0
  47. package/dist/esm/model/nodes/CodeNode.js +136 -0
  48. package/dist/esm/model/nodes/CommentNode.js +69 -0
  49. package/dist/esm/model/nodes/CompareNode.js +138 -0
  50. package/dist/esm/model/nodes/ContextNode.js +99 -0
  51. package/dist/esm/model/nodes/CreateDatasetNode.js +71 -0
  52. package/dist/esm/model/nodes/DatasetNearestNeigborsNode.js +97 -0
  53. package/dist/esm/model/nodes/DelayNode.js +105 -0
  54. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +136 -0
  55. package/dist/esm/model/nodes/DestructureNode.js +86 -0
  56. package/dist/esm/model/nodes/EvaluateNode.js +141 -0
  57. package/dist/esm/model/nodes/ExternalCallNode.js +162 -0
  58. package/dist/esm/model/nodes/ExtractJsonNode.js +122 -0
  59. package/dist/esm/model/nodes/ExtractMarkdownCodeBlocksNode.js +100 -0
  60. package/dist/esm/model/nodes/ExtractObjectPathNode.js +128 -0
  61. package/dist/esm/model/nodes/ExtractRegexNode.js +201 -0
  62. package/dist/esm/model/nodes/ExtractYamlNode.js +214 -0
  63. package/dist/esm/model/nodes/FilterNode.js +73 -0
  64. package/dist/esm/model/nodes/GetAllDatasetsNode.js +53 -0
  65. package/dist/esm/model/nodes/GetDatasetRowNode.js +99 -0
  66. package/dist/esm/model/nodes/GetEmbeddingNode.js +130 -0
  67. package/dist/esm/model/nodes/GetGlobalNode.js +139 -0
  68. package/dist/esm/model/nodes/GptFunctionNode.js +169 -0
  69. package/dist/esm/model/nodes/GraphInputNode.js +130 -0
  70. package/dist/esm/model/nodes/GraphOutputNode.js +104 -0
  71. package/dist/esm/model/nodes/GraphReferenceNode.js +128 -0
  72. package/dist/esm/model/nodes/HashNode.js +97 -0
  73. package/dist/esm/model/nodes/HttpCallNode.js +257 -0
  74. package/dist/esm/model/nodes/IfElseNode.js +138 -0
  75. package/dist/esm/model/nodes/IfNode.js +124 -0
  76. package/dist/esm/model/nodes/ImageNode.js +107 -0
  77. package/dist/esm/model/nodes/JoinNode.js +135 -0
  78. package/dist/esm/model/nodes/ListGraphsNode.js +61 -0
  79. package/dist/esm/model/nodes/LoadDatasetNode.js +83 -0
  80. package/dist/esm/model/nodes/LoopControllerNode.js +206 -0
  81. package/dist/esm/model/nodes/MatchNode.js +137 -0
  82. package/dist/esm/model/nodes/NumberNode.js +86 -0
  83. package/dist/esm/model/nodes/ObjectNode.js +121 -0
  84. package/dist/esm/model/nodes/PassthroughNode.js +78 -0
  85. package/dist/esm/model/nodes/PlayAudioNode.js +61 -0
  86. package/dist/esm/model/nodes/PopNode.js +89 -0
  87. package/dist/esm/model/nodes/PromptNode.js +227 -0
  88. package/dist/esm/model/nodes/RaceInputsNode.js +86 -0
  89. package/dist/esm/model/nodes/RaiseEventNode.js +84 -0
  90. package/dist/esm/model/nodes/RandomNumberNode.js +106 -0
  91. package/dist/esm/model/nodes/ReadDirectoryNode.js +165 -0
  92. package/dist/esm/model/nodes/ReadFileNode.js +114 -0
  93. package/dist/esm/model/nodes/ReplaceDatasetNode.js +118 -0
  94. package/dist/esm/model/nodes/SetGlobalNode.js +124 -0
  95. package/dist/esm/model/nodes/ShuffleNode.js +64 -0
  96. package/dist/esm/model/nodes/SliceNode.js +100 -0
  97. package/dist/esm/model/nodes/SplitNode.js +101 -0
  98. package/dist/esm/model/nodes/SubGraphNode.js +181 -0
  99. package/dist/esm/model/nodes/TextNode.js +97 -0
  100. package/dist/esm/model/nodes/ToJsonNode.js +78 -0
  101. package/dist/esm/model/nodes/ToYamlNode.js +68 -0
  102. package/dist/esm/model/nodes/TrimChatMessagesNode.js +120 -0
  103. package/dist/esm/model/nodes/URLReferenceNode.js +79 -0
  104. package/dist/esm/model/nodes/UserInputNode.js +111 -0
  105. package/dist/esm/model/nodes/VectorNearestNeighborsNode.js +127 -0
  106. package/dist/esm/model/nodes/VectorStoreNode.js +124 -0
  107. package/dist/esm/model/nodes/WaitForEventNode.js +88 -0
  108. package/dist/esm/native/BaseDir.js +32 -0
  109. package/dist/esm/native/BrowserNativeApi.js +19 -0
  110. package/dist/esm/native/NativeApi.js +1 -0
  111. package/dist/esm/plugins/aidon/index.js +2 -0
  112. package/dist/esm/plugins/aidon/nodes/ChatAidonNode.js +215 -0
  113. package/dist/esm/plugins/aidon/plugin.js +9 -0
  114. package/dist/esm/plugins/anthropic/anthropic.js +187 -0
  115. package/dist/esm/plugins/anthropic/fetchEventSource.js +106 -0
  116. package/dist/esm/plugins/anthropic/index.js +2 -0
  117. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +652 -0
  118. package/dist/esm/plugins/anthropic/plugin.js +18 -0
  119. package/dist/esm/plugins/assemblyAi/LemurActionItemsNode.js +75 -0
  120. package/dist/esm/plugins/assemblyAi/LemurQaNode.js +155 -0
  121. package/dist/esm/plugins/assemblyAi/LemurSummaryNode.js +79 -0
  122. package/dist/esm/plugins/assemblyAi/LemurTaskNode.js +82 -0
  123. package/dist/esm/plugins/assemblyAi/TranscribeAudioNode.js +125 -0
  124. package/dist/esm/plugins/assemblyAi/index.js +2 -0
  125. package/dist/esm/plugins/assemblyAi/lemurHelpers.js +114 -0
  126. package/dist/esm/plugins/assemblyAi/plugin.js +32 -0
  127. package/dist/esm/plugins/autoevals/AutoEvalsNode.js +223 -0
  128. package/dist/esm/plugins/autoevals/index.js +2 -0
  129. package/dist/esm/plugins/autoevals/plugin.js +8 -0
  130. package/dist/esm/plugins/gentrace/index.js +2 -0
  131. package/dist/esm/plugins/gentrace/plugin.js +192 -0
  132. package/dist/esm/plugins/google/google.js +60 -0
  133. package/dist/esm/plugins/google/index.js +2 -0
  134. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +364 -0
  135. package/dist/esm/plugins/google/plugin.js +32 -0
  136. package/dist/esm/plugins/huggingface/index.js +2 -0
  137. package/dist/esm/plugins/huggingface/nodes/ChatHuggingFace.js +243 -0
  138. package/dist/esm/plugins/huggingface/nodes/TextToImageHuggingFace.js +189 -0
  139. package/dist/esm/plugins/huggingface/plugin.js +26 -0
  140. package/dist/esm/plugins/openai/handleOpenaiError.js +17 -0
  141. package/dist/esm/plugins/openai/index.js +2 -0
  142. package/dist/esm/plugins/openai/nodes/AttachAssistantFileNode.js +123 -0
  143. package/dist/esm/plugins/openai/nodes/CreateAssistantNode.js +289 -0
  144. package/dist/esm/plugins/openai/nodes/CreateThreadMessageNode.js +176 -0
  145. package/dist/esm/plugins/openai/nodes/CreateThreadNode.js +157 -0
  146. package/dist/esm/plugins/openai/nodes/DeleteAssistantNode.js +104 -0
  147. package/dist/esm/plugins/openai/nodes/DeleteThreadNode.js +97 -0
  148. package/dist/esm/plugins/openai/nodes/GetAssistantNode.js +118 -0
  149. package/dist/esm/plugins/openai/nodes/GetOpenAIFileNode.js +100 -0
  150. package/dist/esm/plugins/openai/nodes/GetThreadNode.js +108 -0
  151. package/dist/esm/plugins/openai/nodes/ListAssistantsNode.js +202 -0
  152. package/dist/esm/plugins/openai/nodes/ListOpenAIFilesNode.js +94 -0
  153. package/dist/esm/plugins/openai/nodes/ListThreadMessagesNode.js +224 -0
  154. package/dist/esm/plugins/openai/nodes/RunThreadNode.js +630 -0
  155. package/dist/esm/plugins/openai/nodes/ThreadMessageNode.js +145 -0
  156. package/dist/esm/plugins/openai/nodes/UploadFileNode.js +121 -0
  157. package/dist/esm/plugins/openai/plugin.js +44 -0
  158. package/dist/esm/plugins/pinecone/PineconeVectorDatabase.js +88 -0
  159. package/dist/esm/plugins/pinecone/index.js +2 -0
  160. package/dist/esm/plugins/pinecone/plugin.js +19 -0
  161. package/dist/esm/plugins.js +21 -0
  162. package/dist/esm/recording/ExecutionRecorder.js +177 -0
  163. package/dist/esm/recording/RecordedEvents.js +1 -0
  164. package/dist/esm/utils/assertNever.js +3 -0
  165. package/dist/esm/utils/base64.js +25 -0
  166. package/dist/esm/utils/chatMessageToOpenAIChatCompletionMessage.js +60 -0
  167. package/dist/esm/utils/coerceType.js +322 -0
  168. package/dist/esm/utils/compatibility.js +27 -0
  169. package/dist/esm/utils/copyToClipboard.js +10 -0
  170. package/dist/esm/utils/defaults.js +2 -0
  171. package/dist/esm/utils/errors.js +7 -0
  172. package/dist/esm/utils/expectType.js +34 -0
  173. package/dist/esm/utils/fetchEventSource.js +120 -0
  174. package/dist/esm/utils/genericUtilFunctions.js +25 -0
  175. package/dist/esm/utils/getPluginConfig.js +23 -0
  176. package/dist/esm/utils/handleEscapeCharacters.js +11 -0
  177. package/dist/esm/utils/index.js +14 -0
  178. package/dist/esm/utils/inputs.js +16 -0
  179. package/dist/esm/utils/interpolation.js +6 -0
  180. package/dist/esm/utils/misc.js +1 -0
  181. package/dist/esm/utils/newId.js +4 -0
  182. package/dist/esm/utils/openai.js +219 -0
  183. package/dist/esm/utils/outputs.js +14 -0
  184. package/dist/esm/utils/serialization/serialization.js +86 -0
  185. package/dist/esm/utils/serialization/serializationUtils.js +13 -0
  186. package/dist/esm/utils/serialization/serialization_v1.js +19 -0
  187. package/dist/esm/utils/serialization/serialization_v2.js +24 -0
  188. package/dist/esm/utils/serialization/serialization_v3.js +145 -0
  189. package/dist/esm/utils/serialization/serialization_v4.js +200 -0
  190. package/dist/esm/utils/symbols.js +2 -0
  191. package/dist/esm/utils/time.js +14 -0
  192. package/dist/esm/utils/typeSafety.js +42 -0
  193. package/dist/types/api/createProcessor.d.ts +37 -0
  194. package/dist/types/api/streaming.d.ts +56 -0
  195. package/dist/types/exports.d.ts +33 -0
  196. package/dist/types/index.d.ts +4 -0
  197. package/dist/types/integrations/AudioProvider.d.ts +4 -0
  198. package/dist/types/integrations/DatasetProvider.d.ts +33 -0
  199. package/dist/types/integrations/EmbeddingGenerator.d.ts +3 -0
  200. package/dist/types/integrations/GptTokenizerTokenizer.d.ts +20 -0
  201. package/dist/types/integrations/LLMProvider.d.ts +7 -0
  202. package/dist/types/integrations/Tokenizer.d.ts +11 -0
  203. package/dist/types/integrations/VectorDatabase.d.ts +7 -0
  204. package/dist/types/integrations/enableIntegrations.d.ts +1 -0
  205. package/dist/types/integrations/integrations.d.ts +12 -0
  206. package/dist/types/integrations/openai/OpenAIEmbeddingGenerator.d.ts +10 -0
  207. package/dist/types/model/DataValue.d.ts +138 -0
  208. package/dist/types/model/Dataset.d.ts +19 -0
  209. package/dist/types/model/EditorDefinition.d.ts +142 -0
  210. package/dist/types/model/GraphProcessor.d.ts +192 -0
  211. package/dist/types/model/NodeBase.d.ts +110 -0
  212. package/dist/types/model/NodeBodySpec.d.ts +19 -0
  213. package/dist/types/model/NodeDefinition.d.ts +13 -0
  214. package/dist/types/model/NodeGraph.d.ts +15 -0
  215. package/dist/types/model/NodeImpl.d.ts +55 -0
  216. package/dist/types/model/NodeRegistration.d.ts +24 -0
  217. package/dist/types/model/Nodes.d.ts +84 -0
  218. package/dist/types/model/PluginLoadSpec.d.ts +17 -0
  219. package/dist/types/model/ProcessContext.d.ts +69 -0
  220. package/dist/types/model/Project.d.ts +17 -0
  221. package/dist/types/model/RivetPlugin.d.ts +45 -0
  222. package/dist/types/model/RivetUIContext.d.ts +18 -0
  223. package/dist/types/model/Settings.d.ts +15 -0
  224. package/dist/types/model/nodes/AbortGraphNode.d.ts +22 -0
  225. package/dist/types/model/nodes/AppendToDatasetNode.d.ts +21 -0
  226. package/dist/types/model/nodes/ArrayNode.d.ts +20 -0
  227. package/dist/types/model/nodes/AssembleMessageNode.d.ts +23 -0
  228. package/dist/types/model/nodes/AssemblePromptNode.d.ts +20 -0
  229. package/dist/types/model/nodes/AudioNode.d.ts +20 -0
  230. package/dist/types/model/nodes/BooleanNode.d.ts +19 -0
  231. package/dist/types/model/nodes/CallGraphNode.d.ts +16 -0
  232. package/dist/types/model/nodes/ChatNode.d.ts +77 -0
  233. package/dist/types/model/nodes/ChunkNode.d.ts +22 -0
  234. package/dist/types/model/nodes/CoalesceNode.d.ts +14 -0
  235. package/dist/types/model/nodes/CodeNode.d.ts +21 -0
  236. package/dist/types/model/nodes/CommentNode.d.ts +20 -0
  237. package/dist/types/model/nodes/CompareNode.d.ts +19 -0
  238. package/dist/types/model/nodes/ContextNode.d.ts +24 -0
  239. package/dist/types/model/nodes/CreateDatasetNode.d.ts +13 -0
  240. package/dist/types/model/nodes/DatasetNearestNeigborsNode.d.ts +19 -0
  241. package/dist/types/model/nodes/DelayNode.d.ts +20 -0
  242. package/dist/types/model/nodes/DelegateFunctionCallNode.d.ts +25 -0
  243. package/dist/types/model/nodes/DestructureNode.d.ts +18 -0
  244. package/dist/types/model/nodes/EvaluateNode.d.ts +19 -0
  245. package/dist/types/model/nodes/ExternalCallNode.d.ts +22 -0
  246. package/dist/types/model/nodes/ExtractJsonNode.d.ts +13 -0
  247. package/dist/types/model/nodes/ExtractMarkdownCodeBlocksNode.d.ts +12 -0
  248. package/dist/types/model/nodes/ExtractObjectPathNode.d.ts +19 -0
  249. package/dist/types/model/nodes/ExtractRegexNode.d.ts +22 -0
  250. package/dist/types/model/nodes/ExtractYamlNode.d.ts +21 -0
  251. package/dist/types/model/nodes/FilterNode.d.ts +13 -0
  252. package/dist/types/model/nodes/GetAllDatasetsNode.d.ts +14 -0
  253. package/dist/types/model/nodes/GetDatasetRowNode.d.ts +19 -0
  254. package/dist/types/model/nodes/GetEmbeddingNode.d.ts +24 -0
  255. package/dist/types/model/nodes/GetGlobalNode.d.ts +29 -0
  256. package/dist/types/model/nodes/GptFunctionNode.d.ts +25 -0
  257. package/dist/types/model/nodes/GraphInputNode.d.ts +24 -0
  258. package/dist/types/model/nodes/GraphOutputNode.d.ts +22 -0
  259. package/dist/types/model/nodes/GraphReferenceNode.d.ts +22 -0
  260. package/dist/types/model/nodes/HashNode.d.ts +17 -0
  261. package/dist/types/model/nodes/HttpCallNode.d.ts +27 -0
  262. package/dist/types/model/nodes/IfElseNode.d.ts +18 -0
  263. package/dist/types/model/nodes/IfNode.d.ts +17 -0
  264. package/dist/types/model/nodes/ImageNode.d.ts +20 -0
  265. package/dist/types/model/nodes/JoinNode.d.ts +21 -0
  266. package/dist/types/model/nodes/ListGraphsNode.d.ts +14 -0
  267. package/dist/types/model/nodes/LoadDatasetNode.d.ts +17 -0
  268. package/dist/types/model/nodes/LoopControllerNode.d.ts +20 -0
  269. package/dist/types/model/nodes/MatchNode.d.ts +19 -0
  270. package/dist/types/model/nodes/NumberNode.d.ts +21 -0
  271. package/dist/types/model/nodes/ObjectNode.d.ts +18 -0
  272. package/dist/types/model/nodes/PassthroughNode.d.ts +14 -0
  273. package/dist/types/model/nodes/PlayAudioNode.d.ts +15 -0
  274. package/dist/types/model/nodes/PopNode.d.ts +19 -0
  275. package/dist/types/model/nodes/PromptNode.d.ts +23 -0
  276. package/dist/types/model/nodes/RaceInputsNode.d.ts +17 -0
  277. package/dist/types/model/nodes/RaiseEventNode.d.ts +22 -0
  278. package/dist/types/model/nodes/RandomNumberNode.d.ts +23 -0
  279. package/dist/types/model/nodes/ReadDirectoryNode.d.ts +30 -0
  280. package/dist/types/model/nodes/ReadFileNode.d.ts +23 -0
  281. package/dist/types/model/nodes/ReplaceDatasetNode.d.ts +21 -0
  282. package/dist/types/model/nodes/SetGlobalNode.d.ts +23 -0
  283. package/dist/types/model/nodes/ShuffleNode.d.ts +12 -0
  284. package/dist/types/model/nodes/SliceNode.d.ts +22 -0
  285. package/dist/types/model/nodes/SplitNode.d.ts +19 -0
  286. package/dist/types/model/nodes/SubGraphNode.d.ts +29 -0
  287. package/dist/types/model/nodes/TextNode.d.ts +18 -0
  288. package/dist/types/model/nodes/ToJsonNode.d.ts +18 -0
  289. package/dist/types/model/nodes/ToYamlNode.d.ts +13 -0
  290. package/dist/types/model/nodes/TrimChatMessagesNode.d.ts +20 -0
  291. package/dist/types/model/nodes/URLReferenceNode.d.ts +19 -0
  292. package/dist/types/model/nodes/UserInputNode.d.ts +21 -0
  293. package/dist/types/model/nodes/VectorNearestNeighborsNode.d.ts +24 -0
  294. package/dist/types/model/nodes/VectorStoreNode.d.ts +22 -0
  295. package/dist/types/model/nodes/WaitForEventNode.d.ts +21 -0
  296. package/dist/types/native/BaseDir.d.ts +29 -0
  297. package/dist/types/native/BrowserNativeApi.d.ts +11 -0
  298. package/dist/types/native/NativeApi.d.ts +17 -0
  299. package/dist/types/plugins/aidon/index.d.ts +2 -0
  300. package/dist/types/plugins/aidon/nodes/ChatAidonNode.d.ts +3 -0
  301. package/dist/types/plugins/aidon/plugin.d.ts +2 -0
  302. package/dist/types/plugins/anthropic/anthropic.d.ts +216 -0
  303. package/dist/types/plugins/anthropic/fetchEventSource.d.ts +11 -0
  304. package/dist/types/plugins/anthropic/index.d.ts +2 -0
  305. package/dist/types/plugins/anthropic/nodes/ChatAnthropicNode.d.ts +30 -0
  306. package/dist/types/plugins/anthropic/plugin.d.ts +2 -0
  307. package/dist/types/plugins/assemblyAi/LemurActionItemsNode.d.ts +6 -0
  308. package/dist/types/plugins/assemblyAi/LemurQaNode.d.ts +22 -0
  309. package/dist/types/plugins/assemblyAi/LemurSummaryNode.d.ts +8 -0
  310. package/dist/types/plugins/assemblyAi/LemurTaskNode.d.ts +8 -0
  311. package/dist/types/plugins/assemblyAi/TranscribeAudioNode.d.ts +7 -0
  312. package/dist/types/plugins/assemblyAi/index.d.ts +2 -0
  313. package/dist/types/plugins/assemblyAi/lemurHelpers.d.ts +67 -0
  314. package/dist/types/plugins/assemblyAi/plugin.d.ts +2 -0
  315. package/dist/types/plugins/autoevals/AutoEvalsNode.d.ts +8 -0
  316. package/dist/types/plugins/autoevals/index.d.ts +2 -0
  317. package/dist/types/plugins/autoevals/plugin.d.ts +2 -0
  318. package/dist/types/plugins/gentrace/index.d.ts +2 -0
  319. package/dist/types/plugins/gentrace/plugin.d.ts +5 -0
  320. package/dist/types/plugins/google/google.d.ts +60 -0
  321. package/dist/types/plugins/google/index.d.ts +2 -0
  322. package/dist/types/plugins/google/nodes/ChatGoogleNode.d.ts +27 -0
  323. package/dist/types/plugins/google/plugin.d.ts +2 -0
  324. package/dist/types/plugins/huggingface/index.d.ts +2 -0
  325. package/dist/types/plugins/huggingface/nodes/ChatHuggingFace.d.ts +24 -0
  326. package/dist/types/plugins/huggingface/nodes/TextToImageHuggingFace.d.ts +20 -0
  327. package/dist/types/plugins/huggingface/plugin.d.ts +2 -0
  328. package/dist/types/plugins/openai/handleOpenaiError.d.ts +1 -0
  329. package/dist/types/plugins/openai/index.d.ts +2 -0
  330. package/dist/types/plugins/openai/nodes/AttachAssistantFileNode.d.ts +10 -0
  331. package/dist/types/plugins/openai/nodes/CreateAssistantNode.d.ts +26 -0
  332. package/dist/types/plugins/openai/nodes/CreateThreadMessageNode.d.ts +15 -0
  333. package/dist/types/plugins/openai/nodes/CreateThreadNode.d.ts +13 -0
  334. package/dist/types/plugins/openai/nodes/DeleteAssistantNode.d.ts +8 -0
  335. package/dist/types/plugins/openai/nodes/DeleteThreadNode.d.ts +8 -0
  336. package/dist/types/plugins/openai/nodes/GetAssistantNode.d.ts +8 -0
  337. package/dist/types/plugins/openai/nodes/GetOpenAIFileNode.d.ts +8 -0
  338. package/dist/types/plugins/openai/nodes/GetThreadNode.d.ts +8 -0
  339. package/dist/types/plugins/openai/nodes/ListAssistantsNode.d.ts +14 -0
  340. package/dist/types/plugins/openai/nodes/ListOpenAIFilesNode.d.ts +8 -0
  341. package/dist/types/plugins/openai/nodes/ListThreadMessagesNode.d.ts +16 -0
  342. package/dist/types/plugins/openai/nodes/RunThreadNode.d.ts +28 -0
  343. package/dist/types/plugins/openai/nodes/ThreadMessageNode.d.ts +14 -0
  344. package/dist/types/plugins/openai/nodes/UploadFileNode.d.ts +7 -0
  345. package/dist/types/plugins/openai/plugin.d.ts +2 -0
  346. package/dist/types/plugins/pinecone/PineconeVectorDatabase.d.ts +9 -0
  347. package/dist/types/plugins/pinecone/index.d.ts +2 -0
  348. package/dist/types/plugins/pinecone/plugin.d.ts +2 -0
  349. package/dist/types/plugins.d.ts +20 -0
  350. package/dist/types/recording/ExecutionRecorder.d.ts +25 -0
  351. package/dist/types/recording/RecordedEvents.d.ts +100 -0
  352. package/dist/types/utils/assertNever.d.ts +1 -0
  353. package/dist/types/utils/base64.d.ts +2 -0
  354. package/dist/types/utils/chatMessageToOpenAIChatCompletionMessage.d.ts +3 -0
  355. package/dist/types/utils/coerceType.d.ts +6 -0
  356. package/dist/types/utils/compatibility.d.ts +3 -0
  357. package/dist/types/utils/copyToClipboard.d.ts +1 -0
  358. package/dist/types/utils/defaults.d.ts +2 -0
  359. package/dist/types/utils/errors.d.ts +2 -0
  360. package/dist/types/utils/expectType.d.ts +3 -0
  361. package/dist/types/utils/fetchEventSource.d.ts +12 -0
  362. package/dist/types/utils/genericUtilFunctions.d.ts +21 -0
  363. package/dist/types/utils/getPluginConfig.d.ts +2 -0
  364. package/dist/types/utils/handleEscapeCharacters.d.ts +2 -0
  365. package/dist/types/utils/index.d.ts +14 -0
  366. package/dist/types/utils/inputs.d.ts +3 -0
  367. package/dist/types/utils/interpolation.d.ts +1 -0
  368. package/dist/types/utils/misc.d.ts +1 -0
  369. package/dist/types/utils/newId.d.ts +1 -0
  370. package/dist/types/utils/openai.d.ts +739 -0
  371. package/dist/types/utils/outputs.d.ts +3 -0
  372. package/dist/types/utils/serialization/serialization.d.ts +12 -0
  373. package/dist/types/utils/serialization/serializationUtils.d.ts +6 -0
  374. package/dist/types/utils/serialization/serialization_v1.d.ts +3 -0
  375. package/dist/types/utils/serialization/serialization_v2.d.ts +3 -0
  376. package/dist/types/utils/serialization/serialization_v3.d.ts +19 -0
  377. package/dist/types/utils/serialization/serialization_v4.d.ts +9 -0
  378. package/dist/types/utils/symbols.d.ts +3 -0
  379. package/dist/types/utils/time.d.ts +22 -0
  380. package/dist/types/utils/typeSafety.d.ts +37 -0
  381. package/package.json +97 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/index.ts", "../../src/utils/coerceType.ts", "../../src/utils/genericUtilFunctions.ts", "../../src/model/DataValue.ts", "../../src/utils/expectType.ts", "../../src/utils/errors.ts", "../../src/utils/serialization/serialization.ts", "../../src/utils/serialization/serialization_v3.ts", "../../src/utils/serialization/serializationUtils.ts", "../../src/utils/serialization/serialization_v4.ts", "../../src/utils/typeSafety.ts", "../../src/utils/serialization/serialization_v2.ts", "../../src/utils/serialization/serialization_v1.ts", "../../src/utils/symbols.ts", "../../src/utils/outputs.ts", "../../src/utils/base64.ts", "../../src/utils/inputs.ts", "../../src/utils/misc.ts", "../../src/utils/getPluginConfig.ts", "../../src/utils/newId.ts", "../../src/utils/handleEscapeCharacters.ts", "../../src/utils/compatibility.ts", "../../src/utils/defaults.ts", "../../src/model/GraphProcessor.ts", "../../src/model/NodeImpl.ts", "../../src/model/NodeRegistration.ts", "../../src/model/nodes/UserInputNode.ts", "../../src/model/NodeDefinition.ts", "../../src/model/nodes/TextNode.ts", "../../src/utils/interpolation.ts", "../../src/model/nodes/ChatNode.ts", "../../src/utils/openai.ts", "../../src/utils/fetchEventSource.ts", "../../src/utils/chatMessageToOpenAIChatCompletionMessage.ts", "../../src/model/nodes/PromptNode.ts", "../../src/model/nodes/ExtractRegexNode.ts", "../../src/model/nodes/CodeNode.ts", "../../src/model/nodes/MatchNode.ts", "../../src/model/nodes/IfNode.ts", "../../src/model/nodes/ReadDirectoryNode.ts", "../../src/model/nodes/ReadFileNode.ts", "../../src/model/nodes/IfElseNode.ts", "../../src/model/nodes/ChunkNode.ts", "../../src/model/nodes/GraphInputNode.ts", "../../src/model/nodes/GraphOutputNode.ts", "../../src/model/NodeGraph.ts", "../../src/model/nodes/SubGraphNode.ts", "../../src/model/nodes/ArrayNode.ts", "../../src/model/nodes/ExtractJsonNode.ts", "../../src/model/nodes/AssemblePromptNode.ts", "../../src/model/nodes/ExtractYamlNode.ts", "../../src/model/nodes/LoopControllerNode.ts", "../../src/model/nodes/TrimChatMessagesNode.ts", "../../src/model/nodes/ExternalCallNode.ts", "../../src/model/nodes/ExtractObjectPathNode.ts", "../../src/model/nodes/RaiseEventNode.ts", "../../src/model/nodes/ContextNode.ts", "../../src/model/nodes/CoalesceNode.ts", "../../src/model/nodes/PassthroughNode.ts", "../../src/model/nodes/PopNode.ts", "../../src/model/nodes/SetGlobalNode.ts", "../../src/model/nodes/GetGlobalNode.ts", "../../src/model/nodes/WaitForEventNode.ts", "../../src/model/nodes/GptFunctionNode.ts", "../../src/model/nodes/ToYamlNode.ts", "../../src/model/nodes/GetEmbeddingNode.ts", "../../src/integrations/integrations.ts", "../../src/model/nodes/VectorStoreNode.ts", "../../src/model/nodes/VectorNearestNeighborsNode.ts", "../../src/model/nodes/HashNode.ts", "../../src/model/nodes/AbortGraphNode.ts", "../../src/model/nodes/RaceInputsNode.ts", "../../src/model/nodes/ToJsonNode.ts", "../../src/model/nodes/JoinNode.ts", "../../src/model/nodes/FilterNode.ts", "../../src/model/nodes/ObjectNode.ts", "../../src/model/nodes/BooleanNode.ts", "../../src/model/nodes/CompareNode.ts", "../../src/model/nodes/EvaluateNode.ts", "../../src/model/nodes/NumberNode.ts", "../../src/model/nodes/RandomNumberNode.ts", "../../src/model/nodes/ShuffleNode.ts", "../../src/model/nodes/CommentNode.ts", "../../src/model/nodes/ImageNode.ts", "../../src/model/nodes/AudioNode.ts", "../../src/model/nodes/HttpCallNode.ts", "../../src/model/nodes/DelayNode.ts", "../../src/model/nodes/AppendToDatasetNode.ts", "../../src/model/nodes/CreateDatasetNode.ts", "../../src/model/nodes/LoadDatasetNode.ts", "../../src/model/nodes/GetAllDatasetsNode.ts", "../../src/model/nodes/SplitNode.ts", "../../src/model/nodes/DatasetNearestNeigborsNode.ts", "../../src/model/nodes/GetDatasetRowNode.ts", "../../src/model/nodes/SliceNode.ts", "../../src/model/nodes/ExtractMarkdownCodeBlocksNode.ts", "../../src/model/nodes/AssembleMessageNode.ts", "../../src/model/nodes/URLReferenceNode.ts", "../../src/model/nodes/DestructureNode.ts", "../../src/model/nodes/ReplaceDatasetNode.ts", "../../src/model/nodes/ListGraphsNode.ts", "../../src/model/nodes/GraphReferenceNode.ts", "../../src/model/nodes/CallGraphNode.ts", "../../src/model/nodes/DelegateFunctionCallNode.ts", "../../src/model/nodes/PlayAudioNode.ts", "../../src/model/Nodes.ts", "../../src/integrations/GptTokenizerTokenizer.ts", "../../src/native/BaseDir.ts", "../../src/native/BrowserNativeApi.ts", "../../src/integrations/openai/OpenAIEmbeddingGenerator.ts", "../../src/integrations/enableIntegrations.ts", "../../src/recording/ExecutionRecorder.ts", "../../src/plugins/aidon/nodes/ChatAidonNode.ts", "../../src/plugins/aidon/plugin.ts", "../../src/plugins/aidon/index.ts", "../../src/plugins/anthropic/fetchEventSource.ts", "../../src/plugins/anthropic/anthropic.ts", "../../src/plugins/anthropic/nodes/ChatAnthropicNode.ts", "../../src/utils/assertNever.ts", "../../src/plugins/anthropic/plugin.ts", "../../src/plugins/anthropic/index.ts", "../../src/plugins/autoevals/AutoEvalsNode.ts", "../../src/plugins/autoevals/plugin.ts", "../../src/plugins/autoevals/index.ts", "../../src/plugins/assemblyAi/LemurQaNode.ts", "../../src/plugins/assemblyAi/lemurHelpers.ts", "../../src/plugins/assemblyAi/TranscribeAudioNode.ts", "../../src/plugins/assemblyAi/LemurSummaryNode.ts", "../../src/plugins/assemblyAi/LemurTaskNode.ts", "../../src/plugins/assemblyAi/LemurActionItemsNode.ts", "../../src/plugins/assemblyAi/plugin.ts", "../../src/plugins/assemblyAi/index.ts", "../../src/plugins/huggingface/nodes/ChatHuggingFace.ts", "../../src/plugins/huggingface/nodes/TextToImageHuggingFace.ts", "../../src/plugins/huggingface/plugin.ts", "../../src/plugins/pinecone/PineconeVectorDatabase.ts", "../../src/plugins/pinecone/plugin.ts", "../../src/plugins/pinecone/index.ts", "../../src/plugins/gentrace/plugin.ts", "../../src/plugins/gentrace/index.ts", "../../src/plugins/openai/nodes/CreateThreadNode.ts", "../../src/plugins/openai/nodes/GetThreadNode.ts", "../../src/plugins/openai/nodes/DeleteThreadNode.ts", "../../src/plugins/openai/handleOpenaiError.ts", "../../src/plugins/openai/nodes/CreateAssistantNode.ts", "../../src/plugins/openai/nodes/GetAssistantNode.ts", "../../src/plugins/openai/nodes/ListAssistantsNode.ts", "../../src/plugins/openai/nodes/DeleteAssistantNode.ts", "../../src/plugins/openai/nodes/UploadFileNode.ts", "../../src/plugins/openai/nodes/ListOpenAIFilesNode.ts", "../../src/plugins/openai/nodes/GetOpenAIFileNode.ts", "../../src/plugins/openai/nodes/AttachAssistantFileNode.ts", "../../src/plugins/openai/nodes/CreateThreadMessageNode.ts", "../../src/plugins/openai/nodes/ListThreadMessagesNode.ts", "../../src/plugins/openai/nodes/RunThreadNode.ts", "../../src/plugins/openai/nodes/ThreadMessageNode.ts", "../../src/plugins/openai/plugin.ts", "../../src/plugins/google/google.ts", "../../src/plugins/google/nodes/ChatGoogleNode.ts", "../../src/plugins/google/plugin.ts", "../../src/plugins.ts", "../../src/integrations/DatasetProvider.ts", "../../src/api/streaming.ts", "../../src/api/createProcessor.ts"],
4
+ "sourcesContent": ["import type * as RivetTypes from './exports.js';\nexport * from './exports.js';\n\nexport const Rivet: typeof RivetTypes = undefined!;\n\nexport type RivetPluginInitializer = (rivet: typeof Rivet) => RivetTypes.RivetPlugin;\n", "import { match } from 'ts-pattern';\nimport {\n type ChatMessage,\n type DataType,\n type DataValue,\n type GetDataValue,\n getScalarTypeOf,\n isArrayDataType,\n isArrayDataValue,\n unwrapDataValue,\n} from '../model/DataValue.js';\nimport { expectTypeOptional } from './expectType.js';\nimport type { GraphId } from '../index.js';\n\nexport function coerceTypeOptional<T extends DataType>(\n wrapped: DataValue | undefined,\n type: T,\n): GetDataValue<T>['value'] | undefined {\n const value = wrapped ? unwrapDataValue(wrapped) : undefined;\n\n // Coerce 'true' to [true] for example\n if (isArrayDataType(type) && !isArrayDataValue(value)) {\n const coerced = coerceTypeOptional(value, getScalarTypeOf(type));\n if (coerced === undefined) {\n return undefined;\n }\n\n return [coerced] as any;\n }\n\n // Coerce foo[] to bar[]\n if (isArrayDataType(type) && isArrayDataValue(value) && getScalarTypeOf(type) !== getScalarTypeOf(value.type)) {\n return value.value.map((v) =>\n coerceTypeOptional({ type: getScalarTypeOf(value.type), value: v } as DataValue, getScalarTypeOf(type)),\n ) as any;\n }\n\n const result = match(type as DataType)\n .with('string', () => coerceToString(value))\n .with('boolean', () => coerceToBoolean(value))\n .with('chat-message', () => coerceToChatMessage(value))\n .with('number', () => coerceToNumber(value))\n .with('object', () => coerceToObject(value))\n .with('binary', () => coerceToBinary(value))\n .with('graph-reference', () => coerceToGraphReference(value))\n .otherwise(() => {\n if (!value) {\n return value;\n }\n\n if (getScalarTypeOf(value.type) === 'any' || getScalarTypeOf(type) === 'any') {\n return value.value;\n }\n\n return expectTypeOptional(value, type);\n });\n\n return result as GetDataValue<T>['value'] | undefined;\n}\n\nexport function coerceType<T extends DataType>(value: DataValue | undefined, type: T): GetDataValue<T>['value'] {\n const result = coerceTypeOptional(value, type);\n if (result === undefined) {\n throw new Error(`Expected value of type ${type} but got undefined`);\n }\n return result as GetDataValue<T>['value'];\n}\n\nexport function inferType(value: unknown): DataValue {\n if (value === undefined) {\n return { type: 'any', value: undefined };\n }\n\n if (value === null) {\n return { type: 'any', value: null };\n }\n\n if (typeof value === 'function') {\n return { type: 'fn<any>', value: value as () => unknown };\n }\n\n if (typeof value === 'string') {\n return { type: 'string', value };\n }\n\n if (typeof value === 'boolean') {\n return { type: 'boolean', value };\n }\n\n if (typeof value === 'number') {\n return { type: 'number', value };\n }\n\n if (value instanceof Date) {\n return { type: 'datetime', value: value.toISOString() };\n }\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return { type: 'any[]', value: [] };\n }\n\n const inferredType = inferType(value[0]);\n\n return { type: inferredType.type + '[]', value } as DataValue;\n }\n\n if (typeof value === 'object') {\n return { type: 'object', value: value as Record<string, unknown> };\n }\n\n throw new Error(`Cannot infer type of value: ${value}`);\n}\n\nfunction coerceToString(value: DataValue | undefined): string | undefined {\n if (!value) {\n return '';\n }\n\n if (isArrayDataValue(value)) {\n return value.value\n .map((v) => coerceTypeOptional({ type: getScalarTypeOf(value.type), value: v } as DataValue, 'string'))\n .join('\\n');\n }\n\n if (value.type === 'string') {\n return value.value;\n }\n\n if (value.type === 'boolean') {\n return value.value.toString();\n }\n\n if (value.type === 'number') {\n return value.value.toString();\n }\n\n if (value.type === 'date') {\n return value.value;\n }\n\n if (value.type === 'time') {\n return value.value;\n }\n\n if (value.type === 'datetime') {\n return value.value;\n }\n\n if (value.type === 'chat-message') {\n const messageParts = Array.isArray(value.value.message) ? value.value.message : [value.value.message];\n const singleString = messageParts\n .map((part) => {\n if (typeof part === 'string') {\n return part;\n }\n\n return part.type === 'url' ? `(Image: ${part.url})` : '(Image)';\n })\n .join('\\n\\n');\n return singleString;\n }\n\n if (value.value === undefined) {\n return undefined;\n }\n\n if (value.value === null) {\n return undefined;\n }\n\n if (typeof value.value === 'object' && !Array.isArray(value.value)) {\n return JSON.stringify(value.value);\n }\n\n // Don't know, so try to infer it from the type of the value\n // Any and object are basically the same...\n if (value.type === 'any' || value.type === 'object') {\n const inferred = inferType(value.value);\n return coerceTypeOptional(inferred, 'string');\n }\n\n return JSON.stringify(value.value);\n}\n\nfunction coerceToChatMessage(value: DataValue | undefined): ChatMessage | undefined {\n const chatMessage = coerceToChatMessageRaw(value);\n\n if (chatMessage?.type === 'assistant') {\n // Double check that arguments is a string, stringify if needed\n if (chatMessage.function_call?.arguments && typeof chatMessage.function_call.arguments !== 'string') {\n chatMessage.function_call.arguments = JSON.stringify(chatMessage.function_call.arguments);\n }\n }\n\n return chatMessage;\n}\n\nfunction coerceToChatMessageRaw(value: DataValue | undefined): ChatMessage | undefined {\n if (!value || value.value == null) {\n return undefined;\n }\n\n if (value.type === 'chat-message') {\n return value.value;\n }\n\n if (value.type === 'string') {\n return { type: 'user', message: value.value };\n }\n\n if (\n value.type === 'object' &&\n 'type' in value.value &&\n 'message' in value.value &&\n typeof value.value.type === 'string' &&\n typeof value.value.message === 'string'\n ) {\n return value.value as ChatMessage;\n }\n\n if (value.type === 'any') {\n const inferred = inferType(value.value);\n return coerceTypeOptional(inferred, 'chat-message');\n }\n}\n\nfunction coerceToBoolean(value: DataValue | undefined) {\n if (!value || !value.value) {\n return false;\n }\n\n if (isArrayDataValue(value)) {\n return value.value\n .map((v) => coerceTypeOptional({ type: value.type.replace('[]', ''), value: v } as DataValue, 'boolean'))\n .every((v) => v);\n }\n\n if (value.type === 'string') {\n return value.value.length > 0 && value.value !== 'false';\n }\n\n if (value.type === 'boolean') {\n return value.value;\n }\n\n if (value.type === 'number') {\n return value.value !== 0;\n }\n\n if (value.type === 'date') {\n return true;\n }\n\n if (value.type === 'time') {\n return true;\n }\n\n if (value.type === 'datetime') {\n return true;\n }\n\n if (value.type === 'chat-message') {\n const hasValue =\n (Array.isArray(value.value.message) && value.value.message.length > 0) ||\n (typeof value.value.message === 'string' && value.value.message.length > 0) ||\n (typeof value.value.message === 'object' &&\n 'type' in value.value.message &&\n value.value.message.type === 'url' &&\n value.value.message.url.length > 0);\n\n return hasValue;\n }\n\n return !!value.value;\n}\n\nfunction coerceToNumber(value: DataValue | undefined): number | undefined {\n if (!value || value.value == null) {\n return undefined;\n }\n\n if (isArrayDataValue(value)) {\n return undefined;\n }\n\n if (value.type === 'string') {\n return parseFloat(value.value);\n }\n\n if (value.type === 'boolean') {\n return value.value ? 1 : 0;\n }\n\n if (value.type === 'number') {\n return value.value;\n }\n\n if (value.type === 'date') {\n return new Date(value.value).valueOf();\n }\n\n if (value.type === 'time') {\n return new Date(value.value).valueOf();\n }\n\n if (value.type === 'datetime') {\n return new Date(value.value).valueOf();\n }\n\n if (value.type === 'chat-message') {\n if (typeof value.value.message === 'string') {\n return parseFloat(value.value.message);\n }\n\n if (\n Array.isArray(value.value.message) &&\n value.value.message.length === 1 &&\n typeof value.value.message[0] === 'string'\n ) {\n return parseFloat(value.value.message[0]);\n }\n\n return undefined;\n }\n\n if (value.type === 'any' || value.type === 'object') {\n const inferred = inferType(value.value);\n return coerceTypeOptional(inferred, 'number');\n }\n\n return undefined;\n}\n\nfunction coerceToObject(value: DataValue | undefined): object | undefined {\n if (!value || value.value == null) {\n return undefined;\n }\n\n return value.value; // Whatever, consider anything an object\n}\n\nfunction coerceToBinary(value: DataValue | undefined): Uint8Array | undefined {\n if (!value || value.value == null) {\n return undefined;\n }\n\n if (value.type === 'binary') {\n return value.value;\n }\n\n if (value.type === 'string') {\n return new TextEncoder().encode(value.value);\n }\n\n if (value.type === 'boolean') {\n return new TextEncoder().encode(value.value.toString());\n }\n\n if (value.type === 'vector' || value.type === 'number[]') {\n return new Uint8Array(value.value);\n }\n\n if (value.type === 'number') {\n return new Uint8Array([value.value]);\n }\n\n if (value.type === 'audio' || value.type === 'image') {\n return value.value.data;\n }\n\n return new TextEncoder().encode(JSON.stringify(value.value));\n}\n\nfunction coerceToGraphReference(value: DataValue | undefined): { graphName: string; graphId: GraphId } | undefined {\n if (!value || value.value == null) {\n return undefined;\n }\n\n if (value.type === 'graph-reference') {\n return value.value;\n }\n\n if (value.type === 'string') {\n return { graphName: value.value, graphId: '' as GraphId };\n }\n\n if (value.type === 'object' && 'graphName' in value.value && 'graphId' in value.value) {\n return value.value as { graphName: string; graphId: GraphId };\n }\n\n return undefined;\n}\n\nexport function canBeCoercedAny(from: DataType | Readonly<DataType[]>, to: DataType | Readonly<DataType[]>) {\n for (const fromType of Array.isArray(from) ? from : [from]) {\n for (const toType of Array.isArray(to) ? to : [to]) {\n if (canBeCoerced(fromType, toType)) {\n return true;\n }\n }\n }\n return false;\n}\n\n// TODO hard to keep in sync with coerceType\nexport function canBeCoerced(from: DataType, to: DataType) {\n if (to === 'any' || from === 'any') {\n return true;\n }\n\n if (isArrayDataType(to) && isArrayDataType(from)) {\n return canBeCoerced(getScalarTypeOf(from), getScalarTypeOf(to));\n }\n\n if (isArrayDataType(to) && !isArrayDataType(from)) {\n return canBeCoerced(from, getScalarTypeOf(to));\n }\n\n if (isArrayDataType(from) && !isArrayDataType(to)) {\n return to === 'string' || to === 'object';\n }\n\n if (to === 'gpt-function') {\n return from === 'object';\n }\n\n if (to === 'audio' || to === 'binary' || to === 'image') {\n return false;\n }\n\n return true;\n}\n", "export function isNotNull<T>(value: T | undefined | null): value is T {\n return value != null;\n}\n\n/**\n * Checks that the given tuple is exhaustive, ie. it represents all possible values in the union T.\n * Note that this function returns a function, so the function needs to be called like\n * `SpecificStrings.exhaustiveTuple<Furniture>()('v1', 'v2', ...)`.\n * If you miss a value, the type error will tell you which value you missed.\n *\n * Taken from https://stackoverflow.com/a/55266531/\n *\n * @example\n * type Furniture = 'chair' | 'table' | 'lamp' | 'ottoman';\n * const furniture = SpecificStrings.exhaustiveTuple<Furniture>()('chair', 'table', 'lamp', 'ottoman');\n *\n * // error, argument of type '\"chair\"' is not assignable to parameter of type '\"You are missing ottoman\"'.\n * const missingFurniture = SpecificStrings.exhaustiveTuple<Furniture>()('chair', 'table', 'lamp');\n */\nexport const exhaustiveTuple =\n <T extends string>() =>\n // impressive inference from TS: it knows when the condition and the true branch can't both be satisfied\n <L extends T[]>(...x: [T] extends [L[number]] ? L : `You are missing ${Exclude<T, L[number]>}`[]) =>\n x;\n\n/**\n * See exhaustiveTuple above. Does the same thing except returns a Set, not an array.\n */\nexport const exhaustiveSet =\n <T extends string>() =>\n <L extends T[]>(...x: [T] extends [L[number]] ? L : `You are missing ${Exclude<T, L[number]>}`[]) =>\n new Set<(typeof x)[number]>(x);\n", "import type { GraphId } from '../index.js';\nimport { exhaustiveTuple } from '../utils/genericUtilFunctions.js';\nimport type { DataId } from './Project.js';\n\nexport type DataValueDef<Type extends string, RuntimeType> = {\n type: Type;\n value: RuntimeType;\n};\n\nexport type StringDataValue = DataValueDef<'string', string>;\nexport type NumberDataValue = DataValueDef<'number', number>;\nexport type BoolDataValue = DataValueDef<'boolean', boolean>;\n\nexport type SystemChatMessage = {\n type: 'system';\n message: ChatMessageMessagePart | ChatMessageMessagePart[];\n};\n\nexport type UserChatMessage = {\n type: 'user';\n message: ChatMessageMessagePart | ChatMessageMessagePart[];\n};\n\nexport type AssistantChatMessageFunctionCall = {\n id: string | undefined;\n name: string;\n arguments: string; // JSON string\n};\n\nexport type ParsedAssistantChatMessageFunctionCall = {\n id: string | undefined;\n name: string;\n arguments: Record<string, unknown>;\n};\n\nexport type AssistantChatMessage = {\n type: 'assistant';\n message: ChatMessageMessagePart | ChatMessageMessagePart[];\n\n /** @deprecated use function_calls instead */\n function_call: AssistantChatMessageFunctionCall | undefined;\n\n function_calls: AssistantChatMessageFunctionCall[] | undefined;\n};\n\nexport type FunctionResponseChatMessage = {\n type: 'function';\n message: ChatMessageMessagePart | ChatMessageMessagePart[];\n name: string; //use to return the 'tool_call_id' value\n};\n\nexport type ChatMessage = SystemChatMessage | UserChatMessage | AssistantChatMessage | FunctionResponseChatMessage;\n\nexport type ChatMessageMessagePart =\n | string\n | { type: 'image'; mediaType: SupportedMediaTypes; data: Uint8Array }\n | { type: 'url'; url: string };\n\nexport type SupportedMediaTypes = 'image/jpeg' | 'image/png' | 'image/gif';\n\nexport type ChatMessageDataValue = DataValueDef<'chat-message', ChatMessage>;\n\nexport type DateDataValue = DataValueDef<'date', string>;\nexport type TimeDataValue = DataValueDef<'time', string>;\nexport type DateTimeDataValue = DataValueDef<'datetime', string>;\nexport type AnyDataValue = DataValueDef<'any', unknown>;\nexport type ObjectDataValue = DataValueDef<'object', Record<string, unknown>>;\nexport type VectorDataValue = DataValueDef<'vector', number[]>;\nexport type BinaryDataValue = DataValueDef<'binary', Uint8Array>;\nexport type ImageDataValue = DataValueDef<'image', { mediaType: SupportedMediaTypes; data: Uint8Array }>;\nexport type AudioDataValue = DataValueDef<'audio', { mediaType?: string; data: Uint8Array }>;\nexport type GraphReferenceValue = DataValueDef<'graph-reference', { graphId: GraphId; graphName: string }>;\n\n/** GPT function definition */\nexport type GptFunction = {\n name: string;\n namespace?: string;\n description: string;\n parameters: object;\n strict: boolean;\n};\n\nexport type GptFunctionDataValue = DataValueDef<'gpt-function', GptFunction>;\n\nexport type ControlFlowExcludedDataValue = DataValueDef<'control-flow-excluded', undefined | 'loop-not-broken'>;\n\nexport type ScalarDataValue =\n | StringDataValue\n | NumberDataValue\n | DateDataValue\n | TimeDataValue\n | DateTimeDataValue\n | BoolDataValue\n | ChatMessageDataValue\n | ControlFlowExcludedDataValue\n | AnyDataValue\n | ObjectDataValue\n | GptFunctionDataValue\n | VectorDataValue\n | ImageDataValue\n | BinaryDataValue\n | AudioDataValue\n | GraphReferenceValue;\n\nexport type ScalarType = ScalarDataValue['type'];\n\nexport type ArrayDataValue<T extends ScalarDataValue> = DataValueDef<`${T['type']}[]`, T['value'][]>;\n\nexport type FunctionDataValue<T extends ScalarOrArrayDataValue> = DataValueDef<`fn<${T['type']}>`, () => T['value']>;\n\nexport type StringArrayDataValue = ArrayDataValue<StringDataValue>;\n\nexport type ArrayDataValues = {\n [P in ScalarDataValue['type']]: ArrayDataValue<Extract<ScalarDataValue, { type: P }>>;\n}[ScalarDataValue['type']];\n\nexport type ScalarOrArrayDataValue = ScalarDataValue | ArrayDataValues;\n\nexport type FunctionDataValues = {\n [P in ScalarOrArrayDataValue['type']]: FunctionDataValue<Extract<ScalarOrArrayDataValue, { type: P }>>;\n}[ScalarOrArrayDataValue['type']];\n\nexport type DataValue = ScalarDataValue | ArrayDataValues | FunctionDataValues;\n\nexport type DataType = DataValue['type'];\nexport type ScalarDataType = ScalarDataValue['type'];\nexport type ArrayDataType = ArrayDataValues['type'];\nexport type FunctionDataType = FunctionDataValues['type'];\nexport type ScalarOrArrayDataType = ScalarOrArrayDataValue['type'];\n\nexport type GetDataValue<Type extends DataType> = Extract<DataValue, { type: Type }>;\n\n/** A reference to large data stored outside the graphs themselves. */\nexport type DataRef = {\n refId: DataId;\n};\n\nexport const dataTypes = exhaustiveTuple<DataType>()(\n 'any',\n 'any[]',\n 'boolean',\n 'boolean[]',\n 'string',\n 'string[]',\n 'number',\n 'number[]',\n 'date',\n 'date[]',\n 'time',\n 'time[]',\n 'datetime',\n 'datetime[]',\n 'chat-message',\n 'chat-message[]',\n 'control-flow-excluded',\n 'control-flow-excluded[]',\n 'object',\n 'object[]',\n 'fn<string>',\n 'fn<number>',\n 'fn<boolean>',\n 'fn<date>',\n 'fn<time>',\n 'fn<datetime>',\n 'fn<any>',\n 'fn<object>',\n 'fn<chat-message>',\n 'fn<control-flow-excluded>',\n 'fn<string[]>',\n 'fn<number[]>',\n 'fn<boolean[]>',\n 'fn<date[]>',\n 'fn<time[]>',\n 'fn<datetime[]>',\n 'fn<any[]>',\n 'fn<object[]>',\n 'fn<chat-message[]>',\n 'fn<control-flow-excluded[]>',\n 'gpt-function',\n 'gpt-function[]',\n 'fn<gpt-function[]>',\n 'fn<gpt-function>',\n 'vector',\n 'vector[]',\n 'fn<vector>',\n 'fn<vector[]>',\n 'image',\n 'image[]',\n 'fn<image>',\n 'fn<image[]>',\n 'binary',\n 'binary[]',\n 'fn<binary>',\n 'fn<binary[]>',\n 'audio',\n 'audio[]',\n 'fn<audio>',\n 'fn<audio[]>',\n 'graph-reference',\n 'graph-reference[]',\n 'fn<graph-reference>',\n 'fn<graph-reference[]>',\n);\n\nexport const scalarTypes = exhaustiveTuple<ScalarType>()(\n 'any',\n 'boolean',\n 'string',\n 'number',\n 'date',\n 'time',\n 'datetime',\n 'chat-message',\n 'control-flow-excluded',\n 'object',\n 'gpt-function',\n 'vector',\n 'image',\n 'binary',\n 'audio',\n 'graph-reference',\n);\n\nexport const dataTypeDisplayNames: Record<DataType, string> = {\n any: 'Any',\n 'any[]': 'Any Array',\n boolean: 'Boolean',\n 'boolean[]': 'Boolean Array',\n string: 'String',\n 'string[]': 'String Array',\n number: 'Number',\n 'number[]': 'Number Array',\n date: 'Date',\n 'date[]': 'Date Array',\n time: 'Time',\n 'time[]': 'Time Array',\n datetime: 'DateTime',\n 'datetime[]': 'DateTime Array',\n 'chat-message': 'ChatMessage',\n 'chat-message[]': 'ChatMessage Array',\n 'control-flow-excluded': 'ControlFlowExcluded',\n 'control-flow-excluded[]': 'ControlFlowExcluded Array',\n object: 'Object',\n 'object[]': 'Object Array',\n 'gpt-function': 'GPT Function',\n 'gpt-function[]': 'GPT Function Array',\n 'fn<string>': 'Function<String>',\n 'fn<number>': 'Function<Number>',\n 'fn<boolean>': 'Function<Boolean>',\n 'fn<date>': 'Function<Date>',\n 'fn<time>': 'Function<Time>',\n 'fn<datetime>': 'Function<DateTime>',\n 'fn<any>': 'Function<Any>',\n 'fn<object>': 'Function<Object>',\n 'fn<chat-message>': 'Function<ChatMessage>',\n 'fn<control-flow-excluded>': 'Function<ControlFlowExcluded>',\n 'fn<gpt-function>': 'Function<GPT Function>',\n 'fn<string[]>': 'Function<String Array>',\n 'fn<number[]>': 'Function<Number Array>',\n 'fn<boolean[]>': 'Function<Boolean Array>',\n 'fn<date[]>': 'Function<Date Array>',\n 'fn<time[]>': 'Function<Time Array>',\n 'fn<datetime[]>': 'Function<DateTime Array>',\n 'fn<any[]>': 'Function<Any Array>',\n 'fn<object[]>': 'Function<Object Array>',\n 'fn<chat-message[]>': 'Function<ChatMessage Array>',\n 'fn<control-flow-excluded[]>': 'Function<ControlFlowExcluded Array>',\n 'fn<gpt-function[]>': 'Function<GPT Function Array>',\n vector: 'Vector',\n 'vector[]': 'Vector Array',\n 'fn<vector>': 'Function<Vector>',\n 'fn<vector[]>': 'Function<Vector Array>',\n image: 'Image',\n 'image[]': 'Image Array',\n 'fn<image>': 'Function<Image>',\n 'fn<image[]>': 'Function<Image Array>',\n binary: 'Binary',\n 'binary[]': 'Binary Array',\n 'fn<binary>': 'Function<Binary>',\n 'fn<binary[]>': 'Function<Binary Array>',\n audio: 'Audio',\n 'audio[]': 'Audio Array',\n 'fn<audio>': 'Function<Audio>',\n 'fn<audio[]>': 'Function<Audio Array>',\n 'graph-reference': 'Graph Reference',\n 'graph-reference[]': 'Graph Reference Array',\n 'fn<graph-reference>': 'Function<Graph Reference>',\n 'fn<graph-reference[]>': 'Function<Graph Reference Array>',\n};\n\nexport function isScalarDataValue(value: DataValue | undefined): value is ScalarDataValue {\n if (!value) {\n return false;\n }\n\n return !isArrayDataType(value.type) && !isFunctionDataType(value.type);\n}\n\nexport function isScalarDataType(type: DataType): type is ScalarDataType {\n return !isArrayDataType(type) && !isFunctionDataType(type);\n}\n\nexport function isArrayDataValue(value: DataValue | undefined): value is ArrayDataValues {\n if (!value) {\n return false;\n }\n\n return (\n isArrayDataType(value.type) || ((value.type === 'any' || value.type === 'object') && Array.isArray(value.value))\n );\n}\n\nexport function isArrayDataType(type: DataType): type is ArrayDataType {\n return type.endsWith('[]');\n}\n\nexport function isFunctionDataType(type: DataType): type is FunctionDataType {\n return type.startsWith('fn<');\n}\n\nexport function isFunctionDataValue(value: DataValue | undefined): value is FunctionDataValues {\n if (!value) {\n return false;\n }\n return isFunctionDataType(value.type) || (value.type === 'any' && typeof value.value === 'function');\n}\n\nexport function isNotFunctionDataValue(value: DataValue | undefined): value is ScalarOrArrayDataValue {\n return !isFunctionDataValue(value);\n}\n\nexport function functionTypeToScalarType(functionType: FunctionDataType): ScalarDataType {\n return functionType.slice(3, -1) as ScalarDataType;\n}\n\nexport function arrayTypeToScalarType(arrayType: ArrayDataType): ScalarDataType {\n return arrayType.slice(0, -2) as ScalarDataType;\n}\n\nexport function getScalarTypeOf(type: DataType): ScalarDataType {\n if (isArrayDataType(type)) {\n return arrayTypeToScalarType(type);\n }\n\n if (isFunctionDataType(type)) {\n return functionTypeToScalarType(type);\n }\n\n return type;\n}\n\n/** Unwraps a potentially function data value to a concrete value. I.e., evaluates on-demand values. */\nexport function unwrapDataValue(value: DataValue): ScalarOrArrayDataValue;\nexport function unwrapDataValue(value: DataValue | undefined): ScalarOrArrayDataValue | undefined {\n if (!value) {\n return undefined;\n }\n\n if (isFunctionDataValue(value)) {\n return { type: functionTypeToScalarType(value.type), value: value.value() } as ScalarOrArrayDataValue;\n }\n\n return value;\n}\n\n/**\n * Turns a { type: 'string[]', value: string[] } into { type: 'string', value: string }[]\n * or a { type: 'object', value: something[] } into { type: 'object', value: something }[]\n * or a { type: 'any', value: something[] } into { type: 'any', value: something }[]\n * or a { type: 'string', value: string } into [{ type: 'string', value: string }]\n */\nexport const arrayizeDataValue = (value: ScalarOrArrayDataValue): ScalarDataValue[] => {\n const isArray =\n value.type.endsWith('[]') || ((value.type === 'any' || value.type === 'object') && Array.isArray(value.value));\n if (!isArray) {\n return [value as ScalarDataValue];\n }\n\n const unwrappedType = value.type.endsWith('[]') ? value.type.slice(0, -2) : value.type;\n\n return (value.value as unknown[]).map((v) => ({ type: unwrappedType as ScalarType, value: v })) as ScalarDataValue[];\n};\n\nexport const scalarDefaults: { [P in ScalarDataType]: Extract<ScalarDataValue, { type: P }>['value'] } = {\n string: '',\n number: 0,\n boolean: false,\n any: undefined,\n 'chat-message': {\n type: 'user',\n message: '',\n },\n 'control-flow-excluded': undefined,\n date: new Date().toISOString(),\n time: new Date().toISOString(),\n datetime: new Date().toISOString(),\n object: {},\n 'gpt-function': {\n name: 'unknown',\n description: '',\n parameters: {},\n namespace: undefined,\n strict: false,\n },\n vector: [],\n image: {\n mediaType: 'image/jpeg',\n data: new Uint8Array(),\n },\n binary: new Uint8Array(),\n audio: { data: new Uint8Array() },\n 'graph-reference': { graphId: '' as GraphId, graphName: '' },\n};\n\nexport function getDefaultValue<T extends DataType>(type: T): (DataValue & { type: T })['value'] {\n if (isArrayDataType(type)) {\n return [] as any;\n }\n\n if (isFunctionDataType(type)) {\n return (() => scalarDefaults[getScalarTypeOf(type)]) as any;\n }\n\n return scalarDefaults[getScalarTypeOf(type)] as any;\n}\n", "import {\n type DataType,\n type DataValue,\n type GetDataValue,\n getScalarTypeOf,\n isArrayDataType,\n isFunctionDataType,\n isScalarDataValue,\n unwrapDataValue,\n} from '../model/DataValue.js';\n\nexport function expectType<T extends DataType>(value: DataValue | undefined, type: T): GetDataValue<T>['value'] {\n // Allow a string to be expected for a string[], just return an array of one element\n if (isArrayDataType(type) && isScalarDataValue(value) && getScalarTypeOf(type) === value.type) {\n return [value.value] as GetDataValue<T>['value'];\n }\n\n if (type === 'any' || type === 'any[]' || value?.type === 'any' || value?.type === 'any[]') {\n return value?.value as GetDataValue<T>['value'];\n }\n\n if ((isFunctionDataType(type) && value?.type === `fn<${type}>`) || type === 'fn<any>') {\n return (() => value!.value) as GetDataValue<T>['value'];\n }\n\n if (value?.type !== type) {\n throw new Error(`Expected value of type ${type} but got ${value?.type}`);\n }\n return value.value as GetDataValue<T>['value'];\n}\n\nexport function expectTypeOptional<T extends DataType>(\n value: DataValue | undefined,\n type: T,\n): GetDataValue<T>['value'] | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n // Allow a string to be expected for a string[], just return an array of one element\n if (isArrayDataType(type) && isScalarDataValue(value) && getScalarTypeOf(type) === value.type) {\n return [value.value] as GetDataValue<T>['value'] | undefined;\n }\n\n // We allow a fn<string> to be expected for a string, so unwrap it on demand\n if (isFunctionDataType(value.type) && value.type === `fn<${type}>`) {\n value = unwrapDataValue(value);\n }\n\n if (value.type !== type) {\n throw new Error(`Expected value of type ${type} but got ${value?.type}`);\n }\n return value.value as GetDataValue<T>['value'] | undefined;\n}\n", "/** Gets an Error from an unknown error object (strict unknown errors is enabled, helper util). */\nexport function getError(error: unknown): Error {\n const errorInstance =\n typeof error === 'object' && error instanceof Error\n ? error\n : new Error(error != null ? error.toString() : 'Unknown error');\n return errorInstance;\n}\n", "// @ts-ignore\nimport * as yaml from 'yaml';\nimport { graphV3Deserializer, projectV3Deserializer } from './serialization_v3.js';\nimport type { Project, NodeGraph, ProjectId, DatasetProvider, Dataset, DatasetMetadata } from '../../index.js';\nimport { getError } from '../errors.js';\nimport { type AttachedData, yamlProblem } from './serializationUtils.js';\nimport {\n datasetV4Deserializer,\n datasetV4Serializer,\n graphV4Deserializer,\n graphV4Serializer,\n projectV4Deserializer,\n projectV4Serializer,\n} from './serialization_v4.js';\nimport { graphV2Deserializer, projectV2Deserializer } from './serialization_v2.js';\nimport { graphV1Deserializer, projectV1Deserializer } from './serialization_v1.js';\n\nexport function serializeProject(project: Project, attachedData?: AttachedData): unknown {\n return projectV4Serializer(project, attachedData);\n}\n\nconst errMessage = (err: unknown) => `${getError(err).message}\\n${getError(err).stack}`;\n\nexport function deserializeProject(serializedProject: unknown, path: string | null = null): [Project, AttachedData] {\n try {\n const result = projectV4Deserializer(serializedProject);\n if (path !== null) result[0].metadata.path = path;\n return result;\n } catch (err) {\n if (err instanceof yaml.YAMLError) {\n yamlProblem(err);\n }\n console.warn(`Failed to deserialize project v4: ${errMessage(err)}`);\n\n try {\n const project = projectV3Deserializer(serializedProject);\n return [project, {}];\n } catch (err) {\n if (err instanceof yaml.YAMLError) {\n yamlProblem(err);\n }\n console.warn(`Failed to deserialize project v3: ${errMessage(err)}`);\n\n try {\n const project = projectV2Deserializer(serializedProject);\n return [project, {}];\n } catch (err) {\n if (err instanceof yaml.YAMLError) {\n yamlProblem(err);\n }\n console.warn(`Failed to deserialize project v2: ${errMessage(err)}`);\n\n try {\n const project = projectV1Deserializer(serializedProject);\n return [project, {}];\n } catch (err) {\n console.warn(`Failed to deserialize project v1: ${errMessage(err)}`);\n throw new Error('Could not deserialize project');\n }\n }\n }\n }\n}\n\nexport function serializeGraph(graph: NodeGraph): unknown {\n return graphV4Serializer(graph);\n}\n\nexport function deserializeGraph(serializedGraph: unknown): NodeGraph {\n try {\n return graphV4Deserializer(serializedGraph);\n } catch (err) {\n try {\n return graphV3Deserializer(serializedGraph);\n } catch (err) {\n try {\n return graphV2Deserializer(serializedGraph);\n } catch (err) {\n try {\n return graphV1Deserializer(serializedGraph);\n } catch (err) {\n throw new Error('Could not deserialize graph');\n }\n }\n }\n }\n}\n\nexport type CombinedDataset = {\n meta: DatasetMetadata;\n data: Dataset;\n};\n\nexport function serializeDatasets(datasets: CombinedDataset[]): string {\n return datasetV4Serializer(datasets);\n}\n\nexport function deserializeDatasets(serializedDatasets: string): CombinedDataset[] {\n return datasetV4Deserializer(serializedDatasets);\n}\n", "import { mapValues } from 'lodash-es';\nimport type {\n NodeGraph,\n Project,\n GraphId,\n NodeId,\n NodeConnection,\n ChartNode,\n PortId,\n ChartNodeVariant,\n ProjectId,\n} from '../../index.js';\nimport stableStringify from 'safe-stable-stringify';\n// @ts-ignore\nimport * as yaml from 'yaml';\nimport { doubleCheckProject } from './serializationUtils.js';\n\ntype SerializedProject = {\n metadata: {\n id: ProjectId;\n title: string;\n description: string;\n };\n\n graphs: Record<GraphId, SerializedGraph>;\n};\n\ntype SerializedGraph = {\n metadata: {\n id: GraphId;\n name: string;\n description: string;\n };\n\n nodes: Record<NodeId, SerializedNode>;\n};\n\nexport type SerializedNode = {\n type: string;\n id: string;\n title: string;\n description?: string;\n isSplitRun?: boolean;\n splitRunMax?: number;\n\n // x/y/width/zIndex\n visualData: `${string}/${string}/${string}/${string}`;\n outgoingConnections: SerializedNodeConnection[];\n data?: unknown;\n variants?: ChartNodeVariant<unknown>[];\n};\n\n/** x/y/width/zIndex */\ntype SerializedVisualData = `${string}/${string}/${string}/${string}`;\n\n// portId->nodeId/portId\ntype SerializedNodeConnection = `${string}->\"${string}\" ${string}/${string}`;\n\nexport function projectV3Deserializer(data: unknown): Project {\n if (typeof data !== 'string') {\n throw new Error('Project v3 deserializer requires a string');\n }\n\n const serializedProject = yaml.parse(data) as { version: number; data: SerializedProject };\n\n if (serializedProject.version !== 3) {\n throw new Error('Project v3 deserializer requires a version 3 project');\n }\n\n const project = fromSerializedProject(serializedProject.data);\n\n doubleCheckProject(project);\n\n return project;\n}\n\nexport function graphV3Deserializer(data: unknown): NodeGraph {\n if (typeof data !== 'string') {\n throw new Error('Graph v3 deserializer requires a string');\n }\n\n const serializedGraph = yaml.parse(data) as { version: number; data: SerializedGraph };\n\n if (serializedGraph.version !== 3) {\n throw new Error('Graph v3 deserializer requires a version 3 graph');\n }\n\n return fromSerializedGraph(serializedGraph.data);\n}\n\nexport function projectV3Serializer(project: Project): unknown {\n // Make sure all data is ordered deterministically first\n const stabilized = JSON.parse(stableStringify(toSerializedProject(project)));\n\n const serialized = yaml.stringify(\n {\n version: 3,\n data: stabilized,\n },\n null,\n {\n indent: 2,\n },\n );\n\n return serialized;\n}\n\nexport function graphV3Serializer(graph: NodeGraph): unknown {\n // Make sure all data is ordered deterministically first\n const stabilized = JSON.parse(stableStringify(toSerializedGraph(graph)));\n\n const serialized = yaml.stringify(\n {\n version: 4,\n data: stabilized,\n },\n null,\n {\n indent: 2,\n },\n );\n\n return serialized;\n}\n\nfunction toSerializedProject(project: Project): SerializedProject {\n return {\n metadata: project.metadata,\n graphs: mapValues(project.graphs, (graph) => toSerializedGraph(graph)),\n };\n}\n\nfunction fromSerializedProject(serializedProject: SerializedProject): Project {\n return {\n metadata: serializedProject.metadata,\n graphs: mapValues(serializedProject.graphs, (graph) => fromSerializedGraph(graph)) as Record<GraphId, NodeGraph>,\n plugins: [],\n };\n}\n\nfunction toSerializedGraph(graph: NodeGraph): SerializedGraph {\n return {\n metadata: {\n id: graph.metadata!.id!,\n name: graph.metadata!.name!,\n description: graph.metadata!.description!,\n },\n nodes: graph.nodes.reduce(\n (acc, node) => ({\n ...acc,\n [node.id]: toSerializedNode(node, graph.nodes, graph.connections),\n }),\n {} as Record<NodeId, SerializedNode>,\n ),\n };\n}\n\nfunction fromSerializedGraph(serializedGraph: SerializedGraph): NodeGraph {\n const allConnections: NodeConnection[] = [];\n const allNodes: ChartNode[] = [];\n\n for (const node of Object.values(serializedGraph.nodes)) {\n const [chartNode, connections] = fromSerializedNode(node);\n allNodes.push(chartNode);\n allConnections.push(...connections);\n }\n\n return {\n metadata: {\n id: serializedGraph.metadata.id,\n name: serializedGraph.metadata.name,\n description: serializedGraph.metadata.description,\n },\n nodes: allNodes,\n connections: allConnections,\n };\n}\n\nfunction toSerializedNode(node: ChartNode, allNodes: ChartNode[], allConnections: NodeConnection[]): SerializedNode {\n return {\n id: node.id,\n title: node.title,\n description: node.description,\n type: node.type,\n visualData: `${node.visualData.x}/${node.visualData.y}/${node.visualData.width ?? 'null'}/${\n node.visualData.zIndex ?? 'null'\n }`,\n isSplitRun: node.isSplitRun,\n splitRunMax: node.splitRunMax,\n data: node.data,\n outgoingConnections: allConnections\n .filter((connection) => connection.outputNodeId === node.id)\n .map((connection) => toSerializedConnection(connection, allNodes))\n .sort(),\n variants: (node.variants?.length ?? 0) > 0 ? node.variants : undefined,\n };\n}\n\nfunction fromSerializedNode(serializedNode: SerializedNode): [ChartNode, NodeConnection[]] {\n const [x, y, width, zIndex] = serializedNode.visualData.split('/');\n\n const connections = serializedNode.outgoingConnections.map((serializedConnection) =>\n fromSerializedConnection(serializedConnection, serializedNode),\n );\n\n return [\n {\n id: serializedNode.id as NodeId,\n title: serializedNode.title,\n description: serializedNode.description,\n type: serializedNode.type,\n isSplitRun: serializedNode.isSplitRun,\n splitRunMax: serializedNode.splitRunMax,\n visualData: {\n x: parseFloat(x!),\n y: parseFloat(y!),\n width: width === 'null' ? undefined : parseFloat(width!),\n zIndex: zIndex === 'null' ? undefined : parseFloat(zIndex!),\n },\n data: serializedNode.data,\n variants: serializedNode.variants,\n },\n connections,\n ];\n}\n\nfunction toSerializedConnection(connection: NodeConnection, allNodes: ChartNode[]): SerializedNodeConnection {\n return `${connection.outputId}->\"${allNodes.find((node) => node.id === connection.inputNodeId)?.title}\" ${\n connection.inputNodeId\n }/${connection.inputId}`;\n}\n\nfunction fromSerializedConnection(connection: SerializedNodeConnection, outgoingNode: SerializedNode): NodeConnection {\n const [, outputId, , inputNodeId, inputId] = connection.match(/(.+)->\"(.+)\" (.+)\\/(.+)/)!;\n\n return {\n outputId: outputId as PortId,\n outputNodeId: outgoingNode.id as NodeId,\n inputId: inputId as PortId,\n inputNodeId: inputNodeId as NodeId,\n };\n}\n", "import type { Project } from '../../index.js';\nimport type * as yaml from 'yaml';\n\n/** Additional data that has been attached to a project/graph, for use by plugins, etc. */\nexport type AttachedData = Record<string, unknown>;\n\nexport function doubleCheckProject(project: Project): void {\n if (\n !project.metadata ||\n !project.metadata!.id ||\n !project.metadata!.title ||\n !project.graphs ||\n typeof project.graphs !== 'object'\n ) {\n throw new Error('Invalid project file');\n }\n}\n\nexport function yamlProblem(err: yaml.YAMLError): never {\n const { code, message, pos, linePos } = err;\n throw new Error(`YAML error: ${code} ${message} at ${pos} ${linePos}`);\n}\n", "import { mapValues } from 'lodash-es';\nimport type {\n NodeGraph,\n Project,\n GraphId,\n NodeId,\n NodeConnection,\n ChartNode,\n PortId,\n ProjectId,\n ChartNodeVariant,\n} from '../../index.js';\nimport stableStringify from 'safe-stable-stringify';\nimport * as yaml from 'yaml';\nimport { type AttachedData, doubleCheckProject } from './serializationUtils.js';\nimport { entries } from '../typeSafety.js';\nimport type { PluginLoadSpec } from '../../model/PluginLoadSpec.js';\nimport type { CombinedDataset } from './serialization.js';\n\ntype SerializedProject = {\n metadata: {\n id: ProjectId;\n title: string;\n description: string;\n };\n\n graphs: Record<GraphId, SerializedGraph>;\n\n attachedData?: AttachedData;\n plugins?: PluginLoadSpec[];\n};\n\ntype SerializedGraphMetadata = {\n id: GraphId;\n name: string;\n description: string;\n attachedData?: AttachedData;\n};\n\ntype SerializedGraph = {\n metadata: SerializedGraphMetadata;\n nodes: Record<SerializedGraphNodeKey, SerializedNode>;\n};\n\ntype SerializedNode = {\n description?: string;\n isSplitRun?: boolean;\n splitRunMax?: number;\n isSplitSequential?: boolean;\n visualData: SerializedVisualData;\n outgoingConnections: SerializedNodeConnection[] | undefined;\n data?: unknown;\n variants?: ChartNodeVariant<unknown>[];\n disabled?: boolean;\n};\n\n/** x/y/width/zIndex */\ntype SerializedVisualData = `${string}/${string}/${string}/${string}`;\n\n// portId->nodeId/portId\ntype SerializedNodeConnection = `${string}->\"${string}\" ${string}/${string}`;\n\nexport function projectV4Deserializer(data: unknown): [Project, AttachedData] {\n if (typeof data !== 'string') {\n throw new Error('Project v4 deserializer requires a string');\n }\n\n const serializedProject = yaml.parse(data) as { version: number; data: SerializedProject };\n\n if (serializedProject.version !== 4) {\n throw new Error('Project v4 deserializer requires a version 4 project');\n }\n\n const [project, attachedData] = fromSerializedProject(serializedProject.data);\n\n doubleCheckProject(project);\n\n return [project, attachedData];\n}\n\nexport function graphV4Deserializer(data: unknown): NodeGraph {\n if (typeof data !== 'string') {\n throw new Error('Graph v4 deserializer requires a string');\n }\n\n const serializedGraph = yaml.parse(data) as { version: number; data: SerializedGraph };\n\n if (serializedGraph.version !== 4) {\n throw new Error('Graph v4 deserializer requires a version 4 graph');\n }\n\n return fromSerializedGraph(serializedGraph.data);\n}\n\nexport function projectV4Serializer(project: Project, attachedData?: AttachedData): unknown {\n const filteredProject = {\n ...project,\n metadata: {\n ...project.metadata,\n path: undefined,\n },\n };\n\n // Make sure all data is ordered deterministically first\n const stabilized = JSON.parse(stableStringify(toSerializedProject(filteredProject, attachedData)));\n\n const serialized = yaml.stringify(\n {\n version: 4,\n data: stabilized,\n },\n null,\n {\n indent: 2,\n },\n );\n\n return serialized;\n}\n\nexport function graphV4Serializer(graph: NodeGraph): unknown {\n // Make sure all data is ordered deterministically first\n const stabilized = JSON.parse(stableStringify(toSerializedGraph(graph)));\n\n const serialized = yaml.stringify(\n {\n version: 4,\n data: stabilized,\n },\n null,\n {\n indent: 2,\n },\n );\n\n return serialized;\n}\n\nfunction toSerializedProject(project: Project, attachedData?: AttachedData): SerializedProject {\n return {\n metadata: project.metadata,\n graphs: mapValues(project.graphs, (graph) => toSerializedGraph(graph)),\n attachedData,\n plugins: project.plugins ?? [],\n };\n}\n\nfunction fromSerializedProject(serializedProject: SerializedProject): [Project, AttachedData] {\n return [\n {\n metadata: serializedProject.metadata,\n graphs: mapValues(serializedProject.graphs, (graph) => fromSerializedGraph(graph)) as Record<GraphId, NodeGraph>,\n plugins: serializedProject.plugins ?? [],\n },\n serializedProject.attachedData ?? {},\n ];\n}\n\nfunction toSerializedGraph(graph: NodeGraph): SerializedGraph {\n const graphMetadata: SerializedGraphMetadata = {\n id: graph.metadata!.id!,\n name: graph.metadata!.name!,\n description: graph.metadata!.description!,\n };\n\n if (graph.metadata!.attachedData) {\n graphMetadata.attachedData = graph.metadata!.attachedData;\n }\n\n return {\n metadata: graphMetadata,\n nodes: graph.nodes.reduce(\n (acc, node) => ({\n ...acc,\n [getGraphNodeKey(node)]: toSerializedNode(node, graph.nodes, graph.connections),\n }),\n {} as Record<NodeId, SerializedNode>,\n ),\n };\n}\n\n/** [nodeId]:type \"Title of Node\" */\ntype SerializedGraphNodeKey = `[${NodeId}]:${string} \"${string}\"`;\n\nfunction getGraphNodeKey(node: ChartNode): string {\n return `[${node.id}]:${node.type} \"${node.title}\"`;\n}\n\nfunction deserializeGraphNodeKey(key: string): [NodeId, string, string] {\n const { nodeId, type, title } = key.match(/^\\[(?<nodeId>[^\\]]+)\\]:(?<type>[^\\s]+) \"(?<title>.*)\"$/)?.groups ?? {};\n if (!nodeId || !type || !title) {\n throw new Error(`Invalid graph node key: ${key}`);\n }\n return [nodeId as NodeId, type, title];\n}\n\nfunction fromSerializedGraph(serializedGraph: SerializedGraph): NodeGraph {\n const allConnections: NodeConnection[] = [];\n const allNodes: ChartNode[] = [];\n\n for (const [serializedNodeInfo, node] of entries(serializedGraph.nodes)) {\n const [chartNode, connections] = fromSerializedNode(node, serializedNodeInfo);\n allNodes.push(chartNode);\n allConnections.push(...connections);\n }\n\n const metadata: SerializedGraphMetadata = {\n id: serializedGraph.metadata.id,\n name: serializedGraph.metadata.name,\n description: serializedGraph.metadata.description,\n };\n\n if (serializedGraph.metadata.attachedData) {\n metadata.attachedData = serializedGraph.metadata.attachedData;\n }\n\n return {\n metadata,\n nodes: allNodes,\n connections: allConnections,\n };\n}\n\nfunction toSerializedNode(node: ChartNode, allNodes: ChartNode[], allConnections: NodeConnection[]): SerializedNode {\n const outgoingConnections = allConnections\n .filter((connection) => connection.outputNodeId === node.id)\n .map((connection) => toSerializedConnection(connection, allNodes))\n .sort();\n return {\n description: node.description?.trim() ? node.description : undefined,\n visualData: `${node.visualData.x}/${node.visualData.y}/${node.visualData.width ?? 'null'}/${\n node.visualData.zIndex ?? 'null'\n }/${node.visualData.color?.border ?? ''}/${node.visualData.color?.bg ?? ''}`,\n isSplitRun: node.isSplitRun ? true : undefined,\n splitRunMax: node.isSplitRun ? node.splitRunMax : undefined,\n isSplitSequential: node.isSplitSequential ? true : undefined,\n data: Object.keys(node.data ?? {}).length > 0 ? node.data : undefined,\n outgoingConnections: outgoingConnections.length > 0 ? outgoingConnections : undefined,\n variants: (node.variants?.length ?? 0) > 0 ? node.variants : undefined,\n disabled: node.disabled ? true : undefined,\n };\n}\n\nfunction fromSerializedNode(\n serializedNode: SerializedNode,\n serializedNodeInfo: SerializedGraphNodeKey,\n): [ChartNode, NodeConnection[]] {\n const [nodeId, type, title] = deserializeGraphNodeKey(serializedNodeInfo);\n\n const [x, y, width, zIndex, borderColor, bgColor] = serializedNode.visualData.split('/');\n\n const connections =\n serializedNode.outgoingConnections?.map((serializedConnection) =>\n fromSerializedConnection(serializedConnection, nodeId),\n ) ?? [];\n\n const color = borderColor || bgColor ? { border: borderColor!, bg: bgColor! } : undefined;\n\n return [\n {\n id: nodeId,\n type,\n title,\n description: serializedNode.description,\n isSplitRun: serializedNode.isSplitRun ?? false,\n splitRunMax: serializedNode.splitRunMax ?? 10,\n isSplitSequential: serializedNode.isSplitSequential ?? false,\n visualData: {\n x: parseFloat(x!),\n y: parseFloat(y!),\n width: width === 'null' ? undefined : parseFloat(width!),\n zIndex: zIndex === 'null' ? undefined : parseFloat(zIndex!),\n color,\n },\n data: serializedNode.data ?? {},\n variants: serializedNode.variants ?? [],\n disabled: serializedNode.disabled,\n },\n connections,\n ];\n}\n\nfunction toSerializedConnection(connection: NodeConnection, allNodes: ChartNode[]): SerializedNodeConnection {\n return `${connection.outputId}->\"${allNodes.find((node) => node.id === connection.inputNodeId)?.title}\" ${\n connection.inputNodeId\n }/${connection.inputId}`;\n}\n\nfunction fromSerializedConnection(connection: SerializedNodeConnection, nodeId: NodeId): NodeConnection {\n try {\n const [, outputId, , inputNodeId, inputId] = connection.match(/(.+)->\"(.+)\"\\s+(.+)\\/(.+)/)!;\n\n return {\n outputId: outputId as PortId,\n outputNodeId: nodeId,\n inputId: inputId as PortId,\n inputNodeId: inputNodeId as NodeId,\n };\n } catch (err) {\n throw new Error(`Invalid connection: ${connection}`);\n }\n}\n\nexport function datasetV4Serializer(datasets: CombinedDataset[]): string {\n const dataContainer = {\n datasets,\n };\n\n const data = JSON.stringify(dataContainer);\n\n return data;\n}\n\nexport function datasetV4Deserializer(serializedDatasets: string): CombinedDataset[] {\n const stringData = serializedDatasets as string;\n\n const dataContainer = JSON.parse(stringData) as { datasets: CombinedDataset[] };\n\n if (!dataContainer.datasets) {\n throw new Error('Invalid dataset data');\n }\n\n return dataContainer.datasets;\n}\n", "/**\n * Type-safe version of {@link Object.entries} which can infer the type for the keys in the\n * returned pairs when the input object has a branded type as its key.\n *\n * @example\n * type MyId = string & { __myIdBrand: unknown };\n * // Types check out!\n * const things: [MyId, Thing][] = Objects.entries({} as Record<MyId, Thing>);\n *\n * @see {@link fromEntries}\n */\nexport const entries = <K extends string, V>(\n // In principle we should be able to use only Partial<> as the type is a superset of the non-\n // Partial type, but in practice this causes the compiler to infer a too-restricted type for V\n // in some cases involving unions.\n object: Record<K, V> | Partial<Record<K, V>> | undefined | null,\n): [K, V][] => (object == null ? [] : (Object.entries(object) as [K, V][]));\n\n/**\n * Type-safe version of {@link Object.fromEntries} which can infer the type for the key in the\n * returned object when the input array has a branded type as its key.\n *\n * @example\n * type MyId = string & { __myIdBrand: unknown };\n * // Types check out!\n * const things: Partial<Record<MyId, Thing>> = Objects.fromEntries([] as [MyId, Thing][]);\n *\n * @see {@link entries}\n */\n// This returns a Partial<> because we can't guarantee that every key is present when K is a\n// string literal union (which is what Record<K, V> would be saying). As a side effect, this means\n// that using this with branded IDs will force null checks downstream, which is good practice.\nexport function fromEntries<K extends string, V>(entries_: Iterable<[K, V]>): Partial<Record<K, V>> {\n return Object.fromEntries(entries_) as Partial<Record<K, V>>;\n}\n\n/**\n * Type safe version of Object.keys()\n */\nexport function keys<K extends string>(o: Record<K, unknown>): K[];\nexport function keys<T>(o: T): (keyof T)[];\nexport function keys(o: object) {\n return Object.keys(o);\n}\n\n/**\n * Type safe version of Object.values()\n */\nexport function values<V extends string>(o: Record<keyof any, V>): V[];\nexport function values<T>(o: T): T[keyof T][];\nexport function values(o: object) {\n return Object.values(o);\n}\n\nexport function mapValues<T extends object, U>(\n o: T,\n fn: (value: T[keyof T]) => U,\n): {\n [K in keyof T]: U;\n} {\n return Object.fromEntries(Object.entries(o).map(([key, value]) => [key, fn(value)])) as any;\n}\n", "import type { Project, NodeGraph } from '../../index.js';\nimport { doubleCheckProject } from './serializationUtils.js';\n// @ts-ignore\nimport * as yaml from 'yaml';\n\nexport function projectV2Deserializer(data: unknown): Project {\n if (typeof data !== 'string') {\n throw new Error('Project v2 deserializer requires a string');\n }\n\n const project = yaml.parse(data) as { version: number; data: Project };\n\n if (project.version !== 2) {\n throw new Error('Project v2 deserializer requires a version 2 project');\n }\n\n doubleCheckProject(project.data);\n\n return project.data;\n}\n\nexport function graphV2Deserializer(data: unknown): NodeGraph {\n if (typeof data !== 'string') {\n throw new Error('Graph v2 deserializer requires a string');\n }\n\n const graph = yaml.parse(data) as { version: number; data: NodeGraph };\n\n if (graph.version !== 2) {\n throw new Error('Graph v2 deserializer requires a version 2 graph');\n }\n\n return graph.data;\n}\n", "import type { Project, NodeGraph } from '../../index.js';\nimport { doubleCheckProject } from './serializationUtils.js';\n\nexport function projectV1Deserializer(data: unknown): Project {\n if (typeof data !== 'string') {\n throw new Error('Project v1 deserializer requires a string');\n }\n\n const project = JSON.parse(data);\n\n doubleCheckProject(project);\n\n return project;\n}\n\nexport function graphV1Deserializer(data: unknown): NodeGraph {\n if (typeof data !== 'string') {\n throw new Error('Graph v1 deserializer requires a string');\n }\n\n const graph = JSON.parse(data);\n\n if (!graph.nodes || !graph.connections) {\n throw new Error('Invalid graph file');\n }\n\n return graph;\n}\n", "import type { PortId } from '../model/NodeBase.js';\n\nexport const Warnings = '__internalPort_Warnings';\nexport const WarningsPort = Warnings as unknown as PortId;\n", "import type { Outputs } from '../index.js';\nimport type { ArrayDataValue, StringDataValue } from '../model/DataValue.js';\nimport { expectType } from './expectType.js';\nimport { WarningsPort } from './symbols.js';\n\nexport function addWarning(outputs: Outputs, warning: string): void {\n if (!outputs[WarningsPort]) {\n outputs[WarningsPort] = { type: 'string[]', value: [] };\n }\n\n (outputs[WarningsPort] as ArrayDataValue<StringDataValue>).value.push(warning);\n}\n\nexport function getWarnings(outputs: Outputs | undefined): string[] | undefined {\n if (!outputs?.[WarningsPort]) {\n return undefined;\n }\n\n return expectType(outputs[WarningsPort], 'string[]');\n}\n", "export async function uint8ArrayToBase64(uint8Array: Uint8Array) {\n if (typeof window === 'undefined') {\n // Node executor\n return Buffer.from(uint8Array).toString('base64');\n } else {\n // Browser executor\n const blob = new Blob([uint8Array], { type: 'application/octet-stream' });\n const dataUrl = await new Promise<string>((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as string);\n reader.readAsDataURL(blob);\n });\n return dataUrl.split(',')[1];\n }\n}\n\nexport function base64ToUint8Array(base64: string) {\n const binaryString = atob(base64);\n const len = binaryString.length;\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\n", "import type { DataType, GetDataValue, Inputs, PortId } from '../index.js';\nimport { coerceTypeOptional } from './coerceType.js';\nimport { entries } from './typeSafety.js';\n\nexport function getInputOrData<Data extends object, T extends DataType = 'string'>(\n data: Data,\n inputs: Inputs,\n inputAndDataKey: keyof Data & string,\n type?: T,\n useInputToggleDataKey?: keyof Data & string,\n): GetDataValue<T>['value'] {\n if (!useInputToggleDataKey) {\n const capitalized = inputAndDataKey[0]!.toUpperCase() + inputAndDataKey.slice(1);\n const key = `use${capitalized}Input` as keyof Data & string;\n useInputToggleDataKey = key;\n }\n const value =\n data[useInputToggleDataKey] && inputs[inputAndDataKey as PortId] != null\n ? coerceTypeOptional(inputs[inputAndDataKey as PortId], type ?? 'string') ?? data[inputAndDataKey]\n : data[inputAndDataKey];\n return value as GetDataValue<T>['value'];\n}\n\nexport function cleanHeaders(headers: Record<string, string>): Record<string, string> {\n return Object.fromEntries(entries(headers).filter(([key]) => key.trim()));\n}\n", "export { dedent } from 'ts-dedent';\n", "import type { RivetPlugin, Settings, StringPluginConfigurationSpec } from '../index.js';\n\nexport function getPluginConfig(plugin: RivetPlugin | undefined, settings: Settings, name: string) {\n if (!plugin) {\n return undefined;\n }\n\n const configSpec = plugin?.configSpec?.[name];\n\n if (!configSpec) {\n return undefined;\n }\n\n const pluginSettings = settings.pluginSettings?.[plugin.id];\n if (pluginSettings) {\n const value = pluginSettings[name];\n if (!value || typeof value !== 'string') {\n return undefined;\n }\n\n return value;\n }\n\n const envFallback = (configSpec as StringPluginConfigurationSpec).pullEnvironmentVariable;\n const envFallbackName = envFallback === true ? name : envFallback;\n\n if (envFallbackName && settings.pluginEnv?.[envFallbackName]) {\n return settings.pluginEnv[envFallbackName];\n }\n\n return undefined;\n}\n", "import { nanoid } from 'nanoid/non-secure';\n\nexport function newId<T extends string>(): T {\n return nanoid() as T;\n}\n", "/** Let the user type things like \\n and \\t in the editor, and they'll be replaced with the actual characters. */\nexport function handleEscapeCharacters(inputString: string): string {\n // Would use negative lookbehind but not supported in some recent safari versions >.<\n return inputString\n .replace(/([^\\\\]|^)\\\\n/g, '$1\\n')\n .replace(/([^\\\\]|^)\\\\t/g, '$1\\t')\n .replace(/([^\\\\]|^)\\\\r/g, '$1\\r')\n .replace(/([^\\\\]|^)\\\\f/g, '$1\\f')\n .replace(/([^\\\\]|^)\\\\b/g, '$1\\b')\n .replace(/([^\\\\]|^)\\\\v/g, '$1\\v');\n}\n", "import { isArrayDataType, type DataType } from '../model/DataValue.js';\n\nexport function isDataTypeAccepted(\n inputType: DataType | Readonly<DataType[]>,\n accepted: DataType | Readonly<DataType[]>,\n) {\n inputType = Array.isArray(inputType) ? inputType : [inputType];\n accepted = Array.isArray(accepted) ? accepted : [accepted];\n\n for (const input of inputType) {\n for (const accept of accepted) {\n if (isDataTypeCompatible(input, accept)) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function isDataTypeCompatible(inputType: DataType, accepted: DataType): boolean {\n // Any is always compatible on either side\n if (inputType === 'any' || accepted === 'any') {\n return true;\n }\n\n // If they're both arrays, and either is 'any[]', it's compatible\n if (isArrayDataType(inputType) && isArrayDataType(accepted) && (inputType === 'any[]' || accepted === 'any[]')) {\n return true;\n }\n\n if (inputType === accepted) {\n return true;\n }\n\n return false;\n}\n", "export const DEFAULT_CHAT_ENDPOINT = 'https://api.openai.com/v1/chat/completions';\n\nexport const DEFAULT_CHAT_NODE_TIMEOUT = 30_000;\n", "import { max, range, sum, uniqBy } from 'lodash-es';\nimport {\n type DataValue,\n type ArrayDataValue,\n type AnyDataValue,\n type StringArrayDataValue,\n type ControlFlowExcludedDataValue,\n isArrayDataValue,\n arrayizeDataValue,\n type ScalarOrArrayDataValue,\n getScalarTypeOf,\n} from './DataValue.js';\nimport type {\n ChartNode,\n NodeConnection,\n NodeId,\n NodeInputDefinition,\n NodeOutputDefinition,\n PortId,\n} from './NodeBase.js';\nimport type { GraphId, NodeGraph } from './NodeGraph.js';\nimport type { NodeImpl } from './NodeImpl.js';\nimport type { UserInputNode, UserInputNodeImpl } from './nodes/UserInputNode.js';\nimport PQueueImport from 'p-queue';\nimport { getError } from '../utils/errors.js';\nimport Emittery from 'emittery';\nimport { entries, fromEntries, values } from '../utils/typeSafety.js';\nimport { isNotNull } from '../utils/genericUtilFunctions.js';\nimport type { Project } from './Project.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport type { InternalProcessContext, ProcessContext, ProcessId } from './ProcessContext.js';\nimport type { ExecutionRecorder } from '../recording/ExecutionRecorder.js';\nimport { P, match } from 'ts-pattern';\nimport type { Opaque } from 'type-fest';\nimport { coerceTypeOptional } from '../utils/coerceType.js';\nimport { globalRivetNodeRegistry } from './Nodes.js';\nimport type { BuiltInNodeType, BuiltInNodes } from './Nodes.js';\nimport type { NodeRegistration } from './NodeRegistration.js';\nimport { getPluginConfig } from '../utils/index.js';\nimport { GptTokenizerTokenizer } from '../integrations/GptTokenizerTokenizer.js';\n\n// CJS compatibility, gets default.default for whatever reason\nlet PQueue = PQueueImport;\nif (typeof PQueue !== 'function') {\n PQueue = (PQueueImport as any).default;\n}\n\nexport type ProcessEvents = {\n /** Called when processing has started. */\n start: { project: Project; startGraph: NodeGraph; inputs: GraphInputs; contextValues: Record<string, DataValue> };\n\n /** Called when a graph or subgraph has started. */\n graphStart: { graph: NodeGraph; inputs: GraphInputs };\n\n /** Called when a graph or subgraph has errored. */\n graphError: { graph: NodeGraph; error: Error | string };\n\n /** Called when a graph or a subgraph has finished. */\n graphFinish: { graph: NodeGraph; outputs: GraphOutputs };\n\n /** Called when a graph has been aborted. */\n graphAbort: { successful: boolean; graph: NodeGraph; error?: Error | string };\n\n /** Called when a node has started processing, with the input values for the node. */\n nodeStart: { node: ChartNode; inputs: Inputs; processId: ProcessId };\n\n /** Called when a node has finished processing, with the output values for the node. */\n nodeFinish: { node: ChartNode; outputs: Outputs; processId: ProcessId };\n\n /** Called when a node has errored during processing. */\n nodeError: { node: ChartNode; error: Error | string; processId: ProcessId };\n\n /** Called when a node has been excluded from processing. */\n nodeExcluded: { node: ChartNode; processId: ProcessId; inputs: Inputs; outputs: Outputs; reason: string };\n\n /** Called when a user input node requires user input. Call the callback when finished, or call userInput() on the GraphProcessor with the results. */\n userInput: {\n node: UserInputNode;\n inputs: Inputs;\n callback: (values: StringArrayDataValue) => void;\n processId: ProcessId;\n };\n\n /** Called when a node has partially processed, with the current partial output values for the node. */\n partialOutput: { node: ChartNode; outputs: Outputs; index: number; processId: ProcessId };\n\n /** Called when the outputs of a node have been cleared entirely. If processId is present, only the one process() should be cleared. */\n nodeOutputsCleared: { node: ChartNode; processId?: ProcessId };\n\n /** Called when the root graph has errored. The root graph will also throw. */\n error: { error: Error | string };\n\n /** Called when processing has completed. */\n done: { results: GraphOutputs };\n\n /** Called when processing has been aborted. */\n abort: { successful: boolean; error?: string | Error };\n\n /** Called when processing has finished either successfully or unsuccessfully. */\n finish: void;\n\n /** Called for trace level logs. */\n trace: string;\n\n /** Called when the graph has been paused. */\n pause: void;\n\n /** Called when the graph has been resumed. */\n resume: void;\n\n /** Called when a global variable has been set in a graph. */\n globalSet: { id: string; value: ScalarOrArrayDataValue; processId: ProcessId };\n\n /** Called when an AbortController has been created. Used by node to increase the max event listeners. */\n newAbortController: AbortController;\n} & {\n /** Listen for any user event. */\n [key: `userEvent:${string}`]: DataValue | undefined;\n} & {\n [key: `globalSet:${string}`]: ScalarOrArrayDataValue | undefined;\n};\n\nexport type ProcessEvent = {\n [P in keyof ProcessEvents]: { type: P } & ProcessEvents[P];\n}[keyof ProcessEvents];\n\nexport type GraphOutputs = Record<string, DataValue>;\nexport type GraphInputs = Record<string, DataValue>;\n\nexport type NodeResults = Map<NodeId, Outputs>;\nexport type Inputs = Record<PortId, DataValue | undefined>;\nexport type Outputs = Record<PortId, DataValue | undefined>;\n\nexport type ExternalFunctionProcessContext = Omit<InternalProcessContext, 'setGlobal'>;\n\nexport type ExternalFunction = (\n context: ExternalFunctionProcessContext,\n ...args: unknown[]\n) => Promise<DataValue & { cost?: number }>;\n\nexport type RaceId = Opaque<string, 'RaceId'>;\n\nexport type LoopInfo = AttachedNodeDataItem & {\n /** ID of the controller of the loop */\n loopControllerId: NodeId;\n\n /** Nodes add themselves to this as the loop processes */\n nodes: Set<NodeId>;\n\n iterationCount: number;\n};\n\nexport type AttachedNodeDataItem = {\n propagate: boolean | ((parent: ChartNode, connections: NodeConnection[]) => boolean);\n};\n\nexport type AttachedNodeData = {\n loopInfo?: LoopInfo;\n races?: {\n propagate: boolean;\n raceIds: RaceId[];\n\n // The race is completed by some branch\n completed: boolean;\n };\n\n [key: string]: AttachedNodeDataItem | undefined;\n};\n\nexport class GraphProcessor {\n // Per-instance state\n readonly #graph: NodeGraph;\n readonly #project: Project;\n readonly #nodesById: Record<NodeId, ChartNode>;\n readonly #nodeInstances: Record<NodeId, NodeImpl<ChartNode>>;\n readonly #connections: Record<NodeId, NodeConnection[]>;\n readonly #definitions: Record<NodeId, { inputs: NodeInputDefinition[]; outputs: NodeOutputDefinition[] }>;\n readonly #emitter: Emittery<ProcessEvents> = new Emittery();\n #running = false;\n #isSubProcessor = false;\n readonly #scc: ChartNode[][];\n readonly #nodesNotInCycle: ChartNode[];\n #externalFunctions: Record<string, ExternalFunction> = {};\n slowMode = false;\n #isPaused = false;\n #parent: GraphProcessor | undefined;\n readonly #registry: NodeRegistration;\n id = nanoid();\n\n executor?: 'nodejs' | 'browser';\n\n /** If set, specifies the node(s) that the graph will run TO, instead of the nodes without any dependents. */\n runToNodeIds?: NodeId[];\n\n /** The node that is executing this graph, almost always a subgraph node. Undefined for root. */\n #executor:\n | {\n nodeId: NodeId;\n index: number;\n processId: ProcessId;\n }\n | undefined;\n\n /** The interval between nodeFinish events when playing back a recording. I.e. how fast the playback is. */\n recordingPlaybackChatLatency = 1000;\n\n warnOnInvalidGraph = false;\n\n // Per-process state\n #erroredNodes: Map<NodeId, string> = undefined!;\n #remainingNodes: Set<NodeId> = undefined!;\n #visitedNodes: Set<NodeId> = undefined!;\n #currentlyProcessing: Set<NodeId> = undefined!;\n #context: ProcessContext = undefined!;\n #nodeResults: NodeResults = undefined!;\n #abortController: AbortController = undefined!;\n #processingQueue: PQueueImport = undefined!;\n #graphInputs: GraphInputs = undefined!;\n #graphOutputs: GraphOutputs = undefined!;\n #executionCache: Map<string, unknown> = undefined!;\n #queuedNodes: Set<NodeId> = undefined!;\n #loopControllersSeen: Set<NodeId> = undefined!;\n #subprocessors: Set<GraphProcessor> = undefined!;\n #contextValues: Record<string, DataValue> = undefined!;\n #globals: Map<string, ScalarOrArrayDataValue> = undefined!;\n #attachedNodeData: Map<NodeId, AttachedNodeData> = undefined!;\n #aborted = false;\n #abortSuccessfully = false;\n #abortError: Error | string | undefined = undefined;\n #totalCost: number = 0;\n #ignoreNodes: Set<NodeId> = undefined!;\n\n #nodeAbortControllers = new Map<`${NodeId}-${ProcessId}`, AbortController>();\n\n /** User input nodes that are pending user input. */\n #pendingUserInputs: Record<\n NodeId,\n { resolve: (values: StringArrayDataValue) => void; reject: (error: unknown) => void }\n > = undefined!;\n\n get isRunning() {\n return this.#running;\n }\n\n constructor(project: Project, graphId?: GraphId, registry?: NodeRegistration) {\n this.#project = project;\n const graph = graphId\n ? project.graphs[graphId]\n : project.metadata.mainGraphId\n ? project.graphs[project.metadata.mainGraphId]\n : undefined;\n\n if (!graph) {\n throw new Error(`Graph ${graphId} not found in project`);\n }\n this.#graph = graph;\n\n this.#nodeInstances = {};\n this.#connections = {};\n this.#nodesById = {};\n this.#registry = registry ?? (globalRivetNodeRegistry as unknown as NodeRegistration);\n\n this.#emitter.bindMethods(this as any, ['on', 'off', 'once', 'onAny', 'offAny']);\n\n // Create node instances and store them in a lookup table\n for (const node of this.#graph.nodes) {\n this.#nodeInstances[node.id] = this.#registry.createDynamicImpl(node);\n this.#nodesById[node.id] = node;\n }\n\n // Store connections in a lookup table\n for (const conn of this.#graph.connections) {\n if (!this.#nodesById[conn.inputNodeId] || !this.#nodesById[conn.outputNodeId]) {\n if (this.warnOnInvalidGraph) {\n if (!this.#nodesById[conn.inputNodeId]) {\n console.warn(\n `Missing node ${conn.inputNodeId} in graph ${graphId} (connection from ${\n this.#nodesById[conn.outputNodeId]?.title\n })`,\n );\n } else {\n console.warn(\n `Missing node ${conn.outputNodeId} in graph ${graphId} (connection to ${\n this.#nodesById[conn.inputNodeId]?.title\n }) `,\n );\n }\n }\n continue;\n }\n\n this.#connections[conn.inputNodeId] ??= [];\n this.#connections[conn.outputNodeId] ??= [];\n this.#connections[conn.inputNodeId]!.push(conn);\n this.#connections[conn.outputNodeId]!.push(conn);\n }\n\n // Store input and output definitions in a lookup table\n this.#definitions = {};\n for (const node of this.#graph.nodes) {\n const connectionsForNode = this.#connections[node.id] ?? [];\n const inputDefs = this.#nodeInstances[node.id]!.getInputDefinitions(\n connectionsForNode,\n this.#nodesById,\n this.#project,\n );\n\n const outputDefs = this.#nodeInstances[node.id]!.getOutputDefinitions(\n connectionsForNode,\n this.#nodesById,\n this.#project,\n );\n\n this.#definitions[node.id] = { inputs: inputDefs, outputs: outputDefs };\n\n // Find all invalid connections to or from the node, then remove them from consideration\n const invalidConnections = connectionsForNode.filter((connection) => {\n if (connection.inputNodeId === node.id) {\n const inputDef = inputDefs.find((def) => def.id === connection.inputId);\n\n if (!inputDef) {\n if (this.warnOnInvalidGraph) {\n const nodeFrom = this.#nodesById[connection.outputNodeId];\n console.warn(\n `[Warn] Invalid connection going from \"${nodeFrom?.title}\".${connection.outputId} to \"${node.title}\".${connection.inputId}`,\n );\n }\n\n return true;\n }\n } else {\n const outputDef = outputDefs.find((def) => def.id === connection.outputId);\n\n if (!outputDef) {\n if (this.warnOnInvalidGraph) {\n const nodeTo = this.#nodesById[connection.inputNodeId];\n console.warn(\n `[Warn] Invalid connection going from \"${node.title}\".${connection.outputId} to \"${nodeTo?.title}\".${connection.inputId}`,\n );\n }\n\n return true;\n }\n }\n\n return false;\n });\n\n for (const connections of values(this.#connections)) {\n for (const invalidConnection of invalidConnections) {\n const index = connections.indexOf(invalidConnection);\n if (index !== -1) {\n connections.splice(index, 1);\n }\n }\n }\n }\n\n this.#scc = this.#tarjanSCC();\n this.#nodesNotInCycle = this.#scc.filter((cycle) => cycle.length === 1).flat();\n\n this.setExternalFunction('echo', async (value) => ({ type: 'any', value }) satisfies DataValue);\n\n this.#emitter.on('globalSet', ({ id, value }) => {\n this.#emitter.emit(`globalSet:${id}`, value);\n });\n }\n\n on = undefined! as Emittery<ProcessEvents>['on'];\n off = undefined! as Emittery<ProcessEvents>['off'];\n once = undefined! as Emittery<ProcessEvents>['once'];\n onAny = undefined! as Emittery<ProcessEvents>['onAny'];\n offAny = undefined! as Emittery<ProcessEvents>['offAny'];\n\n readonly #onUserEventHandlers: Map<(event: DataValue | undefined) => void, Function> = new Map();\n\n onUserEvent(onEvent: string, listener: (event: DataValue | undefined) => void): void {\n const handler = (event: string, value: unknown) => {\n if (event === `userEvent:${onEvent}`) {\n listener(value as DataValue | undefined);\n }\n };\n\n this.#onUserEventHandlers.set(listener, handler);\n this.#emitter.onAny(handler);\n }\n\n offUserEvent(listener: (data: DataValue | undefined) => void): void {\n const internalHandler = this.#onUserEventHandlers.get(listener);\n this.#emitter.offAny(internalHandler as any);\n }\n\n userInput(nodeId: NodeId, values: StringArrayDataValue): void {\n const pending = this.#pendingUserInputs[nodeId];\n if (pending) {\n pending.resolve(values as StringArrayDataValue);\n delete this.#pendingUserInputs[nodeId];\n }\n\n for (const processor of this.#subprocessors) {\n processor.userInput(nodeId, values);\n }\n }\n\n setExternalFunction(name: string, fn: ExternalFunction): void {\n this.#externalFunctions[name] = fn;\n }\n\n async abort(successful: boolean = false, error?: Error | string): Promise<void> {\n if (!this.#running || this.#aborted) {\n return Promise.resolve();\n }\n\n this.#abortController.abort();\n this.#abortSuccessfully = successful;\n this.#abortError = error;\n\n this.#emitter.emit('graphAbort', { successful, error, graph: this.#graph });\n\n if (!this.#isSubProcessor) {\n this.#emitter.emit('abort', { successful, error });\n }\n\n await this.#processingQueue.onIdle();\n }\n\n pause(): void {\n if (this.#isPaused === false) {\n this.#isPaused = true;\n this.#emitter.emit('pause', void 0);\n }\n }\n\n resume(): void {\n if (this.#isPaused) {\n this.#isPaused = false;\n this.#emitter.emit('resume', void 0);\n }\n }\n\n setSlowMode(slowMode: boolean): void {\n this.slowMode = slowMode;\n }\n\n async #waitUntilUnpaused(): Promise<void> {\n if (!this.#isPaused) {\n return;\n }\n\n await this.#emitter.once('resume');\n }\n\n async *events(): AsyncGenerator<ProcessEvent> {\n for await (const [event, data] of this.#emitter.anyEvent()) {\n yield { type: event, ...(data as any) };\n\n if (event === 'finish') {\n break;\n }\n }\n }\n\n async replayRecording(recorder: ExecutionRecorder): Promise<GraphOutputs> {\n const { events } = recorder;\n\n this.#initProcessState();\n\n try {\n const nodesByIdAllGraphs: Record<NodeId, ChartNode> = {};\n for (const graph of Object.values(this.#project.graphs)) {\n for (const node of graph.nodes) {\n nodesByIdAllGraphs[node.id] = node;\n }\n }\n\n const getGraph = (graphId: GraphId) => {\n const graph = this.#project.graphs[graphId];\n if (!graph) {\n throw new Error(`Mismatch between project and recording: graph ${graphId} not found in project`);\n }\n return graph;\n };\n\n const getNode = (nodeId: NodeId) => {\n const node = nodesByIdAllGraphs[nodeId];\n\n if (!node) {\n throw new Error(`Mismatch between project and recording: node ${nodeId} not found in any graph in project`);\n }\n\n return node;\n };\n\n for (const event of events) {\n if (this.#aborted) {\n break;\n }\n\n await this.#waitUntilUnpaused();\n\n await match(event)\n .with({ type: 'start' }, ({ data }) => {\n this.#emitter.emit('start', {\n project: this.#project,\n contextValues: data.contextValues,\n inputs: data.inputs,\n startGraph: getGraph(data.startGraph),\n });\n this.#contextValues = data.contextValues;\n this.#graphInputs = data.inputs;\n })\n .with({ type: 'abort' }, ({ data }) => {\n this.#emitter.emit('abort', data);\n })\n .with({ type: 'pause' }, () => {})\n .with({ type: 'resume' }, () => {})\n .with({ type: 'done' }, ({ data }) => {\n this.#emitter.emit('done', data);\n this.#graphOutputs = data.results;\n this.#running = false;\n })\n .with({ type: 'error' }, ({ data }) => {\n this.#emitter.emit('error', data);\n })\n .with({ type: 'globalSet' }, ({ data }) => {\n this.#emitter.emit('globalSet', data);\n })\n .with({ type: 'trace' }, ({ data }) => {\n this.#emitter.emit('trace', data);\n })\n .with({ type: 'graphStart' }, ({ data }) => {\n this.#emitter.emit('graphStart', {\n graph: getGraph(data.graphId),\n inputs: data.inputs,\n });\n })\n .with({ type: 'graphFinish' }, ({ data }) => {\n this.#emitter.emit('graphFinish', {\n graph: getGraph(data.graphId),\n outputs: data.outputs,\n });\n })\n .with({ type: 'graphError' }, ({ data }) => {\n this.#emitter.emit('graphError', {\n graph: getGraph(data.graphId),\n error: data.error,\n });\n })\n .with({ type: 'graphAbort' }, ({ data }) => {\n this.#emitter.emit('graphAbort', {\n graph: getGraph(data.graphId),\n error: data.error,\n successful: data.successful,\n });\n })\n .with({ type: 'nodeStart' }, async ({ data }) => {\n const node = getNode(data.nodeId);\n this.#emitter.emit('nodeStart', {\n node: getNode(data.nodeId),\n inputs: data.inputs,\n processId: data.processId,\n });\n\n // Every time a chat node starts, we wait for the playback interval\n if (node.type === 'chat') {\n await new Promise((resolve) => setTimeout(resolve, this.recordingPlaybackChatLatency));\n }\n })\n .with({ type: 'nodeFinish' }, ({ data }) => {\n const node = getNode(data.nodeId);\n this.#emitter.emit('nodeFinish', {\n node,\n outputs: data.outputs,\n processId: data.processId,\n });\n\n this.#nodeResults.set(data.nodeId, data.outputs);\n this.#visitedNodes.add(data.nodeId);\n })\n .with({ type: 'nodeError' }, ({ data }) => {\n this.#emitter.emit('nodeError', {\n node: getNode(data.nodeId),\n error: data.error,\n processId: data.processId,\n });\n\n this.#erroredNodes.set(data.nodeId, data.error);\n this.#visitedNodes.add(data.nodeId);\n })\n .with({ type: 'nodeExcluded' }, ({ data }) => {\n this.#emitter.emit('nodeExcluded', {\n node: getNode(data.nodeId),\n processId: data.processId,\n inputs: data.inputs,\n outputs: data.outputs,\n reason: data.reason,\n });\n\n this.#visitedNodes.add(data.nodeId);\n })\n .with({ type: 'nodeOutputsCleared' }, () => {})\n .with({ type: 'partialOutput' }, () => {})\n .with({ type: 'userInput' }, ({ data }) => {\n this.#emitter.emit('userInput', {\n callback: undefined!,\n inputs: data.inputs,\n node: getNode(data.nodeId) as UserInputNode,\n processId: data.processId,\n });\n })\n .with({ type: P.string.startsWith('globalSet:') }, ({ type, data }) => {\n this.#emitter.emit(type, data);\n })\n .with({ type: P.string.startsWith('userEvent:') }, ({ type, data }) => {\n this.#emitter.emit(type, data);\n })\n .with({ type: 'newAbortController' }, () => {})\n .with({ type: 'finish' }, () => {\n this.#emitter.emit('finish', undefined);\n })\n// .with(undefined, () => {})\n .exhaustive();\n }\n } catch (err) {\n this.#emitter.emit('error', { error: getError(err) });\n } finally {\n this.#running = false;\n }\n\n return this.#graphOutputs;\n }\n\n #initProcessState() {\n this.#running = true;\n this.#nodeResults = new Map();\n this.#erroredNodes = new Map();\n this.#visitedNodes = new Set();\n this.#currentlyProcessing = new Set();\n this.#remainingNodes = new Set(this.#graph.nodes.map((n) => n.id));\n this.#pendingUserInputs = {};\n this.#processingQueue = new PQueue({ concurrency: Infinity });\n this.#graphOutputs = {};\n this.#executionCache ??= new Map();\n this.#queuedNodes = new Set();\n this.#loopControllersSeen = new Set();\n this.#subprocessors = new Set();\n this.#attachedNodeData = new Map();\n this.#globals ??= new Map();\n this.#ignoreNodes = new Set();\n\n this.#abortController = this.#newAbortController();\n this.#abortController.signal.addEventListener('abort', () => {\n this.#aborted = true;\n });\n this.#aborted = false;\n this.#abortError = undefined;\n this.#abortSuccessfully = false;\n this.#nodeAbortControllers = new Map();\n }\n\n /** Main function for running a graph. Runs a graph and returns the outputs from the output nodes of the graph. */\n async processGraph(\n /** Required and optional context available to the nodes and all subgraphs. */\n context: ProcessContext,\n\n /** Inputs to the main graph. You should pass all inputs required by the GraphInputNodes of the graph. */\n inputs: Record<string, DataValue> = {},\n\n /** Contextual data available to all graphs and subgraphs. Kind of like react context, avoids drilling down data into subgraphs. Be careful when using it. */\n contextValues: Record<string, DataValue> = {},\n ): Promise<GraphOutputs> {\n try {\n if (this.#running) {\n throw new Error('Cannot process graph while already processing');\n }\n\n this.#initProcessState();\n\n this.#context = context;\n this.#graphInputs = inputs;\n this.#contextValues ??= contextValues;\n\n if (this.#context.tokenizer) {\n this.#context.tokenizer.on('error', (error) => {\n this.#emitter.emit('error', { error });\n });\n }\n\n if (!this.#isSubProcessor) {\n this.#emitter.emit('start', {\n contextValues: this.#contextValues,\n inputs: this.#graphInputs,\n project: this.#project,\n startGraph: this.#graph,\n });\n }\n\n this.#emitter.emit('graphStart', { graph: this.#graph, inputs: this.#graphInputs });\n\n const startNodes = this.runToNodeIds\n ? this.#graph.nodes.filter((node) => this.runToNodeIds?.includes(node.id))\n : this.#graph.nodes.filter((node) => this.#outputNodesFrom(node).nodes.length === 0);\n\n await this.#waitUntilUnpaused();\n\n for (const startNode of startNodes) {\n this.#processingQueue.add(async () => {\n await this.#fetchNodeDataAndProcessNode(startNode);\n });\n }\n\n // Anything not queued at this phase here should be ignored\n if (this.runToNodeIds) {\n // For safety, we'll only activate this if runToNodeIds is set, in case there are bugs in the first pass\n for (const node of this.#graph.nodes) {\n if (this.#queuedNodes.has(node.id) === false) {\n this.#ignoreNodes.add(node.id);\n }\n }\n }\n\n await this.#processingQueue.onIdle();\n\n // If we've aborted successfully, we can treat the graph like it succeeded\n const erroredNodes = [...this.#erroredNodes.entries()].filter(([nodeId]) => {\n const erroredNodeAttachedData = this.#getAttachedDataTo(nodeId);\n return erroredNodeAttachedData.races == null || erroredNodeAttachedData.races.completed === false;\n });\n if (erroredNodes.length && !this.#abortSuccessfully) {\n const error =\n this.#abortError ??\n Error(\n `Graph ${this.#graph.metadata!.name} (${\n this.#graph.metadata!.id\n }) failed to process due to errors in nodes: ${erroredNodes\n .map(([nodeId, error]) => `${this.#nodesById[nodeId]!.title} (${nodeId}): ${error}`)\n .join(', ')}`,\n );\n\n this.#emitter.emit('graphError', { graph: this.#graph, error });\n\n if (!this.#isSubProcessor) {\n this.#emitter.emit('error', { error });\n }\n\n throw error;\n }\n\n if (this.#graphOutputs['cost' as PortId] == null) {\n this.#graphOutputs['cost' as PortId] = {\n type: 'number',\n value: this.#totalCost,\n };\n }\n\n const outputValues = this.#graphOutputs;\n\n this.#running = false;\n\n this.#emitter.emit('graphFinish', { graph: this.#graph, outputs: outputValues });\n\n if (!this.#isSubProcessor) {\n this.#emitter.emit('done', { results: outputValues });\n this.#emitter.emit('finish', undefined);\n }\n\n return outputValues;\n } finally {\n this.#running = false;\n\n if (!this.#isSubProcessor) {\n this.#emitter.emit('finish', undefined);\n }\n }\n }\n\n async #fetchNodeDataAndProcessNode(node: ChartNode): Promise<void> {\n if (this.#currentlyProcessing.has(node.id) || this.#queuedNodes.has(node.id)) {\n return;\n }\n\n if (this.#nodeResults.has(node.id) || this.#erroredNodes.has(node.id)) {\n return;\n }\n\n const inputNodes = this.#inputNodesTo(node);\n\n // Check if all input nodes are free of errors\n for (const inputNode of inputNodes) {\n if (this.#erroredNodes.has(inputNode.id)) {\n return;\n }\n }\n\n // Check if all required inputs have connections and if the connected output nodes have been visited\n const connections = this.#connections[node.id] ?? [];\n const inputsReady = this.#definitions[node.id]!.inputs.every((input) => {\n const connectionToInput = connections?.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);\n return connectionToInput || !input.required;\n });\n\n if (!inputsReady) {\n return;\n }\n this.#emitter.emit(\n 'trace',\n `Node ${node.title} has required inputs nodes: ${inputNodes.map((n) => n.title).join(', ')}`,\n );\n\n const attachedData = this.#getAttachedDataTo(node);\n\n if (node.type === 'raceInputs' || attachedData.races) {\n for (const inputNode of inputNodes) {\n const inputNodeAttachedData = this.#getAttachedDataTo(inputNode);\n const raceIds = new Set<RaceId>([...(attachedData.races?.raceIds ?? ([] as RaceId[]))]);\n\n if (node.type === 'raceInputs') {\n raceIds.add(`race-${node.id}` as RaceId);\n }\n\n inputNodeAttachedData.races = {\n propagate: false,\n raceIds: [...raceIds],\n completed: false,\n };\n }\n }\n\n this.#queuedNodes.add(node.id);\n\n this.#processingQueue.addAll(\n inputNodes.map((inputNode) => {\n return async () => {\n this.#emitter.emit('trace', `Fetching required data for node ${inputNode.title} (${inputNode.id})`);\n await this.#fetchNodeDataAndProcessNode(inputNode);\n };\n }),\n );\n\n await this.#processNodeIfAllInputsAvailable(node);\n }\n\n /** If all inputs are present, all conditions met, processes the node. */\n async #processNodeIfAllInputsAvailable(node: ChartNode): Promise<void> {\n const builtInNode = node as BuiltInNodes;\n\n if (this.#ignoreNodes.has(node.id)) {\n this.#emitter.emit('trace', `Node ${node.title} is ignored`);\n return;\n }\n\n if (this.#currentlyProcessing.has(node.id)) {\n this.#emitter.emit('trace', `Node ${node.title} is already being processed`);\n return;\n }\n\n // For a loop controller, it can run multiple times, otherwise we already processed this node so bail out\n if (this.#visitedNodes.has(node.id) && node.type !== 'loopController') {\n this.#emitter.emit('trace', `Node ${node.title} has already been processed`);\n return;\n }\n\n if (this.#erroredNodes.has(node.id)) {\n this.#emitter.emit('trace', `Node ${node.title} has already errored`);\n return;\n }\n\n const inputNodes = this.#inputNodesTo(node);\n\n // Check if all input nodes are free of errors\n for (const inputNode of inputNodes) {\n if (this.#erroredNodes.has(inputNode.id)) {\n this.#emitter.emit('trace', `Node ${node.title} has errored input node ${inputNode.title}`);\n return;\n }\n }\n\n // Check if all required inputs have connections and if the connected output nodes have been visited\n const connections = this.#connections[node.id] ?? [];\n const inputsReady = this.#definitions[node.id]!.inputs.every((input) => {\n const connectionToInput = connections?.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);\n return connectionToInput || !input.required;\n });\n\n if (!inputsReady) {\n this.#emitter.emit(\n 'trace',\n `Node ${node.title} has required inputs nodes: ${inputNodes.map((n) => n.title).join(', ')}`,\n );\n return;\n }\n\n // Excluded because control flow is still in a loop - difference between \"will not execute\" and \"has not executed yet\"\n const inputValues = this.#getInputValuesForNode(node);\n\n if (this.#excludedDueToControlFlow(node, inputValues, nanoid() as ProcessId, 'loop-not-broken')) {\n this.#emitter.emit('trace', `Node ${node.title} is excluded due to control flow`);\n return;\n }\n\n let waitingForInputNode: false | string = false;\n const anyInputIsValid = Object.values(inputValues).some(\n (value) => value && value.type.includes('control-flow-excluded') === false,\n );\n for (const inputNode of inputNodes) {\n // For loop controllers, allow nodes in the same cycle to be not processed yet,\n // but if we're in a 2nd iteration, we do need to wait for them\n if (\n node.type === 'loopController' &&\n !this.#loopControllersSeen.has(node.id) &&\n this.#nodesAreInSameCycle(node.id, inputNode.id)\n ) {\n continue;\n }\n\n // Only one visited node required for a raceInputs node\n if (node.type === 'raceInputs' && this.#visitedNodes.has(inputNode.id) && anyInputIsValid) {\n waitingForInputNode = false;\n break;\n }\n\n if (waitingForInputNode === false && this.#visitedNodes.has(inputNode.id) === false) {\n waitingForInputNode = inputNode.title;\n }\n }\n\n if (waitingForInputNode) {\n this.#emitter.emit('trace', `Node ${node.title} is waiting for input node ${waitingForInputNode}`);\n return;\n }\n\n this.#currentlyProcessing.add(node.id);\n\n if (node.type === 'loopController') {\n this.#loopControllersSeen.add(node.id);\n }\n\n const attachedData = this.#getAttachedDataTo(node);\n\n if (attachedData.loopInfo && attachedData.loopInfo.loopControllerId !== node.id) {\n attachedData.loopInfo.nodes.add(node.id);\n }\n\n if (attachedData.races?.completed) {\n this.#emitter.emit('trace', `Node ${node.title} is part of a race that was completed`);\n return;\n }\n\n const processId = await this.#processNode(node);\n\n if (this.slowMode) {\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n\n this.#emitter.emit('trace', `Finished processing node ${node.title} (${node.id})`);\n this.#visitedNodes.add(node.id);\n this.#currentlyProcessing.delete(node.id);\n this.#remainingNodes.delete(node.id);\n\n const outputNodes = this.#outputNodesFrom(node);\n\n // Aggressive - each iteration of the loop controller, we clear everything in the same cycle as the controller\n if (node.type === 'loopController') {\n const loopControllerResults = this.#nodeResults.get(node.id)!;\n\n // If the loop controller is excluded, we have to \"break\" it or else it'll loop forever...\n const breakValue = loopControllerResults['break' as PortId];\n const didBreak =\n !(breakValue?.type === 'control-flow-excluded' && breakValue?.value === 'loop-not-broken') ??\n this.#excludedDueToControlFlow(node, this.#getInputValuesForNode(node), nanoid() as ProcessId);\n\n if (!didBreak) {\n this.#emitter.emit('trace', `Loop controller ${node.title} did not break, so we're looping again`);\n for (const loopNodeId of attachedData.loopInfo?.nodes ?? []) {\n const cycleNode = this.#nodesById[loopNodeId]!;\n this.#emitter.emit('trace', `Clearing cycle node ${cycleNode.title} (${cycleNode.id})`);\n this.#visitedNodes.delete(cycleNode.id);\n this.#currentlyProcessing.delete(cycleNode.id);\n this.#remainingNodes.add(cycleNode.id);\n this.#nodeResults.delete(cycleNode.id);\n }\n }\n }\n\n // Abort everything the race depends on - everything already executed won't\n // be aborted, but everything that hasn't will be, effectively terminating all slower branches\n if (node.type === 'raceInputs') {\n const allNodesForRace = [...this.#attachedNodeData.entries()].filter(([, { races }]) =>\n races?.raceIds.includes(`race-${node.id}` as RaceId),\n );\n for (const [nodeId] of allNodesForRace) {\n for (const [key, abortController] of this.#nodeAbortControllers.entries()) {\n if (key.startsWith(nodeId)) {\n this.#emitter.emit('trace', `Aborting node ${nodeId} because other race branch won`);\n abortController.abort();\n }\n }\n\n // Mark every attached data as completed for the race\n for (const [, nodeAttachedData] of [...this.#attachedNodeData.entries()]) {\n if (nodeAttachedData.races?.raceIds.includes(`race-${node.id}` as RaceId)) {\n nodeAttachedData.races.completed = true;\n }\n }\n }\n }\n\n let childLoopInfo = attachedData.loopInfo;\n if (builtInNode.type === 'loopController') {\n if (childLoopInfo != null && childLoopInfo.loopControllerId !== builtInNode.id) {\n this.#nodeErrored(node, new Error('Nested loops are not supported'), processId);\n return;\n }\n\n childLoopInfo = {\n propagate: (parent, connectionsFromParent) => {\n if (\n parent.type === 'loopController' &&\n connectionsFromParent.some((c) => c.outputId === ('break' as PortId))\n ) {\n return false;\n }\n return true;\n },\n\n loopControllerId: node.id,\n\n // We want to be able to clear every node that _potentially_ could run in the loop\n nodes: childLoopInfo?.nodes ?? new Set(),\n\n iterationCount: (childLoopInfo?.iterationCount ?? 0) + 1,\n };\n\n attachedData.loopInfo = childLoopInfo; // Not 100% sure if this is right - sets the childLoopInfo on the loop controller itself, probably fine?\n }\n\n for (const { node: outputNode, connections: connectionsToOutputNode } of outputNodes.connectionsToNodes) {\n const outputNodeAttachedData = this.#getAttachedDataTo(outputNode);\n\n const propagatedAttachedData = Object.entries(attachedData).filter(([, value]): boolean => {\n if (!value) {\n return false;\n }\n\n if (typeof value.propagate === 'boolean') {\n return value.propagate;\n }\n\n return value.propagate(node, connectionsToOutputNode);\n });\n\n for (const [key, value] of propagatedAttachedData) {\n outputNodeAttachedData[key] = value;\n }\n }\n\n // Node is finished, check if we can run any more nodes that depend on this one\n this.#processingQueue.addAll(\n outputNodes.nodes.map((outputNode) => async () => {\n this.#emitter.emit(\n 'trace',\n `Trying to run output node from ${node.title}: ${outputNode.title} (${outputNode.id})`,\n );\n\n await this.#processNodeIfAllInputsAvailable(outputNode);\n }),\n );\n }\n\n #getAttachedDataTo(node: ChartNode | NodeId): AttachedNodeData {\n const nodeId = typeof node === 'string' ? node : node.id;\n let nodeData = this.#attachedNodeData.get(nodeId);\n if (nodeData == null) {\n nodeData = {};\n this.#attachedNodeData.set(nodeId, nodeData);\n }\n return nodeData;\n }\n\n async #processNode(node: ChartNode) {\n const processId = nanoid() as ProcessId;\n\n if (this.#abortController.signal.aborted) {\n this.#nodeErrored(node, new Error('Processing aborted'), processId);\n return processId;\n }\n\n const inputNodes = this.#inputNodesTo(node);\n const erroredInputNodes = inputNodes.filter((inputNode) => this.#erroredNodes.has(inputNode.id));\n if (erroredInputNodes.length > 0) {\n const error = new Error(\n `Cannot process node ${node.title} (${node.id}) because it depends on errored nodes: ${erroredInputNodes\n .map((n) => `${n.title} (${n.id})`)\n .join(', ')}`,\n );\n this.#nodeErrored(node, error, processId);\n return processId;\n }\n\n if (this.#isNodeOfType('userInput', node)) {\n await this.#processUserInputNode(node, processId);\n } else if (node.isSplitRun) {\n await this.#processSplitRunNode(node, processId);\n } else {\n await this.#processNormalNode(node, processId);\n }\n\n return processId;\n }\n\n #isNodeOfType<T extends BuiltInNodes['type']>(type: T, node: ChartNode): node is Extract<BuiltInNodes, { type: T }> {\n return node.type === type;\n }\n\n async #processUserInputNode(node: UserInputNode, processId: ProcessId) {\n try {\n const inputValues = this.#getInputValuesForNode(node);\n if (this.#excludedDueToControlFlow(node, inputValues, processId)) {\n return;\n }\n\n this.#emitter.emit('nodeStart', { node, inputs: inputValues, processId });\n\n const results = await new Promise<StringArrayDataValue>((resolve, reject) => {\n this.#pendingUserInputs[node.id] = {\n resolve,\n reject,\n };\n\n this.#abortController.signal.addEventListener('abort', () => {\n delete this.#pendingUserInputs[node.id];\n reject(new Error('Processing aborted'));\n });\n\n this.#emitter.emit('userInput', {\n node,\n inputs: inputValues,\n callback: (results) => {\n resolve(results);\n\n delete this.#pendingUserInputs[node.id];\n },\n processId,\n });\n });\n\n const outputValues = (this.#nodeInstances[node.id] as UserInputNodeImpl).getOutputValuesFromUserInput(\n inputValues,\n results,\n );\n\n this.#nodeResults.set(node.id, outputValues);\n this.#visitedNodes.add(node.id);\n\n this.#emitter.emit('nodeFinish', { node, outputs: outputValues, processId });\n } catch (e) {\n this.#nodeErrored(node, e, processId);\n }\n }\n\n async #processSplitRunNode(node: ChartNode, processId: ProcessId) {\n const inputValues = this.#getInputValuesForNode(node);\n\n if (this.#excludedDueToControlFlow(node, inputValues, processId)) {\n return;\n }\n\n const splittingAmount = Math.min(\n max(values(inputValues).map((value) => (Array.isArray(value?.value) ? value?.value.length : 1))) ?? 1,\n node.splitRunMax ?? 10,\n );\n\n this.#emitter.emit('nodeStart', { node, inputs: inputValues, processId });\n\n try {\n let results: (\n | {\n type: string;\n output: Outputs;\n error?: Error;\n }\n | {\n type: string;\n error: Error;\n output?: Outputs;\n }\n )[] = [];\n\n if (node.isSplitSequential) {\n for (let i = 0; i < splittingAmount; i++) {\n if (this.#aborted) {\n throw new Error('Processing aborted');\n }\n\n const inputs = fromEntries(\n entries(inputValues).map(([port, value]) => [\n port as PortId,\n isArrayDataValue(value) ? arrayizeDataValue(value)[i] ?? undefined : value,\n ]),\n );\n\n try {\n const output = await this.#processNodeWithInputData(\n node,\n inputs as Inputs,\n i,\n processId,\n (node, partialOutputs, index) =>\n this.#emitter.emit('partialOutput', { node, outputs: partialOutputs, index, processId }),\n );\n\n if (output['cost' as PortId]?.type === 'number') {\n this.#totalCost += coerceTypeOptional(output['cost' as PortId], 'number') ?? 0;\n }\n results.push({ type: 'output', output });\n } catch (error) {\n results.push({ type: 'error', error: getError(error) });\n }\n }\n } else {\n results = await Promise.all(\n range(0, splittingAmount).map(async (i) => {\n const inputs = fromEntries(\n entries(inputValues).map(([port, value]) => [\n port as PortId,\n isArrayDataValue(value) ? arrayizeDataValue(value)[i] ?? undefined : value,\n ]),\n );\n\n try {\n const output = await this.#processNodeWithInputData(\n node,\n inputs as Inputs,\n i,\n processId,\n (node, partialOutputs, index) =>\n this.#emitter.emit('partialOutput', { node, outputs: partialOutputs, index, processId }),\n );\n\n if (output['cost' as PortId]?.type === 'number') {\n this.#totalCost += coerceTypeOptional(output['cost' as PortId], 'number') ?? 0;\n }\n return { type: 'output', output };\n } catch (error) {\n return { type: 'error', error: getError(error) };\n }\n }),\n );\n }\n\n const errors = results.filter((r) => r.type === 'error').map((r) => r.error!);\n if (errors.length === 1) {\n const e = errors[0]!;\n throw e;\n } else if (errors.length > 0) {\n throw new Error(errors.join('\\n'));\n }\n\n // Combine the parallel results into the final output\n\n // Turn a Record<PortId, DataValue[]> into a Record<PortId, AnyArrayDataValue>\n const aggregateResults = results.reduce((acc, result) => {\n for (const [portId, value] of entries(result.output!)) {\n acc[portId as PortId] ??= { type: (value?.type + '[]') as DataValue['type'], value: [] } as DataValue;\n (acc[portId as PortId] as ArrayDataValue<AnyDataValue>).value.push(value?.value);\n }\n return acc;\n }, {} as Outputs);\n\n this.#nodeResults.set(node.id, aggregateResults);\n this.#visitedNodes.add(node.id);\n this.#totalCost += sum(results.map((r) => coerceTypeOptional(r.output?.['cost' as PortId], 'number') ?? 0));\n this.#emitter.emit('nodeFinish', { node, outputs: aggregateResults, processId });\n } catch (error) {\n this.#nodeErrored(node, error, processId);\n }\n }\n\n async #processNormalNode(node: ChartNode, processId: ProcessId) {\n const inputValues = this.#getInputValuesForNode(node);\n\n if (this.#excludedDueToControlFlow(node, inputValues, processId)) {\n return;\n }\n\n this.#emitter.emit('nodeStart', { node, inputs: inputValues, processId });\n\n try {\n const outputValues = await this.#processNodeWithInputData(\n node,\n inputValues,\n 0,\n processId,\n (node, partialOutputs, index) =>\n this.#emitter.emit('partialOutput', { node, outputs: partialOutputs, index, processId }),\n );\n\n this.#nodeResults.set(node.id, outputValues);\n this.#visitedNodes.add(node.id);\n if (outputValues['cost' as PortId]?.type === 'number') {\n this.#totalCost += coerceTypeOptional(outputValues['cost' as PortId], 'number') ?? 0;\n }\n this.#emitter.emit('nodeFinish', { node, outputs: outputValues, processId });\n } catch (error) {\n this.#nodeErrored(node, error, processId);\n }\n }\n\n #nodeErrored(node: ChartNode, e: unknown, processId: ProcessId) {\n const error = getError(e);\n this.#emitter.emit('nodeError', { node, error, processId });\n this.#emitter.emit('trace', `Node ${node.title} (${node.id}-${processId}) errored: ${error.stack}`);\n this.#erroredNodes.set(node.id, error.toString());\n }\n\n getRootProcessor(): GraphProcessor {\n let processor: GraphProcessor = this;\n while (processor.#parent) {\n processor = processor.#parent;\n }\n return processor;\n }\n\n /** Raise a user event on the processor, all subprocessors, and their children. */\n raiseEvent(event: string, data: DataValue) {\n this.#emitter.emit(`userEvent:${event}`, data);\n\n for (const subprocessor of this.#subprocessors) {\n subprocessor.raiseEvent(event, data);\n }\n }\n\n #newAbortController() {\n const controller = new AbortController();\n this.#emitter.emit('newAbortController', controller);\n return controller;\n }\n\n async #processNodeWithInputData(\n node: ChartNode,\n inputValues: Inputs,\n index: number,\n processId: ProcessId,\n partialOutput?: (node: ChartNode, partialOutputs: Outputs, index: number) => void,\n ) {\n const instance = this.#nodeInstances[node.id]!;\n const nodeAbortController = this.#newAbortController();\n const abortListener = () => {\n nodeAbortController.abort();\n };\n this.#nodeAbortControllers.set(`${node.id}-${processId}`, nodeAbortController);\n this.#abortController.signal.addEventListener('abort', abortListener);\n\n const plugin = this.#registry.getPluginFor(node.type);\n\n let tokenizer = this.#context.tokenizer;\n if (!tokenizer) {\n tokenizer = new GptTokenizerTokenizer();\n tokenizer.on('error', (e) => this.#emitter.emit('error', { error: e }));\n }\n\n const context: InternalProcessContext = {\n ...this.#context,\n node,\n tokenizer,\n executor: this.executor ?? 'nodejs',\n project: this.#project,\n executionCache: this.#executionCache,\n graphInputs: this.#graphInputs,\n graphOutputs: this.#graphOutputs,\n attachedData: this.#getAttachedDataTo(node),\n waitEvent: async (event) => {\n return new Promise((resolve, reject) => {\n this.#emitter.once(`userEvent:${event}`).then(resolve).catch(reject);\n nodeAbortController.signal.addEventListener('abort', () => {\n reject(new Error('Process aborted'));\n });\n });\n },\n raiseEvent: (event, data) => {\n this.getRootProcessor().raiseEvent(event, data as DataValue);\n },\n contextValues: this.#contextValues,\n externalFunctions: { ...this.#externalFunctions },\n onPartialOutputs: (partialOutputs) => {\n partialOutput?.(node, partialOutputs, index);\n\n const { useAsGraphPartialOutput } = (node.data as { useAsGraphPartialOutput?: boolean } | undefined) ?? {};\n\n if (useAsGraphPartialOutput && this.#executor && this.#parent) {\n const executorNode = this.#parent.#nodesById[this.#executor.nodeId];\n if (executorNode) {\n this.#emitter.emit('partialOutput', {\n index: this.#executor.index,\n node: executorNode,\n outputs: partialOutputs,\n processId: this.#executor.processId,\n });\n }\n }\n },\n signal: nodeAbortController.signal,\n processId,\n getGlobal: (id) => this.#globals.get(id),\n setGlobal: (id, value) => {\n this.#globals.set(id, value);\n this.#emitter.emit('globalSet', { id, value, processId });\n },\n waitForGlobal: async (id) => {\n if (this.#globals.has(id)) {\n return this.#globals.get(id)!;\n }\n await this.getRootProcessor().#emitter.once(`globalSet:${id}`);\n return this.#globals.get(id)!;\n },\n createSubProcessor: (subGraphId: GraphId | undefined, { signal }: { signal?: AbortSignal } = {}) => {\n const processor = new GraphProcessor(this.#project, subGraphId, this.#registry);\n processor.executor = this.executor;\n processor.#isSubProcessor = true;\n processor.#executionCache = this.#executionCache;\n processor.#externalFunctions = this.#externalFunctions;\n processor.#contextValues = this.#contextValues;\n processor.#parent = this;\n processor.#globals = this.#globals;\n processor.#executor = {\n nodeId: node.id,\n index,\n processId,\n };\n processor.on('nodeError', (e) => this.#emitter.emit('nodeError', e));\n processor.on('nodeFinish', (e) => this.#emitter.emit('nodeFinish', e));\n processor.on('partialOutput', (e) => this.#emitter.emit('partialOutput', e));\n processor.on('nodeExcluded', (e) => this.#emitter.emit('nodeExcluded', e));\n processor.on('nodeStart', (e) => this.#emitter.emit('nodeStart', e));\n processor.on('graphAbort', (e) => this.#emitter.emit('graphAbort', e));\n processor.on('userInput', (e) => this.#emitter.emit('userInput', e)); // TODO!\n processor.on('graphStart', (e) => this.#emitter.emit('graphStart', e));\n processor.on('graphFinish', (e) => this.#emitter.emit('graphFinish', e));\n processor.on('globalSet', (e) => this.#emitter.emit('globalSet', e));\n processor.on('pause', () => {\n if (!this.#isPaused) {\n this.pause();\n }\n });\n processor.on('resume', () => {\n if (this.#isPaused) {\n this.resume();\n }\n });\n\n processor.onAny((event, data) => {\n if (event.startsWith('globalSet:')) {\n this.#emitter.emit(event, data);\n }\n });\n\n this.#subprocessors.add(processor);\n\n if (signal) {\n signal.addEventListener('abort', () => processor.abort());\n }\n\n // If parent is aborted, abort subgraph with error (it's fine, success state is on the parent)\n this.#abortController.signal.addEventListener('abort', () => processor.abort());\n\n this.on('pause', () => processor.pause());\n this.on('resume', () => processor.resume());\n\n return processor;\n },\n trace: (message) => {\n this.#emitter.emit('trace', message);\n },\n abortGraph: (error) => {\n this.abort(error === undefined, error);\n },\n getPluginConfig: (name) => getPluginConfig(plugin, this.#context.settings, name),\n };\n\n await this.#waitUntilUnpaused();\n const results = await instance.process(inputValues, context);\n this.#nodeAbortControllers.delete(`${node.id}-${processId}`);\n this.#abortController.signal.removeEventListener('abort', abortListener);\n\n if (nodeAbortController.signal.aborted) {\n throw new Error('Aborted');\n }\n\n return results;\n }\n\n #excludedDueToControlFlow(\n node: ChartNode,\n inputValues: Inputs,\n processId: ProcessId,\n typeOfExclusion: ControlFlowExcludedDataValue['value'] = undefined,\n ) {\n if (node.disabled) {\n this.#emitter.emit('trace', `Excluding node ${node.title} because it's disabled`);\n\n this.#visitedNodes.add(node.id);\n this.#markAsExcluded(node, processId, inputValues, 'disabled');\n\n return true;\n }\n\n const inputsWithValues = entries(inputValues);\n const controlFlowExcludedValues = inputsWithValues.filter(\n ([, value]) =>\n value &&\n getScalarTypeOf(value.type) === 'control-flow-excluded' &&\n (!typeOfExclusion || value.value === typeOfExclusion),\n );\n const inputIsExcludedValue = inputsWithValues.length > 0 && controlFlowExcludedValues.length > 0;\n\n const isWaitingForLoop = controlFlowExcludedValues.some((value) => value?.[1]?.value === 'loop-not-broken');\n\n const nodesAllowedToConsumeExcludedValue: BuiltInNodeType[] = [\n 'if',\n 'ifElse',\n 'coalesce',\n 'graphOutput',\n 'raceInputs',\n 'loopController',\n ];\n\n const allowedToConsumedExcludedValue =\n nodesAllowedToConsumeExcludedValue.includes(node.type as BuiltInNodeType) && !isWaitingForLoop;\n\n if (inputIsExcludedValue && !allowedToConsumedExcludedValue) {\n if (!isWaitingForLoop) {\n if (inputIsExcludedValue) {\n this.#emitter.emit(\n 'trace',\n `Excluding node ${node.title} because of control flow. Input is has excluded value: ${controlFlowExcludedValues[0]?.[0]}`,\n );\n }\n\n this.#visitedNodes.add(node.id);\n this.#markAsExcluded(node, processId, inputValues, 'input is excluded value');\n }\n\n return true;\n }\n\n return false;\n }\n\n #markAsExcluded(node: ChartNode, processId: ProcessId, inputValues: Inputs, reason: string) {\n const outputs: Outputs = {};\n for (const output of this.#definitions[node.id]!.outputs) {\n outputs[output.id] = { type: 'control-flow-excluded', value: undefined };\n }\n\n // Prevent infinite loop, a control-flow-excluded to loop controller shouldn't set the break port, let the loop controller handle it\n if (node.type === 'loopController') {\n outputs['break' as PortId] = { type: 'control-flow-excluded', value: 'loop-not-broken' };\n }\n\n this.#nodeResults.set(node.id, outputs);\n\n this.#emitter.emit('nodeExcluded', {\n node,\n processId,\n inputs: inputValues,\n outputs,\n reason,\n });\n }\n\n #getInputValuesForNode(node: ChartNode): Inputs {\n const connections = this.#connections[node.id];\n return this.#definitions[node.id]!.inputs.reduce(\n (values, input) => {\n if (!connections) {\n return values;\n }\n const connection = connections.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);\n if (connection) {\n const outputNode = this.#nodeInstances[connection.outputNodeId]!.chartNode;\n const outputNodeOutputs = this.#nodeResults.get(outputNode.id);\n const outputResult = outputNodeOutputs?.[connection.outputId];\n\n values[input.id] = outputResult;\n }\n return values;\n },\n {} as Record<string, any>,\n );\n }\n\n /** Gets the nodes that are inputting to the given node. */\n #inputNodesTo(node: ChartNode): ChartNode[] {\n const connections = this.#connections[node.id];\n if (!connections) {\n return [];\n }\n\n const connectionsToNode = connections.filter((conn) => conn.inputNodeId === node.id).filter(isNotNull);\n\n // Filter out invalid connections\n const inputDefinitions = this.#definitions[node.id]?.inputs ?? [];\n return connectionsToNode\n .filter((connection) => {\n const connectionDefinition = inputDefinitions.find((def) => def.id === connection.inputId);\n return connectionDefinition != null;\n })\n .map((conn) => this.#nodesById[conn.outputNodeId])\n .filter(isNotNull);\n }\n\n /** Gets the nodes that the given node it outputting to. */\n #outputNodesFrom(node: ChartNode): {\n nodes: ChartNode[];\n connections: NodeConnection[];\n connectionsToNodes: { connections: NodeConnection[]; node: ChartNode }[];\n } {\n const connections = this.#connections[node.id];\n if (!connections) {\n return { nodes: [], connections: [], connectionsToNodes: [] };\n }\n\n const connectionsToNode = connections.filter((conn) => conn.outputNodeId === node.id);\n\n // Filter out invalid connections\n const outputDefinitions = this.#definitions[node.id]?.outputs ?? [];\n const outputConnections = connectionsToNode.filter((connection) => {\n const connectionDefinition = outputDefinitions.find((def) => def.id === connection.outputId);\n return connectionDefinition != null;\n });\n\n const outputNodes = uniqBy(\n outputConnections.map((conn) => this.#nodesById[conn.inputNodeId]).filter(isNotNull),\n (x) => x.id,\n );\n\n const connectionsToNodes: { connections: NodeConnection[]; node: ChartNode }[] = [];\n\n outputNodes.forEach((node) => {\n const connections = outputConnections.filter((conn) => conn.inputNodeId === node.id);\n connectionsToNodes.push({ connections, node });\n });\n\n return { nodes: outputNodes, connections: outputConnections, connectionsToNodes };\n }\n\n #tarjanSCC(): ChartNode[][] {\n let index = 0;\n const stack: ChartNode[] = [];\n const indices: Map<string, number> = new Map();\n const lowLinks: Map<string, number> = new Map();\n const onStack: Map<string, boolean> = new Map();\n const sccs: ChartNode[][] = [];\n\n const strongConnect = (node: ChartNode) => {\n indices.set(node.id, index);\n lowLinks.set(node.id, index);\n index++;\n stack.push(node);\n onStack.set(node.id, true);\n\n const outgoingConnections = this.#connections[node.id]?.filter((conn) => conn.outputNodeId === node.id);\n for (const connection of outgoingConnections ?? []) {\n const successor = this.#nodesById[connection.inputNodeId]!;\n\n if (!indices.has(successor.id)) {\n strongConnect(successor);\n lowLinks.set(node.id, Math.min(lowLinks.get(node.id)!, lowLinks.get(successor.id)!));\n } else if (onStack.get(successor.id)) {\n lowLinks.set(node.id, Math.min(lowLinks.get(node.id)!, indices.get(successor.id)!));\n }\n }\n\n if (lowLinks.get(node.id) === indices.get(node.id)) {\n const scc: Array<ChartNode> = [];\n let connectedNode: ChartNode;\n\n do {\n connectedNode = stack.pop()!;\n onStack.set(connectedNode.id, false);\n scc.push(connectedNode);\n } while (connectedNode.id !== node.id);\n\n sccs.push(scc);\n }\n };\n\n for (const node of this.#graph.nodes) {\n if (!indices.has(node.id)) {\n strongConnect(node);\n }\n }\n\n return sccs;\n }\n\n #nodeIsInCycle(nodeId: NodeId) {\n return this.#nodesNotInCycle.find((node) => node.id === nodeId) == null;\n }\n\n #nodesAreInSameCycle(a: NodeId, b: NodeId) {\n return this.#scc.find((cycle) => cycle.find((node) => node.id === a) && cycle.find((node) => node.id === b));\n }\n}\n", "import type { Inputs, Outputs } from './GraphProcessor.js';\nimport type { ChartNode, NodeConnection, NodeId, NodeInputDefinition, NodeOutputDefinition } from './NodeBase.js';\nimport type { Project } from './Project.js';\nimport type { InternalProcessContext } from './ProcessContext.js';\nimport type { EditorDefinition } from './EditorDefinition.js';\nimport type { NodeBodySpec } from './NodeBodySpec.js';\nimport type { RivetUIContext } from './RivetUIContext.js';\n\nexport interface PluginNodeImpl<T extends ChartNode> {\n getInputDefinitions(\n data: T['data'],\n connections: NodeConnection[],\n nodes: Record<NodeId, ChartNode>,\n project: Project,\n ): NodeInputDefinition[];\n\n getOutputDefinitions(\n data: T['data'],\n connections: NodeConnection[],\n nodes: Record<NodeId, ChartNode>,\n project: Project,\n ): NodeOutputDefinition[];\n\n process(data: T['data'], inputData: Inputs, context: InternalProcessContext): Promise<Outputs>;\n\n getEditors(data: T['data'], context: RivetUIContext): EditorDefinition<T>[] | Promise<EditorDefinition<T>[]>;\n\n getBody(data: T['data'], context: RivetUIContext): NodeBody | Promise<NodeBody>;\n\n create(): T;\n\n getUIData(context: RivetUIContext): NodeUIData | Promise<NodeUIData>;\n}\n\nexport abstract class NodeImpl<T extends ChartNode, Type extends T['type'] = T['type']> {\n readonly chartNode: T;\n\n constructor(chartNode: T) {\n this.chartNode = chartNode;\n }\n\n get id(): string {\n return this.chartNode.id;\n }\n\n get type(): Type {\n return this.chartNode.type as Type;\n }\n\n get title(): string {\n return this.chartNode.title;\n }\n\n get visualData(): { x: number; y: number } {\n return this.chartNode.visualData;\n }\n\n get data(): T['data'] {\n return this.chartNode.data;\n }\n\n abstract getInputDefinitions(\n connections: NodeConnection[],\n nodes: Record<NodeId, ChartNode>,\n project: Project,\n ): NodeInputDefinition[];\n\n abstract getOutputDefinitions(\n connections: NodeConnection[],\n nodes: Record<NodeId, ChartNode>,\n project: Project,\n ): NodeOutputDefinition[];\n\n abstract process(inputData: Inputs, context: InternalProcessContext): Promise<Outputs>;\n\n getEditors(_context: RivetUIContext): EditorDefinition<T>[] | Promise<EditorDefinition<T>[]> {\n return [];\n }\n\n getBody(_context: RivetUIContext): NodeBody | Promise<NodeBody> {\n return undefined;\n }\n}\n\nexport type NodeBody = string | NodeBodySpec | NodeBodySpec[] | undefined;\n\nexport class PluginNodeImplClass<T extends ChartNode, Type extends T['type'] = T['type']> extends NodeImpl<T, Type> {\n readonly impl: PluginNodeImpl<T>;\n\n constructor(chartNode: T, impl: PluginNodeImpl<T>) {\n super(chartNode);\n this.impl = impl;\n }\n\n getInputDefinitions(\n connections: NodeConnection[],\n nodes: Record<NodeId, ChartNode>,\n project: Project,\n ): NodeInputDefinition[] {\n return this.impl.getInputDefinitions(this.data, connections, nodes, project);\n }\n\n getOutputDefinitions(\n connections: NodeConnection[],\n nodes: Record<NodeId, ChartNode>,\n project: Project,\n ): NodeOutputDefinition[] {\n return this.impl.getOutputDefinitions(this.data, connections, nodes, project);\n }\n\n process(inputData: Inputs, context: InternalProcessContext): Promise<Outputs> {\n return this.impl.process(this.data, inputData, context);\n }\n\n getEditors(context: RivetUIContext): EditorDefinition<T>[] | Promise<EditorDefinition<T>[]> {\n return this.impl.getEditors(this.data, context);\n }\n\n getBody(context: RivetUIContext): NodeBody | Promise<NodeBody> {\n return this.impl.getBody(this.data, context);\n }\n}\n\nexport type NodeUIData = {\n contextMenuTitle?: string;\n infoBoxTitle?: string;\n infoBoxBody?: string;\n infoBoxImageUri?: string;\n group?: string | string[];\n};\n\nexport type NodeImplConstructor<T extends ChartNode> = {\n new (chartNode: T, pluginImpl: PluginNodeImpl<T> | undefined): NodeImpl<T>;\n\n create(pluginImpl?: PluginNodeImpl<T>): T;\n\n getUIData(context: RivetUIContext): NodeUIData | Promise<NodeUIData>;\n};\n", "import { type ChartNode, type NodeImplConstructor, type NodeImpl, type PluginNodeImpl } from '../index.js';\nimport { mapValues, values } from '../utils/typeSafety.js';\nimport type { NodeDefinition, PluginNodeDefinition } from './NodeDefinition.js';\nimport { type RivetPlugin } from './RivetPlugin.js';\nimport { type RivetUIContext } from './RivetUIContext.js';\nimport { PluginNodeImplClass } from './NodeImpl.js';\n\nexport class NodeRegistration<NodeTypes extends string = never, Nodes extends ChartNode = never> {\n NodesType: Nodes = undefined!;\n NodeTypesType: NodeTypes = undefined!;\n\n #infos = {} as {\n [P in NodeTypes]: {\n displayName: string;\n impl: NodeImplConstructor<Extract<Nodes, { type: P }>>;\n plugin?: RivetPlugin;\n pluginImpl?: PluginNodeImpl<Extract<Nodes, { type: P }>>;\n };\n };\n\n readonly #plugins = [] as RivetPlugin[];\n\n #implsMap = {} as Record<string, { impl: NodeImplConstructor<ChartNode>; pluginImpl?: PluginNodeImpl<ChartNode> }>;\n readonly #nodeTypes = [] as NodeTypes[];\n\n register<T extends ChartNode>(\n definition: NodeDefinition<T>,\n plugin?: RivetPlugin,\n ): NodeRegistration<NodeTypes | T['type'], Nodes | T> {\n const newRegistration = this as NodeRegistration<NodeTypes | T['type'], Nodes | T>;\n\n const typeStr = definition.impl.create(undefined).type as T['type'];\n\n if (newRegistration.#infos[typeStr]) {\n throw new Error(`Duplicate node type: ${typeStr}`);\n }\n\n newRegistration.#infos[typeStr] = {\n displayName: definition.displayName,\n impl: definition.impl as any,\n plugin,\n };\n\n newRegistration.#implsMap[typeStr] = {\n impl: definition.impl as any,\n pluginImpl: undefined,\n };\n\n newRegistration.#nodeTypes.push(typeStr);\n\n return newRegistration;\n }\n\n registerPluginNode<T extends ChartNode>(\n definition: PluginNodeDefinition<T>,\n plugin: RivetPlugin,\n ): NodeRegistration<NodeTypes | T['type'], Nodes | T> {\n const newRegistration = this as NodeRegistration<NodeTypes | T['type'], Nodes | T>;\n\n const typeStr = definition.impl.create().type as T['type'];\n\n if (newRegistration.#infos[typeStr]) {\n throw new Error(`Duplicate node type: ${typeStr}`);\n }\n\n const pluginClass = class extends PluginNodeImplClass<T> {\n static create() {\n return definition.impl.create();\n }\n\n static getUIData(context: RivetUIContext) {\n return definition.impl.getUIData(context);\n }\n };\n\n newRegistration.#infos[typeStr] = {\n displayName: definition.displayName,\n impl: pluginClass as any,\n plugin,\n pluginImpl: definition.impl as any,\n };\n\n newRegistration.#implsMap[typeStr] = {\n impl: pluginClass as any,\n pluginImpl: definition.impl as any,\n };\n\n newRegistration.#nodeTypes.push(typeStr);\n\n return newRegistration;\n }\n\n get #dynamicImpls(): Record<\n string,\n { impl: NodeImplConstructor<ChartNode>; pluginImpl?: PluginNodeImpl<ChartNode> }\n > {\n return this.#implsMap;\n }\n\n get #dynamicDisplayNames(): Record<string, string> {\n const displayNameMap = mapValues(this.#infos, (info) => info.displayName);\n return displayNameMap as Record<string, string>;\n }\n\n registerPlugin(plugin: RivetPlugin) {\n if (plugin.register) {\n plugin.register((definition) => this.registerPluginNode(definition, plugin));\n }\n this.#plugins.push(plugin);\n }\n\n create<T extends NodeTypes>(type: T): Extract<Nodes, { type: T }> {\n const info = this.#infos[type];\n if (!info) {\n throw new Error(`Unknown node type: ${type}`);\n }\n\n return info.impl.create(info.pluginImpl) as unknown as Extract<Nodes, { type: T }>;\n }\n\n createDynamic(type: string): ChartNode {\n const implClass = this.#dynamicImpls[type];\n if (!implClass) {\n throw new Error(`Unknown node type: ${type}`);\n }\n return implClass.impl.create(implClass.pluginImpl);\n }\n\n createImpl<T extends Nodes>(node: T): NodeImpl<T> {\n const type = node.type as Extract<NodeTypes, T['type']>;\n\n const info = this.#infos[type];\n\n if (!info) {\n throw new Error(`Unknown node type: ${type}`);\n }\n\n const { impl: ImplClass, pluginImpl } = info;\n\n const impl = new ImplClass(node as any, pluginImpl) as unknown as NodeImpl<T>;\n if (!impl) {\n throw new Error(`Unknown node type: ${type}`);\n }\n\n return impl;\n }\n\n createDynamicImpl(node: ChartNode): NodeImpl<ChartNode> {\n const { type } = node;\n const ImplClass = this.#dynamicImpls[type];\n\n if (!ImplClass) {\n throw new Error(`Unknown node type: ${type}`);\n }\n\n // eslint-disable-next-line new-cap\n const impl = new ImplClass.impl(node, ImplClass.pluginImpl) as unknown as NodeImpl<ChartNode>;\n if (!impl) {\n throw new Error(`Unknown node type: ${type}`);\n }\n\n return impl;\n }\n\n getDisplayName<T extends NodeTypes>(type: T): string {\n const info = this.#infos[type];\n\n if (!info) {\n throw new Error(`Unknown node type: ${type}`);\n }\n\n return info.displayName;\n }\n\n getDynamicDisplayName(type: string) {\n const displayName = this.#dynamicDisplayNames[type];\n if (!displayName) {\n throw new Error(`Unknown node type: ${type}`);\n }\n\n return displayName;\n }\n\n isRegistered(type: NodeTypes): boolean {\n return this.#infos[type] !== undefined;\n }\n\n getNodeTypes(): NodeTypes[] {\n return this.#nodeTypes;\n }\n\n getNodeConstructors(): NodeImplConstructor<ChartNode>[] {\n return values(this.#dynamicImpls).map((info) => info.impl);\n }\n\n getPluginFor(type: string): RivetPlugin | undefined {\n const info = this.#infos[type as NodeTypes];\n\n if (!info) {\n throw new Error(`Unknown node type: ${type}`);\n }\n\n return info.plugin;\n }\n\n getPlugins() {\n return this.#plugins;\n }\n}\n", "import { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport type { ChartNode, NodeId, NodeInputDefinition, NodeOutputDefinition, PortId } from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport type { ArrayDataValue, StringDataValue } from '../DataValue.js';\nimport { zip } from 'lodash-es';\nimport { type Outputs, type Inputs, type EditorDefinition, type NodeBodySpec } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport type UserInputNode = ChartNode<'userInput', UserInputNodeData>;\n\nexport type UserInputNodeData = {\n prompt: string;\n useInput: boolean;\n\n renderingFormat?: 'preformatted' | 'markdown';\n};\n\nexport class UserInputNodeImpl extends NodeImpl<UserInputNode> {\n static create(): UserInputNode {\n const chartNode: UserInputNode = {\n type: 'userInput',\n title: 'User Input',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n prompt: 'This is an example question?',\n useInput: false,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n if (this.chartNode.data.useInput) {\n return [\n {\n dataType: 'string[]',\n id: 'questions' as PortId,\n title: 'Questions',\n },\n ];\n }\n return [];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'string[]',\n id: 'output' as PortId,\n title: 'Answers Only',\n },\n {\n dataType: 'string[]',\n id: 'questionsAndAnswers' as PortId,\n title: 'Q & A',\n },\n ];\n }\n\n getEditors(): EditorDefinition<UserInputNode>[] {\n return [\n {\n type: 'code',\n label: 'Prompt',\n dataKey: 'prompt',\n useInputToggleDataKey: 'useInput',\n language: 'plain-text',\n },\n {\n type: 'group',\n label: 'Rendering',\n editors: [\n {\n type: 'dropdown',\n dataKey: 'renderingFormat',\n label: 'Format',\n options: [\n { label: 'Preformatted', value: 'preformatted' },\n { label: 'Markdown', value: 'markdown' },\n ],\n defaultValue: 'markdown',\n },\n ],\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n return this.data.useInput ? '(Using input)' : this.data.prompt;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Prompts the user for input during the execution of the graph. The user's response becomes the output of this node.\n `,\n infoBoxTitle: 'User Input Node',\n contextMenuTitle: 'User Input',\n group: ['Input/Output'],\n };\n }\n\n async process(): Promise<Outputs> {\n return {\n ['output' as PortId]: undefined!,\n ['questionsAndAnswers' as PortId]: undefined!,\n };\n }\n\n getOutputValuesFromUserInput(questions: Inputs, answers: ArrayDataValue<StringDataValue>): Outputs {\n const questionsList = this.data.useInput\n ? coerceType(questions['questions' as PortId], 'string[]')\n : [this.data.prompt];\n\n return {\n ['output' as PortId]: answers,\n ['questionsAndAnswers' as PortId]: {\n type: 'string[]',\n value: zip(questionsList, answers.value).map(([q, a]) => `${q}\\n${a}`),\n },\n };\n }\n}\n\nexport const userInputNode = nodeDefinition(UserInputNodeImpl, 'User Input');\n", "import type { ChartNode } from './NodeBase.js';\nimport type { NodeImplConstructor, PluginNodeImpl } from './NodeImpl.js';\n\nexport type NodeDefinition<T extends ChartNode> = {\n impl: NodeImplConstructor<T>;\n displayName: string;\n};\n\nexport type PluginNodeDefinition<T extends ChartNode> = {\n impl: PluginNodeImpl<T>;\n displayName: string;\n};\n\nexport type UnknownNodeDefinition = NodeDefinition<ChartNode>;\n\nexport function nodeDefinition<T extends ChartNode>(\n impl: NodeImplConstructor<T>,\n displayName: string,\n): NodeDefinition<T> {\n return {\n impl,\n displayName,\n };\n}\n\nexport function pluginNodeDefinition<T extends ChartNode>(\n impl: PluginNodeImpl<T>,\n displayName: string,\n): PluginNodeDefinition<T> {\n return {\n impl,\n displayName,\n };\n}\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { type EditorDefinition, type NodeBodySpec } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\nimport { interpolate } from '../../utils/interpolation.js';\n\nexport type TextNode = ChartNode<'text', TextNodeData>;\n\nexport type TextNodeData = {\n text: string;\n};\n\nexport class TextNodeImpl extends NodeImpl<TextNode> {\n static create(): TextNode {\n const chartNode: TextNode = {\n type: 'text',\n title: 'Text',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 300,\n },\n data: {\n text: '{{input}}',\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n // Extract inputs from text, everything like {{input}}\n const inputNames = [...new Set(this.chartNode.data.text.match(/\\{\\{([^}]+)\\}\\}/g))];\n return (\n inputNames?.map((inputName) => {\n return {\n type: 'string',\n // id and title should not have the {{ and }}\n id: inputName.slice(2, -2) as PortId,\n title: inputName.slice(2, -2),\n dataType: 'string',\n required: false,\n };\n }) ?? []\n );\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'output' as PortId,\n title: 'Output',\n dataType: 'string',\n },\n ];\n }\n\n getEditors(): EditorDefinition<TextNode>[] {\n return [\n {\n type: 'code',\n label: 'Text',\n dataKey: 'text',\n language: 'prompt-interpolation-markdown',\n theme: 'prompt-interpolation',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n const truncated = this.data.text.split('\\n').slice(0, 15).join('\\n').trim();\n\n return {\n type: 'colorized',\n language: 'prompt-interpolation-markdown',\n theme: 'prompt-interpolation',\n text: truncated,\n };\n }\n\n async process(inputs: Record<string, DataValue>): Promise<Record<string, DataValue>> {\n const inputMap = Object.keys(inputs).reduce(\n (acc, key) => {\n const stringValue = coerceTypeOptional(inputs[key], 'string') ?? '';\n\n acc[key] = stringValue;\n return acc;\n },\n {} as Record<string, string>,\n );\n\n const outputValue = interpolate(this.chartNode.data.text, inputMap);\n\n return {\n output: {\n type: 'string',\n value: outputValue,\n },\n };\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Outputs a string of text. It can also interpolate values using <span style=\"color: var(--primary)\">{{tags}}</span>.\n\n The inputs are dynamic based on the interpolation tags.\n `,\n contextMenuTitle: 'Text',\n infoBoxTitle: 'Text Node',\n group: ['Common', 'Text'],\n };\n }\n}\n\nexport const textNode = nodeDefinition(TextNodeImpl, 'Text');\n", "export function interpolate(baseString: string, values: Record<string, string>): string {\n return baseString.replace(/\\{\\{([^}]+)\\}\\}/g, (_m, p1) => {\n const value = values[p1];\n return value !== undefined ? value : '';\n });\n}\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { type ChatMessage, type ScalarDataValue, getScalarTypeOf, isArrayDataValue } from '../DataValue.js';\nimport { addWarning } from '../../utils/outputs.js';\nimport {\n type ChatCompletionOptions,\n OpenAIError,\n openAiModelOptions,\n openaiModels,\n streamChatCompletions,\n type ChatCompletionTool,\n} from '../../utils/openai.js';\nimport retry from 'p-retry';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\nimport { match } from 'ts-pattern';\nimport { coerceType, coerceTypeOptional } from '../../utils/coerceType.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { getInputOrData, cleanHeaders } from '../../utils/inputs.js';\nimport { getError } from '../../utils/errors.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport type { TokenizerCallInfo } from '../../integrations/Tokenizer.js';\nimport { DEFAULT_CHAT_ENDPOINT } from '../../utils/defaults.js';\nimport { chatMessageToOpenAIChatCompletionMessage } from '../../utils/chatMessageToOpenAIChatCompletionMessage.js';\n\nexport type ChatNode = ChartNode<'chat', ChatNodeData>;\n\nexport type ChatNodeConfigData = {\n model: string;\n temperature: number;\n useTopP: boolean;\n top_p?: number;\n maxTokens: number;\n stop?: string;\n presencePenalty?: number;\n frequencyPenalty?: number;\n enableFunctionUse?: boolean;\n user?: string;\n numberOfChoices?: number;\n endpoint?: string;\n overrideModel?: string;\n overrideMaxTokens?: number;\n headers?: { key: string; value: string }[];\n seed?: number;\n toolChoice?: 'none' | 'auto' | 'function';\n toolChoiceFunction?: string;\n responseFormat?: '' | 'text' | 'json' | 'json_schema';\n parallelFunctionCalling?: boolean;\n additionalParameters?: { key: string; value: string }[];\n responseSchemaName?: string;\n};\n\nexport type ChatNodeData = ChatNodeConfigData & {\n useModelInput: boolean;\n useTemperatureInput: boolean;\n useTopPInput: boolean;\n useTopP: boolean;\n useUseTopPInput: boolean;\n useMaxTokensInput: boolean;\n useStop: boolean;\n useStopInput: boolean;\n usePresencePenaltyInput: boolean;\n useFrequencyPenaltyInput: boolean;\n useUserInput?: boolean;\n useNumberOfChoicesInput?: boolean;\n useEndpointInput?: boolean;\n useHeadersInput?: boolean;\n useSeedInput?: boolean;\n useToolChoiceInput?: boolean;\n useToolChoiceFunctionInput?: boolean;\n useResponseFormatInput?: boolean;\n useAdditionalParametersInput?: boolean;\n useResponseSchemaNameInput?: boolean;\n\n /** Given the same set of inputs, return the same output without hitting GPT */\n cache: boolean;\n\n useAsGraphPartialOutput?: boolean;\n};\n\n// Temporary\nconst cache = new Map<string, Outputs>();\n\nexport class ChatNodeImpl extends NodeImpl<ChatNode> {\n static create(): ChatNode {\n const chartNode: ChatNode = {\n type: 'chat',\n title: 'Chat',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 200,\n },\n data: {\n model: 'gpt-4o-mini',\n useModelInput: false,\n\n temperature: 0.5,\n useTemperatureInput: false,\n\n top_p: 1,\n useTopPInput: false,\n\n useTopP: false,\n useUseTopPInput: false,\n\n maxTokens: 1024,\n useMaxTokensInput: false,\n\n useStop: false,\n stop: '',\n useStopInput: false,\n\n presencePenalty: undefined,\n usePresencePenaltyInput: false,\n\n frequencyPenalty: undefined,\n useFrequencyPenaltyInput: false,\n\n user: undefined,\n useUserInput: false,\n\n enableFunctionUse: false,\n\n cache: false,\n useAsGraphPartialOutput: true,\n\n parallelFunctionCalling: true,\n\n additionalParameters: [],\n useAdditionalParametersInput: false,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n\n if (this.data.useEndpointInput) {\n inputs.push({\n dataType: 'string',\n id: 'endpoint' as PortId,\n title: 'Endpoint',\n description:\n 'The endpoint to use for the OpenAI API. You can use this to replace with any OpenAI-compatible API. Leave blank for the default: https://api.openai.com/api/v1/chat/completions',\n });\n }\n\n inputs.push({\n id: 'systemPrompt' as PortId,\n title: 'System Prompt',\n dataType: 'string',\n required: false,\n description: 'The system prompt to send to the model.',\n coerced: true,\n });\n\n if (this.data.useModelInput) {\n inputs.push({\n id: 'model' as PortId,\n title: 'Model',\n dataType: 'string',\n required: false,\n description: 'The model to use for the chat.',\n });\n }\n\n if (this.data.useTemperatureInput) {\n inputs.push({\n dataType: 'number',\n id: 'temperature' as PortId,\n title: 'Temperature',\n description:\n 'What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.',\n });\n }\n\n if (this.data.useTopPInput) {\n inputs.push({\n dataType: 'number',\n id: 'top_p' as PortId,\n title: 'Top P',\n description:\n 'An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.',\n });\n }\n\n if (this.data.useUseTopPInput) {\n inputs.push({\n dataType: 'boolean',\n id: 'useTopP' as PortId,\n title: 'Use Top P',\n description: 'Whether to use top p sampling, or temperature sampling.',\n });\n }\n\n if (this.data.useMaxTokensInput) {\n inputs.push({\n dataType: 'number',\n id: 'maxTokens' as PortId,\n title: 'Max Tokens',\n description: 'The maximum number of tokens to generate in the chat completion.',\n });\n }\n\n if (this.data.useStopInput) {\n inputs.push({\n dataType: 'string',\n id: 'stop' as PortId,\n title: 'Stop',\n description: 'A sequence where the API will stop generating further tokens.',\n });\n }\n\n if (this.data.usePresencePenaltyInput) {\n inputs.push({\n dataType: 'number',\n id: 'presencePenalty' as PortId,\n title: 'Presence Penalty',\n description: `Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.`,\n });\n }\n\n if (this.data.useFrequencyPenaltyInput) {\n inputs.push({\n dataType: 'number',\n id: 'frequencyPenalty' as PortId,\n title: 'Frequency Penalty',\n description: `Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.`,\n });\n }\n\n if (this.data.useUserInput) {\n inputs.push({\n dataType: 'string',\n id: 'user' as PortId,\n title: 'User',\n description:\n 'A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.',\n });\n }\n\n if (this.data.useNumberOfChoicesInput) {\n inputs.push({\n dataType: 'number',\n id: 'numberOfChoices' as PortId,\n title: 'Number of Choices',\n description: 'If greater than 1, the model will return multiple choices and the response will be an array.',\n });\n }\n\n if (this.data.useHeadersInput) {\n inputs.push({\n dataType: 'object',\n id: 'headers' as PortId,\n title: 'Headers',\n description: 'Additional headers to send to the API.',\n });\n }\n\n inputs.push({\n dataType: ['chat-message', 'chat-message[]'] as const,\n id: 'prompt' as PortId,\n title: 'Prompt',\n description: 'The prompt message or messages to send to the model.',\n coerced: true,\n });\n\n if (this.data.enableFunctionUse) {\n inputs.push({\n dataType: ['gpt-function', 'gpt-function[]'] as const,\n id: 'functions' as PortId,\n title: 'Functions',\n description: 'Functions to use in the model. To connect multiple functions, use an Array node.',\n coerced: false,\n });\n }\n\n if (this.data.useSeedInput) {\n inputs.push({\n dataType: 'number',\n id: 'seed' as PortId,\n title: 'Seed',\n coerced: true,\n description:\n 'If specified, OpenAI will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.',\n });\n }\n\n if (this.data.useToolChoiceInput) {\n inputs.push({\n dataType: 'string',\n id: 'toolChoice' as PortId,\n title: 'Tool Choice',\n coerced: true,\n description:\n 'Controls which (if any) function is called by the model. `none` is the default when no functions are present. `auto` is the default if functions are present. `function` forces the model to call a function.',\n });\n }\n\n if (this.data.useToolChoiceInput || this.data.useToolChoiceFunctionInput) {\n inputs.push({\n dataType: 'string',\n id: 'toolChoiceFunction' as PortId,\n title: 'Tool Choice Function',\n coerced: true,\n description: 'The name of the function to force the model to call.',\n });\n }\n\n if (this.data.useResponseFormatInput) {\n inputs.push({\n dataType: 'string',\n id: 'responseFormat' as PortId,\n title: 'Response Format',\n coerced: true,\n description: 'The format to force the model to reply in.',\n });\n }\n\n if (this.data.useAdditionalParametersInput) {\n inputs.push({\n dataType: 'object',\n id: 'additionalParameters' as PortId,\n title: 'Additional Parameters',\n description: 'Additional chat completion parameters to send to the API.',\n });\n }\n\n if (this.data.responseFormat === 'json_schema') {\n inputs.push({\n dataType: 'object',\n id: 'responseSchema' as PortId,\n title: 'Response Schema',\n description: 'The JSON schema that the response will adhere to (Structured Outputs).',\n required: true,\n });\n\n if (this.data.useResponseSchemaNameInput) {\n inputs.push({\n dataType: 'string',\n id: 'responseSchemaName' as PortId,\n title: 'Response Schema Name',\n description: 'The name of the JSON schema that the response will adhere to (Structured Outputs).',\n required: false,\n });\n }\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n const outputs: NodeOutputDefinition[] = [];\n\n if (this.data.useNumberOfChoicesInput || (this.data.numberOfChoices ?? 1) > 1) {\n outputs.push({\n dataType: 'string[]',\n id: 'response' as PortId,\n title: 'Responses',\n description: 'All responses from the model.',\n });\n } else {\n outputs.push({\n dataType: 'string',\n id: 'response' as PortId,\n title: 'Response',\n description: 'The textual response from the model.',\n });\n }\n\n if (this.data.enableFunctionUse) {\n if (this.data.parallelFunctionCalling) {\n outputs.push({\n dataType: 'object[]',\n id: 'function-calls' as PortId,\n title: 'Function Calls',\n description: 'The function calls that were made, if any.',\n });\n } else {\n outputs.push({\n dataType: 'object',\n id: 'function-call' as PortId,\n title: 'Function Call',\n description: 'The function call that was made, if any.',\n });\n }\n }\n\n outputs.push({\n dataType: 'chat-message[]',\n id: 'in-messages' as PortId,\n title: 'Messages Sent',\n description: 'All messages sent to the model.',\n });\n\n if (!(this.data.useNumberOfChoicesInput || (this.data.numberOfChoices ?? 1) > 1)) {\n outputs.push({\n dataType: 'chat-message[]',\n id: 'all-messages' as PortId,\n title: 'All Messages',\n description: 'All messages, with the response appended.',\n });\n }\n\n outputs.push({\n dataType: 'number',\n id: 'responseTokens' as PortId,\n title: 'Response Tokens',\n description: 'The number of tokens in the response from the LLM. For a multi-response, this is the sum.',\n });\n\n return outputs;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Makes a call to an LLM chat model. Supports GPT and any OpenAI-compatible API. The settings contains many options for tweaking the model's behavior.\n\n The \\`System Prompt\\` input specifies a system prompt as the first message to the model. This is useful for providing context to the model.\n\n The \\`Prompt\\` input takes one or more strings or chat-messages (from a Prompt node) to send to the model.\n `,\n contextMenuTitle: 'Chat',\n infoBoxTitle: 'Chat Node',\n group: ['Common', 'AI'],\n };\n }\n\n getEditors(): EditorDefinition<ChatNode>[] {\n return [\n {\n type: 'dropdown',\n label: 'GPT Model',\n dataKey: 'model',\n useInputToggleDataKey: 'useModelInput',\n options: openAiModelOptions,\n disableIf: (data) => {\n return !!data.overrideModel?.trim();\n },\n helperMessage: (data) => {\n if (data.overrideModel?.trim()) {\n return `Model overridden to: ${data.overrideModel}`;\n }\n if (data.model === 'local-model') {\n return 'Local model is an indicator for your own convenience, it does not affect the local LLM used.';\n }\n },\n },\n {\n type: 'group',\n label: 'Parameters',\n editors: [\n {\n type: 'number',\n label: 'Temperature',\n dataKey: 'temperature',\n useInputToggleDataKey: 'useTemperatureInput',\n min: 0,\n max: 2,\n step: 0.1,\n helperMessage:\n 'What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.',\n },\n {\n type: 'number',\n label: 'Top P',\n dataKey: 'top_p',\n useInputToggleDataKey: 'useTopPInput',\n min: 0,\n max: 1,\n step: 0.1,\n helperMessage:\n 'An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.',\n },\n {\n type: 'toggle',\n label: 'Use Top P',\n dataKey: 'useTopP',\n useInputToggleDataKey: 'useUseTopPInput',\n helperMessage: 'Whether to use top p sampling, or temperature sampling.',\n },\n {\n type: 'number',\n label: 'Max Tokens',\n dataKey: 'maxTokens',\n useInputToggleDataKey: 'useMaxTokensInput',\n min: 0,\n max: Number.MAX_SAFE_INTEGER,\n step: 1,\n helperMessage: 'The maximum number of tokens to generate in the chat completion.',\n },\n {\n type: 'string',\n label: 'Stop',\n dataKey: 'stop',\n useInputToggleDataKey: 'useStopInput',\n helperMessage: 'A sequence where the API will stop generating further tokens.',\n },\n {\n type: 'number',\n label: 'Presence Penalty',\n dataKey: 'presencePenalty',\n useInputToggleDataKey: 'usePresencePenaltyInput',\n min: 0,\n max: 2,\n step: 0.1,\n allowEmpty: true,\n helperMessage: `Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.`,\n },\n {\n type: 'number',\n label: 'Frequency Penalty',\n dataKey: 'frequencyPenalty',\n useInputToggleDataKey: 'useFrequencyPenaltyInput',\n min: 0,\n max: 2,\n step: 0.1,\n allowEmpty: true,\n helperMessage: `Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.`,\n },\n {\n type: 'dropdown',\n label: 'Response Format',\n dataKey: 'responseFormat',\n useInputToggleDataKey: 'useResponseFormatInput',\n options: [\n { value: '', label: 'Default' },\n { value: 'text', label: 'Text' },\n { value: 'json', label: 'JSON Object' },\n { value: 'json_schema', label: 'JSON Schema' },\n ],\n defaultValue: '',\n helperMessage: 'The format to force the model to reply in.',\n },\n {\n type: 'string',\n label: 'Response Schema Name',\n dataKey: 'responseSchemaName',\n useInputToggleDataKey: 'useResponseSchemaNameInput',\n helperMessage:\n 'The name of the JSON schema that the response will adhere to (Structured Outputs). Defaults to response_schema',\n hideIf: (data) => data.responseFormat !== 'json_schema',\n },\n {\n type: 'number',\n label: 'Seed',\n dataKey: 'seed',\n useInputToggleDataKey: 'useSeedInput',\n step: 1,\n allowEmpty: true,\n helperMessage:\n 'If specified, OpenAI will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.',\n },\n ],\n },\n {\n type: 'group',\n label: 'GPT Tools',\n editors: [\n {\n type: 'toggle',\n label: 'Enable Function Use',\n dataKey: 'enableFunctionUse',\n },\n {\n type: 'toggle',\n label: 'Enable Parallel Function Calling',\n dataKey: 'parallelFunctionCalling',\n hideIf: (data) => !data.enableFunctionUse,\n },\n {\n type: 'dropdown',\n label: 'Tool Choice',\n dataKey: 'toolChoice',\n useInputToggleDataKey: 'useToolChoiceInput',\n options: [\n { value: '', label: 'Default' },\n { value: 'none', label: 'None' },\n { value: 'auto', label: 'Auto' },\n { value: 'function', label: 'Function' },\n { value: 'required', label: 'Required' },\n ],\n defaultValue: '',\n helperMessage:\n 'Controls which (if any) function is called by the model. None is the default when no functions are present. Auto is the default if functions are present.',\n hideIf: (data) => !data.enableFunctionUse,\n },\n {\n type: 'string',\n label: 'Tool Choice Function',\n dataKey: 'toolChoiceFunction',\n useInputToggleDataKey: 'useToolChoiceFunctionInput',\n helperMessage: 'The name of the function to force the model to call.',\n hideIf: (data) => data.toolChoice !== 'function' || !data.enableFunctionUse,\n },\n ],\n },\n {\n type: 'group',\n label: 'Advanced',\n editors: [\n {\n type: 'string',\n label: 'User',\n dataKey: 'user',\n useInputToggleDataKey: 'useUserInput',\n helperMessage:\n 'A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.',\n },\n {\n type: 'number',\n label: 'Number of Choices',\n dataKey: 'numberOfChoices',\n useInputToggleDataKey: 'useNumberOfChoicesInput',\n min: 1,\n max: 10,\n step: 1,\n defaultValue: 1,\n helperMessage:\n 'If greater than 1, the model will return multiple choices and the response will be an array.',\n },\n {\n type: 'string',\n label: 'Endpoint',\n dataKey: 'endpoint',\n useInputToggleDataKey: 'useEndpointInput',\n helperMessage:\n 'The endpoint to use for the OpenAI API. You can use this to replace with any OpenAI-compatible API. Leave blank for the default: https://api.openai.com/api/v1/chat/completions',\n },\n {\n type: 'string',\n label: 'Custom Model',\n dataKey: 'overrideModel',\n helperMessage: 'Overrides the model selected above with a custom string for the model.',\n },\n {\n type: 'number',\n label: 'Custom Max Tokens',\n dataKey: 'overrideMaxTokens',\n allowEmpty: true,\n helperMessage:\n 'Overrides the max number of tokens a model can support. Leave blank for preconfigured token limits.',\n },\n {\n type: 'keyValuePair',\n label: 'Headers',\n dataKey: 'headers',\n useInputToggleDataKey: 'useHeadersInput',\n keyPlaceholder: 'Header',\n helperMessage: 'Additional headers to send to the API.',\n },\n {\n type: 'toggle',\n label: 'Cache In Rivet',\n dataKey: 'cache',\n helperMessage:\n 'If on, requests with the same parameters and messages will be cached in Rivet, for immediate responses without an API call.',\n },\n {\n type: 'toggle',\n label: 'Use for subgraph partial output',\n dataKey: 'useAsGraphPartialOutput',\n helperMessage:\n 'If on, streaming responses from this node will be shown in Subgraph nodes that call this graph.',\n },\n {\n type: 'keyValuePair',\n label: 'Additional Parameters',\n dataKey: 'additionalParameters',\n useInputToggleDataKey: 'useAdditionalParametersInput',\n keyPlaceholder: 'Parameter',\n valuePlaceholder: 'Value',\n helperMessage:\n 'Additional chat completion parameters to send to the API. If the value appears to be a number, it will be sent as a number.',\n },\n ],\n },\n ];\n }\n\n getBody() {\n return dedent`\n ${this.data.endpoint ? `${this.data.endpoint}` : ''}\n ${this.data.useMaxTokensInput ? 'Max Tokens: (Using Input)' : `${this.data.maxTokens} tokens`}\n Model: ${this.data.useModelInput ? '(Using Input)' : this.data.overrideModel || this.data.model}\n ${this.data.useTopP ? 'Top P' : 'Temperature'}:\n ${\n this.data.useTopP\n ? this.data.useTopPInput\n ? '(Using Input)'\n : this.data.top_p\n : this.data.useTemperatureInput\n ? '(Using Input)'\n : this.data.temperature\n }\n ${this.data.useStop ? `Stop: ${this.data.useStopInput ? '(Using Input)' : this.data.stop}` : ''}\n ${\n (this.data.frequencyPenalty ?? 0) !== 0\n ? `Frequency Penalty: ${this.data.useFrequencyPenaltyInput ? '(Using Input)' : this.data.frequencyPenalty}`\n : ''\n }\n ${\n (this.data.presencePenalty ?? 0) !== 0\n ? `Presence Penalty: ${this.data.usePresencePenaltyInput ? '(Using Input)' : this.data.presencePenalty}`\n : ''\n }\n `.trim();\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const output: Outputs = {};\n\n const model = getInputOrData(this.data, inputs, 'model');\n const temperature = getInputOrData(this.data, inputs, 'temperature', 'number');\n\n const topP = this.data.useTopPInput\n ? coerceTypeOptional(inputs['top_p' as PortId], 'number') ?? this.data.top_p\n : this.data.top_p;\n\n const useTopP = getInputOrData(this.data, inputs, 'useTopP', 'boolean');\n const stop = this.data.useStopInput\n ? this.data.useStop\n ? coerceTypeOptional(inputs['stop' as PortId], 'string') ?? this.data.stop\n : undefined\n : this.data.stop;\n\n const presencePenalty = getInputOrData(this.data, inputs, 'presencePenalty', 'number');\n const frequencyPenalty = getInputOrData(this.data, inputs, 'frequencyPenalty', 'number');\n const numberOfChoices = getInputOrData(this.data, inputs, 'numberOfChoices', 'number');\n const endpoint = getInputOrData(this.data, inputs, 'endpoint');\n const overrideModel = getInputOrData(this.data, inputs, 'overrideModel');\n const seed = getInputOrData(this.data, inputs, 'seed', 'number');\n const responseFormat = getInputOrData(this.data, inputs, 'responseFormat') as 'text' | 'json' | 'json_schema' | '';\n const toolChoiceMode = getInputOrData(this.data, inputs, 'toolChoice', 'string') as 'none' | 'auto' | 'function';\n\n const toolChoice: ChatCompletionOptions['tool_choice'] =\n !toolChoiceMode || !this.data.enableFunctionUse\n ? undefined\n : toolChoiceMode === 'function'\n ? {\n type: 'function',\n function: {\n name: getInputOrData(this.data, inputs, 'toolChoiceFunction', 'string'),\n },\n }\n : toolChoiceMode;\n\n let responseSchema: object | undefined;\n\n const responseSchemaInput = inputs['responseSchema' as PortId];\n if (responseSchemaInput?.type === 'gpt-function') {\n responseSchema = responseSchemaInput.value.parameters;\n } else if (responseSchemaInput != null) {\n responseSchema = coerceType(responseSchemaInput, 'object');\n }\n\n const openaiResponseFormat = !responseFormat?.trim()\n ? undefined\n : responseFormat === 'json'\n ? ({\n type: 'json_object',\n } as const)\n : responseFormat === 'json_schema'\n ? {\n type: 'json_schema' as const,\n json_schema: {\n name: getInputOrData(this.data, inputs, 'responseSchemaName', 'string') || 'response_schema',\n strict: true,\n schema: responseSchema ?? {},\n },\n }\n : ({\n type: 'text',\n } as const);\n\n const headersFromData = (this.data.headers ?? []).reduce(\n (acc, header) => {\n acc[header.key] = header.value;\n return acc;\n },\n {} as Record<string, string>,\n );\n const additionalHeaders = this.data.useHeadersInput\n ? (coerceTypeOptional(inputs['headers' as PortId], 'object') as Record<string, string> | undefined) ??\n headersFromData\n : headersFromData;\n\n const additionalParametersFromData = (this.data.additionalParameters ?? []).reduce(\n (acc, param) => {\n acc[param.key] = Number.isNaN(parseFloat(param.value)) ? param.value : parseFloat(param.value);\n return acc;\n },\n {} as Record<string, string | number>,\n );\n const additionalParameters = this.data.useAdditionalParametersInput\n ? (coerceTypeOptional(inputs['additionalParameters' as PortId], 'object') as\n | Record<string, string>\n | undefined) ?? additionalParametersFromData\n : additionalParametersFromData;\n\n // If using a model input, that's priority, otherwise override > main\n const finalModel = this.data.useModelInput && inputs['model' as PortId] != null ? model : overrideModel || model;\n\n const functions = coerceTypeOptional(inputs['functions' as PortId], 'gpt-function[]');\n\n const tools = (functions ?? []).map(\n (fn): ChatCompletionTool => ({\n function: fn,\n type: 'function',\n }),\n );\n\n const { messages } = getChatNodeMessages(inputs);\n\n const completionMessages = await Promise.all(\n messages.map((message) => chatMessageToOpenAIChatCompletionMessage(message)),\n );\n\n let { maxTokens } = this.data;\n\n const openaiModel = {\n ...(openaiModels[model as keyof typeof openaiModels] ?? {\n maxTokens: this.data.overrideMaxTokens ?? 8192,\n cost: {\n completion: 0,\n prompt: 0,\n },\n displayName: 'Custom Model',\n }),\n };\n\n if (this.data.overrideMaxTokens) {\n openaiModel.maxTokens = this.data.overrideMaxTokens;\n }\n\n const isMultiResponse = this.data.useNumberOfChoicesInput || (this.data.numberOfChoices ?? 1) > 1;\n\n // Resolve to final endpoint if configured in ProcessContext\n const configuredEndpoint = endpoint || context.settings.openAiEndpoint || DEFAULT_CHAT_ENDPOINT;\n const resolvedEndpointAndHeaders = context.getChatNodeEndpoint\n ? await context.getChatNodeEndpoint(configuredEndpoint, finalModel)\n : {\n endpoint: configuredEndpoint,\n headers: {},\n };\n\n const allAdditionalHeaders = cleanHeaders({\n ...context.settings.chatNodeHeaders,\n ...additionalHeaders,\n ...resolvedEndpointAndHeaders.headers,\n });\n\n const tokenizerInfo: TokenizerCallInfo = {\n node: this.chartNode,\n model: finalModel,\n endpoint: resolvedEndpointAndHeaders.endpoint,\n };\n const tokenCount = await context.tokenizer.getTokenCountForMessages(messages, functions, tokenizerInfo);\n\n if (tokenCount >= openaiModel.maxTokens) {\n throw new Error(\n `The model ${model} can only handle ${openaiModel.maxTokens} tokens, but ${tokenCount} were provided in the prompts alone.`,\n );\n }\n\n if (tokenCount + maxTokens > openaiModel.maxTokens) {\n const message = `The model can only handle a maximum of ${\n openaiModel.maxTokens\n } tokens, but the prompts and max tokens together exceed this limit. The max tokens has been reduced to ${\n openaiModel.maxTokens - tokenCount\n }.`;\n addWarning(output, message);\n maxTokens = Math.floor((openaiModel.maxTokens - tokenCount) * 0.95); // reduce max tokens by 5% to be safe, calculation is a little wrong.\n }\n\n try {\n return await retry(\n async () => {\n const options: Omit<ChatCompletionOptions, 'auth' | 'signal'> = {\n messages: completionMessages,\n model: finalModel,\n temperature: useTopP ? undefined : temperature,\n top_p: useTopP ? topP : undefined,\n max_tokens: maxTokens,\n n: numberOfChoices,\n frequency_penalty: frequencyPenalty,\n presence_penalty: presencePenalty,\n stop: stop || undefined,\n tools: tools.length > 0 ? tools : undefined,\n endpoint: resolvedEndpointAndHeaders.endpoint,\n seed,\n response_format: openaiResponseFormat,\n tool_choice: toolChoice,\n ...additionalParameters,\n };\n\n const cacheKey = JSON.stringify(options);\n\n if (this.data.cache) {\n const cached = cache.get(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n const startTime = Date.now();\n\n const chunks = streamChatCompletions({\n auth: {\n apiKey: context.settings.openAiKey ?? '',\n organization: context.settings.openAiOrganization,\n },\n headers: allAdditionalHeaders,\n signal: context.signal,\n timeout: context.settings.chatNodeTimeout,\n ...options,\n });\n\n const responseChoicesParts: string[][] = [];\n\n // First array is the function calls per choice, inner array is the functions calls inside the choice\n const functionCalls: {\n type: 'function';\n id: string;\n name: string;\n arguments: string;\n lastParsedArguments?: string;\n }[][] = [];\n\n for await (const chunk of chunks) {\n if (!chunk.choices) {\n // Could be error for some reason \uD83E\uDD37\u200D\u2642\uFE0F but ignoring has worked for me so far.\n continue;\n }\n\n for (const { delta, index } of chunk.choices) {\n if (delta.content != null) {\n responseChoicesParts[index] ??= [];\n responseChoicesParts[index]!.push(delta.content);\n }\n\n if (delta.tool_calls) {\n // Are we sure that tool_calls will always be full and not a bunch of deltas?\n functionCalls[index] ??= [];\n\n for (const toolCall of delta.tool_calls) {\n functionCalls[index]![toolCall.index] ??= {\n type: 'function',\n arguments: '',\n lastParsedArguments: undefined,\n name: '',\n id: '',\n };\n\n if (toolCall.id) {\n functionCalls[index]![toolCall.index]!.id = toolCall.id;\n }\n\n if (toolCall.function.name) {\n functionCalls[index]![toolCall.index]!.name += toolCall.function.name;\n }\n\n if (toolCall.function.arguments) {\n functionCalls[index]![toolCall.index]!.arguments += toolCall.function.arguments;\n\n try {\n functionCalls[index]![toolCall.index]!.lastParsedArguments = JSON.parse(\n functionCalls[index]![toolCall.index]!.arguments,\n );\n } catch (error) {\n // Ignore\n }\n }\n }\n }\n }\n\n if (isMultiResponse) {\n output['response' as PortId] = {\n type: 'string[]',\n value: responseChoicesParts.map((parts) => parts.join('')),\n };\n } else {\n output['response' as PortId] = {\n type: 'string',\n value: responseChoicesParts[0]?.join('') ?? '',\n };\n }\n\n if (functionCalls.length > 0) {\n\t\t\t\t\t\t\tif (isMultiResponse) {\n\t\t\t\t\t\t\t\toutput['function-call' as PortId] = {\n\t\t\t\t\t\t\t\t\ttype: 'object[]',\n\t\t\t\t\t\t\t\t\tvalue: functionCalls.flat().map((functionCall) => ({\n\t\t\t\t\t\t\t\t\t\tname: functionCall.name,\n\t\t\t\t\t\t\t\t\t\targuments: functionCall.lastParsedArguments,\n\t\t\t\t\t\t\t\t\t\tid: functionCall.id,\n\t\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\toutput['function-call' as PortId] = {\n\t\t\t\t\t\t\t\t\ttype: 'object[]',\n\t\t\t\t\t\t\t\t\tvalue: functionCalls[0]!.map((functionCall) => ({\n\t\t\t\t\t\t\t\t\t\tname: functionCall.name,\n\t\t\t\t\t\t\t\t\t\targuments: functionCall.lastParsedArguments,\n\t\t\t\t\t\t\t\t\t\tid: functionCall.id,\n\t\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n }\n\n context.onPartialOutputs?.(output);\n }\n\n if (!isMultiResponse) {\n output['all-messages' as PortId] = {\n type: 'chat-message[]',\n value: [\n ...messages,\n {\n type: 'assistant',\n message: responseChoicesParts[0]?.join('') ?? '',\n function_call: functionCalls[0]\n ? {\n name: functionCalls[0][0]!.name,\n arguments: functionCalls[0][0]!.arguments, // Needs the stringified one here in chat list\n id: functionCalls[0][0]!.id,\n }\n : undefined,\n function_calls: functionCalls[0]\n ? functionCalls[0].map((fc) => ({\n name: fc.name,\n arguments: fc.arguments,\n id: fc.id,\n }))\n : undefined,\n },\n ],\n };\n }\n\n const endTime = Date.now();\n\n if (responseChoicesParts.length === 0 && functionCalls.length === 0) {\n throw new Error('No response from OpenAI');\n }\n\n output['in-messages' as PortId] = { type: 'chat-message[]', value: messages };\n output['requestTokens' as PortId] = { type: 'number', value: tokenCount * (numberOfChoices ?? 1) };\n\n let responseTokenCount = 0;\n for (const choiceParts of responseChoicesParts) {\n responseTokenCount += await context.tokenizer.getTokenCountForString(choiceParts.join(), tokenizerInfo);\n }\n\n output['responseTokens' as PortId] = { type: 'number', value: responseTokenCount };\n\n const promptCostPerThousand =\n model in openaiModels ? openaiModels[model as keyof typeof openaiModels].cost.prompt : 0;\n const completionCostPerThousand =\n model in openaiModels ? openaiModels[model as keyof typeof openaiModels].cost.completion : 0;\n\n const promptCost = getCostForTokens(tokenCount, 'prompt', promptCostPerThousand);\n const completionCost = getCostForTokens(responseTokenCount, 'completion', completionCostPerThousand);\n\n const cost = promptCost + completionCost;\n\n output['cost' as PortId] = { type: 'number', value: cost };\n output['__hidden_token_count' as PortId] = { type: 'number', value: tokenCount + responseTokenCount };\n\n const duration = endTime - startTime;\n\n output['duration' as PortId] = { type: 'number', value: duration };\n\n Object.freeze(output);\n cache.set(cacheKey, output);\n\n return output;\n },\n {\n forever: true,\n retries: 10000,\n maxRetryTime: 1000 * 60 * 5,\n factor: 2.5,\n minTimeout: 500,\n maxTimeout: 5000,\n randomize: true,\n signal: context.signal,\n onFailedAttempt(err) {\n if (err.toString().includes('fetch failed') && err.cause) {\n const cause =\n getError(err.cause) instanceof AggregateError\n ? (err.cause as AggregateError).errors[0]\n : getError(err.cause);\n\n err = cause;\n }\n\n context.trace(`ChatNode failed, retrying: ${err.toString()}`);\n\n if (context.signal.aborted) {\n throw new Error('Aborted');\n }\n\n const { retriesLeft } = err;\n\n if (!(err instanceof OpenAIError)) {\n if ('code' in err) {\n throw err;\n }\n\n return; // Just retry?\n }\n\n if (err.status === 429) {\n if (retriesLeft) {\n context.onPartialOutputs?.({\n ['response' as PortId]: {\n type: 'string',\n value: 'OpenAI API rate limit exceeded, retrying...',\n },\n });\n return;\n }\n }\n\n if (err.status === 408) {\n if (retriesLeft) {\n context.onPartialOutputs?.({\n ['response' as PortId]: {\n type: 'string',\n value: 'OpenAI API timed out, retrying...',\n },\n });\n return;\n }\n }\n\n // We did something wrong (besides rate limit)\n if (err.status >= 400 && err.status < 500) {\n throw new Error(err.message);\n }\n },\n },\n );\n } catch (error) {\n context.trace(getError(error).stack ?? 'Missing stack');\n throw new Error(`Error processing ChatNode: ${(error as Error).message}`);\n }\n }\n}\n\nexport const chatNode = nodeDefinition(ChatNodeImpl, 'Chat');\n\nexport function getChatNodeMessages(inputs: Inputs) {\n const prompt = inputs['prompt' as PortId];\n\n let messages: ChatMessage[] = match(prompt)\n .with({ type: 'chat-message' }, (p) => [p.value])\n .with({ type: 'chat-message[]' }, (p) => p.value)\n .with({ type: 'string' }, (p): ChatMessage[] => [{ type: 'user', message: p.value }])\n .with({ type: 'string[]' }, (p): ChatMessage[] => p.value.map((v) => ({ type: 'user', message: v })))\n .otherwise((p): ChatMessage[] => {\n if (!p) {\n return [];\n }\n\n if (isArrayDataValue(p)) {\n const stringValues = (p.value as readonly unknown[]).map((v) =>\n coerceType(\n {\n type: getScalarTypeOf(p.type),\n value: v,\n } as ScalarDataValue,\n 'string',\n ),\n );\n\n return stringValues.filter((v) => v != null).map((v) => ({ type: 'user', message: v }));\n }\n\n const coercedMessage = coerceTypeOptional(p, 'chat-message');\n if (coercedMessage != null) {\n return [coercedMessage];\n }\n\n const coercedString = coerceTypeOptional(p, 'string');\n return coercedString != null ? [{ type: 'user', message: coerceType(p, 'string') }] : [];\n });\n\n const systemPrompt = inputs['systemPrompt' as PortId];\n if (systemPrompt) {\n messages = [{ type: 'system', message: coerceType(systemPrompt, 'string') }, ...messages];\n }\n\n return { messages, systemPrompt };\n}\n\nexport function getCostForTokens(tokenCount: number, type: 'prompt' | 'completion', costPerThousand: number) {\n return (tokenCount / 1000) * costPerThousand;\n}\n", "import { orderBy } from 'lodash-es';\nimport { DEFAULT_CHAT_NODE_TIMEOUT } from './defaults.js';\nimport fetchEventSource from './fetchEventSource.js';\n\n// https://github.com/openai/openai-node/issues/18#issuecomment-1518715285\n\nexport type OpenAIModel = {\n maxTokens: number;\n cost: {\n prompt: number;\n completion: number;\n };\n displayName: string;\n};\n\nexport const openaiModels = {\n 'gpt-4': {\n maxTokens: 8192,\n cost: {\n prompt: 0.03,\n completion: 0.06,\n },\n displayName: 'GPT-4',\n },\n 'gpt-4-32k': {\n maxTokens: 32768,\n cost: {\n prompt: 0.06,\n completion: 0.12,\n },\n displayName: 'GPT-4 32k',\n },\n 'gpt-4-0613': {\n maxTokens: 8192,\n cost: {\n prompt: 0.03,\n completion: 0.06,\n },\n displayName: 'GPT-4 (v0613)',\n },\n 'gpt-4-32k-0613': {\n maxTokens: 32768,\n cost: {\n prompt: 0.06,\n completion: 0.12,\n },\n displayName: 'GPT-4 32k (v0613)',\n },\n 'gpt-3.5-turbo': {\n maxTokens: 4096,\n cost: {\n prompt: 0.002,\n completion: 0.002,\n },\n displayName: 'GPT-3.5 Turbo',\n },\n 'gpt-3.5-turbo-16k': {\n maxTokens: 16384,\n cost: {\n prompt: 0.001,\n completion: 0.002,\n },\n displayName: 'GPT-3.5 16k',\n },\n 'gpt-3.5-turbo-0613': {\n maxTokens: 16384,\n cost: {\n prompt: 0.002,\n completion: 0.002,\n },\n displayName: 'GPT-3.5 (v0613)',\n },\n 'gpt-3.5-turbo-1106': {\n maxTokens: 16385,\n cost: {\n prompt: 0.001,\n completion: 0.002,\n },\n displayName: 'GPT-3.5 (v1106)',\n },\n 'gpt-3.5-turbo-16k-0613': {\n maxTokens: 16384,\n cost: {\n prompt: 0.001,\n completion: 0.002,\n },\n displayName: 'GPT-3.5 16k (v0613)',\n },\n 'gpt-3.5-turbo-0301': {\n maxTokens: 16384,\n cost: {\n prompt: 0.002,\n completion: 0.002,\n },\n displayName: 'GPT-3.5 (v0301)',\n },\n 'gpt-4-0314': {\n maxTokens: 8192,\n cost: {\n prompt: 0.03,\n completion: 0.06,\n },\n displayName: 'GPT-4 (v0314)',\n },\n 'gpt-4-32k-0314': {\n maxTokens: 32768,\n cost: {\n prompt: 0.06,\n completion: 0.12,\n },\n displayName: 'GPT-4 32k (v0314)',\n },\n 'gpt-4-1106-preview': {\n maxTokens: 128000,\n cost: {\n prompt: 0.01,\n completion: 0.03,\n },\n displayName: 'GPT-4 Turbo 128K (1106 Preview)',\n },\n 'gpt-4-turbo': {\n maxTokens: 128000,\n cost: {\n prompt: 0.01,\n completion: 0.03,\n },\n displayName: 'GPT-4 Turbo 128K with Vision',\n },\n 'gpt-4-vision-preview': {\n maxTokens: 128000,\n cost: {\n prompt: 0.01,\n completion: 0.03,\n },\n displayName: 'GPT-4 Vision (Preview)',\n },\n 'gpt-4o': {\n maxTokens: 128000,\n cost: {\n prompt: 0.005,\n completion: 0.015,\n },\n displayName: 'GPT-4o',\n },\n 'gpt-4o-mini': {\n maxTokens: 128000,\n cost: {\n prompt: 0.00015,\n completion: 0.00075,\n },\n displayName: 'GPT-4o mini',\n },\n 'gpt-4o-mini-2024-07-18': {\n maxTokens: 128000,\n cost: {\n prompt: 0.00015,\n completion: 0.00075,\n },\n displayName: 'GPT-4o mini (2024-07-18)',\n },\n 'local-model': {\n maxTokens: Number.MAX_SAFE_INTEGER,\n cost: {\n prompt: 0,\n completion: 0,\n },\n displayName: 'Local Model',\n },\n} satisfies Record<string, OpenAIModel>;\n\nexport const openAiModelOptions = orderBy(\n Object.entries(openaiModels).map(([id, { displayName }]) => ({\n value: id,\n label: displayName,\n })),\n 'label',\n);\n\nexport class OpenAIError extends Error {\n constructor(\n readonly status: number,\n readonly responseJson: any,\n ) {\n super(`OpenAIError: ${status} ${JSON.stringify(responseJson)}`);\n this.name = 'OpenAIError';\n }\n}\n\nexport type ChatCompletionRole = ChatCompletionRequestMessage['role'];\n\nexport type ChatCompletionRequestMessage =\n | ChatCompletionRequestSystemMessage\n | ChatCompletionRequestUserMessage\n | ChatCompletionRequestAssistantMessage\n | ChatCompletionRequestToolMessage;\n\nexport type ChatCompletionRequestSystemMessage = {\n role: 'system';\n content: string | null;\n};\n\nexport type ChatCompletionRequestUserMessage = {\n role: 'user';\n content: string | ChatCompletionRequestUserMessageContent[];\n};\n\nexport type ChatCompletionRequestUserMessageContent =\n | ChatCompletionRequestUserMessageTextContent\n | ChatCompletionRequestUserMessageImageContent;\n\nexport type ChatCompletionRequestUserMessageTextContent = {\n type: 'text';\n text: string;\n};\n\nexport type ChatCompletionRequestUserMessageImageContent = {\n type: 'image_url';\n image_url: {\n url: string;\n /**\n * low will disable the \u201Chigh res\u201D model. The model will receive a low-res 512 x 512 version of the image, and represent the image with a budget of 65 tokens. This allows the API to return faster responses and consume fewer input tokens for use cases that do not require high detail.\n * high will enable \u201Chigh res\u201D mode, which first allows the model to see the low res image and then creates detailed crops of input images as 512px squares based on the input image size. Each of the detailed crops uses twice the token budget (65 tokens) for a total of 129 tokens.\n */\n detail?: 'low' | 'high';\n };\n};\n\nexport type ChatCompletionRequestAssistantMessage = {\n role: 'assistant';\n content: string | null;\n tool_calls?: ChatCompletionRequestAssistantMessageToolCall[];\n};\n\nexport type ChatCompletionRequestAssistantMessageToolCall = {\n type: 'function';\n id: string;\n function: GptFunctionCall;\n};\n\nexport type ChatCompletionRequestToolMessage = {\n role: 'tool';\n content: string | null;\n tool_call_id: string;\n};\n\n// https://platform.openai.com/docs/api-reference/chat/create\nexport type ChatCompletionOptions = {\n endpoint: string;\n auth: { apiKey: string; organization?: string };\n headers?: Record<string, string>;\n signal?: AbortSignal;\n\n /** The timeout in milliseconds before an initial response, before retrying. */\n timeout?: number;\n\n model: string;\n messages: ChatCompletionRequestMessage[];\n temperature?: number;\n top_p?: number;\n max_tokens?: number;\n n?: number;\n stop?: string | string[];\n presence_penalty?: number;\n frequency_penalty?: number;\n logit_bias?: {\n [key: number]: number;\n };\n\n /** This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same seed and parameters should return the same result. Determinism is not guaranteed, and you should refer to the system_fingerprint response parameter to monitor changes in the backend. */\n seed?: number;\n\n tools?: ChatCompletionTool[];\n tool_choice?:\n | 'none'\n | 'auto'\n | 'required'\n | {\n type: 'function';\n function: {\n name: string;\n };\n };\n\n /** An object specifying the format that the model must output. Used to enable JSON mode. */\n response_format?:\n | {\n type: 'text';\n }\n | {\n /**\n * Setting to json_object enables JSON mode. This guarantees that the message the model generates is valid JSON.\n * Note that your system prompt must still instruct the model to produce JSON, and to help ensure you don't forget, the API will throw an error if the string JSON does not appear in your system message. Also note that the message content may be partial (i.e. cut off) if finish_reason=\"length\", which indicates the generation exceeded max_tokens or the conversation exceeded the max context length.\n * Must be one of text or json_object.\n */\n type: 'json_object';\n }\n | {\n type: 'json_schema';\n json_schema: {\n name: string;\n strict: boolean;\n schema: object;\n };\n };\n};\n\nexport type ChatCompletionResponse = {\n /** A unique identifier for the chat completion. */\n id: string;\n\n /** The object type, which is always chat.completion. */\n object: 'text_completion';\n\n /** The Unix timestamp (in seconds) of when the chat completion was created. */\n created: number;\n\n /** The model used for the chat completion. */\n model: string;\n\n /**\n * This fingerprint represents the backend configuration that the model runs with.\n * Can be used in conjunction with the seed request parameter to understand when backend changes have been made that might impact determinism.\n */\n system_fingerprint: string;\n\n /** Usage statistics for the completion request. */\n usage: {\n /** Number of tokens in the generated completion. */\n completion_tokens: number;\n\n /** Number of tokens in the prompt. */\n prompt_tokens: number;\n\n /** Total number of tokens used in the request (prompt + completion). */\n total_tokens: number;\n };\n\n /** A list of chat completion choices. Can be more than one if n is greater than 1. */\n choices: ChatCompletionResponseChoice[];\n};\n\nexport type ChatCompletionResponseChoice = {\n /** The index of the choice in the list of choices. */\n index: number;\n\n /**\n * The reason the model stopped generating tokens. This will be stop if the model hit a natural stop point or a provided stop sequence,\n * length if the maximum number of tokens specified in the request was reached, content_filter if content was omitted due to a flag\n * from our content filters, tool_calls if the model called a tool, or function_call (deprecated) if the model called a function.\n */\n finish_reason: 'stop' | 'length' | 'content_filter' | 'insufficient_tokens' | 'tool_calls';\n\n /** A chat completion message generated by the model. */\n message: ChatCompletionResponseMessage;\n};\n\nexport type ChatCompletionResponseMessage = {\n /** The role of the author of this message. */\n role: ChatCompletionRole;\n\n /** The contents of the message. */\n content: string | null;\n\n /** The tool calls generated by the model, such as function calls. */\n tool_calls: OpenAIFunctionToolCall[];\n};\n\nexport type ChatCompletionChunk = {\n object: 'chat.completion.chunk';\n created: number;\n model: string;\n choices?: ChatCompletionChunkChoice[];\n};\n\nexport type GptFunctionCall = {\n name: string;\n arguments: string;\n};\n\nexport type GptFunctionCallDelta = {\n name?: string;\n arguments?: string;\n};\n\nexport type ChatCompletionChunkChoice = {\n index: number;\n message_index: number;\n delta: {\n role?: 'assistant';\n content?: string;\n tool_calls?: ChatCompletionChunkChoiceToolCall[];\n };\n finish_reason: null | 'stop' | 'length' | 'insufficient_tokens' | 'content_filter' | 'tool_calls';\n};\n\nexport type ChatCompletionChunkChoiceToolCall = {\n index: number;\n id: string;\n type: 'function';\n function: GptFunctionCall;\n};\n\nexport type ChatCompletionTool = ChatCompletionFunctionTool;\n\nexport type ChatCompletionFunctionTool = {\n type: 'function';\n function: ChatCompletionFunction;\n};\n\nexport type ChatCompletionFunction = {\n name: string;\n description: string;\n parameters: object;\n strict: boolean;\n};\n\nexport async function* streamChatCompletions({\n endpoint,\n auth,\n signal,\n headers,\n timeout,\n ...rest\n}: ChatCompletionOptions): AsyncGenerator<ChatCompletionChunk> {\n const abortSignal = signal ?? new AbortController().signal;\n\n const response = await fetchEventSource(\n endpoint,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${auth.apiKey}`,\n ...(auth.organization ? { 'OpenAI-Organization': auth.organization } : {}),\n ...headers,\n },\n body: JSON.stringify({\n ...rest,\n stream: true,\n }),\n signal: abortSignal,\n },\n timeout ?? DEFAULT_CHAT_NODE_TIMEOUT,\n );\n\n let hadChunks = false;\n\n for await (const chunk of response.events()) {\n hadChunks = true;\n\n if (chunk === '[DONE]' || abortSignal?.aborted) {\n return;\n }\n let data: ChatCompletionChunk;\n try {\n data = JSON.parse(chunk);\n } catch (err) {\n console.error('JSON parse failed on chunk: ', chunk);\n throw err;\n }\n\n yield data;\n }\n\n if (!hadChunks) {\n const responseJson = await response.json();\n throw new OpenAIError(response.status, responseJson);\n }\n}\n\nexport type OpenAIAssistant = {\n /** The identifier, which can be referenced in API endpoints. */\n id: string;\n\n /** The object type, which is always assistant. */\n object: 'assistant';\n\n /** The Unix timestamp (in seconds) for when the assistant was created. */\n created_at: number;\n\n /** The name of the assistant. The maximum length is 256 characters. */\n name: string | null;\n\n /** The description of the assistant. The maximum length is 512 characters. */\n description: string | null;\n\n /** ID of the model to use. You can use the List models API to see all of your available models, or see our Model overview for descriptions of them. */\n model: string;\n\n /** The system instructions that the assistant uses. The maximum length is 32768 characters. */\n instructions: string | null;\n\n /** A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types code_interpreter, retrieval, or function. */\n tools: OpenAIAssistantTool[];\n\n /** A list of file IDs attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. */\n file_ids: string[];\n\n /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */\n metadata: Record<string, string>;\n};\n\nexport type OpenAIAssistantCodeInterpreterTool = {\n /** The type of tool being defined: code_interpreter */\n type: 'code_interpreter';\n};\n\nexport type OpenAIAssistantRetrievalTool = {\n /** The type of tool being defined: retrieval */\n type: 'retrieval';\n};\n\nexport type OpenAIAssistantFunctionTool = {\n /** The type of tool being defined: function */\n type: 'function';\n\n /** The function definition. */\n function: ChatCompletionFunction;\n};\n\nexport type OpenAIAssistantTool =\n | OpenAIAssistantCodeInterpreterTool\n | OpenAIAssistantRetrievalTool\n | OpenAIAssistantFunctionTool;\n\n/**\n * POST https://api.openai.com/v1/assistants\n * Create an assistant with a model and instructions.\n */\nexport type CreateAssistantBody = {\n /** ID of the model to use. You can use the List models API to see all of your available models, or see our Model overview for descriptions of them. */\n model?: string;\n\n /** The name of the assistant. The maximum length is 256 characters. */\n name?: string | null;\n\n /** The description of the assistant. The maximum length is 512 characters. */\n description?: string | null;\n\n /** The system instructions that the assistant uses. The maximum length is 32768 characters. */\n instructions?: string | null;\n\n /** A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types code_interpreter, retrieval, or function. */\n tools?: OpenAIAssistantTool[];\n\n /** A list of file IDs attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. */\n file_ids?: string[];\n\n /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */\n metadata?: Record<string, string>;\n};\n\nexport type CreateAssistantResponse = OpenAIAssistant;\n\nexport type OpenAIPaginationQuery = {\n /** A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. */\n limit?: string;\n\n /** Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. */\n order?: string;\n\n /** A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. */\n after?: string;\n\n /** A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. */\n before?: string;\n};\n\nexport type OpenAIAssistantFile = {\n /** The identifier, which can be referenced in API endpoints. */\n id: string;\n\n /** The object type, which is always assistant.file. */\n object: 'assistant.file';\n\n /** The Unix timestamp (in seconds) for when the assistant file was created. */\n created_at: number;\n\n /** The assistant ID that the file is attached to. */\n assistant_id: string;\n};\n\nexport type CreateAssistantFileBody = {\n file_id: string;\n};\n\nexport type OpenAIFile = {\n /** The file identifier, which can be referenced in the API endpoints. */\n id: string;\n\n /** The size of the file, in bytes. */\n bytes: number;\n\n /** The Unix timestamp (in seconds) for when the file was created. */\n created_at: number;\n\n /** The name of the file. */\n filename: string;\n\n /** The object type, which is always file. */\n object: 'file';\n\n /** The intended purpose of the file. Supported values are fine-tune, fine-tune-results, assistants, and assistants_output. */\n purpose: OpenAIFilePurpose;\n};\n\nexport type OpenAIFilePurpose = 'fine-tune' | 'fine-tune-results' | 'assistants' | 'assistants_output';\n\nexport const openAIFilePurposeOptions = [\n { value: 'fine-tune', label: 'Fine-tuning' },\n { value: 'fine-tune-results', label: 'Fine-tuning Results' },\n { value: 'assistants', label: 'Assistants' },\n { value: 'assistants_output', label: 'Assistants Output' },\n];\n\nexport const openAIFileUploadPurposeOptions = [\n { value: 'fine-tune', label: 'Fine-tuning' },\n { value: 'assistants', label: 'Assistants' },\n { value: 'assistants_output', label: 'Assistants Output' },\n];\n\nexport type OpenAIThread = {\n /** The identifier, which can be referenced in API endpoints. */\n id: string;\n\n /** The object type, which is always thread. */\n object: 'thread';\n\n /** The Unix timestamp (in seconds) for when the thread was created. */\n created_at: number;\n\n /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */\n metadata: Record<string, string>;\n};\n\nexport type OpenAIThreadMessage = {\n /** The identifier, which can be referenced in API endpoints. */\n id: string;\n\n /** The object type, which is always thread.message. */\n object: 'thread.message';\n\n /** The Unix timestamp (in seconds) for when the message was created. */\n created_at: number;\n\n /** The thread ID that this message belongs to. */\n thread_id: string;\n\n /** The entity that produced the message. One of user or assistant. */\n role: 'user' | 'assistant';\n\n /** The content of the message in array of text and/or images. */\n content: OpenAIThreadMessageContent[];\n};\n\nexport type OpenAIThreadMessageContent = OpenAIThreadMessageImageFileContent | OpenAIThreadMessageTextContent;\n\n/** References an image File in the content of a message. */\nexport type OpenAIThreadMessageImageFileContent = {\n /** Always image_file. */\n type: 'image_file';\n image_file: {\n /** The File ID of the image in the message content. */\n file_id: string;\n };\n};\n\n/** The text content that is part of a message. */\nexport type OpenAIThreadMessageTextContent = {\n /** Always text. */\n type: 'text';\n text: {\n /** The data that makes up the text. */\n value: string;\n annotations: OpenAIThreadMessageContentAnnotation[];\n };\n};\n\nexport type OpenAIThreadMessageContentAnnotation =\n | OpenAIThreadMessageTextContentFileCitationAnnotation\n | OpenAIThreadMessageTextContentFilePathAnnotation;\n\n/** A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the \"retrieval\" tool to search files. */\nexport type OpenAIThreadMessageTextContentFileCitationAnnotation = {\n /** Always file_citation. */\n type: 'file_citation';\n\n /** The text in the message content that needs to be replaced. */\n text: string;\n\n file_citation: {\n /** The ID of the specific File the citation is from. */\n file_id: string;\n\n /** The specific quote in the file. */\n quote: string;\n };\n\n start_index: number;\n end_index: number;\n};\n\n/** A URL for the file that's generated when the assistant used the code_interpreter tool to generate a file. */\nexport type OpenAIThreadMessageTextContentFilePathAnnotation = {\n /** Always file_path. */\n type: 'file_path';\n\n /** The text in the message content that needs to be replaced. */\n text: string;\n\n file_path: {\n /** The ID of the file that was generated. */\n file_id: string;\n };\n\n start_index: number;\n end_index: number;\n};\n\nexport type CreateMessageBody = {\n /** The role of the entity that is creating the message. Currently only user is supported. */\n role: 'user';\n\n /** The content of the message. */\n content: string;\n\n /** A list of File IDs that the message should use. There can be a maximum of 10 files attached to a message. Useful for tools like retrieval and code_interpreter that can access and use files. */\n file_ids?: string[];\n\n /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */\n metadata?: Record<string, string>;\n};\n\nexport type CreateThreadBody = {\n /** A list of messages to start the thread with. */\n messages: CreateMessageBody[];\n\n /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */\n metadata: Record<string, string>;\n};\n\nexport type OpenAIRun = {\n /** The identifier, which can be referenced in API endpoints. */\n id: string;\n\n /** The object type, which is always assistant.run. */\n object: 'assistant.run';\n\n /** The Unix timestamp (in seconds) for when the run was created. */\n created_at: number;\n\n /** The ID of the thread that was executed on as a part of this run. */\n thread_id: string;\n\n /** The ID of the assistant used for execution of this run. */\n assistant_id: string;\n\n /** The status of the run, which can be either queued, in_progress, requires_action, cancelling, cancelled, failed, completed, or expired. */\n status:\n | 'queued'\n | 'in_progress'\n | 'requires_action'\n | 'cancelling'\n | 'cancelled'\n | 'failed'\n | 'completed'\n | 'expired';\n\n /** Details on the action required to continue the run. Will be null if no action is required. */\n required_action: OpenAIRunRequiredAction | null;\n\n /** The last error associated with this run. Will be null if there are no errors. */\n last_error: {\n /** One of server_error or rate_limit_exceeded. */\n code: string;\n\n /** A human-readable description of the error. */\n message: string;\n } | null;\n\n /** The Unix timestamp (in seconds) for when the run will expire. */\n expires_at: number;\n\n /** The Unix timestamp (in seconds) for when the run was started. */\n started_at: number;\n\n /** The Unix timestamp (in seconds) for when the run was cancelled. */\n cancelled_at: number;\n\n /** The Unix timestamp (in seconds) for when the run failed. */\n failed_at: number;\n\n /** The Unix timestamp (in seconds) for when the run was completed. */\n completed_at: number;\n\n /** The model that the assistant used for this run. */\n model: string;\n\n /** The instructions that the assistant used for this run. */\n instructions: string;\n\n /** The list of tools that the assistant used for this run. */\n tools: OpenAIAssistantTool[];\n\n /** The list of File IDs the assistant used for this run. */\n file_ids: string[];\n\n /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */\n metadata: Record<string, string>;\n};\n\nexport type OpenAIRunRequiredAction = OpenAIRunRequiredActionSubmitToolOutputs;\n\nexport type OpenAIRunRequiredActionSubmitToolOutputs = {\n /** For now, this is always submit_tool_outputs. */\n type: 'submit_tool_outputs';\n\n /** Details on the tool outputs needed for this run to continue. */\n submit_tool_outputs: {\n /** A list of the relevant tool calls. */\n tool_calls: OpenAIFunctionToolCall[];\n };\n};\n\nexport type OpenAIRunToolCall = OpenAIFunctionToolCall | OpenAIRunRetrievalToolCall | OpenAIRunCodeInterpreterToolCall;\n\nexport type OpenAIFunctionToolCall = {\n /** The ID of the tool call. This ID must be referenced when you submit the tool outputs in using the Submit tool outputs to run endpoint. */\n id: string;\n\n /** The type of tool call the output is required for. For now, this is always function. */\n type: 'function';\n\n /** The function definition. */\n function: OpenAIRunFunctionToolCallFunction;\n};\n\nexport type OpenAIRunFunctionToolCallFunction = {\n /** The name of the function. */\n name: string;\n\n /** The arguments that the model expects you to pass to the function. */\n arguments: string;\n\n /** The output of the function. This will be null if the outputs have not been submitted yet. Ignore when submitting tool calls. */\n output?: string | null;\n};\n\nexport type OpenAIRunRetrievalToolCall = {\n /** The ID of the tool call object. */\n id: string;\n\n /** The type of tool call. This is always going to be retrieval for this type of tool call. */\n type: 'retrieval';\n\n /** For now, this is always going to be an empty object. */\n retrieval: {};\n};\n\n/** Details of the Code Interpreter tool call the run step was involved in. */\nexport type OpenAIRunCodeInterpreterToolCall = {\n /** The ID of the tool call. */\n id: string;\n\n /** The type of tool call. This is always going to be code_interpreter for this type of tool call. */\n type: 'code_interpreter';\n\n /** The Code Interpreter tool call definition. */\n code_interpreter: {\n /**I The input to the Code Interpreter tool call. */\n input: string;\n\n /** The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (logs) or images (image). Each of these are represented by a different object type. */\n outputs: OpenAIRunCodeInterpreterToolCallOutput[];\n };\n};\n\nexport type OpenAIRunCodeInterpreterToolCallOutput =\n | OpenAIRunCodeInterpreterToolCallLogOutput\n | OpenAIRunCodeInterpreterToolCallImageOutput;\n\n/** Text output from the Code Interpreter tool call as part of a run step. */\nexport type OpenAIRunCodeInterpreterToolCallLogOutput = {\n /** Always logs. */\n type: 'logs';\n\n /** The text output from the Code Interpreter tool call. */\n logs: string;\n};\n\n/** Code interpreter image output */\nexport type OpenAIRunCodeInterpreterToolCallImageOutput = {\n /** Always image. */\n type: 'image';\n image: {\n /** The file ID of the image. */\n file_id: string;\n };\n};\n\nexport type ListThreadMessagesQuery = {\n /** A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. */\n limit?: number;\n\n /** Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. */\n order?: string;\n\n /** A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. */\n after?: string;\n\n /** A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. */\n before?: string;\n};\n\nexport type CreateRunBody = {\n assistant_id: string;\n model?: string;\n instructions?: string;\n tools?: OpenAIAssistantTool[];\n metadata?: Record<string, string>;\n};\n\nexport type SubmitToolOutputsBody = {\n tool_outputs: SubmitToolOutputsBodyToolOutput[];\n};\n\nexport type SubmitToolOutputsBodyToolOutput = {\n // Dunno why these are optional\n\n /** The ID of the tool call in the required_action object within the run object the output is being submitted for. */\n tool_call_id?: string;\n\n /** The output of the tool call to be submitted to continue the run. */\n output?: string;\n};\n\n/** Represents a step in execution of a run. */\nexport type OpenAIRunStep = {\n /** The identifier of the run step, which can be referenced in API endpoints. */\n id: string;\n\n /** The object type, which is always `assistant.run.step``. */\n object: 'thread.run.step';\n\n /** The Unix timestamp (in seconds) for when the run step was created. */\n created_at: number;\n\n /** The ID of the assistant associated with the run step. */\n assistant_id: string;\n\n /** The ID of the thread that was run. */\n thread_id: string;\n\n /** The ID of the run that this run step is a part of. */\n run_id: string;\n\n /** The type of run step, which can be either message_creation or tool_calls. */\n type: 'message_creation' | 'tool_calls';\n\n /** The status of the run, which can be either in_progress, cancelled, failed, completed, or expired. */\n status: 'in_progress' | 'cancelled' | 'failed' | 'completed' | 'expired';\n\n /** The details of the run step. */\n step_details: OpenAIRunStepDetails;\n\n /** The last error associated with this run step. Will be null if there are no errors. */\n last_error: OpenAIErrorInfo | null;\n\n /** The Unix timestamp (in seconds) for when the run step expired. A step is considered expired if the parent run is expired. */\n expired_at: number | null;\n\n /** The Unix timestamp (in seconds) for when the run step was cancelled. */\n cancelled_at: number | null;\n\n /** The Unix timestamp (in seconds) for when the run step failed. */\n failed_at: number | null;\n\n /** The Unix timestamp (in seconds) for when the run step completed. */\n completed_at: number | null;\n\n /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */\n metadata: Record<string, string>;\n};\n\nexport type OpenAIRunStepDetails = OpenAIMessageCreationRunStepDetails | OpenAIToolCallRunStepDetails;\n\n/** Details of the message creation by the run step. */\nexport type OpenAIMessageCreationRunStepDetails = {\n /** Always `message_creation``. */\n type: 'message_creation';\n\n message_creation: {\n /** The ID of the message that was created by this run step. */\n message_id: string;\n };\n};\n\nexport type OpenAIErrorInfo = {\n /** One of server_error or rate_limit_exceeded. */\n code: 'server_error' | 'rate_limit_exceeded';\n\n /** A human-readable description of the error. */\n message: string;\n};\n\nexport type OpenAIToolCallRunStepDetails = {\n type: 'tool_calls';\n\n /** An array of tool calls the run step was involved in. These can be associated with one of three types of tools: code_interpreter, retrieval, or function. */\n tool_calls: OpenAIRunToolCall[];\n};\n\nexport type OpenAIListResponse<T> = {\n object: 'list';\n data: T[];\n first_id: string;\n last_id: string;\n has_more: boolean;\n};\n", "import { getError } from './errors.js';\nimport { DEFAULT_CHAT_NODE_TIMEOUT } from './defaults.js';\n\n// https://github.com/openai/openai-node/issues/18#issuecomment-1518715285\nexport class EventSourceResponse extends Response {\n name: string;\n timeout?: number;\n readonly streams: {\n eventStream: ReadableStream<string>;\n textStream: ReadableStream<string>;\n } | null;\n\n constructor(body: ReadableStream<Uint8Array> | null, init?: ResponseInit, timeout?: number) {\n if (body == null) {\n super(null, init);\n this.name = 'EventSourceResponse';\n this.streams = null;\n this.timeout = timeout;\n return;\n }\n\n const [bodyForString, bodyForEvents] = body.tee();\n const streams = createEventStream(bodyForEvents);\n // By passing our transformed stream into the Response constructor, we prevent anyone\n // from accidentally accessing the raw response.body stream.\n super(bodyForString, init);\n this.name = 'EventSourceResponse';\n this.streams = streams;\n this.timeout = timeout;\n }\n\n async *events(): AsyncGenerator<string> {\n if (this.streams == null) {\n return;\n }\n const reader = this.streams.eventStream.getReader();\n\n try {\n while (true) {\n const { done, value } = await this.raceWithTimeout(reader.read(), this.timeout);\n if (done) {\n break;\n }\n yield value;\n }\n } finally {\n try {\n reader.releaseLock();\n } catch (err) {\n console.error(`Failed to release read lock on event source: ${getError(err).toString()}`);\n }\n }\n }\n\n private async raceWithTimeout<T>(promise: Promise<T>, timeout?: number): Promise<T> {\n const raceTimeout = timeout ?? DEFAULT_CHAT_NODE_TIMEOUT;\n\n // eslint-disable-next-line no-async-promise-executor -- Error handled correctly\n return new Promise(async (resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new Error('Timeout: API response took too long.'));\n }, raceTimeout);\n\n try {\n const result = await promise;\n clearTimeout(timer);\n resolve(result);\n } catch (error) {\n clearTimeout(timer);\n reject(error);\n }\n });\n }\n}\n\nexport default async function fetchEventSource(\n url: string,\n init?: RequestInit,\n timeout?: number,\n): Promise<EventSourceResponse> {\n const headers = {\n ...init?.headers,\n accept: 'text/event-stream',\n };\n\n const response = await fetch(url, {\n ...init,\n headers,\n });\n\n return new EventSourceResponse(response.body, response, timeout);\n}\n\nclass LineSplitter implements Transformer<string, string> {\n private buffer = '';\n constructor(readonly separator = /\\n+/) {}\n\n transform(chunk: string, controller: TransformStreamDefaultController<string>): void {\n this.buffer += chunk;\n const lines = this.buffer.split(this.separator);\n this.buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n controller.enqueue(line);\n }\n }\n\n flush(controller: TransformStreamDefaultController<string>): void {\n if (this.buffer.length > 0) {\n controller.enqueue(this.buffer);\n this.buffer = '';\n }\n }\n}\n\nfunction createEventStream(body: ReadableStream<Uint8Array> | null) {\n if (body == null) {\n return null;\n }\n\n const textStream = body.pipeThrough(new TextDecoderStream());\n\n const eventStream = textStream.pipeThrough(new TransformStream(new LineSplitter())).pipeThrough(\n new TransformStream<string, string>({\n transform(line, controller) {\n if (line.trim().length === 0) {\n return;\n }\n\n if (line.startsWith('data: ')) {\n const data = line.slice(6).trim();\n controller.enqueue(data);\n } else if (line.startsWith('event: ')) {\n const event = line.slice(7).trim();\n controller.enqueue(`[${event}]`);\n }\n },\n }),\n );\n return { eventStream, textStream };\n}\n", "import { match } from 'ts-pattern';\nimport type { ChatMessage } from '../index.js';\nimport { uint8ArrayToBase64 } from './index.js';\nimport type { ChatCompletionRequestMessage, ChatCompletionRequestUserMessageContent } from './openai.js';\n\nexport async function chatMessageToOpenAIChatCompletionMessage(\n message: ChatMessage,\n): Promise<ChatCompletionRequestMessage> {\n const onlyStringContent = (message: ChatMessage): string => {\n const parts = Array.isArray(message.message) ? message.message : [message.message];\n const stringContent = parts\n .map((part) => {\n if (typeof part !== 'string') {\n throw new Error('System prompt must be a string');\n }\n\n return part;\n })\n .join('\\n\\n');\n return stringContent;\n };\n\n return match(message)\n .with({ type: 'system' }, (m): ChatCompletionRequestMessage => ({ role: m.type, content: onlyStringContent(m) }))\n .with({ type: 'user' }, async (m): Promise<ChatCompletionRequestMessage> => {\n const parts = Array.isArray(m.message) ? m.message : [m.message];\n\n if (parts.length === 1 && typeof parts[0] === 'string') {\n return { role: m.type, content: parts[0] };\n }\n\n const chatMessageParts = await Promise.all(\n parts.map(async (part): Promise<ChatCompletionRequestUserMessageContent> => {\n if (typeof part === 'string') {\n return { type: 'text', text: part };\n }\n\n const url =\n part.type === 'url' ? part.url : `data:${part.mediaType};base64,${await uint8ArrayToBase64(part.data)}`;\n\n return {\n type: 'image_url',\n image_url: { url },\n };\n }),\n );\n\n return { role: m.type, content: chatMessageParts };\n })\n .with(\n { type: 'assistant' },\n (m): ChatCompletionRequestMessage => ({\n role: m.type,\n content: onlyStringContent(m),\n\n tool_calls: m.function_calls\n ? m.function_calls.map((fc) => ({\n id: fc.id ?? 'unknown_function_call',\n type: 'function',\n function: fc,\n }))\n : m.function_call\n ? [\n {\n id: m.function_call.id ?? 'unknown_function_call',\n type: 'function',\n function: m.function_call,\n },\n ]\n : undefined,\n }),\n )\n .with(\n { type: 'function' },\n (m): ChatCompletionRequestMessage => ({\n role: 'tool',\n content: onlyStringContent(m),\n tool_call_id: m.name ?? 'unknown_function_call',\n }),\n )\n .exhaustive();\n}\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport {\n type AssistantChatMessage,\n type AssistantChatMessageFunctionCall,\n type ChatMessage,\n type EditorDefinition,\n type Inputs,\n type InternalProcessContext,\n type NodeBodySpec,\n type Outputs,\n} from '../../index.js';\nimport { mapValues } from 'lodash-es';\nimport { dedent } from 'ts-dedent';\nimport { coerceType, coerceTypeOptional } from '../../utils/coerceType.js';\nimport { getInputOrData } from '../../utils/index.js';\nimport { interpolate } from '../../utils/interpolation.js';\nimport { match } from 'ts-pattern';\n\nexport type PromptNode = ChartNode<'prompt', PromptNodeData>;\n\nexport type PromptNodeData = {\n type: 'system' | 'user' | 'assistant' | 'function';\n useTypeInput: boolean;\n\n promptText: string;\n\n name?: string;\n useNameInput?: boolean;\n enableFunctionCall?: boolean;\n computeTokenCount?: boolean;\n};\n\nexport class PromptNodeImpl extends NodeImpl<PromptNode> {\n static create(): PromptNode {\n const chartNode: PromptNode = {\n type: 'prompt',\n title: 'Prompt',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n type: 'user',\n useTypeInput: false,\n promptText: '{{input}}',\n enableFunctionCall: false,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n let inputs: NodeInputDefinition[] = [];\n\n if (this.data.enableFunctionCall) {\n inputs.push({\n id: 'function-call' as PortId,\n title: 'Function Call',\n dataType: 'object',\n });\n }\n\n if (this.data.useTypeInput) {\n inputs.push({\n id: 'type' as PortId,\n title: 'Type',\n dataType: 'string',\n });\n }\n\n if (this.data.useNameInput) {\n inputs.push({\n id: 'name' as PortId,\n title: 'Name/ID',\n dataType: 'string',\n });\n }\n\n // Extract inputs from promptText, everything like {{input}}\n const inputNames = [...new Set(this.chartNode.data.promptText.match(/\\{\\{([^}]+)\\}\\}/g))];\n inputs = [\n ...inputs,\n ...(inputNames?.map((inputName): NodeInputDefinition => {\n return {\n // id and title should not have the {{ and }}\n id: inputName.slice(2, -2) as PortId,\n title: inputName.slice(2, -2),\n dataType: 'string',\n required: false,\n };\n }) ?? []),\n ];\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n const outputs: NodeOutputDefinition[] = [\n {\n id: 'output' as PortId,\n title: 'Output',\n dataType: 'chat-message',\n },\n ];\n\n if (this.chartNode.data.computeTokenCount) {\n outputs.push({\n id: 'tokenCount' as PortId,\n title: 'Token Count',\n dataType: 'number',\n });\n }\n\n return outputs;\n }\n\n getEditors(): EditorDefinition<PromptNode>[] {\n return [\n {\n type: 'dropdown',\n label: 'Type',\n options: [\n { value: 'system', label: 'System' },\n { value: 'user', label: 'User' },\n { value: 'assistant', label: 'Assistant' },\n { value: 'function', label: 'Function' },\n ],\n dataKey: 'type',\n useInputToggleDataKey: 'useTypeInput',\n },\n {\n type: 'string',\n label: 'Name',\n dataKey: 'name',\n useInputToggleDataKey: 'useNameInput',\n hideIf: (data) => data.type !== 'function',\n helperMessage:\n 'For OpenAI, this is the tool call ID. Otherwise, it is the name of the function that is outputting the message.',\n },\n {\n type: 'toggle',\n label: 'Enable Function Call',\n dataKey: 'enableFunctionCall',\n hideIf: (data) => data.type !== 'assistant',\n },\n {\n type: 'toggle',\n label: 'Compute Token Count',\n dataKey: 'computeTokenCount',\n },\n {\n type: 'code',\n label: 'Prompt Text',\n dataKey: 'promptText',\n language: 'prompt-interpolation-markdown',\n theme: 'prompt-interpolation',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | NodeBodySpec[] | undefined {\n return [\n {\n type: 'markdown',\n text: dedent`\n _${typeDisplay[this.data.type]}${this.data.name ? ` (${this.data.name})` : ''}_\n `,\n },\n {\n type: 'colorized',\n text: this.data.promptText.split('\\n').slice(0, 15).join('\\n').trim(),\n language: 'prompt-interpolation-markdown',\n theme: 'prompt-interpolation',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Outputs a chat message, which is a string of text with an attached \"type\" saying who sent the message (User, Assistant, System) and optionally an attached \"name\".\n\n Also provides the same <span style=\"color: var(--primary)\">{{interpolation}}</span> capabilities as a Text node.\n\n Can change one chat message type into another chat message type. For example, changing a User message into a System message.\n `,\n infoBoxTitle: 'Prompt Node',\n contextMenuTitle: 'Prompt',\n group: ['Text'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext<PromptNode>): Promise<Outputs> {\n const inputMap = mapValues(inputs, (input) => coerceType(input, 'string')) as Record<PortId, string>;\n\n const outputValue = interpolate(this.chartNode.data.promptText, inputMap);\n\n const type = getInputOrData(this.data, inputs, 'type', 'string');\n\n if (['assistant', 'system', 'user', 'function'].includes(type) === false) {\n throw new Error(`Invalid type: ${type}`);\n }\n\n const message = match(type)\n .with(\n 'system',\n (type): ChatMessage => ({\n type,\n message: outputValue,\n }),\n )\n .with(\n 'user',\n (type): ChatMessage => ({\n type,\n message: outputValue,\n }),\n )\n .with('assistant', (type): ChatMessage => {\n let functionCall = this.data.enableFunctionCall\n ? coerceTypeOptional(inputs['function-call' as PortId], 'object')\n : undefined;\n\n // If no name is specified, ignore the function call\n if (!functionCall?.name || !functionCall?.arguments) {\n functionCall = undefined;\n }\n\n // GPT is weird - the arguments should be a stringified JSON object https://platform.openai.com/docs/api-reference/chat/create\n if (functionCall?.arguments && typeof functionCall.arguments !== 'string') {\n functionCall.arguments = JSON.stringify(functionCall.arguments);\n }\n\n return {\n type,\n message: outputValue,\n function_call: functionCall as AssistantChatMessageFunctionCall,\n function_calls: functionCall ? [functionCall as AssistantChatMessageFunctionCall] : undefined,\n };\n })\n .with(\n 'function',\n (type): ChatMessage => ({\n type,\n message: outputValue,\n name: getInputOrData(this.data, inputs, 'name', 'string'),\n }),\n )\n .otherwise(() => {\n throw new Error(`Invalid chat-message type: ${type}`);\n });\n\n const outputs: Outputs = {\n ['output' as PortId]: {\n type: 'chat-message',\n value: message,\n },\n };\n\n if (this.chartNode.data.computeTokenCount) {\n const tokenCount = await context.tokenizer.getTokenCountForMessages([message], undefined, {\n node: this.chartNode,\n });\n outputs['tokenCount' as PortId] = {\n type: 'number',\n value: tokenCount,\n };\n }\n\n return outputs;\n }\n}\n\nexport const promptNode = nodeDefinition(PromptNodeImpl, 'Prompt');\n\nconst typeDisplay: Record<PromptNodeData['type'], string> = {\n assistant: 'Assistant',\n system: 'System',\n user: 'User',\n function: 'Function',\n};\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { expectType, expectTypeOptional } from '../../utils/expectType.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\n\nexport type ExtractRegexNode = ChartNode<'extractRegex', ExtractRegexNodeData>;\n\nexport type ExtractRegexNodeData = {\n regex: string;\n useRegexInput: boolean;\n errorOnFailed: boolean;\n multilineMode?: boolean;\n};\n\nexport class ExtractRegexNodeImpl extends NodeImpl<ExtractRegexNode> {\n static create(): ExtractRegexNode {\n const chartNode: ExtractRegexNode = {\n type: 'extractRegex',\n title: 'Extract Regex',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n regex: '([a-zA-Z]+)',\n useRegexInput: false,\n errorOnFailed: false,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [\n {\n id: 'input' as PortId,\n title: 'Input',\n dataType: 'string',\n required: true,\n coerced: false,\n },\n ];\n\n if (this.chartNode.data.useRegexInput) {\n inputs.push({\n id: 'regex' as PortId,\n title: 'Regex',\n dataType: 'string',\n required: false,\n coerced: false,\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n const regex = this.chartNode.data.regex;\n try {\n const regExp = new RegExp(regex, 'g');\n const captureGroupCount = countCaptureGroups(regExp);\n\n const outputs: NodeOutputDefinition[] = [];\n\n for (let i = 0; i < captureGroupCount; i++) {\n outputs.push({\n id: `output${i + 1}` as PortId,\n title: `Output ${i + 1}`,\n dataType: 'string',\n });\n }\n\n outputs.push({\n id: 'matches' as PortId,\n title: 'Matches',\n dataType: 'string[]',\n });\n\n outputs.push(\n {\n id: 'succeeded' as PortId,\n title: 'Succeeded',\n dataType: 'boolean',\n },\n {\n id: 'failed' as PortId,\n title: 'Failed',\n dataType: 'boolean',\n },\n );\n\n return outputs;\n } catch (err) {\n return [];\n }\n }\n\n getEditors(): EditorDefinition<ExtractRegexNode>[] {\n return [\n {\n type: 'custom',\n customEditorId: 'ExtractRegexNodeAiAssist',\n label: 'AI Assist',\n },\n {\n type: 'toggle',\n label: 'Error on failed',\n dataKey: 'errorOnFailed',\n },\n {\n type: 'toggle',\n label: 'Multiline mode',\n dataKey: 'multilineMode',\n },\n {\n type: 'code',\n label: 'Regex',\n dataKey: 'regex',\n useInputToggleDataKey: 'useRegexInput',\n language: 'regex',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n return this.data.useRegexInput ? '(Using regex input)' : this.data.regex;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Extracts data from the input text using the configured regular expression. The regular expression can contain capture groups to extract specific parts of the text.\n\n Each capture group corresponds to an output port of the node.\n `,\n infoBoxTitle: 'Extract With Regex Node',\n contextMenuTitle: 'Extract With Regex',\n group: ['Text'],\n };\n }\n\n async process(inputs: Record<PortId, DataValue>): Promise<Record<PortId, DataValue>> {\n const inputString = expectType(inputs['input' as PortId], 'string');\n const regex = expectTypeOptional(inputs['regex' as PortId], 'string') ?? this.chartNode.data.regex;\n\n const regExp = new RegExp(regex, this.data.multilineMode ? 'gm' : 'g');\n\n let matches = [];\n let match;\n let firstMatch;\n\n while ((match = regExp.exec(inputString)) !== null) {\n if (!firstMatch) {\n firstMatch = match;\n }\n matches.push(match[1]!);\n }\n\n matches = matches.filter((m) => m);\n\n if (matches.length === 0 && this.chartNode.data.errorOnFailed) {\n throw new Error(`No match found for regex ${regex}`);\n }\n\n const outputArray: DataValue = {\n type: 'string[]',\n value: matches,\n };\n\n if (!firstMatch) {\n if (this.chartNode.data.errorOnFailed) {\n throw new Error(`No match found for regex ${regex}`);\n }\n return {\n ['succeeded' as PortId]: {\n type: 'boolean',\n value: false,\n },\n ['failed' as PortId]: {\n type: 'boolean',\n value: true,\n },\n };\n }\n\n const output: Record<PortId, DataValue> = {\n ['succeeded' as PortId]: {\n type: 'boolean',\n value: true,\n },\n ['failed' as PortId]: {\n type: 'boolean',\n value: false,\n },\n };\n\n output['matches' as PortId] = outputArray;\n\n for (let i = 1; i < firstMatch.length; i++) {\n output[`output${i}` as PortId] = {\n type: 'string',\n value: firstMatch[i]!,\n };\n }\n\n return output;\n }\n}\n\nfunction countCaptureGroups(regex: RegExp): number {\n const regexSource = regex.source;\n let count = 0;\n let inCharacterClass = false;\n\n for (let i = 0; i < regexSource.length; i++) {\n const currentChar = regexSource[i];\n const prevChar = i > 0 ? regexSource[i - 1] : null;\n\n if (currentChar === '[' && prevChar !== '\\\\') {\n inCharacterClass = true;\n } else if (currentChar === ']' && prevChar !== '\\\\') {\n inCharacterClass = false;\n } else if (currentChar === '(' && prevChar !== '\\\\' && !inCharacterClass) {\n if (regexSource[i + 1] !== '?' || regexSource[i + 2] === ':') {\n count++;\n }\n }\n }\n\n return count;\n}\n\nexport const extractRegexNode = nodeDefinition(ExtractRegexNodeImpl, 'Extract Regex');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { type DataValue } from '../DataValue.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type CodeNode = ChartNode<'code', CodeNodeData>;\n\nconst maskInput = (name: string) => name.trim().replace(/[^a-zA-Z0-9_]/g, '_');\nconst asValidNames = (names: string[]): string[] => Array(...new Set(names.map(maskInput))).filter(Boolean);\n\nexport type CodeNodeData = {\n code: string;\n inputNames: string | string[];\n outputNames: string | string[];\n};\n\nexport class CodeNodeImpl extends NodeImpl<CodeNode> {\n static create(): CodeNode {\n const chartNode: CodeNode = {\n type: 'code',\n title: 'Code',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n },\n data: {\n code: dedent`\n // This is a code node, you can write and JS in here and it will be executed.\n // Inputs are accessible via an object \\`inputs\\` and data is typed (i.e. inputs.foo.type, inputs.foo.value)\n // Return an object with named outputs that match the output names specified in the node's config.\n // Output values must by typed as well (e.g. { bar: { type: 'string', value: 'bar' } }\n return {\n output1: {\n type: inputs.input1.type,\n value: inputs.input1.value\n }\n };\n `,\n inputNames: 'input1',\n outputNames: 'output1',\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputNames = this.data.inputNames\n ? Array.isArray(this.data.inputNames)\n ? this.data.inputNames\n : [this.data.inputNames]\n : [];\n\n return asValidNames(inputNames).map((inputName) => {\n return {\n type: 'any',\n id: inputName.trim() as PortId,\n title: inputName.trim(),\n dataType: 'string',\n required: false,\n };\n });\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n const outputNames = this.data.outputNames\n ? Array.isArray(this.data.outputNames)\n ? this.data.outputNames\n : [this.data.outputNames]\n : [];\n\n return asValidNames(outputNames).map((outputName) => {\n return {\n id: outputName.trim() as PortId,\n title: outputName.trim(),\n dataType: 'any',\n };\n });\n }\n\n getEditors(): EditorDefinition<CodeNode>[] {\n return [\n {\n type: 'custom',\n customEditorId: 'CodeNodeAIAssist',\n label: 'AI Assist',\n },\n {\n type: 'code',\n label: 'Code',\n dataKey: 'code',\n language: 'javascript',\n },\n {\n type: 'stringList',\n label: 'Inputs',\n dataKey: 'inputNames',\n },\n {\n type: 'stringList',\n label: 'Outputs',\n dataKey: 'outputNames',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n const trimmed = this.data.code\n .split('\\n')\n .slice(0, 15)\n .map((line) => (line.length > 50 ? line.slice(0, 50) + '...' : line))\n .join('\\n')\n .trim();\n\n return {\n type: 'colorized',\n text: trimmed,\n language: 'javascript',\n fontSize: 12,\n fontFamily: 'monospace',\n };\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Executes a piece of JavaScript code. See the Rivet Documentation for more information on how to write code for the Code Node.\n `,\n infoBoxTitle: 'Code Node',\n contextMenuTitle: 'Code',\n group: ['Advanced'],\n };\n }\n\n async process(inputs: Record<string, DataValue>): Promise<Record<string, DataValue>> {\n // eslint-disable-next-line no-new-func\n const codeFunction = new Function('inputs', this.chartNode.data.code);\n const outputs = codeFunction(inputs);\n\n if (outputs == null || typeof outputs !== 'object' || ('then' in outputs && typeof outputs.then === 'function')) {\n throw new Error('Code node must return an object with output values.');\n }\n\n const missingOutputs = this.getOutputDefinitions().filter((output) => !(output.id in outputs));\n if (missingOutputs.length > 0) {\n throw new Error(\n `Code node must return an object with output values for all outputs. To not run an output, return { \"type\": \"control-flow-excluded\", \"value\": undefiend }. To return undefined, return { \"type\": \"any\", \"value\": undefined }. Missing: ${missingOutputs\n .map((output) => output.id)\n .join(', ')}`,\n );\n }\n\n return outputs;\n }\n}\n\nexport const codeNode = nodeDefinition(CodeNodeImpl, 'Code');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { type EditorDefinition, type Inputs, type NodeBody, type Outputs } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceType } from '../../utils/coerceType.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\n\nexport type MatchNode = ChartNode<'match', MatchNodeData>;\n\nexport type MatchNodeData = {\n cases: string[];\n\n /** If true, only the first matching branch will be ran. */\n exclusive?: boolean;\n};\n\nexport class MatchNodeImpl extends NodeImpl<MatchNode> {\n static create(): MatchNode {\n const chartNode: MatchNode = {\n type: 'match',\n title: 'Match',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n cases: ['YES', 'NO'],\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [\n {\n id: 'input' as PortId,\n title: 'Test',\n dataType: 'string',\n required: true,\n description: 'The value that will be tested against each of the cases.',\n },\n {\n id: 'value' as PortId,\n title: 'Value',\n dataType: 'any',\n description:\n 'The value passed through to the output port that matches. If unconnected, the test value will be passed through.',\n },\n ];\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n const outputs: NodeOutputDefinition[] = [];\n\n for (let i = 0; i < this.data.cases.length; i++) {\n outputs.push({\n id: `case${i + 1}` as PortId,\n title: this.data.cases[i]?.trim() ? this.data.cases[i]! : `Case ${i + 1}`,\n dataType: 'string',\n description: `The 'value' (or 'test' if value is unconnected) passed through if the test value matches this regex: /${this\n .data.cases[i]!}/`,\n });\n }\n\n outputs.push({\n id: 'unmatched' as PortId,\n title: 'Unmatched',\n dataType: 'string',\n description: 'The value (or test if value is unconnected) passed through if no regexes match.',\n });\n\n return outputs;\n }\n\n getBody(): NodeBody {\n return dedent`\n ${this.data.exclusive ? 'First Matching Case' : 'All Matching Cases'}\n ${this.data.cases.length} Cases\n `;\n }\n\n getEditors(): EditorDefinition<MatchNode>[] {\n return [\n {\n type: 'toggle',\n dataKey: 'exclusive',\n label: 'Exclusive',\n helperMessage: 'If enabled, only the first matching branch will be ran.',\n },\n {\n type: 'stringList',\n dataKey: 'cases',\n label: 'Cases',\n placeholder: 'Case (regular expression)',\n helperMessage: '(Regular expressions)',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Any number of regular expressions can be configured, each corresponding to an output of the node. The output port of the first matching regex will be ran, and all other output ports will not be ran.\n `,\n infoBoxTitle: 'Match Node',\n contextMenuTitle: 'Match',\n group: ['Logic'],\n };\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const inputString = coerceType(inputs['input' as PortId], 'string');\n const value = inputs['value' as PortId];\n\n const outputType = value === undefined ? 'string' : value.type;\n const outputValue = value === undefined ? inputString : value.value;\n\n const cases = this.data.cases;\n let matched = false;\n const output: Outputs = {};\n\n for (let i = 0; i < cases.length; i++) {\n const regExp = new RegExp(cases[i]!);\n const match = regExp.test(inputString);\n\n const canMatch = !this.data.exclusive || !matched;\n if (match && canMatch) {\n matched = true;\n output[`case${i + 1}` as PortId] = {\n type: outputType,\n value: outputValue,\n } as DataValue;\n } else {\n output[`case${i + 1}` as PortId] = {\n type: 'control-flow-excluded',\n value: undefined,\n };\n }\n }\n\n if (!matched) {\n output['unmatched' as PortId] = {\n type: outputType,\n value: outputValue,\n } as DataValue;\n } else {\n output['unmatched' as PortId] = {\n type: 'control-flow-excluded',\n value: undefined,\n };\n }\n\n return output;\n }\n}\n\nexport const matchNode = nodeDefinition(MatchNodeImpl, 'Match');\n", "import { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport {\n type ControlFlowExcludedDataValue,\n type ScalarDataValue,\n type ArrayDataValue,\n type DataValue,\n} from '../DataValue.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\nimport { dedent } from 'ts-dedent';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport type IfNode = ChartNode<'if', IfNodeData>;\n\nexport type IfNodeData = {\n unconnectedControlFlowExcluded?: boolean;\n};\n\nexport class IfNodeImpl extends NodeImpl<IfNode> {\n static create = (): IfNode => {\n const chartNode: IfNode = {\n type: 'if',\n title: 'If',\n id: nanoid() as NodeId,\n data: {\n // Legacy behavior is false\n unconnectedControlFlowExcluded: true,\n },\n visualData: {\n x: 0,\n y: 0,\n width: 125,\n },\n };\n return chartNode;\n };\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n {\n id: 'if' as PortId,\n title: 'If',\n dataType: 'any',\n description:\n 'If this is truthy, the value will be passed through the True port. Otherwise, it will be passed through the False port. An unconnected port is considered false.',\n },\n {\n id: 'value' as PortId,\n title: 'Value',\n dataType: 'any',\n description: 'The value to pass through the True or False port. If unconnected, it will be undefined.',\n },\n ];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'output' as PortId,\n title: 'True',\n dataType: 'any',\n description: 'The `value` passed through if the condition is truthy.',\n },\n {\n id: 'falseOutput' as PortId,\n title: 'False',\n dataType: 'any',\n description: 'The `value` passed through if the condition is falsy.',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Takes in a condition and a value. If the condition is truthy, the value is passed through the True port, and the False port is not ran.\n If the condition is falsy, the value is passed through the False port, and the True port is not ran.\n `,\n infoBoxTitle: 'If Node',\n contextMenuTitle: 'If',\n group: ['Logic'],\n };\n }\n\n getEditors(): EditorDefinition<IfNode>[] {\n return [\n {\n type: 'toggle',\n label: \"Don't run unconnected value\",\n dataKey: 'unconnectedControlFlowExcluded',\n },\n ];\n }\n\n async process(inputData: Inputs): Promise<Outputs> {\n const unconnectedValue: DataValue = this.data.unconnectedControlFlowExcluded\n ? { type: 'control-flow-excluded', value: undefined }\n : { type: 'any', value: undefined };\n\n const ifValue = inputData['if' as PortId];\n const value = inputData['value' as PortId] ?? unconnectedValue;\n\n const isFalse = {\n output: {\n type: 'control-flow-excluded',\n value: undefined,\n } as ControlFlowExcludedDataValue,\n falseOutput: value,\n };\n\n if (!ifValue) {\n return isFalse;\n }\n\n if (ifValue.type === 'control-flow-excluded') {\n return isFalse;\n }\n\n if (ifValue.type === 'string' && !ifValue.value) {\n return isFalse;\n }\n\n if (ifValue.type === 'boolean' && !ifValue.value) {\n return isFalse;\n }\n\n if (ifValue.type === 'chat-message') {\n const asString = coerceType(ifValue, 'string');\n\n if (!asString) {\n return isFalse;\n }\n }\n\n if (ifValue.type.endsWith('[]')) {\n const value = ifValue as ArrayDataValue<ScalarDataValue>;\n\n if (!value.value || value.value.length === 0) {\n return isFalse;\n }\n }\n\n return {\n ['output' as PortId]: value,\n ['falseOutput' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n } as ControlFlowExcludedDataValue,\n };\n }\n}\n\nexport const ifNode = nodeDefinition(IfNodeImpl, 'If');\n", "import {\n type ChartNode,\n type NodeId,\n type PortId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type NodeBodySpec } from '../../index.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { expectType } from '../../utils/expectType.js';\n\nexport type ReadDirectoryNode = ChartNode<'readDirectory', ReadDirectoryNodeData>;\n\ntype ReadDirectoryNodeData = {\n path: string;\n usePathInput: boolean;\n\n recursive: boolean;\n useRecursiveInput: boolean;\n\n includeDirectories: boolean;\n useIncludeDirectoriesInput: boolean;\n\n filterGlobs: string[];\n useFilterGlobsInput: boolean;\n\n relative: boolean;\n useRelativeInput: boolean;\n\n ignores?: string[];\n useIgnoresInput: boolean;\n};\n\nexport class ReadDirectoryNodeImpl extends NodeImpl<ReadDirectoryNode> {\n static create(): ReadDirectoryNode {\n return {\n id: nanoid() as NodeId,\n type: 'readDirectory',\n title: 'Read Directory',\n visualData: { x: 0, y: 0 },\n data: {\n path: 'examples',\n recursive: false,\n usePathInput: false,\n useRecursiveInput: false,\n includeDirectories: false,\n useIncludeDirectoriesInput: false,\n filterGlobs: [],\n useFilterGlobsInput: false,\n relative: false,\n useRelativeInput: false,\n ignores: [],\n useIgnoresInput: false,\n },\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputDefinitions: NodeInputDefinition[] = [];\n\n if (this.chartNode.data.usePathInput) {\n inputDefinitions.push({\n id: 'path' as PortId,\n title: 'Path',\n dataType: 'string',\n required: true,\n coerced: false,\n });\n }\n\n if (this.chartNode.data.useRecursiveInput) {\n inputDefinitions.push({\n id: 'recursive' as PortId,\n title: 'Recursive',\n dataType: 'boolean',\n required: true,\n coerced: false,\n });\n }\n\n if (this.chartNode.data.useIncludeDirectoriesInput) {\n inputDefinitions.push({\n id: 'includeDirectories' as PortId,\n title: 'Include Directories',\n dataType: 'boolean',\n required: true,\n coerced: false,\n });\n }\n\n if (this.chartNode.data.useFilterGlobsInput) {\n inputDefinitions.push({\n id: 'filterGlobs' as PortId,\n title: 'Filter Globs',\n dataType: 'string[]',\n required: true,\n coerced: false,\n });\n }\n\n if (this.chartNode.data.useRelativeInput) {\n inputDefinitions.push({\n id: 'relative' as PortId,\n title: 'Relative',\n dataType: 'boolean',\n required: true,\n coerced: false,\n });\n }\n\n return inputDefinitions;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'rootPath' as PortId,\n title: 'Root Path',\n dataType: 'string',\n },\n {\n id: 'paths' as PortId,\n title: 'Paths',\n dataType: 'string[]',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n return dedent`\n Path: ${this.data.usePathInput ? '(Input)' : this.data.path}\n Recursive: ${this.data.useRecursiveInput ? '(Input)' : this.data.recursive}\n Include Directories: ${this.data.useIncludeDirectoriesInput ? '(Input)' : this.data.includeDirectories}\n Relative: ${this.data.useRelativeInput ? '(Input)' : this.data.relative}\n Filters: ${\n this.data.useFilterGlobsInput\n ? '(Input)'\n : this.data.filterGlobs.length > 0\n ? this.data.filterGlobs.join(', ')\n : 'None'\n }\n `;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Reads the contents of the specified directory and outputs an array of filenames.\n `,\n infoBoxTitle: 'Read Directory Node',\n contextMenuTitle: 'Read Directory',\n group: ['Input/Output'],\n };\n }\n\n async process(inputData: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const { nativeApi } = context;\n\n if (nativeApi == null) {\n throw new Error('This node requires a native API to run.');\n }\n\n const path = this.chartNode.data.usePathInput\n ? expectType(inputData['path' as PortId], 'string')\n : this.chartNode.data.path;\n\n const recursive = this.chartNode.data.useRecursiveInput\n ? expectType(inputData['recursive' as PortId], 'boolean')\n : this.chartNode.data.recursive;\n\n const includeDirectories = this.chartNode.data.useIncludeDirectoriesInput\n ? expectType(inputData['includeDirectories' as PortId], 'boolean')\n : this.chartNode.data.includeDirectories;\n\n const filterGlobs = this.chartNode.data.useFilterGlobsInput\n ? expectType(inputData['filterGlobs' as PortId], 'string[]')\n : this.chartNode.data.filterGlobs;\n\n const relative = this.chartNode.data.useRelativeInput\n ? expectType(inputData['relative' as PortId], 'boolean')\n : this.chartNode.data.relative;\n\n const ignores = this.chartNode.data.useIgnoresInput\n ? expectType(inputData['ignores' as PortId], 'string[]')\n : this.chartNode.data.ignores;\n\n try {\n const files = await nativeApi.readdir(path, undefined, {\n recursive,\n includeDirectories,\n filterGlobs,\n relative,\n ignores,\n });\n\n const outputs: Outputs = {\n ['paths' as PortId]: { type: 'string[]', value: files },\n ['rootPath' as PortId]: { type: 'string', value: path },\n };\n\n return outputs;\n } catch (err) {\n const outputs: Outputs = {\n ['paths' as PortId]: { type: 'string[]', value: ['(no such path)'] },\n ['rootPath' as PortId]: { type: 'string', value: path },\n };\n\n return outputs;\n }\n }\n}\n\nexport const readDirectoryNode = nodeDefinition(ReadDirectoryNodeImpl, 'Read Directory');\n", "import {\n type ChartNode,\n type NodeId,\n type PortId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { type DataValue } from '../DataValue.js';\nimport { NodeImpl, type NodeBody, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { getInputOrData } from '../../utils/index.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\n\nexport type ReadFileNode = ChartNode<'readFile', ReadFileNodeData>;\n\ntype ReadFileNodeData = {\n path: string;\n usePathInput: boolean;\n\n asBinary?: boolean;\n\n errorOnMissingFile?: boolean;\n};\n\nexport class ReadFileNodeImpl extends NodeImpl<ReadFileNode> {\n static create(): ReadFileNode {\n return {\n id: nanoid() as NodeId,\n type: 'readFile',\n title: 'Read File',\n visualData: { x: 0, y: 0, width: 250 },\n data: {\n path: '',\n asBinary: false,\n usePathInput: true,\n errorOnMissingFile: false,\n },\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputDefinitions: NodeInputDefinition[] = [];\n\n if (this.chartNode.data.usePathInput) {\n inputDefinitions.push({\n id: 'path' as PortId,\n title: 'Path',\n dataType: 'string',\n coerced: false,\n });\n }\n\n return inputDefinitions;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'content' as PortId,\n title: 'Content',\n dataType: this.data.asBinary ? 'binary' : 'string',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Reads the contents of the specified file and outputs it as a string.\n `,\n infoBoxTitle: 'Read File Node',\n contextMenuTitle: 'Read File',\n group: ['Input/Output'],\n };\n }\n\n getEditors(): EditorDefinition<ReadFileNode>[] {\n return [\n {\n type: 'filePathBrowser',\n label: 'Path',\n dataKey: 'path',\n useInputToggleDataKey: 'usePathInput',\n },\n {\n type: 'toggle',\n label: 'Error on Missing File',\n dataKey: 'errorOnMissingFile',\n },\n {\n type: 'toggle',\n label: 'Read as Binary',\n dataKey: 'asBinary',\n },\n ];\n }\n\n getBody(): NodeBody {\n return dedent`\n ${this.data.asBinary ? 'Read as Binary' : 'Read as Text'}\n ${this.data.usePathInput ? '' : `Path: ${this.data.path}`}\n `;\n }\n\n async process(\n inputData: Record<PortId, DataValue>,\n context: InternalProcessContext,\n ): Promise<Record<PortId, DataValue>> {\n const { nativeApi } = context;\n\n if (nativeApi == null) {\n throw new Error('This node requires a native API to run.');\n }\n\n const path = getInputOrData(this.chartNode.data, inputData, 'path');\n\n try {\n if (this.data.asBinary) {\n const content = await nativeApi.readBinaryFile(path);\n const buffer = await content.arrayBuffer();\n return {\n ['content' as PortId]: { type: 'binary', value: new Uint8Array(buffer) },\n };\n } else {\n const content = await nativeApi.readTextFile(path, undefined);\n return {\n ['content' as PortId]: { type: 'string', value: content },\n };\n }\n } catch (err) {\n if (this.chartNode.data.errorOnMissingFile) {\n throw err;\n } else {\n return {\n ['content' as PortId]: { type: 'control-flow-excluded', value: undefined },\n };\n }\n }\n }\n}\n\nexport const readFileNode = nodeDefinition(ReadFileNodeImpl, 'Read File');\n", "import { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { type ArrayDataValue, type DataValue, type ScalarDataValue } from '../DataValue.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport type IfElseNode = ChartNode<'ifElse', IfElseNodeData>;\n\nexport type IfElseNodeData = {\n /** If true, unconnected input ports are control-flow-excluded. */\n unconnectedControlFlowExcluded?: boolean;\n};\n\nexport class IfElseNodeImpl extends NodeImpl<IfElseNode> {\n static create = (): IfElseNode => {\n const chartNode: IfElseNode = {\n type: 'ifElse',\n title: 'If/Else',\n id: nanoid() as NodeId,\n data: {\n // Legacy behavior is false\n unconnectedControlFlowExcluded: true,\n },\n visualData: {\n x: 0,\n y: 0,\n width: 175,\n },\n };\n return chartNode;\n };\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n {\n id: 'if' as PortId,\n title: 'If',\n dataType: 'any',\n description:\n 'If this is truthy, the `true` value will be passed through the output port. Otherwise, the `false` value will be passed through the output port. An unconnected port is considered false. A `Not Ran` value is considered false.',\n },\n {\n id: 'true' as PortId,\n title: 'True',\n dataType: 'any',\n description: 'The value to pass through the output port if the condition is truthy. ',\n },\n {\n id: 'false' as PortId,\n title: 'False',\n dataType: 'any',\n description: 'The value to pass through the output port if the condition is not truthy.',\n },\n ];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'output' as PortId,\n title: 'Output',\n dataType: 'any',\n description: 'The `true` or `false` value, depending on the `if` condition.',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Takes in three inputs: a condition, a true value, and a false value. If the condition is truthy, the true value is passed through the output port. If the condition is not truthy, the false value is passed through the output port.\n\n This node can \"consume\" a \\`Not Ran\\` to continue a graph from that point.\n `,\n infoBoxTitle: 'If/Else Node',\n contextMenuTitle: 'If/Else',\n group: ['Logic'],\n };\n }\n\n getEditors(): EditorDefinition<IfElseNode>[] {\n return [\n {\n type: 'toggle',\n label: \"Don't run unconnected ports\",\n dataKey: 'unconnectedControlFlowExcluded',\n },\n ];\n }\n\n async process(inputData: Record<PortId, DataValue>): Promise<Record<PortId, DataValue>> {\n const unconnectedValue: DataValue = this.data.unconnectedControlFlowExcluded\n ? { type: 'control-flow-excluded', value: undefined }\n : {\n type: 'any',\n value: undefined,\n };\n\n const ifValue = inputData['if' as PortId];\n const trueValue = inputData['true' as PortId] ?? unconnectedValue;\n const falseValue = inputData['false' as PortId] ?? unconnectedValue;\n\n if (!(trueValue || falseValue)) {\n return {\n ['output' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n if (ifValue?.type === 'control-flow-excluded') {\n return {\n ['output' as PortId]: falseValue,\n };\n }\n\n if (ifValue?.value == null) {\n return {\n ['output' as PortId]: falseValue,\n };\n }\n\n if (ifValue?.type && ifValue.type === 'boolean') {\n return {\n ['output' as PortId]: ifValue.value ? trueValue : falseValue,\n };\n }\n\n if (ifValue?.type === 'string') {\n return {\n ['output' as PortId]: ifValue.value.length > 0 ? trueValue : falseValue,\n };\n }\n\n if (ifValue?.type === 'chat-message') {\n const asString = coerceType(ifValue, 'string');\n\n return {\n ['output' as PortId]: asString ? trueValue : falseValue,\n };\n }\n\n if (ifValue?.type.endsWith('[]')) {\n return {\n ['output' as PortId]: (ifValue as ArrayDataValue<ScalarDataValue>).value.length > 0 ? trueValue : falseValue,\n };\n }\n\n if (ifValue?.type === 'any' || ifValue?.type === 'object') {\n return {\n ['output' as PortId]: !!ifValue.value ? trueValue : falseValue,\n };\n }\n\n return {\n ['output' as PortId]: falseValue,\n };\n }\n}\n\nexport const ifElseNode = nodeDefinition(IfElseNodeImpl, 'If/Else');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../../model/NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../../model/NodeImpl.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { dedent } from 'ts-dedent';\nimport { openAiModelOptions, openaiModels } from '../../utils/openai.js';\nimport { type EditorDefinition, type Inputs, type InternalProcessContext, type Outputs } from '../../index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport type { Tokenizer, TokenizerCallInfo } from '../../integrations/Tokenizer.js';\n\nexport type ChunkNodeData = {\n numTokensPerChunk: number;\n\n model: string;\n useModelInput: boolean;\n\n overlap: number;\n};\n\nexport type ChunkNode = ChartNode<'chunk', ChunkNodeData>;\n\nexport class ChunkNodeImpl extends NodeImpl<ChunkNode> {\n static create() {\n const chartNode: ChunkNode = {\n type: 'chunk',\n title: 'Chunk',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 200,\n },\n data: {\n model: 'gpt-3.5-turbo',\n useModelInput: false,\n numTokensPerChunk: 1024,\n overlap: 0,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [\n {\n id: 'input' as PortId,\n title: 'Input',\n dataType: 'string',\n },\n ];\n\n if (this.data.useModelInput) {\n inputs.push({\n id: 'model' as PortId,\n title: 'Model',\n dataType: 'string',\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'chunks' as PortId,\n title: 'Chunks',\n dataType: 'string[]',\n },\n {\n id: 'first' as PortId,\n title: 'First',\n dataType: 'string',\n },\n {\n id: 'last' as PortId,\n title: 'Last',\n dataType: 'string',\n },\n {\n id: 'indexes' as PortId,\n title: 'Indexes',\n dataType: 'number[]',\n },\n {\n id: 'count' as PortId,\n title: 'Count',\n dataType: 'number',\n },\n ];\n }\n\n getEditors(): EditorDefinition<ChunkNode>[] {\n return [\n {\n type: 'dropdown',\n label: 'Model',\n dataKey: 'model',\n options: openAiModelOptions,\n useInputToggleDataKey: 'useModelInput',\n },\n {\n type: 'number',\n label: 'Number of tokens per chunk',\n dataKey: 'numTokensPerChunk',\n min: 1,\n max: 32768,\n step: 1,\n },\n {\n type: 'number',\n label: 'Overlap (in %)',\n dataKey: 'overlap',\n min: 0,\n max: 100,\n step: 1,\n },\n ];\n }\n\n getBody(): string | undefined {\n return dedent`\n Model: ${this.data.model}\n Token Count: ${this.data.numTokensPerChunk.toLocaleString()}\n ${this.data.overlap ? `Overlap: ${this.data.overlap}%` : ''}\n `;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Splits the input text into an array of chunks based on an approximate GPT token count per chunk.\n\n The \"overlap\" setting allows you to partially overlap the chunks for redundancy.\n\n Can also be used for string length truncation by only using the \\`First\\` or \\`Last\\` outputs of the node.\n `,\n infoBoxTitle: 'Chunk Node',\n contextMenuTitle: 'Chunk',\n group: ['Text'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const input = coerceType(inputs['input' as PortId], 'string');\n\n const overlapPercent = this.chartNode.data.overlap / 100;\n\n const chunked = await chunkStringByTokenCount(\n context.tokenizer,\n {\n node: this.chartNode,\n endpoint: undefined,\n model: this.data.model,\n },\n input,\n this.chartNode.data.numTokensPerChunk,\n overlapPercent,\n );\n\n return {\n ['chunks' as PortId]: {\n type: 'string[]',\n value: chunked,\n },\n ['first' as PortId]: {\n type: 'string',\n value: chunked[0]!,\n },\n ['last' as PortId]: {\n type: 'string',\n value: chunked.at(-1)!,\n },\n ['indexes' as PortId]: {\n type: 'number[]',\n value: chunked.map((_, i) => i + 1),\n },\n ['count' as PortId]: {\n type: 'number',\n value: chunked.length,\n },\n };\n }\n}\n\nexport const chunkNode = nodeDefinition(ChunkNodeImpl, 'Chunk');\n\nexport async function chunkStringByTokenCount(\n tokenizer: Tokenizer,\n tokenizerInfo: TokenizerCallInfo,\n input: string,\n targetTokenCount: number,\n overlapPercent: number,\n) {\n overlapPercent = Number.isNaN(overlapPercent) ? 0 : Math.max(0, Math.min(1, overlapPercent));\n\n const chunks: string[] = [];\n const guess = Math.floor(\n targetTokenCount * (input.length / (await tokenizer.getTokenCountForString(input, tokenizerInfo))),\n );\n let remaining = input;\n\n while (remaining.length > 0) {\n chunks.push(remaining.slice(0, guess));\n remaining = remaining.slice(guess - Math.floor(guess * overlapPercent));\n }\n\n return chunks;\n}\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataType, type DataValue, getDefaultValue, isArrayDataType } from '../DataValue.js';\nimport { type Inputs } from '../GraphProcessor.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { type DynamicEditorEditor, type EditorDefinition, type NodeBodySpec } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceTypeOptional, inferType } from '../../utils/coerceType.js';\n\nexport type GraphInputNode = ChartNode<'graphInput', GraphInputNodeData>;\n\nexport type GraphInputNodeData = {\n id: string;\n dataType: DataType;\n defaultValue?: unknown;\n useDefaultValueInput?: boolean;\n editor?: DynamicEditorEditor;\n};\n\nexport class GraphInputNodeImpl extends NodeImpl<GraphInputNode> {\n static create(): GraphInputNode {\n const chartNode: GraphInputNode = {\n type: 'graphInput',\n title: 'Graph Input',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 300,\n },\n data: {\n id: 'input',\n dataType: 'string',\n defaultValue: undefined,\n useDefaultValueInput: false,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n if (this.data.useDefaultValueInput) {\n return [\n {\n id: 'default' as PortId,\n title: 'Default Value',\n dataType: this.chartNode.data.dataType as DataType,\n },\n ];\n }\n\n return [];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'data' as PortId,\n title: this.data.id,\n dataType: this.chartNode.data.dataType as DataType,\n },\n ];\n }\n\n getEditors(): EditorDefinition<GraphInputNode>[] {\n return [\n {\n type: 'string',\n label: 'ID',\n dataKey: 'id',\n },\n {\n type: 'dataTypeSelector',\n label: 'Data Type',\n dataKey: 'dataType',\n },\n {\n type: 'anyData',\n label: 'Default Value',\n dataKey: 'defaultValue',\n useInputToggleDataKey: 'useDefaultValueInput',\n },\n {\n type: 'dropdown',\n label: 'Editor',\n dataKey: 'editor',\n defaultValue: 'auto',\n options: [\n { label: 'None', value: 'none' },\n { label: 'Auto', value: 'auto' },\n { label: 'String', value: 'string' },\n { label: 'Number', value: 'number' },\n { label: 'Code', value: 'code' },\n { label: 'Data Type', value: 'dataTypeSelector' },\n { label: 'String List', value: 'stringList' },\n { label: 'Key Value Pairs', value: 'keyValuePair' },\n { label: 'Toggle', value: 'toggle' },\n ] satisfies { label: string; value: DynamicEditorEditor }[],\n helperMessage: 'The editor to use when editing this value in the UI. Make sure this matches the data type.',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n return dedent`\n ${this.data.id}\n Type: ${this.data.dataType}\n ${this.data.defaultValue == null ? '' : `Default: ${this.data.defaultValue}`}\n `;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Defines an input for the graph which can be passed in when the graph is called, or defines one of the input ports when the graph is a subgraph.\n `,\n infoBoxTitle: 'Graph Input Node',\n contextMenuTitle: 'Graph Input',\n group: ['Input/Output'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Record<string, DataValue>> {\n let inputValue =\n context.graphInputs[this.data.id] == null\n ? undefined\n : coerceTypeOptional(context.graphInputs[this.data.id], this.data.dataType);\n\n if (inputValue == null && this.data.useDefaultValueInput) {\n inputValue = coerceTypeOptional(inputs['default' as PortId], this.data.dataType);\n }\n\n if (inputValue == null) {\n inputValue =\n coerceTypeOptional(inferType(this.data.defaultValue), this.data.dataType) ||\n getDefaultValue(this.data.dataType);\n }\n\n // Resolve undefined for array inputs to empty array\n if (inputValue == null && isArrayDataType(this.data.dataType)) {\n inputValue = { type: this.data.dataType, value: [] } as DataValue;\n }\n\n const value = {\n type: this.data.dataType,\n value: inputValue,\n } as DataValue;\n\n return { ['data' as PortId]: value };\n }\n}\n\nexport const graphInputNode = nodeDefinition(GraphInputNodeImpl, 'Graph Input');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeOutputDefinition,\n type PortId,\n type NodeInputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataType } from '../DataValue.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\n\nexport type GraphOutputNode = ChartNode<'graphOutput', GraphOutputNodeData>;\n\nexport type GraphOutputNodeData = {\n id: string;\n dataType: DataType;\n};\n\nexport class GraphOutputNodeImpl extends NodeImpl<GraphOutputNode> {\n static create(): GraphOutputNode {\n const chartNode: GraphOutputNode = {\n type: 'graphOutput',\n title: 'Graph Output',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 300,\n },\n data: {\n id: 'output',\n dataType: 'string',\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n {\n id: 'value' as PortId,\n title: this.data.id,\n dataType: this.chartNode.data.dataType as DataType,\n },\n ];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'valueOutput' as PortId,\n title: this.data.id,\n dataType: this.chartNode.data.dataType as DataType,\n },\n ];\n }\n\n getEditors(): EditorDefinition<GraphOutputNode>[] {\n return [\n {\n type: 'string',\n label: 'ID',\n dataKey: 'id',\n },\n {\n type: 'dataTypeSelector',\n label: 'Data Type',\n dataKey: 'dataType',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n return dedent`\n ${this.data.id}\n Type: ${this.data.dataType}\n `;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Each instance of this node represents an individual output of the graph. The value passed into this node becomes part of the overall output of the graph.\n `,\n infoBoxTitle: 'Graph Output Node',\n contextMenuTitle: 'Graph Output',\n group: ['Input/Output'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const value = inputs['value' as PortId] ?? { type: 'any', value: undefined };\n\n const isExcluded = value.type === 'control-flow-excluded';\n\n if (isExcluded && context.graphOutputs[this.data.id] == null) {\n context.graphOutputs[this.data.id] = {\n type: 'control-flow-excluded',\n value: undefined,\n };\n } else if (\n (context.graphOutputs[this.data.id] == null ||\n context.graphOutputs[this.data.id]?.type === 'control-flow-excluded') &&\n inputs['value' as PortId]\n ) {\n context.graphOutputs[this.data.id] = value;\n }\n\n if (isExcluded) {\n return {\n ['valueOutput' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n return {\n ['valueOutput' as PortId]: context.graphOutputs[this.data.id],\n };\n }\n}\n\nexport const graphOutputNode = nodeDefinition(GraphOutputNodeImpl, 'Graph Output');\n", "import { nanoid } from 'nanoid/non-secure';\nimport { type ChartNode, type NodeConnection } from './NodeBase.js';\nimport type { Opaque } from 'type-fest';\nimport { type AttachedData } from '../utils/serialization/serializationUtils.js';\n\nexport type GraphId = Opaque<string, 'GraphId'>;\n\nexport interface NodeGraph {\n metadata?: {\n id?: GraphId;\n name?: string;\n description?: string;\n\n attachedData?: AttachedData;\n };\n\n nodes: ChartNode[];\n connections: NodeConnection[];\n}\n\nexport function emptyNodeGraph(): NodeGraph {\n return {\n nodes: [],\n connections: [],\n metadata: {\n id: nanoid() as GraphId,\n name: 'Untitled Graph',\n description: '',\n },\n };\n}\n", "import {\n type ChartNode,\n type NodeConnection,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type GraphId } from '../NodeGraph.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Project } from '../Project.js';\nimport { type GraphInputNode } from './GraphInputNode.js';\nimport { type GraphOutputNode } from './GraphOutputNode.js';\nimport { type DataValue } from '../DataValue.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { type DynamicEditorEditor, type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { getError } from '../../utils/errors.js';\nimport { match } from 'ts-pattern';\nimport type { RivetUIContext } from '../RivetUIContext.js';\n\nexport type SubGraphNode = ChartNode & {\n type: 'subGraph';\n data: {\n graphId: GraphId;\n useErrorOutput?: boolean;\n useAsGraphPartialOutput?: boolean;\n\n /** Data for each of the inputs of the subgraph */\n inputData?: Record<string, DataValue>;\n };\n};\n\nexport class SubGraphNodeImpl extends NodeImpl<SubGraphNode> {\n static create(): SubGraphNode {\n const chartNode: SubGraphNode = {\n type: 'subGraph',\n title: 'Subgraph',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 300,\n },\n data: {\n graphId: '' as GraphId,\n useErrorOutput: false,\n useAsGraphPartialOutput: false,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(\n _connections: NodeConnection[],\n _nodes: Record<NodeId, ChartNode>,\n project: Project,\n ): NodeInputDefinition[] {\n const graph = project.graphs[this.data.graphId];\n if (!graph) {\n return [];\n }\n\n const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput') as GraphInputNode[];\n const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();\n\n return inputIds.map(\n (id): NodeInputDefinition => ({\n id: id as PortId,\n title: id,\n dataType: inputNodes.find((node) => node.data.id === id)!.data.dataType,\n }),\n );\n }\n\n getGraphOutputs(project: Project): NodeOutputDefinition[] {\n const graph = project.graphs[this.data.graphId];\n if (!graph) {\n return [];\n }\n\n const outputNodes = graph.nodes.filter((node) => node.type === 'graphOutput') as GraphOutputNode[];\n const outputIds = [...new Set(outputNodes.map((node) => node.data.id))].sort();\n\n const outputs = outputIds.map(\n (id): NodeOutputDefinition => ({\n id: id as PortId,\n title: id,\n dataType: outputNodes.find((node) => node.data.id === id)!.data.dataType,\n }),\n );\n\n return outputs;\n }\n\n getOutputDefinitions(\n _connections: NodeConnection[],\n _nodes: Record<NodeId, ChartNode>,\n project: Project,\n ): NodeOutputDefinition[] {\n const outputs: NodeOutputDefinition[] = [];\n\n outputs.push(...this.getGraphOutputs(project));\n\n if (this.data.useErrorOutput) {\n outputs.push({\n id: 'error' as PortId,\n title: 'Error',\n dataType: 'string',\n });\n }\n\n return outputs;\n }\n\n getEditors(context: RivetUIContext): EditorDefinition<SubGraphNode>[] {\n const definitions: EditorDefinition<SubGraphNode>[] = [\n {\n type: 'graphSelector',\n label: 'Graph',\n dataKey: 'graphId',\n },\n {\n type: 'toggle',\n label: 'Use Error Output',\n dataKey: 'useErrorOutput',\n },\n ];\n\n if (this.data.graphId) {\n const graph = context.project.graphs[this.data.graphId];\n if (graph) {\n const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput') as GraphInputNode[];\n const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();\n\n for (const inputId of inputIds) {\n const inputNode = inputNodes.find((node) => node.data.id === inputId)!;\n definitions.push({\n type: 'dynamic',\n dataKey: 'inputData',\n dynamicDataKey: inputNode.data.id,\n dataType: inputNode.data.dataType,\n label: inputNode.data.id,\n editor: inputNode.data.editor ?? 'auto',\n });\n }\n }\n }\n\n return definitions;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Executes another graph. Inputs and outputs are defined by Graph Input and Graph Output nodes within the subgraph.\n `,\n infoBoxTitle: 'Subgraph Node',\n contextMenuTitle: 'Subgraph',\n group: ['Advanced'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const { project } = context;\n\n if (!project) {\n throw new Error('SubGraphNode requires a project to be set in the context.');\n }\n\n const graph = project.graphs[this.data.graphId];\n if (!graph) {\n throw new Error(`SubGraphNode requires a graph with id ${this.data.graphId} to be present in the project.`);\n }\n\n const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput') as GraphInputNode[];\n const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();\n\n const inputData = inputIds.reduce((obj, id): Inputs => {\n if (inputs[id as PortId] != null) {\n return {\n ...obj,\n [id]: inputs[id as PortId],\n };\n }\n\n if (this.data.inputData?.[id] != null) {\n return {\n ...obj,\n [id]: this.data.inputData[id],\n };\n }\n\n return obj;\n }, {} as Inputs);\n\n const subGraphProcessor = context.createSubProcessor(this.data.graphId, { signal: context.signal });\n\n try {\n const startTime = Date.now();\n\n const outputs = await subGraphProcessor.processGraph(\n context,\n inputData as Record<string, DataValue>,\n context.contextValues,\n );\n\n const duration = Date.now() - startTime;\n\n if (this.data.useErrorOutput) {\n outputs['error' as PortId] = {\n type: 'control-flow-excluded',\n value: undefined,\n };\n }\n\n if (outputs['duration' as PortId] == null) {\n outputs['duration' as PortId] = {\n type: 'number',\n value: duration,\n };\n }\n\n return outputs;\n } catch (err) {\n if (!this.data.useErrorOutput) {\n throw err;\n }\n\n const outputs: Outputs = this.getGraphOutputs(context.project).reduce(\n (obj, output): Outputs => ({\n ...obj,\n [output.id as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n }),\n {} as Outputs,\n );\n\n outputs['error' as PortId] = {\n type: 'string',\n value: getError(err).message,\n };\n\n return outputs;\n }\n }\n}\n\nexport const subGraphNode = nodeDefinition(SubGraphNodeImpl, 'Subgraph');\n", "import {\n type ChartNode,\n type NodeConnection,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeBody, type NodeUIData } from '../NodeImpl.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { entries } from '../../utils/typeSafety.js';\nimport { flattenDeep } from 'lodash-es';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\n\nexport type ArrayNode = ChartNode<'array', ArrayNodeData>;\n\nexport type ArrayNodeData = {\n flatten?: boolean;\n flattenDeep?: boolean;\n};\n\nexport class ArrayNodeImpl extends NodeImpl<ArrayNode> {\n static create(): ArrayNode {\n const chartNode: ArrayNode = {\n type: 'array',\n title: 'Array',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 200,\n },\n data: {\n flatten: true,\n flattenDeep: false,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n const inputCount = this.#getInputPortCount(connections);\n\n for (let i = 1; i <= inputCount; i++) {\n inputs.push({\n dataType: 'any',\n id: `input${i}` as PortId,\n title: `Input ${i}`,\n description:\n 'An input to create the array from. If an array, will be flattened if the \"Flatten\" option is enabled.',\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'any[]',\n id: 'output' as PortId,\n title: 'Output',\n description: 'The array created from the inputs.',\n },\n {\n dataType: 'number[]',\n id: 'indices' as PortId,\n title: 'Indices',\n description:\n 'The indices of the array. I.e. [0, 1, 2, 3, etc]. Useful for zipping with the output array to get the indexes.',\n },\n {\n dataType: 'number',\n id: 'length' as PortId,\n title: 'Length',\n description: 'The length of the output array.',\n },\n ];\n }\n\n getEditors(): EditorDefinition<ArrayNode>[] {\n return [\n { type: 'toggle', label: 'Flatten', dataKey: 'flatten' },\n {\n type: 'toggle',\n label: 'Deep',\n dataKey: 'flattenDeep',\n },\n ];\n }\n\n #getInputPortCount(connections: NodeConnection[]): number {\n const inputNodeId = this.chartNode.id;\n const inputConnections = connections.filter(\n (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'),\n );\n\n let maxInputNumber = 0;\n for (const connection of inputConnections) {\n const inputNumber = parseInt(connection.inputId.replace('input', ''));\n if (inputNumber > maxInputNumber) {\n maxInputNumber = inputNumber;\n }\n }\n\n return maxInputNumber + 1;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Creates an array from the input values. By default, flattens any arrays which are inputs into a single array. Can be configured to keep the arrays separate, or deeply flatten arrays.\n\n Useful for both creating and merging arrays.\n\n The number of inputs is dynamic based on the number of connections.\n `,\n infoBoxTitle: 'Array Node',\n contextMenuTitle: 'Array',\n group: ['Lists'],\n };\n }\n\n getBody(): NodeBody {\n return dedent`\n ${this.data.flatten ? (this.data.flattenDeep ? 'Flatten (Deep)' : 'Flatten') : 'No Flatten'}\n `;\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const outputArray: any[] = [];\n\n for (const [key, input] of entries(inputs)) {\n if (key.startsWith('input')) {\n if (this.data.flatten) {\n if (Array.isArray(input?.value)) {\n for (const value of input?.value ?? []) {\n if (this.data.flattenDeep) {\n outputArray.push(...(Array.isArray(value) ? flattenDeep(value) : [value]));\n } else {\n outputArray.push(value);\n }\n }\n } else {\n outputArray.push(input?.value);\n }\n } else {\n outputArray.push(input?.value);\n }\n }\n }\n\n return {\n ['output' as PortId]: {\n type: 'any[]',\n value: outputArray,\n },\n ['indices' as PortId]: {\n type: 'number[]',\n value: outputArray.map((_, index) => index),\n },\n ['length' as PortId]: {\n type: 'number',\n value: outputArray.length,\n },\n };\n }\n}\n\nexport const arrayNode = nodeDefinition(ArrayNodeImpl, 'Array');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { expectType } from '../../utils/index.js';\nimport { dedent } from 'ts-dedent';\n\nexport type ExtractJsonNode = ChartNode<'extractJson', ExtractJsonNodeData>;\n\nexport type ExtractJsonNodeData = {};\n\nexport class ExtractJsonNodeImpl extends NodeImpl<ExtractJsonNode> {\n static create(): ExtractJsonNode {\n const chartNode: ExtractJsonNode = {\n type: 'extractJson',\n title: 'Extract JSON',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {},\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n {\n id: 'input' as PortId,\n title: 'Input',\n dataType: 'string',\n required: true,\n coerced: false,\n },\n ];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'output' as PortId,\n title: 'Output',\n dataType: 'object',\n },\n {\n id: 'noMatch' as PortId,\n title: 'No Match',\n dataType: 'string',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Finds and parses the first JSON object in the input text.\n\n Outputs the parsed object.\n `,\n infoBoxTitle: 'Extract JSON Node',\n contextMenuTitle: 'Extract JSON',\n group: ['Objects'],\n };\n }\n\n async process(inputs: Record<PortId, DataValue>): Promise<Record<PortId, DataValue>> {\n const inputString = expectType(inputs['input' as PortId], 'string');\n\n try {\n const parsed = JSON.parse(inputString);\n return {\n ['output' as PortId]: {\n type: 'object',\n value: parsed,\n },\n ['noMatch' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n } catch (_err: unknown) {\n // Fall back to more manual parsing\n }\n\n // Find the first { or [ and the last } or ], and try parsing everything in between including them.\n\n let firstBracket = inputString.indexOf('{');\n let lastBracket = inputString.lastIndexOf('}');\n let firstSquareBracket = inputString.indexOf('[');\n let lastSquareBracket = inputString.lastIndexOf(']');\n\n const firstIndex =\n firstBracket >= 0 && firstSquareBracket >= 0\n ? Math.min(firstBracket, firstSquareBracket)\n : firstBracket >= 0\n ? firstBracket\n : firstSquareBracket;\n\n const lastIndex =\n lastBracket >= 0 && lastSquareBracket >= 0\n ? Math.max(lastBracket, lastSquareBracket)\n : lastBracket >= 0\n ? lastBracket\n : lastSquareBracket;\n\n const substring = inputString.substring(firstIndex, lastIndex + 1);\n\n let jsonObject: Record<string, unknown> | undefined = undefined;\n try {\n jsonObject = JSON.parse(substring);\n } catch (err) {\n return {\n ['noMatch' as PortId]: {\n type: 'string',\n value: inputString,\n },\n ['output' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n return {\n ['output' as PortId]: {\n type: 'object',\n value: jsonObject!,\n },\n ['noMatch' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n}\n\nexport const extractJsonNode = nodeDefinition(ExtractJsonNodeImpl, 'Extract JSON');\n", "import {\n type ChartNode,\n type NodeConnection,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { type ChatMessage, arrayizeDataValue, unwrapDataValue } from '../DataValue.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { orderBy } from 'lodash-es';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\nimport type { InternalProcessContext } from '../ProcessContext.js';\n\nexport type AssemblePromptNode = ChartNode<'assemblePrompt', AssemblePromptNodeData>;\n\nexport type AssemblePromptNodeData = {\n computeTokenCount?: boolean;\n};\n\nexport class AssemblePromptNodeImpl extends NodeImpl<AssemblePromptNode> {\n static create(): AssemblePromptNode {\n const chartNode: AssemblePromptNode = {\n type: 'assemblePrompt',\n title: 'Assemble Prompt',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {},\n };\n\n return chartNode;\n }\n\n getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n const messageCount = this.#getMessagePortCount(connections);\n\n for (let i = 1; i <= messageCount; i++) {\n inputs.push({\n dataType: ['chat-message', 'chat-message[]'] as const,\n id: `message${i}` as PortId,\n title: `Message ${i}`,\n description: 'A message, or messages, to include in the full prompt.',\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n const outputs: NodeOutputDefinition[] = [\n {\n dataType: 'chat-message[]',\n id: 'prompt' as PortId,\n title: 'Prompt',\n description: 'The assembled prompt, a list of chat messages.',\n },\n ];\n\n if (this.data.computeTokenCount) {\n outputs.push({\n dataType: 'number',\n id: 'tokenCount' as PortId,\n title: 'Token Count',\n description: 'The number of tokens in the full output prompt.',\n });\n }\n\n return outputs;\n }\n\n #getMessagePortCount(connections: NodeConnection[]): number {\n const inputNodeId = this.chartNode.id;\n const messageConnections = connections.filter(\n (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('message'),\n );\n\n let maxMessageNumber = 0;\n for (const connection of messageConnections) {\n const messageNumber = parseInt(connection.inputId.replace('message', ''));\n if (messageNumber > maxMessageNumber) {\n maxMessageNumber = messageNumber;\n }\n }\n\n return maxMessageNumber + 1;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Assembles an array of chat messages for use with a Chat node. The inputs can be strings or chat messages.\n\n The number of inputs is dynamic based on the number of connections.\n\n Strings are converted to User type chat messages.\n `,\n infoBoxTitle: 'Assemble Prompt Node',\n contextMenuTitle: 'Assemble Prompt',\n group: ['AI'],\n };\n }\n\n getEditors(_context: RivetUIContext): EditorDefinition<AssemblePromptNode>[] {\n return [\n {\n type: 'toggle',\n label: 'Compute Token Count',\n dataKey: 'computeTokenCount',\n },\n ];\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const output: Outputs = {};\n\n const outMessages: ChatMessage[] = [];\n\n const inputMessages = orderBy(\n Object.entries(inputs).filter(([key]) => key.startsWith('message')),\n ([key]) => key,\n 'asc',\n );\n\n for (const [, inputMessage] of inputMessages) {\n if (!inputMessage || inputMessage.type === 'control-flow-excluded' || !inputMessage.value) {\n continue;\n }\n\n const inMessages = arrayizeDataValue(unwrapDataValue(inputMessage));\n for (const message of inMessages) {\n if (message.type === 'chat-message') {\n outMessages.push(message.value);\n } else {\n const coerced = coerceType(message, 'chat-message');\n\n if (coerced) {\n outMessages.push(coerced);\n }\n }\n }\n }\n\n output['prompt' as PortId] = {\n type: 'chat-message[]',\n value: outMessages,\n };\n\n if (this.data.computeTokenCount) {\n const tokenCount = await context.tokenizer.getTokenCountForMessages(outMessages, undefined, {\n node: this.chartNode,\n });\n output['tokenCount' as PortId] = {\n type: 'number',\n value: tokenCount,\n };\n }\n\n return output;\n }\n}\n\nexport const assemblePromptNode = nodeDefinition(AssemblePromptNodeImpl, 'Assemble Prompt');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport yaml from 'yaml';\nimport { expectType } from '../../utils/expectType.js';\nimport { JSONPath } from 'jsonpath-plus';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition, type NodeBodySpec } from '../../index.js';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport type ExtractYamlNode = ChartNode<'extractYaml', ExtractYamlNodeData>;\n\nexport type ExtractYamlNodeData = {\n rootPropertyName: string;\n useRootPropertyNameInput?: boolean;\n objectPath?: string;\n useObjectPathInput?: boolean;\n};\n\nexport class ExtractYamlNodeImpl extends NodeImpl<ExtractYamlNode> {\n static create(): ExtractYamlNode {\n const chartNode: ExtractYamlNode = {\n type: 'extractYaml',\n title: 'Extract YAML',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n rootPropertyName: 'yamlDocument',\n useRootPropertyNameInput: false,\n useObjectPathInput: false,\n objectPath: undefined,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [\n {\n id: 'input' as PortId,\n title: 'Input',\n dataType: 'string',\n required: true,\n coerced: false,\n },\n ];\n\n if (this.data.useRootPropertyNameInput) {\n inputs.push({\n id: 'rootPropertyName' as PortId,\n title: 'Root Property Name',\n dataType: 'string',\n required: true,\n });\n }\n\n if (this.data.useObjectPathInput) {\n inputs.push({\n id: 'objectPath' as PortId,\n title: 'Object Path',\n dataType: 'string',\n required: true,\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'output' as PortId,\n title: 'Output',\n dataType: 'object',\n },\n {\n id: 'matches' as PortId,\n title: 'Matches',\n dataType: 'any[]',\n },\n {\n id: 'noMatch' as PortId,\n title: 'No Match',\n dataType: 'string',\n },\n ];\n }\n\n getEditors(): EditorDefinition<ExtractYamlNode>[] {\n return [\n {\n type: 'string',\n label: 'Root Property Name',\n dataKey: 'rootPropertyName',\n useInputToggleDataKey: 'useRootPropertyNameInput',\n },\n {\n type: 'code',\n label: 'Object Path',\n dataKey: 'objectPath',\n language: 'jsonpath',\n useInputToggleDataKey: 'useObjectPathInput',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n return dedent`\n Root: ${this.data.useRootPropertyNameInput ? '(Using Input)' : this.data.rootPropertyName}\n ${\n this.data.useObjectPathInput\n ? 'Path: (Using Input)'\n : this.data.objectPath\n ? `Path: ${this.data.objectPath}`\n : ``\n }\n `;\n }\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Finds and parses a YAML object in the input text with a predefined root property name (configurable).\n\n Defaults to \\`yamlDocument\\`, which means the input text must have a \\`yamlDocument:\\` root node somewhere in it. All indented text after that is considered part of the YAML.\n\n Outputs the parsed object.\n `,\n infoBoxTitle: 'Extract YAML Node',\n contextMenuTitle: 'Extract YAML',\n group: ['Objects'],\n };\n }\n\n async process(inputs: Record<PortId, DataValue>): Promise<Record<PortId, DataValue>> {\n const inputString = expectType(inputs['input' as PortId], 'string');\n\n const rootPropertyName = this.data.useRootPropertyNameInput\n ? coerceType(inputs['rootPropertyName' as PortId], 'string')\n : this.data.rootPropertyName;\n\n const objectPath = this.data.useObjectPathInput\n ? coerceType(inputs['objectPath' as PortId], 'string')\n : this.data.objectPath;\n\n const match = new RegExp(`^${rootPropertyName}:`, 'm').exec(inputString);\n const rootPropertyStart = match?.index ?? -1;\n\n const nextLines = inputString.slice(rootPropertyStart).split('\\n');\n const yamlLines = [nextLines.shift()]; // remove the first line, which is the root property name\n\n while (nextLines[0]?.startsWith(' ') || nextLines[0]?.startsWith('\\t') || nextLines[0] === '') {\n yamlLines.push(nextLines.shift());\n }\n\n const potentialYaml = yamlLines.join('\\n');\n\n let yamlObject: Record<string, unknown> | undefined = undefined;\n try {\n yamlObject = yaml.parse(potentialYaml);\n } catch (err) {\n return {\n ['noMatch' as PortId]: {\n type: 'string',\n value: potentialYaml,\n },\n ['output' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n if (!yamlObject?.hasOwnProperty(rootPropertyName)) {\n return {\n ['noMatch' as PortId]: {\n type: 'string',\n value: potentialYaml,\n },\n ['output' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n let matches: unknown[] = [];\n\n if (objectPath) {\n try {\n const extractedValue = JSONPath({ json: yamlObject, path: objectPath.trim() });\n matches = extractedValue;\n yamlObject = extractedValue.length > 0 ? extractedValue[0] : undefined;\n } catch (err) {\n return {\n ['noMatch' as PortId]: {\n type: 'string',\n value: potentialYaml,\n },\n ['output' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n ['matches' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n }\n\n return {\n ['output' as PortId]:\n yamlObject === undefined\n ? {\n type: 'control-flow-excluded',\n value: undefined,\n }\n : this.data.objectPath\n ? {\n type: 'any',\n value: yamlObject,\n }\n : {\n type: 'object',\n value: yamlObject,\n },\n ['noMatch' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n ['matches' as PortId]: {\n type: 'any[]',\n value: matches,\n },\n };\n }\n}\n\nexport const extractYamlNode = nodeDefinition(ExtractYamlNodeImpl, 'Extract YAML');\n", "import {\n type ChartNode,\n type NodeConnection,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../../index.js';\nimport { entries, values } from '../../utils/typeSafety.js';\n\nexport type LoopControllerNode = ChartNode<'loopController', LoopControllerNodeData>;\n\nexport type LoopControllerNodeData = {\n maxIterations?: number;\n atMaxIterationsAction?: 'break' | 'error';\n};\n\nexport class LoopControllerNodeImpl extends NodeImpl<LoopControllerNode> {\n static create(): LoopControllerNode {\n const chartNode: LoopControllerNode = {\n type: 'loopController',\n title: 'Loop Controller',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n maxIterations: 100,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(connections: NodeConnection[], nodes: Record<NodeId, ChartNode>): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n const messageCount = this.#getInputPortCount(connections);\n\n inputs.push({\n dataType: 'any',\n id: 'continue' as PortId,\n title: 'Continue',\n });\n\n let i = 1;\n for (; i <= messageCount + 1; i++) {\n const input: NodeInputDefinition = {\n dataType: 'any',\n id: `input${i}` as PortId,\n title: `Input ${i}`,\n };\n\n const inputConnection = connections.find(\n (connection) => connection.inputId === input.id && connection.inputNodeId === this.id,\n );\n if (inputConnection && nodes[inputConnection.outputNodeId]) {\n input.title = nodes[inputConnection.outputNodeId]!.title;\n }\n\n const inputDefault: NodeInputDefinition = {\n dataType: 'any',\n id: `input${i}Default` as PortId,\n title: `Input ${i} Default`,\n };\n const inputDefaultConnection = connections.find(\n (connection) => connection.inputId === inputDefault.id && connection.inputNodeId === this.id,\n );\n if (inputDefaultConnection && nodes[inputDefaultConnection.outputNodeId]) {\n inputDefault.title = `${nodes[inputDefaultConnection.outputNodeId]!.title} (Default)`;\n }\n\n inputs.push(input);\n inputs.push(inputDefault);\n }\n\n return inputs;\n }\n\n getOutputDefinitions(connections: NodeConnection[], nodes: Record<NodeId, ChartNode>): NodeOutputDefinition[] {\n const messageCount = this.#getInputPortCount(connections);\n\n const outputs: NodeOutputDefinition[] = [];\n\n outputs.push({\n dataType: 'any',\n id: 'break' as PortId,\n title: 'Break',\n });\n\n outputs.push({\n dataType: 'number',\n id: 'iteration' as PortId,\n title: 'Iteration',\n });\n\n for (let i = 1; i <= messageCount; i++) {\n const output: NodeOutputDefinition = {\n dataType: 'any',\n id: `output${i}` as PortId,\n title: `Output ${i}`,\n };\n\n const inputConnection = connections.find(\n (connection) => connection.inputId === `input${i}` && connection.inputNodeId === this.id,\n );\n if (inputConnection && nodes[inputConnection.outputNodeId]) {\n output.title = `${nodes[inputConnection.outputNodeId]!.title}?`;\n }\n\n outputs.push(output);\n }\n\n return outputs;\n }\n\n getEditors(): EditorDefinition<LoopControllerNode>[] {\n return [\n {\n type: 'number',\n label: 'Max Iterations',\n dataKey: 'maxIterations',\n },\n {\n type: 'dropdown',\n options: [\n {\n label: 'Break',\n value: 'break',\n },\n {\n label: 'Error',\n value: 'error',\n },\n ],\n label: 'At Max Iterations',\n dataKey: 'atMaxIterationsAction',\n defaultValue: 'error',\n helperMessage: 'What should happen when the max iterations is reached?',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Defines the entry point for a loop. Values from inside the loop should be passed back through the \"Input\" ports, and their corresponding \"Default\" values can be specified on the input ports as well.\n\n If the \"continue\" input is falsey, then the \"break\" output will run.\n `,\n infoBoxTitle: 'Loop Controller Node',\n contextMenuTitle: 'Loop Controller',\n group: ['Logic'],\n };\n }\n\n #getInputPortCount(connections: NodeConnection[]): number {\n const inputNodeId = this.chartNode.id;\n const messageConnections = connections.filter(\n (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'),\n );\n\n let maxMessageNumber = 0;\n for (const connection of messageConnections) {\n const messageNumber = parseInt(connection.inputId.replace('input', ''));\n if (messageNumber > maxMessageNumber) {\n maxMessageNumber = messageNumber;\n }\n }\n\n return maxMessageNumber;\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const output: Outputs = {};\n\n let inputCount = 0;\n while (inputs[`input${inputCount + 1}` as PortId] || inputs[`input${inputCount + 1}Default` as PortId]) {\n inputCount++;\n }\n\n const defaultInputs = entries(inputs).filter(([key]) => key.endsWith('Default'));\n\n // If any of the default inputs are control-flow-excluded, then exclude all outputs.\n // Technically, it should be \"any node outside of the cycle\" but this should be good enough?\n if (defaultInputs.some(([, value]) => value?.type === 'control-flow-excluded')) {\n for (let i = 0; i <= inputCount; i++) {\n output[`output${i}` as PortId] = { type: 'control-flow-excluded', value: undefined };\n }\n output['break' as PortId] = { type: 'control-flow-excluded', value: undefined };\n\n return output;\n }\n\n const iterationCount = context.attachedData.loopInfo?.iterationCount ?? 0;\n\n output['iteration' as PortId] = { type: 'number', value: iterationCount + 1 };\n\n if (iterationCount >= (this.data.maxIterations ?? 100) && this.data.atMaxIterationsAction !== 'break') {\n throw new Error(`Loop controller exceeded max iterations of ${this.data.maxIterations ?? 100}`);\n }\n\n // If the continue port is not connected (so undefined), or if it's undefined before it's\n // inside the loop itself (connection has not ran yet), then we should continue by default.\n let continueValue = false;\n\n if (inputs['continue' as PortId] === undefined) {\n continueValue = true;\n } else {\n const continueDataValue = inputs['continue' as PortId]!;\n if (continueDataValue.type === 'control-flow-excluded') {\n continueValue = false;\n } else {\n continueValue = coerceType(continueDataValue, 'boolean');\n }\n }\n\n if (iterationCount >= (this.data.maxIterations ?? 100) && this.data.atMaxIterationsAction === 'break') {\n continueValue = false;\n }\n\n if (continueValue) {\n output['break' as PortId] = { type: 'control-flow-excluded', value: 'loop-not-broken' };\n } else {\n const inputValues: unknown[] = [];\n for (let i = 1; i <= inputCount; i++) {\n inputValues.push(inputs[`input${i}` as PortId]?.value);\n }\n\n // Break gets an array of all the input values\n output['break' as PortId] = { type: 'any[]', value: inputValues };\n }\n\n for (let i = 1; i <= inputCount; i++) {\n if (continueValue) {\n const inputId = `input${i}` as PortId;\n const outputId = `output${i}` as PortId;\n\n if (inputs[inputId]) {\n output[outputId] = inputs[inputId]!;\n } else {\n output[outputId] = inputs[`${inputId}Default` as PortId]!;\n }\n } else {\n output[`output${i}` as PortId] = { type: 'control-flow-excluded', value: undefined };\n }\n }\n\n return output;\n }\n}\n\nexport const loopControllerNode = nodeDefinition(LoopControllerNodeImpl, 'Loop Controller');\n", "import {\n type ChartNode,\n type NodeId,\n type PortId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n} from '../../model/NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../../model/NodeImpl.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport {\n type EditorDefinition,\n type Inputs,\n type InternalProcessContext,\n type NodeBodySpec,\n type Outputs,\n} from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport type { TokenizerCallInfo } from '../../integrations/Tokenizer.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { getInputOrData } from '../../utils/index.js';\n\nexport type TrimChatMessagesNodeData = {\n maxTokenCount: number;\n useMaxTokenCountInput?: boolean;\n\n removeFromBeginning: boolean;\n useRemoveFromBeginningInput?: boolean;\n};\n\nexport type TrimChatMessagesNode = ChartNode<'trimChatMessages', TrimChatMessagesNodeData>;\n\nexport class TrimChatMessagesNodeImpl extends NodeImpl<TrimChatMessagesNode> {\n static create() {\n const chartNode: TrimChatMessagesNode = {\n type: 'trimChatMessages',\n title: 'Trim Chat Messages',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 200,\n },\n data: {\n maxTokenCount: 4096,\n removeFromBeginning: true,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [\n {\n id: 'input' as PortId,\n title: 'Input',\n dataType: 'chat-message[]',\n },\n ];\n\n if (this.data.useMaxTokenCountInput) {\n inputs.push({\n id: 'maxTokenCount' as PortId,\n title: 'Max Token Count',\n dataType: 'number',\n });\n }\n\n if (this.data.useRemoveFromBeginningInput) {\n inputs.push({\n id: 'removeFromBeginning' as PortId,\n title: 'Remove From Beginning',\n dataType: 'boolean',\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'trimmed' as PortId,\n title: 'Trimmed',\n dataType: 'chat-message[]',\n },\n ];\n }\n\n getEditors(): EditorDefinition<TrimChatMessagesNode>[] {\n return [\n {\n type: 'number',\n label: 'Max Token Count',\n dataKey: 'maxTokenCount',\n useInputToggleDataKey: 'useMaxTokenCountInput',\n },\n {\n type: 'toggle',\n label: 'Remove From Beginning',\n dataKey: 'removeFromBeginning',\n useInputToggleDataKey: 'useRemoveFromBeginningInput',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n return dedent`\n Max Token Count: ${this.data.useMaxTokenCountInput ? '(From Input)' : this.data.maxTokenCount}\n Remove From Beginning: ${\n this.data.useRemoveFromBeginningInput ? '(From Input)' : this.data.removeFromBeginning ? 'Yes' : 'No'\n }\n `;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Takes an array of chat messages, and slices messages from the beginning or the end of the list until the total length of the messages is under the configured token length.\n\n Useful for setting up infinite message chains that stay under the LLM context limit.\n `,\n infoBoxTitle: 'Trim Chat Messages Node',\n contextMenuTitle: 'Trim Chat Messages',\n group: ['AI'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext<TrimChatMessagesNode>): Promise<Outputs> {\n const input = coerceType(inputs['input' as PortId], 'chat-message[]');\n\n const maxTokenCount = getInputOrData(this.data, inputs, 'maxTokenCount', 'number');\n const removeFromBeginning = getInputOrData(this.data, inputs, 'removeFromBeginning', 'boolean');\n\n const trimmedMessages = [...input];\n\n const tokenizerInfo: TokenizerCallInfo = {\n node: this.chartNode,\n };\n\n let tokenCount = await context.tokenizer.getTokenCountForMessages(trimmedMessages, undefined, tokenizerInfo);\n\n while (tokenCount > maxTokenCount) {\n if (removeFromBeginning) {\n trimmedMessages.shift();\n } else {\n trimmedMessages.pop();\n }\n tokenCount = await context.tokenizer.getTokenCountForMessages(trimmedMessages, undefined, tokenizerInfo);\n }\n\n return {\n ['trimmed' as PortId]: {\n type: 'chat-message[]',\n value: trimmedMessages,\n },\n };\n }\n}\n\nexport const trimChatMessagesNode = nodeDefinition(TrimChatMessagesNodeImpl, 'Trim Chat Messages');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type AnyDataValue, type ArrayDataValue } from '../DataValue.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { getError } from '../../utils/errors.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { omit } from 'lodash-es';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\n\nexport type ExternalCallNode = ChartNode<'externalCall', ExternalCallNodeData>;\n\nexport type ExternalCallNodeData = {\n functionName: string;\n useFunctionNameInput: boolean;\n useErrorOutput: boolean;\n};\n\nexport class ExternalCallNodeImpl extends NodeImpl<ExternalCallNode> {\n static create(): ExternalCallNode {\n return {\n id: nanoid() as NodeId,\n type: 'externalCall',\n title: 'External Call',\n visualData: { x: 0, y: 0, width: 150 },\n data: {\n functionName: '',\n useFunctionNameInput: false,\n useErrorOutput: false,\n },\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputDefinitions: NodeInputDefinition[] = [];\n\n if (this.chartNode.data.useFunctionNameInput) {\n inputDefinitions.push({\n id: 'functionName' as PortId,\n title: 'Function Name',\n dataType: 'string',\n });\n }\n\n inputDefinitions.push({\n id: 'arguments' as PortId,\n title: 'Arguments',\n dataType: 'any[]',\n });\n\n return inputDefinitions;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n const outputs: NodeOutputDefinition[] = [\n {\n id: 'result' as PortId,\n title: 'Result',\n dataType: 'any',\n },\n ];\n\n if (this.chartNode.data.useErrorOutput) {\n outputs.push({\n id: 'error' as PortId,\n title: 'Error',\n dataType: 'string',\n });\n }\n\n return outputs;\n }\n\n getEditors(): EditorDefinition<ExternalCallNode>[] {\n return [\n {\n type: 'string',\n label: 'Function Name',\n dataKey: 'functionName',\n useInputToggleDataKey: 'useFunctionNameInput',\n },\n {\n type: 'toggle',\n label: 'Use Error Output',\n dataKey: 'useErrorOutput',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n return this.data.useFunctionNameInput ? '(Using Input)' : this.data.functionName;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Provides a way to call into the host project from inside a Rivet graph when Rivet graphs are integrated into another project.\n `,\n infoBoxTitle: 'External Call Node',\n contextMenuTitle: 'External Call',\n group: ['Advanced'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const functionName = this.chartNode.data.useFunctionNameInput\n ? coerceType(inputs['functionName' as PortId], 'string')\n : this.chartNode.data.functionName;\n\n const args = inputs['arguments' as PortId];\n let arrayArgs: ArrayDataValue<AnyDataValue> = {\n type: 'any[]',\n value: [],\n };\n\n if (args) {\n if (args.type.endsWith('[]') === false) {\n arrayArgs = {\n type: 'any[]',\n value: [args.value],\n };\n } else {\n arrayArgs = args as ArrayDataValue<AnyDataValue>;\n }\n }\n\n const fn = context.externalFunctions[functionName];\n const externalContext = omit(context, ['setGlobal']);\n\n if (!fn) {\n if (this.data.useErrorOutput) {\n return {\n ['result' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n ['error' as PortId]: {\n type: 'string',\n value: `Function ${functionName} not was not defined using setExternalCall`,\n },\n };\n } else {\n throw new Error(`Function ${functionName} not was not defined using setExternalCall`);\n }\n }\n\n if (this.data.useErrorOutput) {\n try {\n const result = await fn(externalContext, ...arrayArgs.value);\n return {\n ['result' as PortId]: result,\n ['cost' as PortId]: {\n type: 'number',\n value: result.cost ?? 0,\n },\n ['error' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n } catch (error) {\n return {\n ['result' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n ['error' as PortId]: {\n type: 'string',\n value: getError(error).message,\n },\n };\n }\n }\n const result = await fn(externalContext, ...arrayArgs.value);\n return {\n ['result' as PortId]: result,\n };\n }\n}\n\nexport const externalCallNode = nodeDefinition(ExternalCallNodeImpl, 'External Call');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { JSONPath } from 'jsonpath-plus';\nimport { expectType } from '../../utils/expectType.js';\nimport { type EditorDefinition, type NodeBodySpec } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type ExtractObjectPathNode = ChartNode<'extractObjectPath', ExtractObjectPathNodeData>;\n\nexport type ExtractObjectPathNodeData = {\n path: string;\n usePathInput: boolean;\n};\n\nexport class ExtractObjectPathNodeImpl extends NodeImpl<ExtractObjectPathNode> {\n static create(): ExtractObjectPathNode {\n const chartNode: ExtractObjectPathNode = {\n type: 'extractObjectPath',\n title: 'Extract Object Path',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n path: '$',\n usePathInput: false,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputDefinitions: NodeInputDefinition[] = [\n {\n id: 'object' as PortId,\n title: 'Object',\n dataType: 'object',\n required: true,\n },\n ];\n\n if (this.chartNode.data.usePathInput) {\n inputDefinitions.push({\n id: 'path' as PortId,\n title: 'Path',\n dataType: 'string',\n required: true,\n coerced: false,\n });\n }\n\n return inputDefinitions;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'match' as PortId,\n title: 'Match',\n dataType: 'any',\n },\n {\n id: 'all_matches' as PortId,\n title: 'All Matches',\n dataType: 'any[]',\n },\n ];\n }\n\n getEditors(): EditorDefinition<ExtractObjectPathNode>[] {\n return [\n {\n type: 'code',\n label: 'Path',\n dataKey: 'path',\n language: 'jsonpath',\n useInputToggleDataKey: 'usePathInput',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n return this.data.usePathInput ? '(Using Input)' : this.data.path;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Extracts the value at the specified path from the input value. The path uses JSONPath notation to navigate through the value.\n `,\n infoBoxTitle: 'Extract Object Path Node',\n contextMenuTitle: 'Extract Object Path',\n group: ['Objects'],\n };\n }\n\n async process(inputs: Record<PortId, DataValue>): Promise<Record<PortId, DataValue>> {\n const inputObject = coerceTypeOptional(inputs['object' as PortId], 'object');\n const inputPath = this.chartNode.data.usePathInput\n ? expectType(inputs['path' as PortId], 'string')\n : this.chartNode.data.path;\n\n if (!inputPath) {\n throw new Error('Path input is not provided');\n }\n\n let matches: unknown[];\n try {\n // Wrap doesn't seem to wrap when the input is undefined or null...\n const match = JSONPath<unknown>({ json: inputObject ?? null, path: inputPath.trim(), wrap: true });\n matches = match == null ? [] : (match as unknown[]);\n } catch (err) {\n matches = [];\n }\n\n if (matches.length === 0) {\n return {\n ['match' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n ['all_matches' as PortId]: {\n type: 'any[]',\n value: [],\n },\n };\n }\n\n return {\n ['match' as PortId]: {\n type: 'any',\n value: matches[0],\n },\n ['all_matches' as PortId]: {\n type: 'any[]',\n value: matches,\n },\n };\n }\n}\n\nexport const extractObjectPathNode = nodeDefinition(ExtractObjectPathNodeImpl, 'Extract Object Path');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs } from '../GraphProcessor.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\n\nexport type RaiseEventNode = ChartNode<'raiseEvent', RaiseEventNodeData>;\n\nexport type RaiseEventNodeData = {\n eventName: string;\n useEventNameInput: boolean;\n};\n\nexport class RaiseEventNodeImpl extends NodeImpl<RaiseEventNode> {\n static create(): RaiseEventNode {\n return {\n id: nanoid() as NodeId,\n type: 'raiseEvent',\n title: 'Raise Event',\n visualData: { x: 0, y: 0, width: 150 },\n data: {\n eventName: 'toast',\n useEventNameInput: false,\n },\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputDefinitions: NodeInputDefinition[] = [];\n\n if (this.chartNode.data.useEventNameInput) {\n inputDefinitions.push({\n id: 'eventName' as PortId,\n title: 'Event Name',\n dataType: 'string',\n });\n }\n\n inputDefinitions.push({\n id: 'data' as PortId,\n title: 'Data',\n dataType: 'any',\n });\n\n return inputDefinitions;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'result' as PortId,\n title: 'Result',\n dataType: 'any',\n },\n ];\n }\n\n getEditors(): EditorDefinition<RaiseEventNode>[] {\n return [\n {\n type: 'string',\n label: 'Event Name',\n dataKey: 'eventName',\n useInputToggleDataKey: 'useEventNameInput',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n return this.data.useEventNameInput ? '(Using Input)' : this.data.eventName;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Raises an event that the host project or a 'Wait For Event' node can listen for.\n `,\n infoBoxTitle: 'Raise Event Node',\n contextMenuTitle: 'Raise Event',\n group: ['Advanced'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Record<string, DataValue>> {\n const eventName = this.chartNode.data.useEventNameInput\n ? coerceType(inputs['eventName' as PortId], 'string')\n : this.chartNode.data.eventName;\n\n const eventData = inputs['data' as PortId];\n\n context.raiseEvent(eventName, eventData);\n\n return {\n result: eventData as DataValue,\n };\n }\n}\n\nexport const raiseEventNode = nodeDefinition(RaiseEventNodeImpl, 'Raise Event');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { type DataType, type DataValue } from '../DataValue.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type ContextNode = ChartNode<'context', ContextNodeData>;\n\nexport type ContextNodeData = {\n id: string;\n dataType: DataType;\n defaultValue?: unknown;\n useDefaultValueInput?: boolean;\n};\n\nexport class ContextNodeImpl extends NodeImpl<ContextNode> {\n static create(): ContextNode {\n const chartNode: ContextNode = {\n type: 'context',\n title: 'Context',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 300,\n },\n data: {\n id: 'input',\n dataType: 'string',\n defaultValue: undefined,\n useDefaultValueInput: false,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n if (this.data.useDefaultValueInput) {\n return [\n {\n id: 'default' as PortId,\n title: 'Default Value',\n dataType: this.chartNode.data.dataType as DataType,\n },\n ];\n }\n\n return [];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'data' as PortId,\n title: this.data.id,\n dataType: this.chartNode.data.dataType as DataType,\n },\n ];\n }\n\n getEditors(): EditorDefinition<ContextNode>[] {\n return [\n { type: 'string', label: 'ID', dataKey: 'id' },\n { type: 'dataTypeSelector', label: 'Data Type', dataKey: 'dataType' },\n {\n type: 'anyData',\n label: 'Default Value',\n dataKey: 'defaultValue',\n useInputToggleDataKey: 'useDefaultValueInput',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n return dedent`\n ${this.data.id}\n Type: ${this.data.dataType}\n `;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Retrieves a value from the graph's context using a configured id. The context serves as a \"global graph input\", allowing the same values to be accessible from any graph or subgraph.\n `,\n infoBoxTitle: 'Context Node',\n contextMenuTitle: 'Context',\n group: ['Advanced'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const contextValue = context.contextValues[this.data.id];\n\n if (contextValue !== undefined) {\n return {\n ['data' as PortId]: contextValue,\n };\n }\n\n let defaultValue;\n if (this.data.useDefaultValueInput) {\n defaultValue = inputs['default' as PortId]!;\n } else {\n defaultValue = { type: this.data.dataType, value: this.data.defaultValue } as DataValue;\n }\n\n return {\n ['data' as PortId]: defaultValue,\n };\n }\n}\n\nexport const contextNode = nodeDefinition(ContextNodeImpl, 'Context');\n", "import { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport {\n type ChartNode,\n type NodeConnection,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { type DataValue, unwrapDataValue } from '../DataValue.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type CoalesceNode = ChartNode<'coalesce', CoalesceNodeData>;\n\nexport type CoalesceNodeData = {};\n\nexport class CoalesceNodeImpl extends NodeImpl<CoalesceNode> {\n static create = (): CoalesceNode => {\n const chartNode: CoalesceNode = {\n type: 'coalesce',\n title: 'Coalesce',\n id: nanoid() as NodeId,\n data: {},\n visualData: {\n x: 0,\n y: 0,\n width: 150,\n },\n };\n return chartNode;\n };\n\n getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n const inputCount = this.#getInputPortCount(connections);\n\n inputs.push({\n dataType: 'boolean',\n id: 'conditional' as PortId,\n title: 'Conditional',\n });\n\n for (let i = 1; i <= inputCount; i++) {\n inputs.push({\n dataType: 'any',\n id: `input${i}` as PortId,\n title: `Input ${i}`,\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'any',\n id: 'output' as PortId,\n title: 'Output',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Takes in any number of inputs and outputs the first value that exists. Useful for consolidating branches after a Match node. This node can also \"consume\" the \"Not Ran\" value.\n `,\n infoBoxTitle: 'Coalesce Node',\n contextMenuTitle: 'Coalesce',\n group: ['Logic'],\n };\n }\n\n #getInputPortCount(connections: NodeConnection[]): number {\n const inputNodeId = this.chartNode.id;\n const inputConnections = connections.filter(\n (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'),\n );\n\n let maxInputNumber = 0;\n for (const connection of inputConnections) {\n const messageNumber = parseInt(connection.inputId.replace('input', ''), 10);\n if (messageNumber > maxInputNumber) {\n maxInputNumber = messageNumber;\n }\n }\n\n return maxInputNumber + 1;\n }\n\n async process(inputData: Inputs): Promise<Outputs> {\n const conditional = inputData['conditional' as PortId];\n\n // This lets the coalesce actually be control-flow-excluded itself, because otherwise\n // the input control-flow-excluded are consumed.\n if (conditional?.type === 'control-flow-excluded') {\n return {\n ['output' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n const inputCount = Object.keys(inputData).filter((key) => key.startsWith('input')).length;\n const okInputValues: DataValue[] = [];\n\n for (let i = 1; i <= inputCount; i++) {\n const inputValue = inputData[`input${i}` as PortId];\n if (inputValue && inputValue.type !== 'control-flow-excluded' && unwrapDataValue(inputValue) != null) {\n okInputValues.push(inputValue);\n }\n }\n\n if (okInputValues.length === 0) {\n return {\n ['output' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n return {\n ['output' as PortId]: okInputValues[0]!,\n };\n }\n}\n\nexport const coalesceNode = nodeDefinition(CoalesceNodeImpl, 'Coalesce');\n", "import { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport {\n type ChartNode,\n type NodeConnection,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { dedent } from 'ts-dedent';\n\nexport type PassthroughNode = ChartNode<'passthrough', PassthroughNodeData>;\n\nexport type PassthroughNodeData = {};\n\nexport class PassthroughNodeImpl extends NodeImpl<PassthroughNode> {\n static create = (): PassthroughNode => {\n const chartNode: PassthroughNode = {\n type: 'passthrough',\n title: 'Passthrough',\n id: nanoid() as NodeId,\n data: {},\n visualData: {\n x: 0,\n y: 0,\n width: 175,\n },\n };\n return chartNode;\n };\n\n getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n const inputCount = this.#getInputPortCount(connections);\n\n for (let i = 1; i <= inputCount; i++) {\n inputs.push({\n dataType: 'any',\n id: `input${i}` as PortId,\n title: `Input ${i}`,\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(connections: NodeConnection[]): NodeOutputDefinition[] {\n const outputs: NodeOutputDefinition[] = [];\n const inputCount = this.#getInputPortCount(connections);\n\n for (let i = 1; i <= inputCount - 1; i++) {\n outputs.push({\n dataType: 'any',\n id: `output${i}` as PortId,\n title: `Output ${i}`,\n });\n }\n\n return outputs;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Simply passes the input value to the output without any modifications.\n `,\n infoBoxTitle: 'Passthrough Node',\n contextMenuTitle: 'Passthrough',\n group: ['Logic'],\n };\n }\n\n #getInputPortCount(connections: NodeConnection[]): number {\n const inputNodeId = this.chartNode.id;\n const inputConnections = connections.filter(\n (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'),\n );\n\n let maxInputNumber = 0;\n for (const connection of inputConnections) {\n const messageNumber = parseInt(connection.inputId.replace('input', ''), 10);\n if (messageNumber > maxInputNumber) {\n maxInputNumber = messageNumber;\n }\n }\n\n return maxInputNumber + 1;\n }\n\n async process(inputData: Inputs): Promise<Outputs> {\n const inputCount = Object.keys(inputData).filter((key) => key.startsWith('input')).length;\n\n const outputs: Outputs = {};\n\n for (let i = 1; i <= inputCount; i++) {\n const input = inputData[`input${i}` as PortId]!;\n outputs[`output${i}` as PortId] = input;\n }\n\n return outputs;\n }\n}\n\nexport const passthroughNode = nodeDefinition(PassthroughNodeImpl, 'Passthrough');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeBody, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { dedent } from 'ts-dedent';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\n\nexport type PopNode = ChartNode<'pop', PopNodeData>;\n\nexport type PopNodeData = {\n fromFront?: boolean;\n};\n\nexport class PopNodeImpl extends NodeImpl<PopNode> {\n static create(): PopNode {\n const baseNode: PopNode = {\n type: 'pop',\n title: 'Pop',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 200,\n },\n data: {},\n };\n\n return baseNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n {\n dataType: 'any[]',\n id: 'array' as PortId,\n title: 'Array',\n coerced: false,\n },\n ];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'any',\n id: 'lastItem' as PortId,\n title: this.data.fromFront ? 'First' : 'Last',\n },\n {\n dataType: 'any',\n id: 'restOfArray' as PortId,\n title: 'Rest',\n },\n ];\n }\n\n getEditors(_context: RivetUIContext): EditorDefinition<PopNode>[] | Promise<EditorDefinition<PopNode>[]> {\n return [\n {\n label: 'Pop from front',\n type: 'toggle',\n dataKey: 'fromFront',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Pops the last value off the input array and outputs the new array and the popped value.\n\n Can also be used to just extract the last value from an array.\n `,\n infoBoxTitle: 'Pop Node',\n contextMenuTitle: 'Pop',\n group: ['Lists'],\n };\n }\n\n getBody(_context: RivetUIContext): NodeBody | Promise<NodeBody> {\n return this.data.fromFront ? 'From front' : 'From back';\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const inputArray = inputs['array' as PortId]?.value;\n\n if (!Array.isArray(inputArray) || inputArray.length === 0) {\n throw new Error('Input array is empty or not an array');\n }\n\n const lastItem = this.data.fromFront ? inputArray[0] : inputArray[inputArray.length - 1];\n const rest = this.data.fromFront ? inputArray.slice(1) : inputArray.slice(0, inputArray.length - 1);\n\n return {\n ['lastItem' as PortId]: {\n type: 'any',\n value: lastItem,\n },\n ['restOfArray' as PortId]: {\n type: 'any[]',\n value: rest,\n },\n };\n }\n}\n\nexport const popNode = nodeDefinition(PopNodeImpl, 'Pop');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport {\n type DataType,\n type ScalarDataValue,\n isArrayDataType,\n isScalarDataType,\n scalarDefaults,\n unwrapDataValue,\n} from '../DataValue.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\n\nexport type SetGlobalNode = ChartNode<'setGlobal', SetGlobalNodeData>;\n\nexport type SetGlobalNodeData = {\n id: string;\n useIdInput: boolean;\n dataType: DataType;\n};\n\nexport class SetGlobalNodeImpl extends NodeImpl<SetGlobalNode> {\n static create(): SetGlobalNode {\n const chartNode: SetGlobalNode = {\n type: 'setGlobal',\n title: 'Set Global',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 200,\n },\n data: {\n id: 'variable-name',\n dataType: 'string',\n useIdInput: false,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs = [\n {\n id: 'value' as PortId,\n title: 'Value',\n dataType: this.chartNode.data.dataType as DataType,\n },\n ];\n\n if (this.data.useIdInput) {\n inputs.push({\n id: 'id' as PortId,\n title: 'Variable ID',\n dataType: 'string',\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'saved-value' as PortId,\n title: 'Value',\n dataType: this.data.dataType,\n },\n {\n id: 'previous-value' as PortId,\n title: 'Previous Value',\n dataType: this.data.dataType,\n },\n {\n id: 'variable_id_out' as PortId,\n title: 'Variable ID',\n dataType: 'string',\n },\n ];\n }\n\n getEditors(): EditorDefinition<SetGlobalNode>[] {\n return [\n {\n type: 'string',\n dataKey: 'id',\n useInputToggleDataKey: 'useIdInput',\n label: 'ID',\n },\n {\n type: 'dataTypeSelector',\n dataKey: 'dataType',\n label: 'Data Type',\n useInputToggleDataKey: 'useIdInput',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n return dedent`\n ${this.data.id}\n Type: ${this.data.dataType}\n `;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Sets a global value that is shared across all graphs and subgraphs. The id of the global value and the value itself are configured in this node.\n `,\n infoBoxTitle: 'Set Global Node',\n contextMenuTitle: 'Set Global',\n group: ['Advanced'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const rawValue = inputs['value' as PortId]!;\n if (!rawValue) {\n return {};\n }\n\n const id = this.data.useIdInput ? coerceType(inputs['id' as PortId], 'string') : this.data.id;\n\n if (!id) {\n throw new Error('Missing variable ID');\n }\n\n let previousValue = context.getGlobal(this.data.id);\n if (!previousValue && isArrayDataType(this.data.dataType)) {\n previousValue = { type: this.data.dataType, value: [] };\n } else if (!previousValue && isScalarDataType(this.data.dataType)) {\n previousValue = { type: this.data.dataType, value: scalarDefaults[this.data.dataType] } as ScalarDataValue;\n }\n\n const value = unwrapDataValue(rawValue);\n\n context.setGlobal(id, value);\n\n return {\n ['saved-value' as PortId]: value,\n ['previous-value' as PortId]: previousValue,\n ['variable_id_out' as PortId]: { type: 'string', value: id },\n };\n }\n}\n\nexport const setGlobalNode = nodeDefinition(SetGlobalNodeImpl, 'Set Global');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport {\n type FunctionDataValues,\n type ScalarDataType,\n type ScalarDataValue,\n type ScalarOrArrayDataType,\n isArrayDataType,\n isScalarDataType,\n scalarDefaults,\n} from '../DataValue.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition, type NodeBodySpec } from '../../index.js';\n\nexport type GetGlobalNode = ChartNode<'getGlobal', GetGlobalNodeData>;\n\nexport type GetGlobalNodeData = {\n id: string;\n useIdInput: boolean;\n\n dataType: ScalarOrArrayDataType;\n\n /**\n * Returns a fn<value> instead of a value, so that the variable is read when nodes need it, rather than when this node executes.\n * The only time you wouldn't want this is to read a global at the start of a subgraph.\n */\n onDemand: boolean;\n\n /** Wait until the variable is available */\n wait: boolean;\n};\n\nexport class GetGlobalNodeImpl extends NodeImpl<GetGlobalNode> {\n static create(): GetGlobalNode {\n const chartNode: GetGlobalNode = {\n type: 'getGlobal',\n title: 'Get Global',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 200,\n },\n data: {\n id: 'variable-name',\n dataType: 'string',\n onDemand: true,\n useIdInput: false,\n wait: false,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n if (this.data.useIdInput) {\n return [\n {\n id: 'id' as PortId,\n title: 'Variable ID',\n dataType: this.data.dataType as ScalarDataType,\n },\n ];\n }\n\n return [];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n const { onDemand, dataType } = this.chartNode.data;\n return [\n {\n id: 'value' as PortId,\n title: 'Value',\n dataType: onDemand ? (`fn<${dataType}>` as const) : dataType,\n },\n {\n id: 'variable_id_out' as PortId,\n title: 'Variable ID',\n dataType: 'string',\n },\n ];\n }\n\n getEditors(): EditorDefinition<GetGlobalNode>[] {\n return [\n {\n type: 'string',\n label: 'Variable ID',\n dataKey: 'id',\n useInputToggleDataKey: 'useIdInput',\n },\n {\n type: 'dataTypeSelector',\n label: 'Data Type',\n dataKey: 'dataType',\n },\n {\n type: 'toggle',\n label: 'On Demand',\n dataKey: 'onDemand',\n },\n {\n type: 'toggle',\n label: 'Wait',\n dataKey: 'wait',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n return dedent`\n ${this.data.useIdInput ? '(ID from input)' : this.data.id}\n Type: ${this.data.dataType}\n ${this.data.wait ? 'Waits for available data' : ''}\n `;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Retrieves a global value that is shared across all graphs and subgraphs. The id of the global value is configured in this node.\n `,\n infoBoxTitle: 'Get Global Node',\n contextMenuTitle: 'Get Global',\n group: ['Advanced'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n if (this.data.onDemand) {\n if (this.data.wait) {\n throw new Error('Cannot use onDemand and wait together');\n }\n return {\n ['value' as PortId]: {\n type: `fn<${this.data.dataType}>` as const,\n value: () => {\n const id = this.data.useIdInput ? coerceType(inputs['id' as PortId], 'string') : this.data.id;\n\n const value = context.getGlobal(id);\n if (value) {\n return value.value;\n }\n\n // Have some useful defaults before the value is set\n if (isArrayDataType(this.data.dataType)) {\n return [];\n }\n\n return scalarDefaults[this.data.dataType];\n },\n } as FunctionDataValues,\n };\n }\n\n const id = this.data.useIdInput ? coerceType(inputs['id' as PortId], 'string') : this.data.id;\n\n let value = this.data.wait ? await context.waitForGlobal(id) : context.getGlobal(id);\n\n // Have some useful defaults before the value is set\n if (!value && isArrayDataType(this.data.dataType)) {\n value = { type: this.data.dataType, value: [] };\n }\n\n if (!value && isScalarDataType(this.data.dataType)) {\n value = { type: this.data.dataType, value: scalarDefaults[this.data.dataType] } as ScalarDataValue;\n }\n\n return {\n ['value' as PortId]: value,\n ['variable_id_out' as PortId]: { type: 'string', value: id },\n };\n }\n}\n\nexport const getGlobalNode = nodeDefinition(GetGlobalNodeImpl, 'Get Global');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\n\nexport type WaitForEventNode = ChartNode<'waitForEvent', WaitForEventNodeData>;\n\nexport type WaitForEventNodeData = {\n eventName: string;\n useEventNameInput: boolean;\n};\n\nexport class WaitForEventNodeImpl extends NodeImpl<WaitForEventNode> {\n static create(): WaitForEventNode {\n return {\n id: nanoid() as NodeId,\n type: 'waitForEvent',\n title: 'Wait For Event',\n visualData: { x: 0, y: 0, width: 150 },\n data: {\n eventName: 'continue',\n useEventNameInput: false,\n },\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputDefinitions: NodeInputDefinition[] = [];\n\n if (this.chartNode.data.useEventNameInput) {\n inputDefinitions.push({\n id: 'eventName' as PortId,\n title: 'Event Name',\n dataType: 'string',\n });\n }\n\n inputDefinitions.push({\n id: 'inputData' as PortId,\n title: 'Data',\n dataType: 'any',\n });\n\n return inputDefinitions;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'outputData' as PortId,\n title: 'Data',\n dataType: 'any',\n },\n {\n id: 'eventData' as PortId,\n title: 'Event Data',\n dataType: 'any',\n },\n ];\n }\n\n getEditors(): EditorDefinition<WaitForEventNode>[] {\n return [\n {\n type: 'string',\n label: 'Event Name',\n dataKey: 'eventName',\n useInputToggleDataKey: 'useEventNameInput',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n return this.data.useEventNameInput ? '(Using Input)' : this.data.eventName;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Waits for a specific event to be raised by a 'Raise Event' node or the host project. The event name can be configured.\n `,\n infoBoxTitle: 'Wait For Event Node',\n contextMenuTitle: 'Wait For Event',\n group: ['Advanced'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const eventName = this.chartNode.data.useEventNameInput\n ? coerceType(inputs['eventName' as PortId], 'string')\n : this.chartNode.data.eventName;\n\n const eventData = await context.waitEvent(eventName);\n\n return {\n ['outputData' as PortId]: inputs['inputData' as PortId],\n ['eventData' as PortId]: eventData,\n };\n }\n}\n\nexport const waitForEventNode = nodeDefinition(WaitForEventNodeImpl, 'Wait For Event');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\nimport { interpolate } from '../../utils/interpolation.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\nimport { keys } from '../../utils/typeSafety.js';\nimport { coerceTypeOptional, coerceType } from '../../utils/coerceType.js';\nimport { getInputOrData } from '../../utils/index.js';\n\nexport type GptFunctionNode = ChartNode<'gptFunction', GptFunctionNodeData>;\n\nexport type GptFunctionNodeData = {\n name: string;\n useNameInput?: boolean;\n\n description: string;\n useDescriptionInput?: boolean;\n\n schema: string;\n useSchemaInput?: boolean;\n\n strict?: boolean;\n};\n\nexport class GptFunctionNodeImpl extends NodeImpl<GptFunctionNode> {\n static create(): GptFunctionNode {\n const chartNode: GptFunctionNode = {\n type: 'gptFunction',\n title: 'GPT Function',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n name: 'newFunction',\n description: 'No description provided',\n schema: dedent`\n {\n \"type\": \"object\",\n \"properties\": {}\n }`,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n let inputs: NodeInputDefinition[] = [];\n\n if (this.data.useNameInput) {\n inputs.push({\n id: 'name' as PortId,\n title: 'Name',\n dataType: 'string',\n description: 'The name of the function that GPT will see as available to call',\n });\n }\n\n if (this.data.useDescriptionInput) {\n inputs.push({\n id: 'description' as PortId,\n title: 'Description',\n dataType: 'string',\n description: 'The description of the function that GPT will see as available to call',\n });\n }\n\n if (this.data.useSchemaInput) {\n inputs.push({\n id: 'schema' as PortId,\n title: 'Schema',\n dataType: 'object',\n description: 'The schema of the function that GPT will see as available to call',\n });\n }\n\n // Extract inputs from promptText, everything like {{input}}\n const inputNames = this.data.useSchemaInput ? [] : [...new Set(this.data.schema.match(/\\{\\{([^}]+)\\}\\}/g))];\n inputs = [\n ...inputs,\n ...(inputNames?.map((inputName): NodeInputDefinition => {\n const name = inputName.slice(2, -2);\n return {\n // id and title should not have the {{ and }}\n id: `input-${name}` as PortId,\n title: name,\n dataType: 'string',\n description: `An interpolated value in the schema named '${name}'`,\n };\n }) ?? []),\n ];\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'function' as PortId,\n title: 'Function',\n dataType: 'gpt-function',\n description: 'The GPT function that can be called by the LLM.',\n },\n ];\n }\n\n getEditors(): EditorDefinition<GptFunctionNode>[] {\n return [\n {\n type: 'string',\n label: 'Name',\n dataKey: 'name',\n useInputToggleDataKey: 'useNameInput',\n },\n {\n type: 'toggle',\n label: 'Strict',\n dataKey: 'strict',\n helperMessage: 'Sets the strict parameter, which determines if OpenAI Structured Outputs are used.',\n },\n {\n type: 'code',\n label: 'Description',\n dataKey: 'description',\n useInputToggleDataKey: 'useDescriptionInput',\n language: 'markdown',\n height: 100,\n },\n {\n type: 'custom',\n customEditorId: 'GptFunctionNodeJsonSchemaAiAssist',\n label: 'AI Assist',\n },\n {\n type: 'code',\n label: 'Schema',\n dataKey: 'schema',\n language: 'json',\n useInputToggleDataKey: 'useSchemaInput',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n return `!markdown_${this.data.name}_: ${this.data.description}`;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Defines a GPT function, which is a method that the LLM can call in its responses.\n `,\n infoBoxTitle: 'GPT Function Node',\n contextMenuTitle: 'GPT Function',\n group: ['AI'],\n };\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const name = getInputOrData(this.data, inputs, 'name');\n const description = getInputOrData(this.data, inputs, 'description');\n\n let schema: unknown;\n if (this.data.useSchemaInput) {\n schema = coerceType(inputs['schema' as PortId], 'object');\n } else {\n const inputMap = keys(inputs)\n .filter((key) => key.startsWith('input'))\n .reduce(\n (acc, key) => {\n const stringValue = coerceTypeOptional(inputs[key], 'string') ?? '';\n\n const interpolationKey = key.slice('input-'.length);\n acc[interpolationKey] = stringValue;\n return acc;\n },\n {} as Record<string, string>,\n );\n\n const interpolated = interpolate(this.data.schema, inputMap);\n\n schema = JSON.parse(interpolated);\n }\n\n return {\n ['function' as PortId]: {\n type: 'gpt-function',\n value: {\n name,\n description,\n parameters: schema as object,\n strict: this.data.strict ?? false,\n },\n },\n };\n }\n}\n\nexport const gptFunctionNode = nodeDefinition(GptFunctionNodeImpl, 'GPT Function');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\n// @ts-ignore\nimport yaml from 'yaml';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { coerceType } from '../../utils/index.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type ToYamlNode = ChartNode<'toYaml', ToYamlNodeData>;\n\nexport type ToYamlNodeData = {};\n\nexport class ToYamlNodeImpl extends NodeImpl<ToYamlNode> {\n static create(): ToYamlNode {\n const chartNode: ToYamlNode = {\n type: 'toYaml',\n title: 'To YAML',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 175,\n },\n data: {},\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n {\n id: 'object' as PortId,\n title: 'Object',\n dataType: 'object',\n required: true,\n },\n ];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'yaml' as PortId,\n title: 'YAML',\n dataType: 'string',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Turns the input object into YAML text.\n `,\n infoBoxTitle: 'To YAML Node',\n contextMenuTitle: 'To YAML',\n group: ['Text'],\n };\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const object = coerceType(inputs['object' as PortId], 'object');\n\n const toYaml = yaml.stringify(object, null, {\n indent: 2,\n aliasDuplicateObjects: false,\n });\n\n return {\n ['yaml' as PortId]: {\n type: 'string',\n value: toYaml,\n },\n };\n }\n}\n\nexport const toYamlNode = nodeDefinition(ToYamlNodeImpl, 'To YAML');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { getIntegration } from '../../integrations/integrations.js';\n\nexport type GetEmbeddingNode = ChartNode<'getEmbedding', GetEmbeddingNodeData>;\n\nexport type GetEmbeddingNodeData = {\n integration: string;\n model?: string;\n dimensions?: number;\n useIntegrationInput?: boolean;\n useModelInput?: boolean;\n useDimensionsInput?: boolean;\n};\n\nexport class GetEmbeddingNodeImpl extends NodeImpl<GetEmbeddingNode> {\n static create(): GetEmbeddingNode {\n return {\n id: nanoid() as NodeId,\n type: 'getEmbedding',\n title: 'Get Embedding',\n visualData: { x: 0, y: 0, width: 250 },\n data: {\n integration: 'openai',\n useIntegrationInput: false,\n model: undefined,\n dimensions: undefined\n },\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputDefinitions: NodeInputDefinition[] = [];\n\n inputDefinitions.push({\n id: 'input' as PortId,\n title: 'Input',\n dataType: 'string',\n required: true,\n });\n\n if (this.data.useIntegrationInput) {\n inputDefinitions.push({\n id: 'integration' as PortId,\n title: 'Integration',\n dataType: 'string',\n required: true,\n });\n }\n\n if (this.data.useModelInput) {\n inputDefinitions.push({\n id: 'model' as PortId,\n title: 'Model',\n dataType: 'string',\n required: false,\n });\n }\n\n if (this.data.useDimensionsInput) {\n inputDefinitions.push({\n id: 'dimensions' as PortId,\n title: 'Dimensions',\n dataType: 'number',\n required: false,\n });\n }\n\n return inputDefinitions;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n const outputs: NodeOutputDefinition[] = [\n {\n id: 'embedding' as PortId,\n title: 'Embedding',\n dataType: 'vector',\n },\n ];\n\n return outputs;\n }\n\n getEditors(): EditorDefinition<GetEmbeddingNode>[] {\n return [\n {\n type: 'dropdown',\n label: 'Integration',\n dataKey: 'integration',\n options: [{ label: 'OpenAI', value: 'openai' }],\n useInputToggleDataKey: 'useIntegrationInput',\n },\n {\n type: 'string',\n label: 'Model',\n dataKey: 'model',\n useInputToggleDataKey: 'useModelInput',\n },\n {\n type: 'number',\n label: 'Dimensions',\n dataKey: 'dimensions',\n useInputToggleDataKey: 'useDimensionsInput',\n },\n ];\n }\n\n getBody(): string | undefined {\n return `Using ${this.data.useIntegrationInput ? '(input)' : this.data.integration}`;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Gets a OpenAI vector embedding for the input text provided.\n\n Can be used with the Vector Store and Vector KNN nodes.\n `,\n infoBoxTitle: 'Get Embedding Node',\n contextMenuTitle: 'Get Embedding',\n group: ['AI'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const input = coerceType(inputs['input' as PortId], 'string');\n\n const integrationName = this.data.useIntegrationInput\n ? coerceType(inputs['integration' as PortId], 'string')\n : this.data.integration;\n \n const model = this.data.useModelInput ? coerceType(inputs['model' as PortId], 'string') : this.data.model;\n\n const dimensions = this.data.useDimensionsInput\n ? coerceType(inputs['dimensions' as PortId], 'number')\n : this.data.dimensions;\n\n const embeddingGenerator = getIntegration('embeddingGenerator', integrationName, context);\n\n const embedding = await embeddingGenerator.generateEmbedding(input, {\n model,\n dimensions,\n });\n\n return {\n ['embedding' as PortId]: {\n type: 'vector',\n value: embedding,\n },\n };\n }\n}\n\nexport const getEmbeddingNode = nodeDefinition(GetEmbeddingNodeImpl, 'Get Embedding');\n", "import { type InternalProcessContext } from '../model/ProcessContext.js';\nimport { type EmbeddingGenerator } from './EmbeddingGenerator.js';\nimport { type LLMProvider } from './LLMProvider.js';\nimport { type VectorDatabase } from './VectorDatabase.js';\n\nexport type IntegrationFactories = {\n vectorDatabase: (context: InternalProcessContext) => VectorDatabase;\n llmProvider: (context: InternalProcessContext) => LLMProvider;\n embeddingGenerator: (context: InternalProcessContext) => EmbeddingGenerator;\n};\n\nexport type IntegrationType = keyof IntegrationFactories;\n\nconst registeredIntegrations: {\n [P in IntegrationType]: Map<string, IntegrationFactories[P]>;\n} = {\n vectorDatabase: new Map<string, (context: InternalProcessContext) => VectorDatabase>(),\n llmProvider: new Map<string, (context: InternalProcessContext) => LLMProvider>(),\n embeddingGenerator: new Map<string, (context: InternalProcessContext) => EmbeddingGenerator>(),\n};\n\nexport function registerIntegration<T extends IntegrationType>(\n type: T,\n integrationKey: string,\n factory: IntegrationFactories[T],\n): void {\n registeredIntegrations[type].set(integrationKey, factory);\n}\n\nexport function getIntegration<T extends IntegrationType>(\n type: T,\n integrationKey: string,\n context: InternalProcessContext,\n): ReturnType<IntegrationFactories[T]> {\n const factory = registeredIntegrations[type].get(integrationKey);\n if (!factory) {\n throw new Error(`Integration ${integrationKey} not found`);\n }\n return factory(context) as ReturnType<IntegrationFactories[T]>;\n}\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { type EditorDefinition, type VectorDataValue } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { getIntegration } from '../../integrations/integrations.js';\nimport { getInputOrData } from '../../utils/index.js';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type VectorStoreNode = ChartNode<'vectorStore', VectorStoreNodeData>;\n\nexport type VectorStoreNodeData = {\n integration: string;\n useIntegrationInput?: boolean;\n\n collectionId: string;\n useCollectionIdInput?: boolean;\n};\n\nexport class VectorStoreNodeImpl extends NodeImpl<VectorStoreNode> {\n static create(): VectorStoreNode {\n return {\n id: nanoid() as NodeId,\n type: 'vectorStore',\n title: 'Vector Store',\n visualData: { x: 0, y: 0, width: 200 },\n data: {\n integration: 'pinecone',\n collectionId: '',\n },\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputDefinitions: NodeInputDefinition[] = [];\n\n inputDefinitions.push({\n id: 'vector' as PortId,\n title: 'Vector',\n dataType: 'vector',\n required: true,\n });\n\n if (this.data.useCollectionIdInput) {\n inputDefinitions.push({\n id: 'collectionId' as PortId,\n title: 'Collection ID',\n dataType: 'string',\n required: true,\n });\n }\n\n inputDefinitions.push({\n id: 'data' as PortId,\n title: 'Data',\n dataType: 'any',\n required: true,\n });\n\n if (this.data.useIntegrationInput) {\n inputDefinitions.push({\n id: 'integration' as PortId,\n title: 'Integration',\n dataType: 'string',\n required: true,\n });\n }\n\n inputDefinitions.push({\n id: 'id' as PortId,\n title: 'ID',\n dataType: 'string',\n required: false,\n });\n\n return inputDefinitions;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n const outputs: NodeOutputDefinition[] = [\n {\n id: 'complete' as PortId,\n title: 'Complete',\n dataType: 'boolean',\n },\n ];\n\n return outputs;\n }\n\n getEditors(): EditorDefinition<VectorStoreNode>[] {\n return [\n {\n type: 'dropdown',\n label: 'Integration',\n dataKey: 'integration',\n options: [{ label: 'Pinecone', value: 'pinecone' }],\n useInputToggleDataKey: 'useIntegrationInput',\n },\n {\n type: 'string',\n label: 'Collection ID',\n dataKey: 'collectionId',\n useInputToggleDataKey: 'useCollectionIdInput',\n },\n ];\n }\n\n getBody(): string | undefined {\n return dedent`\n Integration: ${this.data.useIntegrationInput ? '(using input)' : this.data.integration}\n Collection Id: ${this.data.useCollectionIdInput ? '(using input)' : this.data.collectionId}\n `;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Takes in a vector, as well as data to store with the vector. This data is stored in the configured vector DB integration for later retrieval.\n `,\n infoBoxTitle: 'Vector Store Node',\n contextMenuTitle: 'Vector Store',\n group: ['Input/Output'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const integration = getInputOrData(this.data, inputs, 'integration');\n const vectorDb = getIntegration('vectorDatabase', integration, context);\n\n const indexUrl = getInputOrData(this.data, inputs, 'collectionId');\n\n if (inputs['vector' as PortId]?.type !== 'vector') {\n throw new Error(`Expected vector input, got ${inputs['vector' as PortId]?.type}`);\n }\n\n await vectorDb.store(\n { type: 'string', value: indexUrl },\n inputs['vector' as PortId] as VectorDataValue,\n inputs['data' as PortId]!,\n {\n id: coerceTypeOptional(inputs['id' as PortId], 'string'),\n },\n );\n\n return {\n ['complete' as PortId]: {\n type: 'boolean',\n value: true,\n },\n };\n }\n}\n\nexport const vectorStoreNode = nodeDefinition(VectorStoreNodeImpl, 'Vector Store');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { type DataValue, type EditorDefinition, type VectorDataValue } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { getIntegration } from '../../integrations/integrations.js';\nimport { getInputOrData } from '../../utils/index.js';\n\nexport type VectorNearestNeighborsNode = ChartNode<'vectorNearestNeighbors', VectorNearestNeighborsNodeData>;\n\nexport type VectorNearestNeighborsNodeData = {\n integration: string;\n useIntegrationInput?: boolean;\n\n k: number;\n useKInput?: boolean;\n\n collectionId: string;\n useCollectionIdInput?: boolean;\n};\n\nexport class VectorNearestNeighborsNodeImpl extends NodeImpl<VectorNearestNeighborsNode> {\n static create(): VectorNearestNeighborsNode {\n return {\n id: nanoid() as NodeId,\n type: 'vectorNearestNeighbors',\n title: 'Vector KNN',\n visualData: { x: 0, y: 0, width: 200 },\n data: {\n k: 10,\n integration: 'pinecone',\n collectionId: '',\n },\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputDefinitions: NodeInputDefinition[] = [];\n\n inputDefinitions.push({\n id: 'vector' as PortId,\n title: 'Vector',\n dataType: 'vector',\n required: true,\n });\n\n if (this.data.useIntegrationInput) {\n inputDefinitions.push({\n id: 'integration' as PortId,\n title: 'Integration',\n dataType: 'string',\n required: true,\n });\n }\n\n if (this.data.useCollectionIdInput) {\n inputDefinitions.push({\n id: 'collectionId' as PortId,\n title: 'Collection ID',\n dataType: 'string',\n required: true,\n });\n }\n\n if (this.data.useKInput) {\n inputDefinitions.push({\n id: 'k' as PortId,\n title: 'K',\n dataType: 'number',\n required: true,\n });\n }\n\n return inputDefinitions;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n const outputs: NodeOutputDefinition[] = [\n {\n id: 'results' as PortId,\n title: 'Results',\n dataType: 'any[]',\n },\n ];\n\n return outputs;\n }\n\n getEditors(): EditorDefinition<VectorNearestNeighborsNode>[] {\n return [\n {\n type: 'dropdown',\n label: 'Integration',\n dataKey: 'integration',\n options: [{ label: 'Pinecone', value: 'pinecone' }],\n useInputToggleDataKey: 'useIntegrationInput',\n },\n {\n type: 'number',\n label: 'K',\n dataKey: 'k',\n min: 1,\n max: 100,\n step: 1,\n defaultValue: 10,\n useInputToggleDataKey: 'useKInput',\n },\n {\n type: 'string',\n label: 'Collection ID',\n dataKey: 'collectionId',\n useInputToggleDataKey: 'useCollectionIdInput',\n },\n ];\n }\n\n getBody(): string | undefined {\n return dedent`\n Integration: ${this.data.useIntegrationInput ? '(using input)' : this.data.integration}\n K: ${this.data.useKInput ? '(using input)' : this.data.k}\n Collection Id: ${this.data.useCollectionIdInput ? '(using input)' : this.data.collectionId}\n `;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Performs a k-nearest neighbors search on the vectors stored in the configured vector DB integration. Takes in a vector and returns the k closest vectors and their corresponding data.\n `,\n infoBoxTitle: 'Vector KNN Node',\n contextMenuTitle: 'Vector KNN',\n group: ['Input/Output'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const integration = getInputOrData(this.data, inputs, 'integration');\n const vectorDb = getIntegration('vectorDatabase', integration, context);\n\n const indexUrl = getInputOrData(this.data, inputs, 'collectionId');\n const k = getInputOrData(this.data, inputs, 'k', 'number');\n\n if (inputs['vector' as PortId]?.type !== 'vector') {\n throw new Error(`Expected vector input, got ${inputs['vector' as PortId]?.type}`);\n }\n\n const results = await vectorDb.nearestNeighbors(\n { type: 'string', value: indexUrl },\n inputs['vector' as PortId] as VectorDataValue,\n k,\n );\n\n return {\n ['results' as PortId]: results as DataValue,\n };\n }\n}\n\nexport const vectorNearestNeighborsNode = nodeDefinition(VectorNearestNeighborsNodeImpl, 'Vector KNN');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type EditorDefinition, type Inputs, type Outputs } from '../../index.js';\nimport * as crypto from 'crypto-js';\nimport { match } from 'ts-pattern';\nimport { dedent } from 'ts-dedent';\nimport { coerceType } from '../../utils/coerceType.js';\n\nconst { SHA256, SHA512, MD5, SHA1 } = crypto;\n\nexport type HashNode = ChartNode<'hash', HashNodeData>;\n\nexport type HashNodeData = {\n algorithm: 'md5' | 'sha1' | 'sha256' | 'sha512';\n};\n\nexport class HashNodeImpl extends NodeImpl<HashNode> {\n static create(): HashNode {\n const chartNode: HashNode = {\n type: 'hash',\n title: 'Hash',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n algorithm: 'sha256',\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n {\n id: 'input' as PortId,\n title: 'Input',\n dataType: 'string',\n required: true,\n },\n ];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'hash' as PortId,\n title: 'Hash',\n dataType: 'string',\n },\n ];\n }\n\n getEditors(): EditorDefinition<HashNode>[] {\n return [\n {\n type: 'dropdown',\n label: 'Algorithm',\n dataKey: 'algorithm',\n options: [\n { value: 'md5', label: 'MD5' },\n { value: 'sha1', label: 'SHA1' },\n { value: 'sha256', label: 'SHA256' },\n { value: 'sha512', label: 'SHA512' },\n ],\n },\n ];\n }\n\n getBody(): string | undefined {\n return algorithmDisplayName[this.data.algorithm];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Computes a hash of the input value using the configured hash function.\n `,\n infoBoxTitle: 'Hash Node',\n contextMenuTitle: 'Hash',\n group: ['Data'],\n };\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const inputText = coerceType(inputs['input' as PortId], 'string');\n\n const hash = match(this.data.algorithm)\n .with('md5', () => MD5(inputText).toString())\n .with('sha1', () => SHA1(inputText).toString())\n .with('sha256', () => SHA256(inputText).toString())\n .with('sha512', () => SHA512(inputText).toString())\n .exhaustive();\n\n return {\n ['hash' as PortId]: {\n type: 'string',\n value: hash,\n },\n };\n }\n}\n\nconst algorithmDisplayName: Record<HashNodeData['algorithm'], string> = {\n md5: 'MD5',\n sha1: 'SHA-1',\n sha256: 'SHA-256',\n sha512: 'SHA-512',\n};\n\nexport const hashNode = nodeDefinition(HashNodeImpl, 'Hash');\n", "import type { ChartNode, NodeId, NodeOutputDefinition, PortId, NodeInputDefinition } from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\nimport type { InternalProcessContext } from '../ProcessContext.js';\nimport type { EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type AbortGraphNode = ChartNode<'abortGraph', AbortGraphNodeData>;\n\nexport type AbortGraphNodeData = {\n /** Did the graph abort, but it's a success? Use this for early-exit instead of \"error abort\". */\n successfully: boolean;\n\n useSuccessfullyInput?: boolean;\n\n errorMessage?: string;\n};\n\nexport class AbortGraphNodeImpl extends NodeImpl<AbortGraphNode> {\n static create(): AbortGraphNode {\n const chartNode: AbortGraphNode = {\n type: 'abortGraph',\n title: 'Abort Graph',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 200,\n },\n data: {\n successfully: true,\n errorMessage: '',\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [\n {\n id: 'data' as PortId,\n title: 'Data or Error',\n dataType: 'any',\n description: 'The message to abort the graph with.',\n },\n ];\n\n if (this.data.useSuccessfullyInput) {\n inputs.push({\n id: 'successfully' as PortId,\n title: 'Successfully',\n dataType: 'boolean',\n description: 'Whether to successfully abort the graph (early-exit), or error abort the graph.',\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [];\n }\n\n getEditors(): EditorDefinition<AbortGraphNode>[] {\n return [\n {\n type: 'toggle',\n label: 'Successfully Abort',\n dataKey: 'successfully',\n useInputToggleDataKey: 'useSuccessfullyInput',\n },\n {\n type: 'string',\n label: 'Error Message (if not successfully aborting)',\n dataKey: 'errorMessage',\n },\n ];\n }\n\n getBody(): string | undefined {\n return dedent`\n ${\n this.data.useSuccessfullyInput\n ? 'Success depends on input'\n : this.data.successfully\n ? 'Successfully Abort'\n : this.data.errorMessage\n ? `Error Abort: ${this.data.errorMessage}`\n : 'Error Abort'\n }\n `;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Aborts the execution of the entire graph immediately.\n\n Can either \"successfully\" abort the graph (early-exit), or \"error\" abort the graph.\n `,\n infoBoxTitle: 'Abort Graph Node',\n contextMenuTitle: 'Abort Graph',\n group: ['Logic'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const successfully = this.data.useSuccessfullyInput\n ? coerceTypeOptional(inputs['successfully' as PortId], 'boolean') ?? this.data.successfully\n : this.data.successfully;\n\n if (successfully) {\n context.abortGraph();\n } else {\n const errorMessage =\n coerceTypeOptional(inputs['data' as PortId], 'string')?.trim() ||\n this.data.errorMessage ||\n 'Graph aborted with error';\n context.abortGraph(errorMessage);\n }\n\n return {};\n }\n}\n\nexport const abortGraphNode = nodeDefinition(AbortGraphNodeImpl, 'Abort Graph');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n type NodeConnection,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../../index.js';\n\nexport type RaceInputsNode = ChartNode<'raceInputs', RaceInputsNodeData>;\n\nexport type RaceInputsNodeData = {};\n\nexport class RaceInputsNodeImpl extends NodeImpl<RaceInputsNode> {\n static create(): RaceInputsNode {\n const chartNode: RaceInputsNode = {\n type: 'raceInputs',\n title: 'Race Inputs',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 300,\n },\n data: {},\n };\n\n return chartNode;\n }\n\n #getInputPortCount(connections: NodeConnection[]): number {\n const inputNodeId = this.chartNode.id;\n const inputConnections = connections.filter(\n (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'),\n );\n\n let maxInputNumber = 0;\n for (const connection of inputConnections) {\n const messageNumber = parseInt(connection.inputId.replace('input', ''), 10);\n if (messageNumber > maxInputNumber) {\n maxInputNumber = messageNumber;\n }\n }\n\n return maxInputNumber + 1;\n }\n\n getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n const inputCount = this.#getInputPortCount(connections);\n\n for (let i = 1; i <= inputCount; i++) {\n inputs.push({\n dataType: 'any',\n id: `input${i}` as PortId,\n title: `Input ${i}`,\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'result' as PortId,\n title: 'Result',\n dataType: 'any',\n },\n ];\n }\n\n getEditors(): EditorDefinition<RaceInputsNode>[] {\n return [];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Takes in multiple inputs and outputs the value of the first one to finish. The other inputs are cancelled.\n `,\n infoBoxTitle: 'Race Inputs Node',\n contextMenuTitle: 'Race Inputs',\n group: ['Logic'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n // GraphProcessor handles most of the racing/aborting logic for us.\n const value = Object.entries(inputs).find(\n ([key, value]) => key.startsWith('input') && value !== undefined && value.type !== 'control-flow-excluded',\n );\n\n if (!value) {\n return {\n ['result' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n return {\n ['result' as PortId]: value[1],\n };\n }\n}\n\nexport const raceInputsNode = nodeDefinition(RaceInputsNodeImpl, 'Race Inputs');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport type ToJsonNode = ChartNode<'toJson', ToJsonNodeData>;\n\nexport type ToJsonNodeData = {\n indented?: boolean;\n};\n\nexport class ToJsonNodeImpl extends NodeImpl<ToJsonNode> {\n static create(): ToJsonNode {\n const chartNode: ToJsonNode = {\n type: 'toJson',\n title: 'To JSON',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 175,\n },\n data: {\n indented: true,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n {\n id: 'data' as PortId,\n title: 'Data',\n dataType: 'any',\n required: true,\n },\n ];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'json' as PortId,\n title: 'JSON',\n dataType: 'string',\n },\n ];\n }\n\n getEditors(): EditorDefinition<ToJsonNode>[] {\n return [\n {\n type: 'toggle',\n label: 'Indented',\n dataKey: 'indented',\n },\n ];\n }\n\n getBody(): string | undefined {\n return this.data.indented ? 'Indented' : 'Not indented';\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Turns the input value into its JSON equivalent (stringifies the value).\n `,\n infoBoxTitle: 'To JSON Node',\n contextMenuTitle: 'To JSON',\n group: ['Text'],\n };\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const data = coerceType(inputs['data' as PortId], 'any');\n\n const toJson = this.data.indented ? JSON.stringify(data, null, 2) : JSON.stringify(data);\n\n return {\n ['json' as PortId]: {\n type: 'string',\n value: toJson,\n },\n };\n }\n}\n\nexport const toJsonNode = nodeDefinition(ToJsonNodeImpl, 'To JSON');\n", "import { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport {\n type ChartNode,\n type NodeConnection,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { isArrayDataValue } from '../DataValue.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { coerceType, coerceTypeOptional, inferType } from '../../utils/coerceType.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { handleEscapeCharacters } from '../../utils/index.js';\n\nexport type JoinNode = ChartNode<'join', JoinNodeData>;\n\nexport type JoinNodeData = {\n flatten?: boolean;\n joinString: string;\n useJoinStringInput?: boolean;\n};\n\nexport class JoinNodeImpl extends NodeImpl<JoinNode> {\n static create = (): JoinNode => {\n const chartNode: JoinNode = {\n type: 'join',\n title: 'Join',\n id: nanoid() as NodeId,\n data: {\n flatten: true,\n joinString: '\\n',\n },\n visualData: {\n x: 0,\n y: 0,\n width: 150,\n },\n };\n return chartNode;\n };\n\n getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n const inputCount = this.#getInputPortCount(connections);\n\n if (this.data.useJoinStringInput) {\n inputs.push({\n dataType: 'string',\n id: 'joinString' as PortId,\n title: 'Join String',\n });\n }\n\n for (let i = 1; i <= inputCount; i++) {\n inputs.push({\n dataType: 'string',\n id: `input${i}` as PortId,\n title: `Input ${i}`,\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'string',\n id: 'output' as PortId,\n title: 'Joined',\n },\n ];\n }\n\n #getInputPortCount(connections: NodeConnection[]): number {\n const inputNodeId = this.chartNode.id;\n const inputConnections = connections.filter(\n (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'),\n );\n\n let maxInputNumber = 0;\n for (const connection of inputConnections) {\n const messageNumber = parseInt(connection.inputId.replace('input', ''), 10);\n if (messageNumber > maxInputNumber) {\n maxInputNumber = messageNumber;\n }\n }\n\n return maxInputNumber + 1;\n }\n\n getEditors(): EditorDefinition<JoinNode>[] {\n return [\n {\n type: 'toggle',\n label: 'Flatten',\n dataKey: 'flatten',\n },\n {\n type: 'code',\n label: 'Join String',\n dataKey: 'joinString',\n useInputToggleDataKey: 'useJoinStringInput',\n language: 'plaintext',\n },\n ];\n }\n\n getBody(): string | undefined {\n return this.data.useJoinStringInput\n ? '(Join value is input)'\n : this.data.joinString === '\\n'\n ? '(New line)'\n : this.data.joinString === '\\t'\n ? '(Tab)'\n : this.data.joinString === ' '\n ? '(Space)'\n : this.data.joinString;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Takes an array of strings, and joins them using the configured delimiter.\n\n Defaults to a newline.\n `,\n infoBoxTitle: 'Join Node',\n contextMenuTitle: 'Join',\n group: ['Text'],\n };\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const joinString = this.data.useJoinStringInput\n ? coerceTypeOptional(inputs['joinString' as PortId], 'string') ?? this.data.joinString\n : this.data.joinString;\n\n const normalizedJoinString = handleEscapeCharacters(joinString);\n\n const inputKeys = Object.keys(inputs).filter((key) => key.startsWith('input'));\n\n const inputValueStrings: string[] = [];\n\n for (let i = 1; i <= inputKeys.length; i++) {\n const inputValue = inputs[`input${i}` as PortId];\n if (isArrayDataValue(inputValue) && this.data.flatten) {\n for (const value of inputValue.value) {\n inputValueStrings.push(coerceType(inferType(value), 'string'));\n }\n } else if (inputValue) {\n inputValueStrings.push(coerceType(inputValue, 'string'));\n }\n }\n\n const outputValue = inputValueStrings.join(normalizedJoinString);\n\n return {\n ['output' as PortId]: {\n type: 'string',\n value: outputValue,\n },\n };\n }\n}\n\nexport const joinNode = nodeDefinition(JoinNodeImpl, 'Coalesce');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type DataValue } from '../../index.js';\nimport { zip } from 'lodash-es';\nimport { dedent } from 'ts-dedent';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport type FilterNode = ChartNode<'filter', FilterNodeData>;\n\nexport type FilterNodeData = {};\n\nexport class FilterNodeImpl extends NodeImpl<FilterNode> {\n static create(): FilterNode {\n const chartNode: FilterNode = {\n type: 'filter',\n title: 'Filter',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 175,\n },\n data: {},\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n {\n id: 'array' as PortId,\n title: 'Array',\n dataType: 'any[]',\n required: true,\n },\n {\n id: 'include' as PortId,\n title: 'Include',\n dataType: 'boolean[]',\n required: true,\n },\n ];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'filtered' as PortId,\n title: 'Filtered',\n dataType: 'any[]',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Takes in both an array of values, and an array of booleans of the same length, and filters the array where the corresponding boolean is true.\n `,\n infoBoxTitle: 'Filter Node',\n contextMenuTitle: 'Filter',\n group: ['Lists'],\n };\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const array = coerceType(inputs['array' as PortId], 'any[]');\n const include = coerceType(inputs['include' as PortId], 'boolean[]');\n\n const zipped = zip(array, include);\n\n const filtered = zipped.filter(([_, include]) => include).map(([value, _]) => value);\n\n return {\n ['filtered' as PortId]: {\n type: inputs['array' as PortId]?.type ?? 'any',\n value: filtered,\n } as DataValue,\n };\n }\n}\n\nexport const filterNode = nodeDefinition(FilterNodeImpl, 'Filter');\n", "import {\n type ChartNode,\n type NodeConnection,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\n\nexport type ObjectNode = ChartNode<'object', ObjectNodeData>;\n\nexport type ObjectNodeData = {\n jsonTemplate: string;\n};\n\nconst DEFAULT_JSON_TEMPLATE = `{\n \"key\": \"{{input}}\"\n}`;\n\nexport class ObjectNodeImpl extends NodeImpl<ObjectNode> {\n static create(): ObjectNode {\n const chartNode: ObjectNode = {\n type: 'object',\n title: 'Object',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 200,\n },\n data: {\n jsonTemplate: DEFAULT_JSON_TEMPLATE,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n // Extract inputs from text, everything like {{input}}\n const inputNames = [...new Set(this.chartNode.data.jsonTemplate.match(/\\{\\{([^}]+)\\}\\}/g))];\n return (\n inputNames?.map((inputName) => {\n return {\n // id and title should not have the {{ and }}\n id: inputName.slice(2, -2) as PortId,\n title: inputName.slice(2, -2),\n dataType: 'any',\n required: false,\n };\n }) ?? []\n );\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: ['object', 'object[]'],\n id: 'output' as PortId,\n title: 'Output',\n },\n ];\n }\n\n getEditors(): EditorDefinition<ObjectNode>[] {\n return [\n {\n type: 'custom',\n customEditorId: 'ObjectNodeAiAssist',\n label: 'AI Assist',\n },\n {\n type: 'code',\n label: 'JSON Template',\n dataKey: 'jsonTemplate',\n language: 'json',\n theme: 'prompt-interpolation',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Creates an object from input values and a JSON template, escaping the input values and inserting them into the template.\n\n Use double-quotes around the input values to escape them. String values are automatically escaped.\n\n Useful for creating objects from multiple inputs.\n `,\n infoBoxTitle: 'Object Node',\n contextMenuTitle: 'Object',\n group: ['Objects'],\n };\n }\n\n interpolate(baseString: string, values: Record<string, any>): string {\n return baseString.replace(/(\"?)\\{\\{([^}]+)\\}\\}(\"?)/g, (_m, openQuote, key, _closeQuote) => {\n const isQuoted = Boolean(openQuote);\n const value = values[key];\n if (value == null) {\n return 'null';\n }\n if (isQuoted && typeof value === 'string') {\n // Adds double-quotes back.\n return JSON.stringify(value);\n }\n if (isQuoted) {\n // Non-strings require a double-stringify, first to turn them into a string, then to escape that string and add quotes.\n return JSON.stringify(JSON.stringify(value));\n }\n // Otherwise, it was not quoted, so no need to double-stringify\n return JSON.stringify(value);\n });\n }\n\n async process(inputs: Record<string, DataValue>): Promise<Record<string, DataValue>> {\n const inputMap = Object.keys(inputs).reduce(\n (acc, key) => {\n acc[key] = (inputs[key] as any)?.value;\n return acc;\n },\n {} as Record<string, any>,\n );\n\n const outputValue = JSON.parse(this.interpolate(this.chartNode.data.jsonTemplate, inputMap)) as Record<\n string,\n unknown\n >;\n\n if (Array.isArray(outputValue)) {\n return {\n output: {\n type: 'object[]',\n value: outputValue,\n },\n };\n }\n\n return {\n output: {\n type: 'object',\n value: outputValue,\n },\n };\n }\n}\n\nexport const objectNode = nodeDefinition(ObjectNodeImpl, 'Object');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type BooleanNode = ChartNode<'boolean', BooleanNodeData>;\n\nexport type BooleanNodeData = {\n value?: boolean;\n useValueInput?: boolean;\n};\n\nexport class BooleanNodeImpl extends NodeImpl<BooleanNode> {\n static create(): BooleanNode {\n const chartNode: BooleanNode = {\n type: 'boolean',\n title: 'Bool',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 130,\n },\n data: {\n value: false,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n return this.data.useValueInput\n ? [\n {\n dataType: 'any',\n id: 'input' as PortId,\n title: 'Input',\n },\n ]\n : [];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'boolean',\n id: 'value' as PortId,\n title: 'Value',\n },\n ];\n }\n\n getEditors(): EditorDefinition<BooleanNode>[] {\n return [{ type: 'toggle', label: 'Value', dataKey: 'value', useInputToggleDataKey: 'useValueInput' }];\n }\n\n getBody(): string | undefined {\n return this.data.useValueInput ? `(Input to bool)` : (this.data.value ?? false).toString();\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Outputs a boolean constant, or converts an input value into a boolean.\n `,\n infoBoxTitle: 'Bool Node',\n contextMenuTitle: 'Bool',\n group: ['Data'],\n };\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const value = this.data.useValueInput\n ? coerceTypeOptional(inputs['input' as PortId], 'boolean') ?? this.data.value ?? false\n : this.data.value ?? false;\n\n return {\n ['value' as PortId]: {\n type: 'boolean',\n value,\n },\n };\n }\n}\n\nexport const booleanNode = nodeDefinition(BooleanNodeImpl, 'Boolean');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { isEqual } from 'lodash-es';\nimport { match } from 'ts-pattern';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { coerceType, coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type CompareNode = ChartNode<'compare', CompareNodeData>;\n\nexport type CompareNodeData = {\n comparisonFunction: '==' | '<' | '>' | '<=' | '>=' | '!=' | 'and' | 'or' | 'xor' | 'nand' | 'nor' | 'xnor';\n useComparisonFunctionInput?: boolean;\n};\n\nexport class CompareNodeImpl extends NodeImpl<CompareNode> {\n static create(): CompareNode {\n const chartNode: CompareNode = {\n type: 'compare',\n title: 'Compare',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 160,\n },\n data: {\n comparisonFunction: '==',\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [\n {\n dataType: 'any',\n id: 'a' as PortId,\n title: 'A',\n },\n {\n dataType: 'any',\n id: 'b' as PortId,\n title: 'B',\n },\n ];\n\n if (this.data.useComparisonFunctionInput) {\n inputs.push({\n dataType: 'string',\n id: 'comparisonFunction' as PortId,\n title: 'Comparison Function',\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'boolean',\n id: 'output' as PortId,\n title: 'Output',\n },\n ];\n }\n\n getEditors(): EditorDefinition<CompareNode>[] {\n return [\n {\n type: 'dropdown',\n label: 'Comparison Function',\n dataKey: 'comparisonFunction',\n options: [\n { label: '==', value: '==' },\n { label: '!=', value: '!=' },\n { label: '<', value: '<' },\n { label: '<=', value: '<=' },\n { label: '>', value: '>' },\n { label: '>=', value: '>=' },\n { label: 'and', value: 'and' },\n { label: 'or', value: 'or' },\n { label: 'xor', value: 'xor' },\n { label: 'nand', value: 'nand' },\n { label: 'nor', value: 'nor' },\n { label: 'xnor', value: 'xnor' },\n ],\n useInputToggleDataKey: 'useComparisonFunctionInput',\n },\n ];\n }\n\n getBody(): string | undefined {\n return this.data.useComparisonFunctionInput ? 'A (Comparison Function) B' : `A ${this.data.comparisonFunction} B`;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Compares two values using the configured operator and outputs the result.\n\n If the data types of the values do not match, then the B value is converted to the type of the A value.\n `,\n infoBoxTitle: 'Compare Node',\n contextMenuTitle: 'Compare',\n group: ['Logic'],\n };\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const comparisonFunction = (\n this.data.useComparisonFunctionInput\n ? coerceType(inputs['comparisonFunction' as PortId], 'string')\n : this.data.comparisonFunction\n ) as CompareNodeData['comparisonFunction'];\n\n const inputA = inputs['a' as PortId];\n const inputB = inputs['b' as PortId];\n\n if (!inputA) {\n return {\n ['output' as PortId]: {\n type: 'boolean',\n value: match(comparisonFunction)\n .with('==', () => !inputB)\n .with('!=', () => !!inputB)\n .otherwise(() => false),\n },\n };\n }\n\n const value1 = inputA.value;\n const value2 = inputB?.type !== inputA.type ? coerceTypeOptional(inputB, inputA.type) : inputB.value;\n\n return {\n ['output' as PortId]: {\n type: 'boolean',\n value: match(comparisonFunction)\n .with('==', () => isEqual(value1, value2))\n .with('!=', () => !isEqual(value1, value2))\n .with('<', () => (value1 as any) < (value2 as any))\n .with('>', () => (value1 as any) > (value2 as any))\n .with('<=', () => (value1 as any) <= (value2 as any))\n .with('>=', () => (value1 as any) >= (value2 as any))\n .with('and', () => !!(value1 && value2))\n .with('or', () => !!(value1 || value2))\n .with('xor', () => !!(value1 ? !value2 : value2))\n .with('nand', () => !(value1 && value2))\n .with('nor', () => !(value1 || value2))\n .with('xnor', () => !(value1 ? !value2 : value2))\n .exhaustive(),\n },\n };\n }\n}\n\nexport const compareNode = nodeDefinition(CompareNodeImpl, 'Compare');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { match } from 'ts-pattern';\nimport { dedent } from 'ts-dedent';\nimport { coerceType, coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type EvaluateNode = ChartNode<'evaluate', EvaluateNodeData>;\n\nexport type EvaluateNodeData = {\n operation: '+' | '-' | '*' | '/' | '^' | '%' | 'abs' | 'negate';\n useOperationInput?: boolean;\n};\n\nconst unaryOperation = ['abs', 'negate'] as const;\ntype Unary = (typeof unaryOperation)[number];\nconst isUnaryOp = (operation: string): operation is Unary => unaryOperation.includes(operation as Unary);\n\nexport class EvaluateNodeImpl extends NodeImpl<EvaluateNode> {\n static create(): EvaluateNode {\n const chartNode: EvaluateNode = {\n type: 'evaluate',\n title: 'Evaluate',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 175,\n },\n data: {\n operation: '+',\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [\n {\n dataType: 'number',\n id: 'a' as PortId,\n title: 'A',\n },\n ];\n\n const isUnary = !this.data.useOperationInput && isUnaryOp(this.data.operation);\n\n if (!isUnary) {\n inputs.push({\n dataType: 'number',\n id: 'b' as PortId,\n title: 'B',\n });\n }\n\n if (this.data.useOperationInput) {\n inputs.push({\n dataType: 'string',\n id: 'operation' as PortId,\n title: 'Operation',\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'number',\n id: 'output' as PortId,\n title: 'Output',\n },\n ];\n }\n\n getEditors(): EditorDefinition<EvaluateNode>[] {\n return [\n {\n type: 'dropdown',\n label: 'Operation',\n dataKey: 'operation',\n options: [\n { label: '+', value: '+' },\n { label: '-', value: '-' },\n { label: '*', value: '*' },\n { label: '/', value: '/' },\n { label: '^', value: '^' },\n { label: '%', value: '%' },\n { label: 'abs', value: 'abs' },\n { label: 'negate', value: 'negate' },\n ],\n useInputToggleDataKey: 'useOperationInput',\n },\n ];\n }\n\n getBody(): string | undefined {\n const isUnary = !this.data.useOperationInput && isUnaryOp(this.data.operation);\n\n if (isUnary) {\n return match(this.data.operation as Unary)\n .with('abs', () => 'abs(A)')\n .with('negate', () => '-A')\n .exhaustive();\n }\n\n if (this.data.operation === '^') {\n return '!markdownA<sup>B</sup>';\n }\n\n return this.data.useOperationInput ? 'A (Operation) B' : `A ${this.data.operation} B`;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Evaluates the configured mathematical operation on the input values and outputs the result.\n\n For more complex operations, you should use the \\`Code\\` node.\n `,\n infoBoxTitle: 'Evaluate Node',\n contextMenuTitle: 'Evaluate',\n group: ['Numbers'],\n };\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const operation = (\n this.data.useOperationInput ? coerceType(inputs['operation' as PortId], 'string') : this.data.operation\n ) as EvaluateNodeData['operation'];\n\n const inputA = coerceTypeOptional(inputs['a' as PortId], 'number');\n const inputB = coerceTypeOptional(inputs['b' as PortId], 'number');\n\n if (isUnaryOp(operation) && inputA) {\n return {\n ['output' as PortId]: {\n type: 'number',\n value: match(operation as Extract<EvaluateNodeData['operation'], Unary>)\n .with('abs', () => Math.abs(inputA))\n .with('negate', () => -inputA)\n .exhaustive(),\n },\n };\n }\n\n if (inputA == null || inputB == null) {\n throw new Error('Missing input');\n }\n\n return {\n ['output' as PortId]: {\n type: 'number',\n value: match(operation as Exclude<EvaluateNodeData['operation'], Unary>)\n .with('+', () => inputA + inputB)\n .with('-', () => inputA - inputB)\n .with('*', () => inputA * inputB)\n .with('/', () => inputA / inputB)\n .with('^', () => Math.pow(inputA, inputB))\n .with('%', () => inputA % inputB)\n .exhaustive(),\n },\n };\n }\n}\n\nexport const evaluateNode = nodeDefinition(EvaluateNodeImpl, 'Evaluate');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type NumberNode = ChartNode<'number', NumberNodeData>;\n\nexport type NumberNodeData = {\n value?: number;\n useValueInput?: boolean;\n round?: boolean;\n roundTo?: number;\n};\n\nexport class NumberNodeImpl extends NodeImpl<NumberNode> {\n static create(): NumberNode {\n const chartNode: NumberNode = {\n type: 'number',\n title: 'Number',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 200,\n },\n data: {\n value: 0,\n round: false,\n roundTo: 0,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n return this.data.useValueInput\n ? [\n {\n dataType: 'any',\n id: 'input' as PortId,\n title: 'Input',\n },\n ]\n : [];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'number',\n id: 'value' as PortId,\n title: 'Value',\n },\n ];\n }\n\n getEditors(): EditorDefinition<NumberNode>[] {\n return [\n { type: 'number', label: 'Value', dataKey: 'value', useInputToggleDataKey: 'useValueInput' },\n { type: 'toggle', label: 'Round', dataKey: 'round' },\n { type: 'number', label: 'Round To', dataKey: 'roundTo' },\n ];\n }\n\n getBody(): string | undefined {\n return this.data.useValueInput ? `(Input to number)` : (this.data.value ?? 0).toLocaleString();\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Outputs a number constant, or converts an input value into a number.\n\n Can be configured to round the number to a certain number of decimal places.\n `,\n infoBoxTitle: 'Number Node',\n contextMenuTitle: 'Number',\n group: ['Numbers'],\n };\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n let value = this.data.useValueInput\n ? coerceTypeOptional(inputs['input' as PortId], 'number') ?? this.data.value ?? 0\n : this.data.value ?? 0;\n\n const { roundTo = 0, round = false } = this.data;\n\n if (round) {\n value = Math.round(value * Math.pow(10, roundTo)) / Math.pow(10, roundTo);\n }\n\n return {\n ['value' as PortId]: {\n type: 'number',\n value,\n },\n };\n }\n}\n\nexport const numberNode = nodeDefinition(NumberNodeImpl, 'Number');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type RandomNumberNode = ChartNode<'randomNumber', RandomNumberNodeData>;\n\nexport type RandomNumberNodeData = {\n min?: number;\n max?: number;\n integers?: boolean;\n maxInclusive?: boolean;\n useMinInput?: boolean;\n useMaxInput?: boolean;\n};\n\nexport class RandomNumberNodeImpl extends NodeImpl<RandomNumberNode> {\n static create(): RandomNumberNode {\n const chartNode: RandomNumberNode = {\n type: 'randomNumber',\n title: 'RNG',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 150,\n },\n data: {\n min: 0,\n max: 1,\n integers: false,\n maxInclusive: false,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n if (this.data.useMinInput) {\n inputs.push({\n dataType: 'number',\n id: 'min' as PortId,\n title: 'Min',\n });\n }\n if (this.data.useMaxInput) {\n inputs.push({\n dataType: 'number',\n id: 'max' as PortId,\n title: 'Max',\n });\n }\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'number',\n id: 'value' as PortId,\n title: 'Value',\n },\n ];\n }\n\n getEditors(): EditorDefinition<RandomNumberNode>[] {\n return [\n { type: 'number', label: 'Min', dataKey: 'min', useInputToggleDataKey: 'useMinInput' },\n { type: 'number', label: 'Max', dataKey: 'max', useInputToggleDataKey: 'useMaxInput' },\n { type: 'toggle', label: 'Integers', dataKey: 'integers' },\n { type: 'toggle', label: 'Max Inclusive', dataKey: 'maxInclusive' },\n ];\n }\n\n getBody(): string | undefined {\n return dedent`\n Min: ${this.data.useMinInput ? '(Input)' : this.data.min ?? 0}\n Max: ${this.data.useMaxInput ? '(Input)' : this.data.max ?? 1}\n ${this.data.integers ? 'Integers' : 'Floats'}\n ${this.data.maxInclusive ? 'Max Inclusive' : 'Max Exclusive'}\n `;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Outputs a random number between the configured min and max values.\n\n Can be configured to output only integers, and whether the max value is inclusive or exclusive.\n `,\n infoBoxTitle: 'RNG Node',\n contextMenuTitle: 'RNG',\n group: ['Numbers'],\n };\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const min = this.data.useMinInput\n ? coerceTypeOptional(inputs['min' as PortId], 'number') ?? this.data.min ?? 0\n : this.data.min ?? 0;\n\n let max = this.data.useMaxInput\n ? coerceTypeOptional(inputs['max' as PortId], 'number') ?? this.data.max ?? 1\n : this.data.max ?? 1;\n\n if (this.data.integers && this.data.maxInclusive) {\n max += 1;\n }\n let value = Math.random() * (max - min) + min;\n\n if (this.data.integers) {\n value = Math.floor(value);\n }\n\n return {\n ['value' as PortId]: {\n type: 'number',\n value,\n },\n };\n }\n}\n\nexport const randomNumberNode = nodeDefinition(RandomNumberNodeImpl, 'Random Number');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { shuffle } from 'lodash-es';\nimport { type DataValue, isArrayDataValue } from '../DataValue.js';\nimport { dedent } from 'ts-dedent';\n\nexport type ShuffleNode = ChartNode<'shuffle'>;\n\nexport class ShuffleNodeImpl extends NodeImpl<ShuffleNode> {\n static create(): ShuffleNode {\n const chartNode: ShuffleNode = {\n type: 'shuffle',\n title: 'Shuffle',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 175,\n },\n data: {},\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n {\n dataType: 'any[]',\n id: 'array' as PortId,\n title: 'Array',\n },\n ];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'any[]',\n id: 'shuffled' as PortId,\n title: 'Shuffled',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Shuffles the input array. Outputs the shuffled array.\n `,\n infoBoxTitle: 'Shuffle Node',\n contextMenuTitle: 'Shuffle',\n group: ['Lists'],\n };\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const input = inputs['array' as PortId];\n\n const items = input ? (isArrayDataValue(input) ? input.value : [input.value]) : [];\n\n const shuffled = shuffle(items);\n\n return {\n ['shuffled' as PortId]: {\n type: inputs['array' as PortId]?.type ?? 'any[]',\n value: shuffled,\n } as DataValue,\n };\n }\n}\n\nexport const shuffleNode = nodeDefinition(ShuffleNodeImpl, 'Shuffle');\n", "import { type ChartNode, type NodeId, type NodeInputDefinition, type NodeOutputDefinition } from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { type DataValue } from '../DataValue.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type CommentNode = ChartNode<'comment', CommentNodeData>;\n\nexport type CommentNodeData = {\n text: string;\n color?: string;\n backgroundColor?: string;\n height: number;\n};\n\nexport class CommentNodeImpl extends NodeImpl<CommentNode> {\n static create(): CommentNode {\n const chartNode: CommentNode = {\n type: 'comment',\n title: 'Comment',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 600,\n },\n data: {\n text: '',\n height: 600,\n color: 'rgba(255,255,255,1)',\n backgroundColor: 'rgba(0,0,0,0.05)',\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [];\n }\n\n getEditors(): EditorDefinition<CommentNode>[] {\n return [\n {\n type: 'color',\n label: 'Color',\n dataKey: 'color',\n },\n {\n type: 'color',\n label: 'Background Color',\n dataKey: 'backgroundColor',\n },\n {\n type: 'code',\n label: 'Text',\n dataKey: 'text',\n language: 'markdown',\n theme: 'vs-dark',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n A comment node is a node that does nothing. It is useful for adding notes to a graph.\n `,\n infoBoxTitle: 'Comment Node',\n contextMenuTitle: 'Comment',\n group: ['Advanced'],\n };\n }\n\n async process(): Promise<Record<string, DataValue>> {\n return {};\n }\n}\n\nexport const commentNode = nodeDefinition(CommentNodeImpl, 'Comment');\n", "import {\n type ChartNode,\n type NodeId,\n type PortId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport {\n type DataRef,\n type EditorDefinition,\n type Inputs,\n type InternalProcessContext,\n type Outputs,\n} from '../../index.js';\nimport { base64ToUint8Array } from '../../utils/base64.js';\nimport { expectType } from '../../utils/expectType.js';\n\nexport type ImageNode = ChartNode<'image', ImageNodeData>;\n\ntype ImageNodeData = {\n data?: DataRef;\n useDataInput: boolean;\n mediaType: 'image/png' | 'image/jpeg' | 'image/gif';\n useMediaTypeInput: boolean;\n};\n\nexport class ImageNodeImpl extends NodeImpl<ImageNode> {\n static create(): ImageNode {\n return {\n id: nanoid() as NodeId,\n type: 'image',\n title: 'Image',\n visualData: { x: 0, y: 0, width: 250 },\n data: {\n useDataInput: false,\n mediaType: 'image/png',\n useMediaTypeInput: false,\n },\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputDefinitions: NodeInputDefinition[] = [];\n\n if (this.chartNode.data.useDataInput) {\n inputDefinitions.push({\n id: 'data' as PortId,\n title: 'Data',\n dataType: 'binary',\n coerced: false,\n });\n }\n\n if (this.chartNode.data.useMediaTypeInput) {\n inputDefinitions.push({\n id: 'mediaType' as PortId,\n title: 'Media Type',\n dataType: 'string',\n });\n }\n\n return inputDefinitions;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'image' as PortId,\n title: 'Image',\n dataType: 'image',\n },\n ];\n }\n\n getEditors(): EditorDefinition<ImageNode>[] {\n return [\n {\n type: 'dropdown',\n label: 'Media Type',\n dataKey: 'mediaType',\n options: [\n { value: 'image/png', label: 'PNG' },\n { value: 'image/jpeg', label: 'JPEG' },\n { value: 'image/gif', label: 'GIF' },\n ],\n useInputToggleDataKey: 'useMediaTypeInput',\n },\n {\n type: 'imageBrowser',\n label: 'Image',\n dataKey: 'data',\n useInputToggleDataKey: 'useDataInput',\n mediaTypeDataKey: 'mediaType',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n contextMenuTitle: 'Image',\n group: 'Data',\n infoBoxTitle: 'Image Node',\n infoBoxBody: 'Defines a static image for use with other nodes. Can convert a binary type into an image type.',\n };\n }\n\n async process(inputData: Inputs, context: InternalProcessContext): Promise<Outputs> {\n let data: Uint8Array;\n\n if (this.chartNode.data.useDataInput) {\n data = expectType(inputData['data' as PortId], 'binary');\n } else {\n const dataRef = this.data.data?.refId;\n if (!dataRef) {\n throw new Error('No data ref');\n }\n\n const encodedData = context.project.data?.[dataRef] as string;\n\n if (!encodedData) {\n throw new Error(`No data at ref ${dataRef}`);\n }\n\n data = base64ToUint8Array(encodedData);\n }\n\n const mediaType = this.chartNode.data.useMediaTypeInput\n ? expectType(inputData['mediaType' as PortId], 'string')\n : this.chartNode.data.mediaType;\n\n return {\n ['image' as PortId]: {\n type: 'image',\n value: { mediaType: mediaType as 'image/png' | 'image/jpeg' | 'image/gif', data },\n },\n };\n }\n}\n\nexport const imageNode = nodeDefinition(ImageNodeImpl, 'Image');\n", "import {\n type ChartNode,\n type NodeId,\n type PortId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport {\n type DataRef,\n type EditorDefinition,\n type Inputs,\n type InternalProcessContext,\n type Outputs,\n} from '../../index.js';\nimport { base64ToUint8Array, expectType } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { getInputOrData } from '../../utils/inputs.js';\n\nexport type AudioNode = ChartNode<'audio', AudioNodeData>;\n\ntype AudioNodeData = {\n data?: DataRef;\n useDataInput: boolean;\n\n mediaType?: 'audio/wav' | 'audio/mp3' | 'audio/ogg';\n useMediaTypeInput: boolean;\n};\n\nexport class AudioNodeImpl extends NodeImpl<AudioNode> {\n static create(): AudioNode {\n return {\n id: nanoid() as NodeId,\n type: 'audio',\n title: 'Audio',\n visualData: { x: 0, y: 0, width: 300 },\n data: {\n useDataInput: false,\n useMediaTypeInput: false,\n },\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputDefinitions: NodeInputDefinition[] = [];\n\n if (this.chartNode.data.useDataInput) {\n inputDefinitions.push({\n id: 'data' as PortId,\n title: 'Data',\n dataType: 'string',\n coerced: false,\n });\n }\n\n if (this.chartNode.data.useMediaTypeInput) {\n inputDefinitions.push({\n id: 'mediaType' as PortId,\n title: 'Media Type',\n dataType: 'string',\n coerced: false,\n });\n }\n\n return inputDefinitions;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'data' as PortId,\n title: 'Audio Data',\n dataType: 'audio',\n },\n ];\n }\n\n getEditors(): EditorDefinition<AudioNode>[] {\n return [\n {\n type: 'fileBrowser',\n label: 'Audio File',\n dataKey: 'data',\n mediaTypeDataKey: 'mediaType',\n useInputToggleDataKey: 'useDataInput',\n accept: 'audio/*',\n },\n {\n type: 'string',\n label: 'Media Type',\n dataKey: 'mediaType',\n useInputToggleDataKey: 'useMediaTypeInput',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n contextMenuTitle: 'Audio',\n group: 'Data',\n infoBoxTitle: 'Audio Node',\n infoBoxBody: 'Defines an audio sample for use with other nodes. Can convert a binary type into an audio type.',\n };\n }\n\n async process(inputData: Inputs, context: InternalProcessContext): Promise<Outputs> {\n let data: Uint8Array;\n\n const mediaType = getInputOrData(this.data, inputData, 'mediaType', 'string') || 'audio/wav';\n\n if (this.chartNode.data.useDataInput) {\n data = expectType(inputData['data' as PortId], 'binary');\n } else {\n const dataRef = this.data.data?.refId;\n if (!dataRef) {\n throw new Error('No data ref');\n }\n\n const encodedData = context.project.data?.[dataRef] as string;\n\n if (!encodedData) {\n throw new Error(`No data at ref ${dataRef}`);\n }\n\n data = base64ToUint8Array(encodedData);\n }\n\n return {\n ['data' as PortId]: {\n type: 'audio',\n value: { data, mediaType },\n },\n };\n }\n}\n\nexport const audioNode = nodeDefinition(AudioNodeImpl, 'Audio');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition, type InternalProcessContext } from '../../index.js';\nimport { coerceType, dedent, getInputOrData } from '../../utils/index.js';\nimport { getError } from '../../utils/errors.js';\n\nexport type HttpCallNode = ChartNode<'httpCall', HttpCallNodeData>;\n\nexport type HttpCallNodeData = {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE';\n useMethodInput?: boolean;\n\n url: string;\n useUrlInput?: boolean;\n\n headers: string;\n useHeadersInput?: boolean;\n\n body: string;\n useBodyInput?: boolean;\n\n isBinaryOutput?: boolean;\n\n errorOnNon200?: boolean;\n};\n\nexport class HttpCallNodeImpl extends NodeImpl<HttpCallNode> {\n static create(): HttpCallNode {\n const chartNode: HttpCallNode = {\n type: 'httpCall',\n title: 'Http Call',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n method: 'GET',\n url: '',\n headers: '',\n body: '',\n errorOnNon200: true,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n\n if (this.data.useMethodInput) {\n inputs.push({\n dataType: 'string',\n id: 'method' as PortId,\n title: 'Method',\n });\n }\n\n if (this.data.useUrlInput) {\n inputs.push({\n dataType: 'string',\n id: 'url' as PortId,\n title: 'URL',\n });\n }\n\n if (this.data.useHeadersInput) {\n inputs.push({\n dataType: 'object',\n id: 'headers' as PortId,\n title: 'Headers',\n });\n }\n\n if (this.data.useBodyInput) {\n inputs.push({\n dataType: 'string',\n id: 'req_body' as PortId,\n title: 'Body',\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n const outputDefinitions: NodeOutputDefinition[] = [];\n if (this.data.isBinaryOutput) {\n outputDefinitions.push({\n dataType: 'binary',\n id: 'binary' as PortId,\n title: 'Binary',\n });\n } else {\n outputDefinitions.push(\n {\n dataType: 'string',\n id: 'res_body' as PortId,\n title: 'Body',\n },\n {\n dataType: 'object',\n id: 'json' as PortId,\n title: 'JSON',\n },\n );\n }\n\n outputDefinitions.push(\n {\n dataType: 'number',\n id: 'statusCode' as PortId,\n title: 'Status Code',\n },\n {\n dataType: 'object',\n id: 'res_headers' as PortId,\n title: 'Headers',\n },\n );\n\n return outputDefinitions;\n }\n\n getEditors(): EditorDefinition<HttpCallNode>[] {\n return [\n {\n type: 'dropdown',\n label: 'Method',\n dataKey: 'method',\n useInputToggleDataKey: 'useMethodInput',\n options: [\n { label: 'GET', value: 'GET' },\n { label: 'POST', value: 'POST' },\n { label: 'PUT', value: 'PUT' },\n { label: 'DELETE', value: 'DELETE' },\n ],\n },\n {\n type: 'string',\n label: 'URL',\n dataKey: 'url',\n useInputToggleDataKey: 'useUrlInput',\n },\n {\n type: 'code',\n label: 'Headers',\n dataKey: 'headers',\n useInputToggleDataKey: 'useHeadersInput',\n language: 'json',\n },\n {\n type: 'code',\n label: 'Body',\n dataKey: 'body',\n useInputToggleDataKey: 'useBodyInput',\n language: 'json',\n },\n {\n type: 'toggle',\n label: 'Whether response body is expected to be a binary',\n dataKey: 'isBinaryOutput',\n },\n {\n type: 'toggle',\n label: 'Error on non-200 status code',\n dataKey: 'errorOnNon200',\n },\n ];\n }\n\n getBody(): string {\n return dedent`\n ${this.data.useMethodInput ? '(Method Using Input)' : this.data.method} ${\n this.data.useUrlInput ? '(URL Using Input)' : this.data.url\n } ${\n this.data.useHeadersInput\n ? '\\nHeaders: (Using Input)'\n : this.data.headers.trim()\n ? `\\nHeaders: ${this.data.headers}`\n : ''\n }${this.data.useBodyInput ? '\\nBody: (Using Input)' : this.data.body.trim() ? `\\nBody: ${this.data.body}` : ''}${\n this.data.errorOnNon200 ? '\\nError on non-200' : ''\n }\n `;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Makes an HTTP call to the specified URL with the given method, headers, and body.\n `,\n infoBoxTitle: 'HTTP Call Node',\n contextMenuTitle: 'HTTP Call',\n group: ['Advanced'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const method = getInputOrData(this.data, inputs, 'method', 'string');\n const url = getInputOrData(this.data, inputs, 'url', 'string');\n\n try {\n new URL(url);\n } catch (err) {\n throw new Error(`Invalid URL: ${url}`);\n }\n\n let headers: Record<string, string> | undefined;\n if (this.data.useHeadersInput) {\n const headersInput = inputs['headers' as PortId];\n if (headersInput?.type === 'string') {\n headers = JSON.parse(headersInput!.value);\n } else if (headersInput?.type === 'object') {\n headers = headersInput!.value as Record<string, string>;\n } else {\n headers = coerceType(headersInput, 'object') as Record<string, string>;\n }\n } else if (this.data.headers.trim()) {\n headers = JSON.parse(this.data.headers);\n }\n\n let body: string | undefined;\n if (this.data.useBodyInput) {\n const bodyInput = inputs['req_body' as PortId];\n if (bodyInput?.type === 'string') {\n body = bodyInput!.value;\n } else if (bodyInput?.type === 'object') {\n body = JSON.stringify(bodyInput!.value);\n } else {\n body = coerceType(bodyInput, 'string');\n }\n } else {\n body = this.data.body || undefined;\n }\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body,\n signal: context.signal,\n mode: 'cors',\n });\n\n const output: Outputs = {\n ['statusCode' as PortId]: {\n type: 'number',\n value: response.status,\n },\n ['res_headers' as PortId]: {\n type: 'object',\n value: Object.fromEntries(response.headers.entries()),\n },\n };\n\n if (this.data.isBinaryOutput) {\n const responseBlob = await response.blob();\n output['binary' as PortId] = {\n type: 'binary',\n value: new Uint8Array(await responseBlob.arrayBuffer()),\n };\n } else {\n const responseText = await response.text();\n output['res_body' as PortId] = {\n type: 'string',\n value: responseText,\n };\n if (response.headers.get('content-type')?.includes('application/json')) {\n const jsonData = JSON.parse(responseText);\n output['json' as PortId] = {\n type: 'object',\n value: jsonData,\n };\n } else {\n output['json' as PortId] = {\n type: 'control-flow-excluded',\n value: undefined,\n };\n }\n }\n\n return output;\n } catch (err) {\n const { message } = getError(err);\n if (message.includes('Load failed') || message.includes('Failed to fetch')) {\n if (context.executor === 'browser') {\n throw new Error(\n 'Failed to make HTTP call. You may be running into CORS problems. Try using the Node executor in the top-right menu.',\n );\n }\n }\n\n throw err;\n }\n }\n}\n\nexport const httpCallNode = nodeDefinition(HttpCallNodeImpl, 'Http Call');\n", "import {\n type ChartNode,\n type NodeConnection,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { getInputOrData } from '../../utils/inputs.js';\n\nexport type DelayNode = ChartNode<'delay', DelayNodeData>;\n\nexport type DelayNodeData = {\n delay: number;\n useDelayInput?: boolean;\n};\n\nexport class DelayNodeImpl extends NodeImpl<DelayNode> {\n static create(): DelayNode {\n const chartNode: DelayNode = {\n type: 'delay',\n title: 'Delay',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 175,\n },\n data: {\n delay: 0,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n const inputCount = this.#getInputPortCount(connections);\n\n if (this.data.useDelayInput) {\n inputs.push({\n dataType: 'number',\n id: 'delay' as PortId,\n title: 'Delay (ms)',\n });\n }\n\n for (let i = 1; i <= inputCount; i++) {\n inputs.push({\n dataType: 'any',\n id: `input${i}` as PortId,\n title: `Input ${i}`,\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(connections: NodeConnection[]): NodeOutputDefinition[] {\n const outputs: NodeOutputDefinition[] = [];\n const inputCount = this.#getInputPortCount(connections);\n\n for (let i = 1; i <= inputCount - 1; i++) {\n outputs.push({\n dataType: 'any',\n id: `output${i}` as PortId,\n title: `Output ${i}`,\n });\n }\n\n return outputs;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Delays the execution and then passes the input value to the output without any modifications.\n `,\n infoBoxTitle: 'Delay Node',\n contextMenuTitle: 'Delay',\n group: ['Logic'],\n };\n }\n\n #getInputPortCount(connections: NodeConnection[]): number {\n const inputNodeId = this.chartNode.id;\n const inputConnections = connections.filter(\n (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'),\n );\n\n let maxInputNumber = 0;\n for (const connection of inputConnections) {\n const messageNumber = parseInt(connection.inputId.replace('input', ''), 10);\n if (messageNumber > maxInputNumber) {\n maxInputNumber = messageNumber;\n }\n }\n\n return maxInputNumber + 1;\n }\n\n getEditors(): EditorDefinition<DelayNode>[] {\n return [\n {\n type: 'number',\n label: 'Delay (ms)',\n dataKey: 'delay',\n useInputToggleDataKey: 'useDelayInput',\n defaultValue: 0,\n },\n ];\n }\n\n getBody(): string | undefined {\n return `Delay ${this.data.useDelayInput ? '(Input ms)' : `${this.chartNode.data.delay}ms`}`;\n }\n\n async process(inputData: Inputs): Promise<Outputs> {\n const delayAmount = getInputOrData(this.data, inputData, 'delay', 'number');\n\n await new Promise((resolve) => setTimeout(resolve, delayAmount));\n\n const inputCount = Object.keys(inputData).filter((key) => key.startsWith('input')).length;\n\n const outputs: Outputs = {};\n\n for (let i = 1; i <= inputCount; i++) {\n const input = inputData[`input${i}` as PortId]!;\n outputs[`output${i}` as PortId] = input;\n }\n\n return outputs;\n }\n}\n\nexport const delayNode = nodeDefinition(DelayNodeImpl, 'Delay');\n", "import type { ChartNode, NodeId, PortId, NodeInputDefinition, NodeOutputDefinition } from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nanoid } from 'nanoid/non-secure';\n\nimport type { InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { getInputOrData, coerceTypeOptional, newId, coerceType } from '../../utils/index.js';\nimport { arrayizeDataValue, unwrapDataValue } from '../DataValue.js';\nimport type { DatasetId, DatasetRow } from '../Dataset.js';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\n\nexport type AppendToDatasetNode = ChartNode<'appendToDataset', AppendToDatasetNodeData>;\n\ntype AppendToDatasetNodeData = {\n datasetId: DatasetId;\n useDatasetIdInput?: boolean;\n};\n\nexport class AppendToDatasetNodeImpl extends NodeImpl<AppendToDatasetNode> {\n static create(): AppendToDatasetNode {\n return {\n id: nanoid() as NodeId,\n type: 'appendToDataset',\n title: 'Append to Dataset',\n visualData: { x: 0, y: 0, width: 250 },\n data: {\n datasetId: '' as DatasetId,\n },\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputDefinitions: NodeInputDefinition[] = [];\n\n inputDefinitions.push({\n id: 'data' as PortId,\n dataType: 'string[]',\n title: 'Data',\n description:\n 'The data to append to the dataset. May be a string or array of strings. If an array, each element will be a column in the dataset.',\n });\n\n inputDefinitions.push({\n id: 'id' as PortId,\n dataType: 'string',\n title: 'ID',\n description:\n 'The ID of the row to append. If not provided, a random ID will be generated. If an existing ID is provided, the row will be overwritten.',\n });\n\n inputDefinitions.push({\n id: 'embedding' as PortId,\n dataType: 'vector',\n title: 'Embedding',\n description: 'The vector embedding to store with the row.',\n });\n\n if (this.data.useDatasetIdInput) {\n inputDefinitions.push({\n id: 'datasetId' as PortId,\n title: 'Dataset ID',\n dataType: 'string',\n description: 'The ID of the dataset to append to.',\n });\n }\n\n return inputDefinitions;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'dataset' as PortId,\n title: 'Dataset',\n dataType: 'object', // technically string[][]...\n },\n {\n id: 'id_out' as PortId,\n title: 'ID',\n dataType: 'string',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Appends a row of data to the specified dataset.\n `,\n infoBoxTitle: 'Append to Dataset Node',\n contextMenuTitle: 'Append to Dataset',\n group: ['Input/Output'],\n };\n }\n\n getEditors(): EditorDefinition<AppendToDatasetNode>[] | Promise<EditorDefinition<AppendToDatasetNode>[]> {\n return [\n {\n type: 'datasetSelector',\n label: 'Dataset',\n dataKey: 'datasetId',\n useInputToggleDataKey: 'useDatasetIdInput',\n },\n ];\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const { datasetProvider } = context;\n\n if (datasetProvider == null) {\n throw new Error('datasetProvider is required');\n }\n\n const datasetId = getInputOrData(this.data, inputs, 'datasetId', 'string') as DatasetId;\n const dataId = coerceTypeOptional(inputs['id' as PortId], 'string') || newId<DatasetId>();\n const embedding = coerceTypeOptional(inputs['embedding' as PortId], 'vector');\n\n const dataInput = inputs['data' as PortId];\n\n if (!dataInput) {\n throw new Error('data input is required');\n }\n\n const data = arrayizeDataValue(unwrapDataValue(dataInput));\n const stringData = data.map((d) => coerceType(d, 'string'));\n\n const newData: DatasetRow = {\n id: dataId,\n data: stringData,\n embedding,\n };\n\n await datasetProvider.putDatasetRow(datasetId, newData);\n\n return {\n ['dataset' as PortId]: {\n type: 'object',\n value: newData as any,\n },\n ['id_out' as PortId]: {\n type: 'string',\n value: datasetId,\n },\n };\n }\n}\n\nexport const appendToDatasetNode = nodeDefinition(AppendToDatasetNodeImpl, 'Append To Dataset');\n", "import type {\n ChartNode,\n DatasetId,\n Inputs,\n InternalProcessContext,\n NodeId,\n NodeInputDefinition,\n NodeOutputDefinition,\n NodeUIData,\n Outputs,\n PortId,\n} from '../../index.js';\nimport { NodeImpl } from '../NodeImpl.js';\nimport { coerceTypeOptional, dedent, newId } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type CreateDatasetNode = ChartNode<'createDataset', CreateDatasetNodeData>;\n\ntype CreateDatasetNodeData = {};\n\nexport class CreateDatasetNodeImpl extends NodeImpl<CreateDatasetNode> {\n static create(): CreateDatasetNode {\n return {\n id: newId<NodeId>(),\n type: 'createDataset',\n title: 'Create Dataset',\n visualData: { x: 0, y: 0, width: 250 },\n data: {},\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n {\n id: 'datasetId' as PortId,\n title: 'Dataset ID',\n dataType: 'string',\n },\n {\n id: 'datasetName' as PortId,\n title: 'Dataset Name',\n dataType: 'string',\n },\n ];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'datasetId_out' as PortId,\n title: 'Dataset ID',\n dataType: 'string',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Creates a new dataset with the provided ID and name. If the dataset already exists, it does nothing.\n `,\n infoBoxTitle: 'Create Dataset Node',\n contextMenuTitle: 'Create Dataset',\n group: ['Input/Output'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const { datasetProvider } = context;\n\n if (datasetProvider == null) {\n throw new Error('datasetProvider is required');\n }\n\n const datasetId =\n (coerceTypeOptional(inputs['datasetId' as PortId], 'string') as DatasetId | undefined) || newId<DatasetId>();\n const datasetName = coerceTypeOptional(inputs['datasetName' as PortId], 'string') || datasetId;\n\n const existingDataset = await datasetProvider.getDatasetMetadata(datasetId);\n\n if (!existingDataset) {\n await datasetProvider.putDatasetMetadata({\n id: datasetId,\n name: datasetName,\n description: '',\n projectId: context.project.metadata.id,\n });\n }\n\n return {\n ['datasetId_out' as PortId]: {\n type: 'string',\n value: datasetId || datasetName,\n },\n };\n }\n}\n\nexport const createDatasetNode = nodeDefinition(CreateDatasetNodeImpl, 'Create Dataset');\n", "import type {\n ChartNode,\n DatasetId,\n Inputs,\n InternalProcessContext,\n NodeId,\n NodeInputDefinition,\n NodeOutputDefinition,\n NodeUIData,\n Outputs,\n PortId,\n EditorDefinition,\n} from '../../index.js';\nimport { NodeImpl } from '../NodeImpl.js';\nimport { coerceTypeOptional, dedent, newId } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type LoadDatasetNode = ChartNode<'loadDataset', LoadDatasetNodeData>;\n\ntype LoadDatasetNodeData = {\n datasetId: DatasetId;\n useDatasetIdInput?: boolean;\n};\n\nexport class LoadDatasetNodeImpl extends NodeImpl<LoadDatasetNode> {\n static create(): LoadDatasetNode {\n return {\n id: newId<NodeId>(),\n type: 'loadDataset',\n title: 'Load Dataset',\n visualData: { x: 0, y: 0, width: 250 },\n data: {\n datasetId: '' as DatasetId,\n },\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n\n if (this.data.useDatasetIdInput) {\n inputs.push({\n id: 'datasetId' as PortId,\n title: 'Dataset ID',\n dataType: 'string',\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'dataset' as PortId,\n title: 'Dataset',\n dataType: 'object[]',\n },\n {\n id: 'datasetId_out' as PortId,\n title: 'Dataset ID',\n dataType: 'string',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Loads a dataset with the provided ID. If the dataset does not exist, it throws an error.\n `,\n infoBoxTitle: 'Load Dataset Node',\n contextMenuTitle: 'Load Dataset',\n group: ['Input/Output'],\n };\n }\n\n getEditors(): EditorDefinition<LoadDatasetNode>[] | Promise<EditorDefinition<LoadDatasetNode>[]> {\n return [\n {\n type: 'datasetSelector',\n label: 'Dataset',\n dataKey: 'datasetId',\n useInputToggleDataKey: 'useDatasetIdInput',\n },\n ];\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const { datasetProvider } = context;\n\n if (datasetProvider == null) {\n throw new Error('datasetProvider is required');\n }\n\n const datasetId = coerceTypeOptional(inputs['datasetId' as PortId], 'string') || this.data.datasetId;\n\n const dataset = await datasetProvider.getDatasetData(datasetId as DatasetId);\n\n if (!dataset) {\n throw new Error(`Dataset with ID ${datasetId} does not exist`);\n }\n\n return {\n ['dataset' as PortId]: {\n type: 'object[]',\n value: dataset.rows,\n },\n ['datasetId_out' as PortId]: {\n type: 'string',\n value: datasetId,\n },\n };\n }\n}\n\nexport const loadDatasetNode = nodeDefinition(LoadDatasetNodeImpl, 'Load Dataset');\n", "import type {\n ChartNode,\n EditorDefinition,\n Inputs,\n InternalProcessContext,\n NodeId,\n NodeInputDefinition,\n NodeOutputDefinition,\n NodeUIData,\n Outputs,\n PortId,\n} from '../../index.js';\nimport { NodeImpl } from '../NodeImpl.js';\nimport { dedent, newId } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type GetAllDatasetsNode = ChartNode<'getAllDatasets', GetAllDatasetsNodeData>;\n\ntype GetAllDatasetsNodeData = {};\n\nexport class GetAllDatasetsNodeImpl extends NodeImpl<GetAllDatasetsNode> {\n static create(): GetAllDatasetsNode {\n return {\n id: newId<NodeId>(),\n type: 'getAllDatasets',\n title: 'Get All Datasets',\n visualData: { x: 0, y: 0, width: 250 },\n data: {},\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'datasets' as PortId,\n title: 'Datasets',\n dataType: 'object[]',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Retrieves all datasets. If no datasets exist, it returns an empty array.\n `,\n infoBoxTitle: 'Get All Datasets Node',\n contextMenuTitle: 'Get All Datasets',\n group: ['Input/Output'],\n };\n }\n\n getEditors(): EditorDefinition<GetAllDatasetsNode>[] | Promise<EditorDefinition<GetAllDatasetsNode>[]> {\n return [];\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const { datasetProvider } = context;\n\n if (datasetProvider == null) {\n throw new Error('datasetProvider is required');\n }\n\n const datasets = await datasetProvider.getDatasetsForProject(context.project.metadata.id);\n\n return {\n ['datasets' as PortId]: {\n type: 'object[]',\n value: datasets,\n },\n };\n }\n}\n\nexport const getAllDatasetsNode = nodeDefinition(GetAllDatasetsNodeImpl, 'Get All Datasets');\n", "import type {\n ChartNode,\n NodeId,\n NodeInputDefinition,\n NodeOutputDefinition,\n NodeUIData,\n EditorDefinition,\n PortId,\n Inputs,\n InternalProcessContext,\n Outputs,\n NodeBodySpec,\n} from '../../index.js';\nimport { NodeImpl } from '../NodeImpl.js';\nimport { coerceType, dedent, getInputOrData, handleEscapeCharacters, newId } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type SplitNode = ChartNode<'split', SplitNodeData>;\n\ntype SplitNodeData = {\n delimiter: string;\n useDelimiterInput?: boolean;\n regex?: boolean;\n};\n\nexport class SplitNodeImpl extends NodeImpl<SplitNode> {\n static create(): SplitNode {\n return {\n id: newId<NodeId>(),\n type: 'split',\n title: 'Split Text',\n visualData: { x: 0, y: 0, width: 250 },\n data: {\n delimiter: ',',\n regex: false,\n },\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [\n {\n id: 'string' as PortId,\n title: 'String',\n dataType: 'string',\n },\n ];\n\n if (this.data.useDelimiterInput) {\n inputs.push({\n id: 'delimiter' as PortId,\n title: 'Delimiter',\n dataType: 'string',\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'splitString' as PortId,\n title: 'Split',\n dataType: 'string[]',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Splits a string by the provided delimiter.\n `,\n infoBoxTitle: 'Split Text Node',\n contextMenuTitle: 'Split Text',\n group: ['Text'],\n };\n }\n\n getEditors(): EditorDefinition<SplitNode>[] | Promise<EditorDefinition<SplitNode>[]> {\n return [\n {\n type: 'toggle',\n label: 'Regex',\n dataKey: 'regex',\n },\n {\n type: 'code',\n label: 'Delimiter',\n language: 'plaintext',\n dataKey: 'delimiter',\n useInputToggleDataKey: 'useDelimiterInput',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | NodeBodySpec[] | undefined {\n if (this.data.useDelimiterInput) {\n return '(Delimiter from input)';\n }\n\n const normalized = handleEscapeCharacters(this.data.delimiter);\n\n if (normalized === '\\n') {\n return '(New line)';\n }\n\n if (normalized === '\\r\\n') {\n return '(New line (windows))';\n }\n\n if (normalized === '\\t') {\n return '(Tab)';\n }\n\n if (normalized === ' ') {\n return '(Space)';\n }\n\n return normalized;\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const delimiter = getInputOrData(this.data, inputs, 'delimiter');\n\n const normalizedDelimiter = this.data.regex ? new RegExp(delimiter) : handleEscapeCharacters(delimiter);\n\n const stringToSplit = coerceType(inputs['string' as PortId], 'string');\n\n const splitString = stringToSplit.split(normalizedDelimiter);\n\n return {\n ['splitString' as PortId]: {\n type: 'string[]',\n value: splitString,\n },\n };\n }\n}\n\nexport const splitNode = nodeDefinition(SplitNodeImpl, 'Split String');\n", "import type {\n ChartNode,\n DatasetId,\n Inputs,\n InternalProcessContext,\n NodeId,\n NodeInputDefinition,\n NodeOutputDefinition,\n NodeUIData,\n Outputs,\n PortId,\n EditorDefinition,\n} from '../../index.js';\nimport { NodeImpl } from '../NodeImpl.js';\nimport { coerceType, dedent, getInputOrData, newId } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type DatasetNearestNeighborsNode = ChartNode<'datasetNearestNeighbors', DatasetNearestNeighborsNodeData>;\n\ntype DatasetNearestNeighborsNodeData = {\n datasetId: DatasetId;\n useDatasetIdInput?: boolean;\n\n k: number;\n useKInput?: boolean;\n};\n\nexport class DatasetNearestNeighborsNodeImpl extends NodeImpl<DatasetNearestNeighborsNode> {\n static create(): DatasetNearestNeighborsNode {\n return {\n id: newId<NodeId>(),\n type: 'datasetNearestNeighbors',\n title: 'KNN Dataset',\n visualData: { x: 0, y: 0, width: 250 },\n data: {\n datasetId: '' as DatasetId,\n k: 5,\n },\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [\n {\n id: 'embedding' as PortId,\n title: 'Embedding',\n dataType: 'object',\n },\n ];\n\n if (this.data.useDatasetIdInput) {\n inputs.push({\n id: 'datasetId' as PortId,\n title: 'Dataset ID',\n dataType: 'string',\n });\n }\n\n if (this.data.useKInput) {\n inputs.push({\n id: 'k' as PortId,\n title: 'K',\n dataType: 'number',\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'nearestNeighbors' as PortId,\n title: 'Nearest Neighbors',\n dataType: 'object[]',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Finds the k nearest neighbors in the dataset with the provided ID, given an embedding.\n `,\n infoBoxTitle: 'KNN Dataset Node',\n contextMenuTitle: 'KNN Dataset',\n group: ['Input/Output'],\n };\n }\n\n getEditors(): EditorDefinition<DatasetNearestNeighborsNode>[] {\n return [\n {\n type: 'datasetSelector',\n label: 'Dataset',\n dataKey: 'datasetId',\n useInputToggleDataKey: 'useDatasetIdInput',\n },\n {\n type: 'number',\n label: 'K',\n dataKey: 'k',\n useInputToggleDataKey: 'useKInput',\n },\n ];\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const { datasetProvider } = context;\n\n if (datasetProvider == null) {\n throw new Error('datasetProvider is required');\n }\n\n const datasetId = getInputOrData(this.data, inputs, 'datasetId');\n const k = getInputOrData(this.data, inputs, 'k', 'number');\n const embedding = coerceType(inputs['embedding' as PortId], 'vector');\n\n const nearestNeighbors = await datasetProvider.knnDatasetRows(datasetId as DatasetId, k, embedding);\n\n return {\n ['nearestNeighbors' as PortId]: {\n type: 'object[]',\n value: nearestNeighbors.map((neighbor) => ({\n id: neighbor.id,\n distance: neighbor.distance,\n data: neighbor.data,\n })),\n },\n };\n }\n}\n\nexport const datasetNearestNeighborsNode = nodeDefinition(DatasetNearestNeighborsNodeImpl, 'Dataset Nearest Neighbors');\n", "import type {\n ChartNode,\n DatasetId,\n Inputs,\n InternalProcessContext,\n NodeId,\n NodeInputDefinition,\n NodeOutputDefinition,\n NodeUIData,\n Outputs,\n PortId,\n EditorDefinition,\n} from '../../index.js';\nimport { NodeImpl } from '../NodeImpl.js';\nimport { dedent, getInputOrData, newId } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type GetDatasetRowNode = ChartNode<'getDatasetRow', GetDatasetRowNodeData>;\n\ntype GetDatasetRowNodeData = {\n datasetId: DatasetId;\n useDatasetIdInput?: boolean;\n\n rowId: string;\n useRowIdInput?: boolean;\n};\n\nexport class GetDatasetRowNodeImpl extends NodeImpl<GetDatasetRowNode> {\n static create(): GetDatasetRowNode {\n return {\n id: newId<NodeId>(),\n type: 'getDatasetRow',\n title: 'Get Dataset Row',\n visualData: { x: 0, y: 0, width: 250 },\n data: {\n datasetId: '' as DatasetId,\n rowId: '',\n },\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n\n if (this.data.useRowIdInput) {\n inputs.push({\n id: 'rowId' as PortId,\n title: 'Row ID',\n dataType: 'string',\n });\n }\n\n if (this.data.useDatasetIdInput) {\n inputs.push({\n id: 'datasetId' as PortId,\n title: 'Dataset ID',\n dataType: 'string',\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'row' as PortId,\n title: 'Row',\n dataType: 'object',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Gets a row from a dataset with the provided ID. If the dataset or row does not exist, it throws an error.\n `,\n infoBoxTitle: 'Get Dataset Row Node',\n contextMenuTitle: 'Get Dataset Row',\n group: ['Input/Output'],\n };\n }\n\n getEditors(): EditorDefinition<GetDatasetRowNode>[] | Promise<EditorDefinition<GetDatasetRowNode>[]> {\n return [\n {\n type: 'datasetSelector',\n label: 'Dataset',\n dataKey: 'datasetId',\n useInputToggleDataKey: 'useDatasetIdInput',\n },\n {\n type: 'string',\n label: 'Row ID',\n dataKey: 'rowId',\n useInputToggleDataKey: 'useRowIdInput',\n },\n ];\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const { datasetProvider } = context;\n\n if (datasetProvider == null) {\n throw new Error('datasetProvider is required');\n }\n\n const datasetId = getInputOrData(this.data, inputs, 'datasetId', 'string') as DatasetId;\n const rowId = getInputOrData(this.data, inputs, 'rowId', 'string') as string;\n\n const dataset = await datasetProvider.getDatasetData(datasetId as DatasetId);\n\n if (!dataset) {\n throw new Error(`Dataset with ID ${datasetId} does not exist`);\n }\n\n // TODO be more efficient\n const row = dataset.rows.find((r) => r.id === rowId);\n\n if (!row) {\n return {\n ['row' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n return {\n ['row' as PortId]: {\n type: 'object',\n value: row,\n },\n };\n }\n}\n\nexport const getDatasetRowNode = nodeDefinition(GetDatasetRowNodeImpl, 'Get Dataset Row');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { entries } from '../../utils/typeSafety.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../../index.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { getInputOrData } from '../../utils/index.js';\n\nexport type SliceNode = ChartNode<'slice', SliceNodeData>;\n\nexport type SliceNodeData = {\n start?: number;\n useStartInput?: boolean;\n\n count?: number;\n useCountInput?: boolean;\n};\n\nexport class SliceNodeImpl extends NodeImpl<SliceNode> {\n static create(): SliceNode {\n const chartNode: SliceNode = {\n type: 'slice',\n title: 'Slice',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 200,\n },\n data: {\n start: 0,\n count: undefined,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [\n {\n dataType: 'any[]',\n id: 'input' as PortId,\n title: 'Input',\n },\n ];\n\n if (this.data.useStartInput) {\n inputs.push({\n dataType: 'number',\n id: 'start' as PortId,\n title: 'Start',\n });\n }\n\n if (this.data.useCountInput) {\n inputs.push({\n dataType: 'number',\n id: 'count' as PortId,\n title: 'Count',\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'any[]',\n id: 'output' as PortId,\n title: 'Output',\n },\n ];\n }\n\n getEditors(): EditorDefinition<SliceNode>[] {\n return [\n { type: 'number', label: 'Start', dataKey: 'start', useInputToggleDataKey: 'useStartInput', allowEmpty: true },\n { type: 'number', label: 'Count', dataKey: 'count', useInputToggleDataKey: 'useCountInput', allowEmpty: true },\n ];\n }\n\n getBody(): string | NodeBodySpec | NodeBodySpec[] | undefined {\n return dedent`\n Start: ${this.data.useStartInput ? '(Using Input)' : this.data.start == null ? '0' : this.data.start}\n Count: ${this.data.useCountInput ? '(Using Input)' : this.data.count == null ? 'All' : this.data.count}\n `;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Slices an array from the start index for the count number of elements.\n\n Useful for extracting a portion of an array.\n `,\n infoBoxTitle: 'Slice Node',\n contextMenuTitle: 'Slice',\n group: ['Lists'],\n };\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const inputArray = coerceType(inputs['input' as PortId], 'any[]');\n\n const start = getInputOrData(this.data, inputs, 'start', 'number') ?? 0;\n const count = getInputOrData(this.data, inputs, 'count', 'number') ?? inputArray.length;\n\n const outputArray = inputArray.slice(start, start + count);\n\n return {\n ['output' as PortId]: {\n type: 'any[]',\n value: outputArray,\n },\n };\n }\n}\n\nexport const sliceNode = nodeDefinition(SliceNodeImpl, 'Slice');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { expectType } from '../../utils/expectType.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\nimport { dedent } from 'ts-dedent';\n\nexport type ExtractMarkdownCodeBlocksNode = ChartNode<'extractMarkdownCodeBlocks', {}>;\n\nexport class ExtractMarkdownCodeBlocksNodeImpl extends NodeImpl<ExtractMarkdownCodeBlocksNode> {\n static create(): ExtractMarkdownCodeBlocksNode {\n const chartNode: ExtractMarkdownCodeBlocksNode = {\n type: 'extractMarkdownCodeBlocks',\n title: 'Extract Markdown Code Blocks',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {},\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n {\n id: 'input' as PortId,\n title: 'Input',\n dataType: 'string',\n required: true,\n },\n ];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'firstBlock' as PortId,\n title: 'First Block',\n dataType: 'string',\n },\n {\n id: 'allBlocks' as PortId,\n title: 'All Blocks',\n dataType: 'string[]',\n },\n {\n id: 'languages' as PortId,\n title: 'Languages',\n dataType: 'string[]',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Extracts the code blocks in the input Markdown text.\n\n Outputs the first matched block, all matched blocks, and the languages specified for the blocks.\n `,\n infoBoxTitle: 'Extract Markdown Code Blocks Node',\n contextMenuTitle: 'Extract Markdown Code Blocks',\n group: ['Text'],\n };\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const inputString = expectType(inputs['input' as PortId], 'string');\n\n const regex = /```(\\w*)\\n([\\s\\S]*?)```/g;\n let match;\n let firstBlock: string | undefined;\n const allBlocks = [];\n const languages = [];\n\n while ((match = regex.exec(inputString)) !== null) {\n const language = match[1];\n const block = match[2];\n\n if (!firstBlock) {\n firstBlock = block!;\n }\n\n allBlocks.push(block!);\n languages.push(language!);\n }\n\n return {\n ['firstBlock' as PortId]:\n firstBlock == null\n ? {\n type: 'control-flow-excluded',\n value: undefined,\n }\n : {\n type: 'string',\n value: firstBlock,\n },\n ['allBlocks' as PortId]: {\n type: 'string[]',\n value: allBlocks,\n },\n ['languages' as PortId]: {\n type: 'string[]',\n value: languages,\n },\n };\n }\n}\n\nexport const extractMarkdownCodeBlocksNode = nodeDefinition(\n ExtractMarkdownCodeBlocksNodeImpl,\n 'Extract Markdown Code Blocks',\n);\n", "import {\n type ChartNode,\n type NodeConnection,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeBody, type NodeUIData } from '../NodeImpl.js';\nimport { type ChatMessage, type ChatMessageMessagePart, arrayizeDataValue, unwrapDataValue } from '../DataValue.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { orderBy } from 'lodash-es';\nimport { coerceTypeOptional, dedent, getInputOrData } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\nimport { match } from 'ts-pattern';\n\nexport type AssembleMessageNode = ChartNode<'assembleMessage', AssembleMessageNodeData>;\n\nexport type AssembleMessageNodeData = {\n type: 'system' | 'user' | 'assistant' | 'function';\n useTypeInput: boolean;\n\n toolCallId: string;\n useToolCallIdInput?: boolean;\n};\n\nconst messageTypeToTitle: Record<ChatMessage['type'], string> = {\n assistant: 'Assistant',\n function: 'Function Tool Call',\n system: 'System',\n user: 'User',\n};\n\nexport class AssembleMessageNodeImpl extends NodeImpl<AssembleMessageNode> {\n static create(): AssembleMessageNode {\n const chartNode: AssembleMessageNode = {\n type: 'assembleMessage',\n title: 'Assemble Message',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n type: 'user',\n useTypeInput: false,\n toolCallId: '',\n useToolCallIdInput: false,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n const messageCount = this.#getInputPortCount(connections);\n\n if (this.data.useTypeInput) {\n inputs.push({\n dataType: 'string',\n id: 'type' as PortId,\n title: 'Type',\n description: 'The type of message to assemble.',\n });\n }\n\n if (this.data.useToolCallIdInput) {\n inputs.push({\n dataType: 'string',\n id: 'toolCallId' as PortId,\n title: 'Tool Call ID',\n description: 'The ID of the tool call to associate with the message.',\n });\n }\n\n for (let i = 1; i <= messageCount; i++) {\n inputs.push({\n dataType: ['string', 'image', 'string[]', 'image[]', 'object', 'object[]'] as const,\n id: `part${i}` as PortId,\n title: `Part ${i}`,\n description: 'A part of the message to assemble.',\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'chat-message',\n id: 'message' as PortId,\n title: 'Message',\n description: 'The assembled message.',\n },\n ];\n }\n\n getEditors(): EditorDefinition<AssembleMessageNode>[] {\n return [\n {\n type: 'dropdown',\n label: 'Type',\n dataKey: 'type',\n options: [\n { value: 'system', label: 'System' },\n { value: 'user', label: 'User' },\n { value: 'assistant', label: 'Assistant' },\n { value: 'function', label: 'Function' },\n ],\n defaultValue: 'user',\n useInputToggleDataKey: 'useTypeInput',\n },\n {\n type: 'string',\n label: 'Tool Call ID',\n dataKey: 'toolCallId',\n useInputToggleDataKey: 'useToolCallIdInput',\n hideIf: (data) => data.type !== 'function',\n },\n ];\n }\n\n #getInputPortCount(connections: NodeConnection[]): number {\n const inputNodeId = this.chartNode.id;\n const messageConnections = connections.filter(\n (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('part'),\n );\n\n let maxMessageNumber = 0;\n for (const connection of messageConnections) {\n const messageNumber = parseInt(connection.inputId.replace('part', ''));\n if (messageNumber > maxMessageNumber) {\n maxMessageNumber = messageNumber;\n }\n }\n\n return maxMessageNumber + 1;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Assembles a single chat message from multiple parts. This is similar to a Prompt node, but works with multimodal\n models, as you can include both text and images in the message.\n `,\n infoBoxTitle: 'Assemble Message Node',\n contextMenuTitle: 'Assemble Message',\n group: 'AI',\n };\n }\n\n getBody(_context: RivetUIContext): NodeBody | Promise<NodeBody> {\n return dedent`\n ${this.data.useTypeInput ? '(Type From Input)' : messageTypeToTitle[this.data.type]}\n ${\n this.data.useTypeInput || this.data.type === 'function'\n ? `Tool Call ID: ${this.data.useToolCallIdInput ? '(From Input)' : this.data.toolCallId}`\n : ``\n }\n `;\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const output: Outputs = {};\n\n const type = getInputOrData(this.data, inputs, 'type');\n\n type MultiMessage = ChatMessage & { message: ChatMessageMessagePart[] };\n const outMessage: MultiMessage = match(type)\n .with(\n 'system',\n (type): MultiMessage => ({\n type,\n message: [],\n }),\n )\n .with(\n 'user',\n (type): MultiMessage => ({\n type,\n message: [],\n }),\n )\n .with(\n 'assistant',\n (type): MultiMessage => ({\n type,\n message: [],\n function_call: undefined, // Not supported yet in Assemble Message node\n function_calls: undefined, // Not supported yet in Assemble Message node\n }),\n )\n .with(\n 'function',\n (type): MultiMessage => ({\n type,\n message: [],\n name: getInputOrData(this.data, inputs, 'toolCallId'),\n }),\n )\n .otherwise(() => {\n throw new Error(`Invalid type: ${type}`);\n });\n\n const inputParts = orderBy(\n Object.entries(inputs).filter(([key]) => key.startsWith('part')),\n ([key]) => key,\n 'asc',\n );\n\n for (const [, inputPart] of inputParts) {\n if (!inputPart || inputPart.type === 'control-flow-excluded' || !inputPart.value) {\n continue;\n }\n\n const inPart = arrayizeDataValue(unwrapDataValue(inputPart));\n for (const message of inPart) {\n if (message.type === 'string') {\n outMessage.message.push(message.value);\n } else if (message.type === 'image') {\n outMessage.message.push({\n type: 'image',\n data: message.value.data,\n mediaType: message.value.mediaType,\n });\n } else if (message.type === 'object') {\n if (\n message.value &&\n 'type' in message.value &&\n message.value.type === 'url_reference' &&\n typeof message.value.url === 'string'\n ) {\n outMessage.message.push({\n type: 'url',\n url: message.value.url,\n });\n }\n } else {\n const coerced = coerceTypeOptional(message, 'string');\n\n if (coerced) {\n outMessage.message.push(coerced);\n }\n }\n }\n }\n\n output['message' as PortId] = {\n type: 'chat-message',\n value: outMessage,\n };\n\n return output;\n }\n}\n\nexport const assembleMessageNode = nodeDefinition(AssembleMessageNodeImpl, 'Assemble Prompt');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl } from '../NodeImpl.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition, type NodeUIData } from '../../index.js';\nimport { nodeDefinition } from '../../model/NodeDefinition.js';\nimport { getInputOrData } from '../../utils/index.js';\n\nexport type UrlReferenceNode = ChartNode<'urlReference', UrlReferenceNodeData>;\n\nexport type UrlReferenceNodeData = {\n url: string;\n useUrlInput?: boolean;\n};\n\nexport class UrlReferenceNodeImpl extends NodeImpl<UrlReferenceNode> {\n static create(): UrlReferenceNode {\n const chartNode: UrlReferenceNode = {\n type: 'urlReference',\n title: 'URL Reference',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 225,\n },\n data: {\n url: '',\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n\n if (this.data.useUrlInput) {\n inputs.push({\n dataType: 'string',\n id: 'url' as PortId,\n title: 'URL',\n description: 'The value to convert into a URL reference.',\n coerced: true,\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'object',\n id: 'urlReference' as PortId,\n title: 'URL Reference',\n description: 'A reference to a URL.',\n },\n ];\n }\n\n getEditors(): EditorDefinition<UrlReferenceNode>[] {\n return [\n {\n type: 'string',\n label: 'URL',\n dataKey: 'url',\n useInputToggleDataKey: 'useUrlInput',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n contextMenuTitle: 'URL Reference',\n group: 'Data',\n infoBoxTitle: 'URL Reference Node',\n infoBoxBody:\n 'Defines a reference to a URL, or converts a string into a URL reference. Used with the Assemble Message node to define URLs for attachments/images.',\n };\n }\n\n getBody(): string {\n return this.data.useUrlInput ? '(URL Using Input)' : this.data.url;\n }\n\n async process(inputs: Inputs): Promise<Outputs> {\n const url = getInputOrData(this.data, inputs, 'url', 'string');\n\n return {\n ['urlReference' as PortId]: {\n type: 'object',\n value: { type: 'url_reference', url },\n },\n };\n }\n}\n\nexport const urlReferenceNode = nodeDefinition(UrlReferenceNodeImpl, 'URL Reference');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { JSONPath } from 'jsonpath-plus';\nimport { type EditorDefinition, type NodeBodySpec } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type DestructureNode = ChartNode<'destructure', DestructureNodeData>;\n\nexport type DestructureNodeData = {\n paths: string[];\n};\n\nexport class DestructureNodeImpl extends NodeImpl<DestructureNode> {\n static create(): DestructureNode {\n const chartNode: DestructureNode = {\n type: 'destructure',\n title: 'Destructure',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n paths: ['$.value'],\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n {\n id: 'object' as PortId,\n title: 'Object',\n dataType: 'object',\n required: true,\n },\n ];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return this.chartNode.data.paths.map((path, index) => ({\n id: `match_${index}` as PortId,\n title: path,\n dataType: 'any',\n }));\n }\n\n getEditors(): EditorDefinition<DestructureNode>[] {\n return [\n {\n type: 'stringList',\n label: 'Paths',\n dataKey: 'paths',\n helperMessage:\n 'One or more JSONPath expressions. Each expression will correspond to an output port of the node.',\n },\n ];\n }\n\n getBody(): string | NodeBodySpec | undefined {\n return '';\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Destructures the input value by extracting values at the specified paths. The paths use JSONPath notation to navigate through the value.\n `,\n infoBoxTitle: 'Destructure Node',\n contextMenuTitle: 'Destructure',\n group: ['Objects'],\n };\n }\n\n async process(inputs: Record<PortId, DataValue>): Promise<Record<PortId, DataValue>> {\n const inputObject = coerceTypeOptional(inputs['object' as PortId], 'object');\n\n const output: Record<PortId, DataValue> = {};\n\n this.data.paths.forEach((path, index) => {\n let match: unknown;\n try {\n match = JSONPath<unknown>({ json: inputObject ?? null, path: path.trim(), wrap: false });\n } catch (err) {\n match = undefined;\n }\n\n output[`match_${index}` as PortId] = {\n type: 'any',\n value: match,\n };\n });\n\n return output;\n }\n}\n\nexport const destructureNode = nodeDefinition(DestructureNodeImpl, 'Destructure');\n", "import type { ChartNode, NodeId, PortId, NodeInputDefinition, NodeOutputDefinition } from '../NodeBase.js';\nimport { NodeImpl, type NodeBody, type NodeUIData } from '../NodeImpl.js';\nimport { nanoid } from 'nanoid/non-secure';\n\nimport type { InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { getInputOrData, coerceType, newId, inferType } from '../../utils/index.js';\nimport { arrayizeDataValue, unwrapDataValue } from '../DataValue.js';\nimport type { DatasetId, DatasetRow } from '../Dataset.js';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\n\nexport type ReplaceDatasetNode = ChartNode<'replaceDataset', ReplaceDatasetNodeData>;\n\ntype ReplaceDatasetNodeData = {\n datasetId: DatasetId;\n useDatasetIdInput?: boolean;\n};\n\nexport class ReplaceDatasetNodeImpl extends NodeImpl<ReplaceDatasetNode> {\n static create(): ReplaceDatasetNode {\n return {\n id: nanoid() as NodeId,\n type: 'replaceDataset',\n title: 'Replace Dataset',\n visualData: { x: 0, y: 0, width: 250 },\n data: {\n datasetId: '' as DatasetId,\n },\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputDefinitions: NodeInputDefinition[] = [];\n\n inputDefinitions.push({\n id: 'data' as PortId,\n dataType: 'object[]',\n title: 'Data',\n description:\n 'The new data of the dataset. If empty, the dataset will be cleared. May be an array of array of strings, or an array of DatasetRow objects with { id, data } properties. If a string[][], IDs will be generated.',\n });\n\n if (this.data.useDatasetIdInput) {\n inputDefinitions.push({\n id: 'datasetId' as PortId,\n title: 'Dataset ID',\n dataType: 'string',\n description: 'The ID of the dataset to replace.',\n });\n }\n\n return inputDefinitions;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'dataset' as PortId,\n title: 'Dataset',\n dataType: 'object[]',\n description: 'The new data of the dataset. An array of DatasetRow objects with { id, data } properties.',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Replaces the data in a dataset with the given data. If no data is given, the dataset will be cleared instead.\n `,\n infoBoxTitle: 'Replace Dataset Node',\n contextMenuTitle: 'Replace Dataset',\n group: ['Input/Output'],\n };\n }\n\n getEditors(): EditorDefinition<ReplaceDatasetNode>[] | Promise<EditorDefinition<ReplaceDatasetNode>[]> {\n return [\n {\n type: 'datasetSelector',\n label: 'Dataset',\n dataKey: 'datasetId',\n useInputToggleDataKey: 'useDatasetIdInput',\n },\n ];\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const { datasetProvider } = context;\n\n if (datasetProvider == null) {\n throw new Error('datasetProvider is required');\n }\n\n const datasetId = getInputOrData(this.data, inputs, 'datasetId', 'string') as DatasetId;\n const dataInput = inputs['data' as PortId];\n\n if (!dataInput) {\n await datasetProvider.putDatasetData(datasetId, { id: datasetId, rows: [] });\n return {\n ['dataset' as PortId]: {\n type: 'object[]',\n value: [],\n },\n };\n }\n\n let dataArrays = unwrapDataValue(dataInput).value as unknown[][] | unknown[] | DatasetRow[];\n if (!Array.isArray(dataArrays)) {\n throw new Error('Data input must be either an array of rows, or an array of columns for a single row.');\n }\n\n const isDatasetRow = (row: unknown): row is DatasetRow => {\n return typeof row === 'object' && row != null && 'id' in row && 'data' in row;\n };\n\n const firstElem = dataArrays[0];\n if (!Array.isArray(firstElem) && !isDatasetRow(firstElem)) {\n dataArrays = [dataArrays as unknown[]];\n }\n\n const rows = (dataArrays as unknown[][] | DatasetRow[]).map((row): DatasetRow => {\n if (Array.isArray(row)) {\n return {\n id: newId(),\n data: row.map((value) => coerceType(inferType(value), 'string')),\n };\n }\n\n if ('id' in row && 'data' in row) {\n return row;\n }\n\n throw new Error('Data input must be an array of strings or DatasetRows');\n });\n\n await datasetProvider.putDatasetData(datasetId, {\n id: datasetId,\n rows,\n });\n\n return {\n ['dataset' as PortId]: {\n type: 'object[]',\n value: rows,\n },\n };\n }\n}\n\nexport const replaceDatasetNode = nodeDefinition(ReplaceDatasetNodeImpl, 'Replace Dataset');\n", "import type {\n ChartNode,\n EditorDefinition,\n GraphId,\n Inputs,\n InternalProcessContext,\n NodeId,\n NodeInputDefinition,\n NodeOutputDefinition,\n NodeUIData,\n Outputs,\n PortId,\n} from '../../index.js';\nimport { NodeImpl } from '../NodeImpl.js';\nimport { dedent, newId } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type ListGraphsNode = ChartNode<'listGraphs', ListSubgraphsData>;\n\ntype ListSubgraphsData = {};\n\nexport class ListGraphsNodeImpl extends NodeImpl<ListGraphsNode> {\n static create(): ListGraphsNode {\n return {\n id: newId<NodeId>(),\n type: 'listGraphs',\n title: 'List Graphs',\n visualData: { x: 0, y: 0, width: 250 },\n data: {},\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [];\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'graphs' as PortId,\n title: 'Graphs',\n dataType: 'graph-reference[]',\n },\n {\n id: 'graph-names' as PortId,\n title: 'Graph Names',\n dataType: 'string[]',\n },\n ];\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Lists all graphs in the project.\n `,\n infoBoxTitle: 'List Graphs Node',\n contextMenuTitle: 'List Graphs',\n group: ['Input/Output'],\n };\n }\n\n getEditors(): EditorDefinition<ListGraphsNode>[] | Promise<EditorDefinition<ListGraphsNode>[]> {\n return [];\n }\n\n async process(_inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const graphs = Object.values(context.project.graphs);\n\n return {\n ['graphs' as PortId]: {\n type: 'graph-reference[]',\n value: graphs.map((graph) => ({\n graphId: graph.metadata!.id ?? ('' as GraphId),\n graphName: graph.metadata!.name ?? '',\n })),\n },\n ['graph-names' as PortId]: {\n type: 'string[]',\n value: graphs.map((graph) => graph.metadata!.name ?? ''),\n },\n };\n }\n}\n\nexport const listGraphsNode = nodeDefinition(ListGraphsNodeImpl, 'List Graphs');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type GraphId } from '../NodeGraph.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { type EditorDefinition, type NodeBody } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport type { RivetUIContext } from '../RivetUIContext.js';\nimport { coerceType } from '../../utils/index.js';\n\nexport type GraphReferenceNode = ChartNode<'graphReference', GraphReferenceNodeData>;\n\nexport type GraphReferenceNodeData = {\n graphId: GraphId;\n useGraphIdOrNameInput: boolean;\n};\n\nexport class GraphReferenceNodeImpl extends NodeImpl<GraphReferenceNode> {\n static create(): GraphReferenceNode {\n const chartNode: GraphReferenceNode = {\n type: 'graphReference',\n title: 'Graph Reference',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 275,\n },\n data: {\n graphId: '' as GraphId,\n useGraphIdOrNameInput: false,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n\n if (this.data.useGraphIdOrNameInput) {\n inputs.push({\n id: 'graph-name-or-id' as PortId,\n dataType: 'string',\n title: 'Graph Name Or ID',\n description: 'The name or ID of the graph to get a reference to.',\n required: true,\n });\n }\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'graph' as PortId,\n dataType: 'graph-reference',\n title: 'Graph',\n description: 'A reference to the graph.',\n },\n ];\n }\n\n getEditors(): EditorDefinition<GraphReferenceNode>[] {\n const definitions: EditorDefinition<GraphReferenceNode>[] = [\n {\n type: 'graphSelector',\n label: 'Graph',\n dataKey: 'graphId',\n useInputToggleDataKey: 'useGraphIdOrNameInput',\n },\n ];\n\n return definitions;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Gets a reference to another graph, that can be used to pass around graphs to call using a Call Graph node.\n `,\n infoBoxTitle: 'Graph Reference Node',\n contextMenuTitle: 'Graph Reference',\n group: ['Advanced'],\n };\n }\n\n getBody(context: RivetUIContext): string {\n if (this.data.useGraphIdOrNameInput) {\n return '(Graph from input)';\n }\n\n const graph = context.project.graphs[this.data.graphId];\n\n if (!graph) {\n return '(Graph not found)';\n }\n\n return graph.metadata!.name ?? '(Unnamed Graph)';\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n if (this.data.useGraphIdOrNameInput) {\n const graphIdOrName = coerceType(inputs['graph-name-or-id' as PortId], 'string');\n\n let graph = context.project.graphs[graphIdOrName as GraphId];\n\n if (!graph) {\n graph = Object.values(context.project.graphs).find((graph) => graph.metadata!.name === graphIdOrName);\n }\n\n if (!graph) {\n return {\n ['graph' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n return {\n ['graph' as PortId]: {\n type: 'graph-reference',\n value: {\n graphId: graph.metadata!.id ?? ('' as GraphId),\n graphName: graph.metadata!.name ?? '',\n },\n },\n };\n }\n\n const graph = context.project.graphs[this.data.graphId];\n\n if (!graph) {\n return {\n ['graph' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n return {\n ['graph' as PortId]: {\n type: 'graph-reference',\n value: {\n graphId: graph.metadata!.id ?? ('' as GraphId),\n graphName: graph.metadata!.name ?? '',\n },\n },\n };\n }\n}\n\nexport const graphReferenceNode = nodeDefinition(GraphReferenceNodeImpl, 'Graph Reference');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type PortId,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type GraphId } from '../NodeGraph.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceType, coerceTypeOptional } from '../../utils/coerceType.js';\nimport { looseDataValuesToDataValues, type LooseDataValue } from '../../index.js';\nimport { getError } from '../../utils/errors.js';\n\nexport type CallGraphNode = ChartNode<'callGraph', CallGraphNodeData>;\n\nexport type CallGraphNodeData = {\n useErrorOutput?: boolean;\n};\n\nexport class CallGraphNodeImpl extends NodeImpl<CallGraphNode> {\n static create(): CallGraphNode {\n const chartNode: CallGraphNode = {\n type: 'callGraph',\n title: 'Call Graph',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 200,\n },\n data: {\n useErrorOutput: false,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n\n inputs.push({\n id: 'graph' as PortId,\n dataType: 'graph-reference',\n title: 'Graph',\n description: 'The reference to the graph to call.',\n required: true,\n });\n\n inputs.push({\n id: 'inputs' as PortId,\n dataType: 'object',\n title: 'Inputs',\n description:\n 'The inputs to pass to the graph. Should be an object where the keys are the input names and the values are the input values.',\n });\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n const outputs: NodeOutputDefinition[] = [\n {\n id: 'outputs' as PortId,\n dataType: 'object',\n title: 'Outputs',\n description: 'The outputs of the graph.',\n },\n ];\n\n if (this.data.useErrorOutput) {\n outputs.push({\n id: 'error' as PortId,\n dataType: 'string',\n title: 'Error',\n description: 'The error message if the graph call failed.',\n });\n }\n\n return outputs;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Calls another graph and passes inputs to it. Use in combination with the Graph Reference node to call dynamic graphs.\n `,\n infoBoxTitle: 'Call Graph Node',\n contextMenuTitle: 'Call Graph',\n group: ['Advanced'],\n };\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const graphRef = coerceTypeOptional(inputs['graph' as PortId], 'graph-reference');\n const graphInputs = coerceTypeOptional(inputs['inputs' as PortId], 'object');\n\n if (!graphRef) {\n return {\n ['outputs' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n const graph = context.project.graphs[graphRef.graphId];\n\n if (!graph) {\n return {\n ['outputs' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n const subGraphProcessor = context.createSubProcessor(graphRef.graphId, { signal: context.signal });\n\n let outputs: Outputs = {};\n\n try {\n const startTime = Date.now();\n\n const inputData = looseDataValuesToDataValues(graphInputs as Record<string, LooseDataValue>);\n\n const graphOutputs = await subGraphProcessor.processGraph(context, inputData, context.contextValues);\n\n const duration = Date.now() - startTime;\n\n outputs['outputs' as PortId] = {\n type: 'object',\n value: graphOutputs,\n };\n\n if (this.data.useErrorOutput) {\n outputs['error' as PortId] = {\n type: 'control-flow-excluded',\n value: undefined,\n };\n }\n\n if (outputs['duration' as PortId] == null) {\n outputs['duration' as PortId] = {\n type: 'number',\n value: duration,\n };\n }\n\n return outputs;\n } catch (err) {\n if (!this.data.useErrorOutput) {\n throw err;\n }\n\n outputs['outputs' as PortId] = {\n type: 'control-flow-excluded',\n value: undefined,\n };\n\n outputs['error' as PortId] = {\n type: 'string',\n value: getError(err).message,\n };\n\n return outputs;\n }\n }\n}\n\nexport const callGraphNode = nodeDefinition(CallGraphNodeImpl, 'Call Graph');\n", "import { nanoid } from 'nanoid';\nimport type {\n AssistantChatMessageFunctionCall,\n DataValue,\n GptFunction,\n ParsedAssistantChatMessageFunctionCall,\n} from '../DataValue.js';\nimport type { ChartNode, NodeId, NodeInputDefinition, NodeOutputDefinition, PortId } from '../NodeBase.js';\nimport type { GraphId } from '../NodeGraph.js';\nimport { NodeImpl, type NodeBody, type NodeUIData } from '../NodeImpl.js';\nimport { dedent } from 'ts-dedent';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport type { InternalProcessContext } from '../ProcessContext.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\nimport { coerceType, coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type DelegateFunctionCallNode = ChartNode<'delegateFunctionCall', DelegateFunctionCallNodeData>;\n\nexport type DelegateFunctionCallNodeData = {\n handlers: { key: string; value: GraphId }[];\n unknownHandler: GraphId | undefined;\n};\n\nexport class DelegateFunctionCallNodeImpl extends NodeImpl<DelegateFunctionCallNode> {\n static create(): DelegateFunctionCallNode {\n const chartNode: DelegateFunctionCallNode = {\n type: 'delegateFunctionCall',\n title: 'Delegate Function Call',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 325,\n },\n data: {\n handlers: [],\n unknownHandler: undefined,\n },\n };\n\n return chartNode;\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n\n inputs.push({\n id: 'function-call' as PortId,\n dataType: 'object',\n title: 'Function Call',\n coerced: true,\n required: true,\n description: 'The function call to delegate to a subgraph.',\n });\n\n return inputs;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n const outputs: NodeOutputDefinition[] = [];\n\n outputs.push({\n id: 'output' as PortId,\n dataType: 'string',\n title: 'Output',\n description: 'The output of the function call.',\n });\n\n outputs.push({\n id: 'message' as PortId,\n dataType: 'object',\n title: 'Message Output',\n description: 'Maps the output for use directly with an Assemble Prompt node and GPT.',\n });\n\n return outputs;\n }\n\n static getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Handles a function call by delegating it to a different subgraph depending on the function call.\n `,\n infoBoxTitle: 'Delegate Function Call Node',\n contextMenuTitle: 'Delegate Function Call',\n group: ['Advanced'],\n };\n }\n\n getEditors(): EditorDefinition<DelegateFunctionCallNode>[] {\n return [\n {\n type: 'custom',\n customEditorId: 'ToolCallHandlers',\n label: 'Handlers',\n dataKey: 'handlers',\n },\n {\n type: 'graphSelector',\n dataKey: 'unknownHandler',\n label: 'Unknown Handler',\n helperMessage: 'The subgraph to delegate to if the function call does not match any handlers.',\n },\n ];\n }\n\n getBody(context: RivetUIContext): NodeBody {\n if (this.data.handlers.length === 0) {\n return 'No handlers defined';\n }\n\n const lines = ['Handlers:'];\n\n this.data.handlers.forEach(({ key, value }) => {\n const subgraphName = context.project.graphs[value]?.metadata!.name! ?? 'Unknown Subgraph';\n lines.push(` ${key || '(MISSING!)'} -> ${subgraphName}`);\n });\n\n return lines.join('\\n');\n }\n\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const functionCall = coerceType(\n inputs['function-call' as PortId],\n 'object',\n ) as ParsedAssistantChatMessageFunctionCall;\n\n let handler = this.data.handlers.find((handler) => handler.key === functionCall.name);\n\n if (!handler) {\n if (this.data.unknownHandler) {\n handler = { key: undefined!, value: this.data.unknownHandler };\n } else {\n throw new Error(`No handler found for function call: ${functionCall.name}`);\n }\n }\n\n const subgraphInputs: Record<string, DataValue> = {\n _function_name: {\n type: 'string',\n value: functionCall.name,\n },\n _arguments: {\n type: 'object',\n value: functionCall.arguments,\n },\n };\n\n for (const [argName, argument] of Object.entries(functionCall.arguments)) {\n subgraphInputs[argName] = {\n type: 'any',\n value: argument,\n };\n }\n\n const handlerGraphId = handler.value;\n const subprocessor = context.createSubProcessor(handlerGraphId, { signal: context.signal });\n\n const outputs = await subprocessor.processGraph(context, subgraphInputs, context.contextValues);\n\n const outputString = coerceTypeOptional(outputs.output, 'string') ?? '';\n\n return {\n ['output' as PortId]: {\n type: 'string',\n value: outputString,\n },\n ['message' as PortId]: {\n type: 'chat-message',\n value: {\n type: 'function',\n message: outputString,\n name: functionCall.id ?? '',\n },\n },\n };\n }\n}\n\nexport const delegateFunctionCallNode = nodeDefinition(DelegateFunctionCallNodeImpl, 'Delegate Function Call');\n", "import {\n type ChartNode,\n type NodeId,\n type PortId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type EditorDefinition, type Inputs, type InternalProcessContext, type Outputs } from '../../index.js';\nimport { expectType } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type PlayAudioNode = ChartNode<'playAudio', PlayAudioNodeData>;\n\ntype PlayAudioNodeData = {};\n\nexport class PlayAudioNodeImpl extends NodeImpl<PlayAudioNode> {\n static create(): PlayAudioNode {\n return {\n id: nanoid() as NodeId,\n type: 'playAudio',\n title: 'Play Audio',\n visualData: { x: 0, y: 0, width: 200 },\n data: {},\n };\n }\n\n getInputDefinitions(): NodeInputDefinition[] {\n const inputDefinitions: NodeInputDefinition[] = [];\n\n inputDefinitions.push({\n id: 'data' as PortId,\n title: 'Data',\n dataType: 'audio',\n coerced: false,\n });\n\n return inputDefinitions;\n }\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'data' as PortId,\n title: 'Audio Data',\n dataType: 'audio',\n },\n ];\n }\n\n getEditors(): EditorDefinition<PlayAudioNode>[] {\n return [];\n }\n\n static getUIData(): NodeUIData {\n return {\n contextMenuTitle: 'Play Audio',\n group: 'Input/Output',\n infoBoxTitle: 'Play Audio Node',\n infoBoxBody: 'Plays audio data to the speakers.',\n };\n }\n\n async process(inputData: Inputs, context: InternalProcessContext): Promise<Outputs> {\n if (!context.audioProvider) {\n throw new Error('Playing audio is not supported in this context');\n }\n\n const data = expectType(inputData['data' as PortId], 'audio');\n\n await context.audioProvider.playAudio({ type: 'audio', value: data }, context.signal);\n\n return {\n ['data' as PortId]: {\n type: 'audio',\n value: data,\n },\n };\n }\n}\n\nexport const playAudioNode = nodeDefinition(PlayAudioNodeImpl, 'Play Audio');\n", "import type { ChartNode } from './NodeBase.js';\nimport { NodeRegistration } from './NodeRegistration.js';\nimport type { NodeImpl } from './NodeImpl.js';\n\nimport { userInputNode } from './nodes/UserInputNode.js';\nexport * from './nodes/UserInputNode.js';\n\nimport { textNode } from './nodes/TextNode.js';\nexport * from './nodes/TextNode.js';\n\nimport { chatNode } from './nodes/ChatNode.js';\nexport * from './nodes/ChatNode.js';\n\nimport { promptNode } from './nodes/PromptNode.js';\nexport * from './nodes/PromptNode.js';\n\nimport { extractRegexNode } from './nodes/ExtractRegexNode.js';\nexport * from './nodes/ExtractRegexNode.js';\n\nimport { codeNode } from './nodes/CodeNode.js';\nexport * from './nodes/CodeNode.js';\n\nimport { matchNode } from './nodes/MatchNode.js';\nexport * from './nodes/MatchNode.js';\n\nimport { ifNode } from './nodes/IfNode.js';\nexport * from './nodes/IfNode.js';\n\nimport { readDirectoryNode } from './nodes/ReadDirectoryNode.js';\nexport * from './nodes/ReadDirectoryNode.js';\n\nimport { readFileNode } from './nodes/ReadFileNode.js';\nexport * from './nodes/ReadFileNode.js';\n\nimport { ifElseNode } from './nodes/IfElseNode.js';\nexport * from './nodes/IfElseNode.js';\n\nimport { chunkNode } from './nodes/ChunkNode.js';\nexport * from './nodes/ChunkNode.js';\n\nimport { graphInputNode } from './nodes/GraphInputNode.js';\nexport * from './nodes/GraphInputNode.js';\n\nimport { graphOutputNode } from './nodes/GraphOutputNode.js';\nexport * from './nodes/GraphOutputNode.js';\n\nimport { subGraphNode } from './nodes/SubGraphNode.js';\nexport * from './nodes/SubGraphNode.js';\n\nimport { arrayNode } from './nodes/ArrayNode.js';\nexport * from './nodes/ArrayNode.js';\n\nimport { extractJsonNode } from './nodes/ExtractJsonNode.js';\nexport * from './nodes/ExtractJsonNode.js';\n\nimport { assemblePromptNode } from './nodes/AssemblePromptNode.js';\nexport * from './nodes/ExtractYamlNode.js';\n\nimport { loopControllerNode } from './nodes/LoopControllerNode.js';\nexport * from './nodes/AssemblePromptNode.js';\n\nimport { trimChatMessagesNode } from './nodes/TrimChatMessagesNode.js';\nexport * from './nodes/LoopControllerNode.js';\n\nimport { extractYamlNode } from './nodes/ExtractYamlNode.js';\nexport * from './nodes/TrimChatMessagesNode.js';\n\nimport { externalCallNode } from './nodes/ExternalCallNode.js';\nexport * from './nodes/ExternalCallNode.js';\n\nimport { extractObjectPathNode } from './nodes/ExtractObjectPathNode.js';\nexport * from './nodes/ExtractObjectPathNode.js';\n\nimport { raiseEventNode } from './nodes/RaiseEventNode.js';\nexport * from './nodes/RaiseEventNode.js';\n\nimport { contextNode } from './nodes/ContextNode.js';\nexport * from './nodes/ContextNode.js';\n\nimport { coalesceNode } from './nodes/CoalesceNode.js';\nexport * from './nodes/CoalesceNode.js';\n\nimport { passthroughNode } from './nodes/PassthroughNode.js';\nexport * from './nodes/PassthroughNode.js';\n\nimport { popNode } from './nodes/PopNode.js';\nexport * from './nodes/PopNode.js';\n\nimport { setGlobalNode } from './nodes/SetGlobalNode.js';\nexport * from './nodes/SetGlobalNode.js';\n\nimport { getGlobalNode } from './nodes/GetGlobalNode.js';\nexport * from './nodes/GetGlobalNode.js';\n\nimport { waitForEventNode } from './nodes/WaitForEventNode.js';\nexport * from './nodes/WaitForEventNode.js';\n\nimport { gptFunctionNode } from './nodes/GptFunctionNode.js';\nexport * from './nodes/GptFunctionNode.js';\n\nimport { toYamlNode } from './nodes/ToYamlNode.js';\nexport * from './nodes/ToYamlNode.js';\n\nimport { getEmbeddingNode } from './nodes/GetEmbeddingNode.js';\nexport * from './nodes/GetEmbeddingNode.js';\n\nimport { vectorStoreNode } from './nodes/VectorStoreNode.js';\nexport * from './nodes/VectorStoreNode.js';\n\nimport { vectorNearestNeighborsNode } from './nodes/VectorNearestNeighborsNode.js';\nexport * from './nodes/VectorNearestNeighborsNode.js';\n\nimport { hashNode } from './nodes/HashNode.js';\nexport * from './nodes/HashNode.js';\n\nimport { abortGraphNode } from './nodes/AbortGraphNode.js';\nexport * from './nodes/AbortGraphNode.js';\n\nimport { raceInputsNode } from './nodes/RaceInputsNode.js';\nexport * from './nodes/RaceInputsNode.js';\n\nimport { toJsonNode } from './nodes/ToJsonNode.js';\nexport * from './nodes/ToJsonNode.js';\n\nimport { joinNode } from './nodes/JoinNode.js';\nexport * from './nodes/JoinNode.js';\n\nimport { filterNode } from './nodes/FilterNode.js';\nexport * from './nodes/FilterNode.js';\n\nimport { objectNode } from './nodes/ObjectNode.js';\nexport * from './nodes/ObjectNode.js';\n\nimport { booleanNode } from './nodes/BooleanNode.js';\nexport * from './nodes/BooleanNode.js';\n\nimport { compareNode } from './nodes/CompareNode.js';\nexport * from './nodes/CompareNode.js';\n\nimport { evaluateNode } from './nodes/EvaluateNode.js';\nexport * from './nodes/EvaluateNode.js';\n\nimport { numberNode } from './nodes/NumberNode.js';\nexport * from './nodes/NumberNode.js';\n\nimport { randomNumberNode } from './nodes/RandomNumberNode.js';\nexport * from './nodes/RandomNumberNode.js';\n\nimport { shuffleNode } from './nodes/ShuffleNode.js';\nexport * from './nodes/ShuffleNode.js';\n\nimport { commentNode } from './nodes/CommentNode.js';\nexport * from './nodes/CommentNode.js';\n\nimport { imageNode } from './nodes/ImageNode.js';\nexport * from './nodes/ImageNode.js';\n\nimport { audioNode } from './nodes/AudioNode.js';\nexport * from './nodes/AudioNode.js';\n\nimport { httpCallNode } from './nodes/HttpCallNode.js';\nexport * from './nodes/HttpCallNode.js';\n\nimport { delayNode } from './nodes/DelayNode.js';\nexport * from './nodes/DelayNode.js';\n\nimport { appendToDatasetNode } from './nodes/AppendToDatasetNode.js';\nexport * from './nodes/AppendToDatasetNode.js';\n\nimport { createDatasetNode } from './nodes/CreateDatasetNode.js';\nexport * from './nodes/CreateDatasetNode.js';\n\nimport { loadDatasetNode } from './nodes/LoadDatasetNode.js';\nexport * from './nodes/LoadDatasetNode.js';\n\nimport { getAllDatasetsNode } from './nodes/GetAllDatasetsNode.js';\nexport * from './nodes/GetAllDatasetsNode.js';\n\nimport { splitNode } from './nodes/SplitNode.js';\nexport * from './nodes/SplitNode.js';\n\nimport { datasetNearestNeighborsNode } from './nodes/DatasetNearestNeigborsNode.js';\nexport * from './nodes/DatasetNearestNeigborsNode.js';\n\nimport { getDatasetRowNode } from './nodes/GetDatasetRowNode.js';\nexport * from './nodes/GetDatasetRowNode.js';\n\nimport { sliceNode } from './nodes/SliceNode.js';\nexport * from './nodes/SliceNode.js';\n\nimport { extractMarkdownCodeBlocksNode } from './nodes/ExtractMarkdownCodeBlocksNode.js';\nexport * from './nodes/ExtractMarkdownCodeBlocksNode.js';\n\nimport { assembleMessageNode } from './nodes/AssembleMessageNode.js';\nexport * from './nodes/AssembleMessageNode.js';\n\nimport { urlReferenceNode } from './nodes/URLReferenceNode.js';\nexport * from './nodes/URLReferenceNode.js';\n\nimport { destructureNode } from './nodes/DestructureNode.js';\nexport * from './nodes/DestructureNode.js';\n\nimport { replaceDatasetNode } from './nodes/ReplaceDatasetNode.js';\nexport * from './nodes/ReplaceDatasetNode.js';\n\nimport { listGraphsNode } from './nodes/ListGraphsNode.js';\nexport * from './nodes/ListGraphsNode.js';\n\nimport { graphReferenceNode } from './nodes/GraphReferenceNode.js';\nexport * from './nodes/GraphReferenceNode.js';\n\nimport { callGraphNode } from './nodes/CallGraphNode.js';\nexport * from './nodes/CallGraphNode.js';\n\nimport { delegateFunctionCallNode } from './nodes/DelegateFunctionCallNode.js';\nexport * from './nodes/DelegateFunctionCallNode.js';\n\nimport { playAudioNode } from './nodes/PlayAudioNode.js';\nexport * from './nodes/PlayAudioNode.js';\n\nexport * from './nodes/CallGraphNode.js';\n\nexport const registerBuiltInNodes = (registry: NodeRegistration) => {\n return registry\n .register(toYamlNode)\n .register(userInputNode)\n .register(textNode)\n .register(chatNode)\n .register(promptNode)\n .register(extractRegexNode)\n .register(codeNode)\n .register(matchNode)\n .register(ifNode)\n .register(readDirectoryNode)\n .register(readFileNode)\n .register(ifElseNode)\n .register(chunkNode)\n .register(graphInputNode)\n .register(graphOutputNode)\n .register(subGraphNode)\n .register(arrayNode)\n .register(extractJsonNode)\n .register(assemblePromptNode)\n .register(loopControllerNode)\n .register(trimChatMessagesNode)\n .register(extractYamlNode)\n .register(externalCallNode)\n .register(extractObjectPathNode)\n .register(raiseEventNode)\n .register(contextNode)\n .register(coalesceNode)\n .register(passthroughNode)\n .register(popNode)\n .register(setGlobalNode)\n .register(getGlobalNode)\n .register(waitForEventNode)\n .register(gptFunctionNode)\n .register(getEmbeddingNode)\n .register(vectorStoreNode)\n .register(vectorNearestNeighborsNode)\n .register(hashNode)\n .register(abortGraphNode)\n .register(raceInputsNode)\n .register(toJsonNode)\n .register(joinNode)\n .register(filterNode)\n .register(objectNode)\n .register(booleanNode)\n .register(compareNode)\n .register(evaluateNode)\n .register(numberNode)\n .register(randomNumberNode)\n .register(shuffleNode)\n .register(commentNode)\n .register(imageNode)\n .register(audioNode)\n .register(httpCallNode)\n .register(delayNode)\n .register(appendToDatasetNode)\n .register(createDatasetNode)\n .register(loadDatasetNode)\n .register(getAllDatasetsNode)\n .register(splitNode)\n .register(datasetNearestNeighborsNode)\n .register(getDatasetRowNode)\n .register(sliceNode)\n .register(extractMarkdownCodeBlocksNode)\n .register(assembleMessageNode)\n .register(urlReferenceNode)\n .register(destructureNode)\n .register(replaceDatasetNode)\n .register(listGraphsNode)\n .register(graphReferenceNode)\n .register(callGraphNode)\n .register(delegateFunctionCallNode)\n .register(playAudioNode);\n};\n\nlet globalRivetNodeRegistry = registerBuiltInNodes(new NodeRegistration());\n\nexport { globalRivetNodeRegistry };\n\nexport type BuiltInNodes = typeof globalRivetNodeRegistry.NodesType;\n\nexport type BuiltInNodeType = typeof globalRivetNodeRegistry.NodeTypesType;\n\nexport type NodeOfType<T extends BuiltInNodeType> = Extract<BuiltInNodes, { type: T }>;\n\n/** Resets the global node registry to a fresh one with only built-in nodes registered. */\nexport function resetGlobalRivetNodeRegistry() {\n globalRivetNodeRegistry = registerBuiltInNodes(new NodeRegistration());\n}\n", "import { type ChatMessage, type GptFunction } from '../index.js';\nimport type { Tokenizer, TokenizerCallInfo } from './Tokenizer.js';\nimport Emittery from 'emittery';\nimport { getError } from '../utils/errors.js';\nimport { chatMessageToOpenAIChatCompletionMessage } from '../utils/chatMessageToOpenAIChatCompletionMessage.js';\nimport type { ChatCompletionRequestUserMessageTextContent } from '../utils/openai.js';\n\nexport class GptTokenizerTokenizer implements Tokenizer {\n emitter = new Emittery<{\n error: Error;\n }>();\n\n on(event: 'error', listener: (err: Error) => void): void {\n this.emitter.on(event, listener);\n }\n\n async getTokenCountForString(input: string, _info: TokenizerCallInfo): Promise<number> {\n const { encode } = await import('gpt-tokenizer');\n return encode(input).length;\n }\n\n async getTokenCountForMessages(\n messages: ChatMessage[],\n functions: GptFunction[] | undefined,\n _info: TokenizerCallInfo,\n ): Promise<number> {\n try {\n const openaiMessages = await Promise.all(\n messages.map((message) => chatMessageToOpenAIChatCompletionMessage(message)),\n );\n\n const validMessages = openaiMessages\n .filter((message) => message.role !== 'tool')\n .map((message) => {\n if (Array.isArray(message.content)) {\n const textContent = message.content\n .filter((c): c is ChatCompletionRequestUserMessageTextContent => c.type === 'text')\n .map((c) => c.text)\n .join('');\n return { ...message, content: textContent };\n }\n\n return message;\n });\n\n const { encode, encodeChat } = await import('gpt-tokenizer');\n\n const encodedChat = encodeChat(validMessages as any, 'gpt-3.5-turbo');\n const encodedFunctions =\n functions && functions.length > 0 ? encode(this.convertGptFunctionsToPromptString(functions)) : [];\n\n return encodedChat.length + encodedFunctions.length;\n } catch (err) {\n this.emitter.emit('error', getError(err));\n return 0;\n }\n }\n\n /**\n * Converts GPT Functions to approximate TypeScript-style string.\n * Per thread: https://community.openai.com/t/how-to-calculate-the-tokens-when-using-function-call/266573/24\n * We should consider using a different library, eg. https://github.com/hmarr/openai-chat-tokens\n * @param functions\n */\n private convertGptFunctionsToPromptString(functions: GptFunction[]): string {\n return `\n# Tools\n\n## functions\n\nnamespace functions {\n${functions\n .map(\n (fn) => `\n// ${fn.description}\ntype ${fn.name} = (_: {\n${Object.entries((fn.parameters as any)?.properties ?? {})\n .map(([parameterName, value]: [string, any]) => `// ${value?.description}\\n${parameterName}?: ${value?.type}`)\n .join('\\n')}\n})\n`,\n )\n .join('')}\n} // namespace functions\n`;\n }\n}\n", "export const baseDirs = {\n app: 'app',\n appCache: 'appCache',\n appConfig: 'appConfig',\n appData: 'appData',\n appLocalData: 'appLocalData',\n appLog: 'appLog',\n audio: 'audio',\n cache: 'cache',\n config: 'config',\n data: 'data',\n desktop: 'desktop',\n document: 'document',\n download: 'download',\n executable: 'executable',\n font: 'font',\n home: 'home',\n localData: 'localData',\n log: 'log',\n picture: 'picture',\n public: 'public',\n resource: 'resource',\n runtime: 'runtime',\n temp: 'temp',\n template: 'template',\n video: 'video',\n} as const;\n\nexport type BaseDir = (typeof baseDirs)[keyof typeof baseDirs];\n\nexport function assertBaseDir(baseDir: string): asserts baseDir is BaseDir {\n if (!(baseDir in baseDirs)) {\n throw new Error(`Invalid base directory: ${baseDir}`);\n }\n}\n", "import { type BaseDir } from './BaseDir.js';\nimport { type NativeApi } from './NativeApi.js';\n\nexport class BrowserNativeApi implements NativeApi {\n readdir(_path: string, _baseDir: BaseDir): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n\n readTextFile(_path: string, _baseDir: BaseDir): Promise<string> {\n throw new Error('Method not implemented.');\n }\n\n readBinaryFile(_path: string, _baseDir: BaseDir): Promise<Blob> {\n throw new Error('Method not implemented.');\n }\n\n writeTextFile(_path: string, _data: string, _baseDir?: BaseDir): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n exec(command: string, args: string[], options?: { cwd?: string | undefined } | undefined): Promise<void> {\n throw new Error('Method not supported.');\n }\n}\n", "import { type Settings } from '../../index.js';\nimport { type EmbeddingGenerator } from '../EmbeddingGenerator.js';\nimport { OpenAI } from 'openai';\n\ntype OpenAIOptions = Pick<OpenAI.EmbeddingCreateParams, 'model' | 'dimensions' >\n\nexport class OpenAIEmbeddingGenerator implements EmbeddingGenerator {\n readonly #settings;\n\n constructor(settings: Settings) {\n this.#settings = settings;\n }\n\n async generateEmbedding(text: string, options?: OpenAIOptions): Promise<number[]> {\n const api = new OpenAI({\n apiKey: this.#settings.openAiKey,\n organization: this.#settings.openAiOrganization,\n dangerouslyAllowBrowser: true, // It's fine in Rivet\n });\n\n const response = await api.embeddings.create({\n input: text,\n model: options?.model ?? 'text-embedding-ada-002',\n dimensions: options?.dimensions\n });\n\n const embeddings = response.data;\n\n return embeddings[0]!.embedding;\n }\n}\n", "import { registerIntegration } from './integrations.js';\nimport { OpenAIEmbeddingGenerator } from './openai/OpenAIEmbeddingGenerator.js';\n\nregisterIntegration('embeddingGenerator', 'openai', (context) => new OpenAIEmbeddingGenerator(context.settings));\n", "import { nanoid } from 'nanoid/non-secure';\nimport {\n type GraphProcessor,\n type ProcessEvents,\n type RecordedEvent,\n type RecordedEvents,\n type Recording,\n type RecordingId,\n type SerializedRecording,\n} from '../index.js';\nimport Emittery from 'emittery';\n\nexport type ExecutionRecorderEvents = {\n finish: { recording: Recording };\n};\n\ntype ProcessEventsUnion = Pick<\n {\n [P in keyof ProcessEvents]: {\n type: P;\n data: ProcessEvents[P];\n };\n },\n keyof ProcessEvents\n>[keyof ProcessEvents];\n\nconst toRecordedEventMap: {\n [P in keyof ProcessEvents]: (data: ProcessEvents[P]) => RecordedEvent<P>['data'];\n} = {\n graphStart: ({ graph, inputs }) => ({ graphId: graph.metadata!.id!, inputs }),\n graphFinish: ({ graph, outputs }) => ({ graphId: graph.metadata!.id!, outputs }),\n graphError: ({ graph, error }) => ({\n graphId: graph.metadata!.id!,\n error: typeof error === 'string' ? error : error.stack!,\n }),\n nodeStart: ({ node, inputs, processId }) => ({\n nodeId: node.id,\n inputs,\n processId,\n }),\n nodeFinish: ({ node, outputs, processId }) => ({\n nodeId: node.id,\n outputs,\n processId,\n }),\n nodeError: ({ node, error, processId }) => ({\n nodeId: node.id,\n error: typeof error === 'string' ? error : error.stack!,\n processId,\n }),\n abort: ({ successful, error }) => ({ successful, error: typeof error === 'string' ? error : error?.stack }),\n graphAbort: ({ successful, error, graph }) => ({\n successful,\n error: typeof error === 'string' ? error : error?.stack,\n graphId: graph.metadata!.id!,\n }),\n nodeExcluded: ({ node, processId, inputs, outputs, reason }) => ({\n nodeId: node.id,\n processId,\n inputs,\n outputs,\n reason,\n }),\n userInput: ({ node, inputs, callback, processId }) => ({\n nodeId: node.id,\n inputs,\n callback,\n processId,\n }),\n partialOutput: ({ node, outputs, index, processId }) => ({\n nodeId: node.id,\n outputs,\n index,\n processId,\n }),\n nodeOutputsCleared: ({ node, processId }) => ({\n nodeId: node.id,\n processId,\n }),\n error: ({ error }) => ({\n error: typeof error === 'string' ? error : error.stack!,\n }),\n done: ({ results }) => ({ results }),\n globalSet: ({ id, processId, value }) => ({ id, processId, value }),\n pause: () => void 0,\n resume: () => void 0,\n start: ({ contextValues, inputs, project, startGraph }) => ({\n contextValues,\n inputs,\n projectId: project.metadata!.id!,\n startGraph: startGraph.metadata!.id!,\n }),\n trace: (message) => message,\n newAbortController: () => {},\n finish: () => void 0,\n};\n\nconst isPrefix = <const T extends string>(s: string, prefix: T): s is `${T}${string}` => s.startsWith(prefix);\n\nfunction toRecordedEvent<T extends keyof ProcessEvents>(event: T, data: ProcessEvents[T]): RecordedEvents {\n if (isPrefix(event, 'globalSet:')) {\n return {\n type: event,\n data: data as ProcessEvents[`globalSet:${string}`],\n ts: Date.now(),\n };\n }\n\n if (isPrefix(event, 'userEvent:')) {\n return {\n type: event,\n data: data as ProcessEvents[`userEvent:${string}`],\n ts: Date.now(),\n };\n }\n\n return {\n type: event,\n data: (toRecordedEventMap[event] as any)(data),\n ts: Date.now(),\n };\n}\n\nexport type ExecutionRecorderOptions = {\n includePartialOutputs?: boolean;\n includeTrace?: boolean;\n};\n\nexport class ExecutionRecorder {\n #events: RecordedEvents[] = [];\n recordingId: RecordingId | undefined;\n readonly #emitter: Emittery<ExecutionRecorderEvents>;\n\n readonly #includePartialOutputs: boolean;\n readonly #includeTrace: boolean;\n\n constructor(options: ExecutionRecorderOptions = {}) {\n this.#emitter = new Emittery();\n this.#emitter.bindMethods(this as any, ['on', 'off', 'once']);\n this.#includePartialOutputs = options.includePartialOutputs ?? false;\n this.#includeTrace = options.includeTrace ?? false;\n }\n\n on: Emittery<ExecutionRecorderEvents>['on'] = undefined!;\n off: Emittery<ExecutionRecorderEvents>['off'] = undefined!;\n once: Emittery<ExecutionRecorderEvents>['once'] = undefined!;\n\n recordSocket(channel: WebSocket) {\n return new Promise<void>((resolve, reject) => {\n this.recordingId = nanoid() as RecordingId;\n\n const listener = (event: MessageEvent) => {\n const { message, data } = JSON.parse(event.data);\n\n if (this.#includePartialOutputs === false && message === 'partialOutput') {\n return;\n }\n\n if (this.#includeTrace === false && message === 'trace') {\n return;\n }\n\n this.#events.push(toRecordedEvent(message, data) as RecordedEvents);\n\n if (message === 'done' || message === 'abort' || message === 'error') {\n this.#emitter.emit('finish', {\n recording: this.getRecording(),\n });\n\n channel.removeEventListener('message', listener);\n\n resolve();\n }\n };\n\n channel.addEventListener('message', listener);\n });\n }\n\n record(processor: GraphProcessor) {\n this.recordingId = nanoid() as RecordingId;\n processor.onAny((event, data) => {\n if (this.#includePartialOutputs === false && event === 'partialOutput') {\n return;\n }\n\n if (this.#includeTrace === false && event === 'trace') {\n return;\n }\n\n this.#events.push(toRecordedEvent(event, data) as RecordedEvents);\n\n if (event === 'done' || event === 'abort' || event === 'error') {\n this.#emitter.emit('finish', {\n recording: this.getRecording(),\n });\n }\n });\n }\n\n getRecording(): Recording {\n return {\n recordingId: this.recordingId!,\n events: this.#events,\n startTs: this.#events[0]?.ts ?? 0,\n finishTs: this.#events[this.#events.length - 1]?.ts ?? 0,\n };\n }\n\n get events() {\n return this.#events;\n }\n\n static deserializeFromString(serialized: string) {\n const recorder = new ExecutionRecorder();\n const serializedRecording = JSON.parse(serialized) as SerializedRecording;\n\n if (serializedRecording.version !== 1) {\n throw new Error('Unsupported serialized events version');\n }\n\n recorder.recordingId = serializedRecording.recording.recordingId;\n recorder.#events = serializedRecording.recording.events;\n return recorder;\n }\n\n serialize() {\n const serialized: SerializedRecording = {\n version: 1,\n recording: this.getRecording(),\n };\n\n return JSON.stringify(serialized);\n }\n}\n", "import {\n type ChartNode,\n type EditorDefinition,\n type Inputs,\n type InternalProcessContext,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type NodeUIData,\n type Outputs,\n type PluginNodeImpl,\n type PortId,\n\tChatNodeImpl,\n\ttype ChatNode,\n\ttype ChatNodeData,\n\ttype ChatMessage, \n\ttype GptFunction,\n\tRivet,\n\tglobalRivetNodeRegistry,\n\ttype DataValue,\n} from '../../../index.js';\n\nimport { omit } from 'lodash-es';\nimport { dedent } from 'ts-dedent';\nimport { coerceTypeOptional } from '../../../utils/coerceType.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\n\n// Temporary\nconst cache = new Map<string, Outputs>();\n\nconst registry = globalRivetNodeRegistry;\n\nexport type ChatAidonNode = ChartNode<'chatAidon', ChatNodeData>;\n\n//comes from Chatbot\ninterface SchemaDetail {\n title: string\n description: string\n url: string\n headers: string\n routeMap: Record<string, string>\n requestInBody: boolean\n}\n\ninterface FunctionCall {\n name: string\n arguments: string\n\tid: string\n};\n\nclass ChatAidonNodeImpl extends ChatNodeImpl {\n\tcreate(): ChatAidonNode {\n\t\tconst chatNode: ChatAidonNode = {\n\t\t\t...this.chartNode,\n\t\t\ttype: 'chatAidon',\n\t\t\ttitle: 'Chat (Aidon)',\n\t\t}\n\t\treturn chatNode\n\t}\n\n\tremoveInvalidInputs(inputs: Inputs): Inputs {\n\t\tif (!inputs['toolSchemas' as PortId]) {\n\t\t\tconst { ['functions' as PortId]: _, ...rest } = inputs\n\t\t\treturn rest\n\t\t}\n\t\treturn inputs\n\t}\n\n\tconvertToolSchemaToSchemaDetail(toolSchema: GptFunction): SchemaDetail {\n\t\tconst { name, description, parameters } = toolSchema\n\t\t// Assuming the structure of parameters from the example\n\t\tconst { headers, requestInBody, routeMap, url } = parameters as {\n\t\t\theaders: string\n\t\t\trequestInBody: boolean\n\t\t\trouteMap: Record<string, string>\n\t\t\turl: string\n\t\t}\n\t\t\n\t\treturn {\n\t\t\ttitle: name,\n\t\t\tdescription,\n\t\t\turl,\n\t\t\theaders,\n\t\t\trouteMap,\n\t\t\trequestInBody\n\t\t}\n\t}\n\n\textractPath(schemaDetail: SchemaDetail, functionName: string, parsedArgs: any) {\n\t\tconst pathTemplate = Object.keys(schemaDetail.routeMap).find(\n\t\t\tkey => schemaDetail.routeMap[key] === functionName\n\t\t)\n\t\n\t\tif (!pathTemplate) {\n\t\t\tthrow new Error(`Path for function ${functionName} not found`)\n\t\t}\n\t\n\t\tconst path = pathTemplate.replace(/:(\\w+)/g, (_, paramName) => {\n\t\t\tconst value = parsedArgs.parameters[paramName]\n\t\t\tif (!value) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Parameter ${paramName} not found for function ${functionName}`\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn encodeURIComponent(value)\n\t\t})\n\t\n\t\tif (!path) {\n\t\t\tthrow new Error(`Path for function ${functionName} not found`)\n\t\t}\n\t\treturn path\n\t}\n\t\n\tasync callToolGet(parsedArgs: any, schemaDetail: SchemaDetail, path: string, data: {}) {\n\t\tconst queryParams = new URLSearchParams(\n\t\t\tparsedArgs.parameters\n\t\t).toString()\n\t\tconst fullUrl = schemaDetail.url + path + (queryParams ? \"?\" + queryParams : \"\")\n\t\tlet headers = {}\n\t\n\t\t// Check if custom headers are set\n\t\tconst customHeaders = schemaDetail.headers\n\t\tif (customHeaders && typeof customHeaders === \"string\") {\n\t\t\theaders = JSON.parse(customHeaders)\n\t\t}\n\t\n\t\tconst response = await fetch(fullUrl, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: headers\n\t\t})\n\t\n\t\tif (!response.ok) {\n\t\t\tdata = {\n\t\t\t\terror: response.statusText\n\t\t\t}\n\t\t} else {\n\t\t\tdata = await response.json()\n\t\t}\n\t\treturn data\n\t}\n\t\n\tasync callToolPost(schemaDetail: SchemaDetail, path: string, parsedArgs: any, data: {}) {\n\t\tlet headers = {\n\t\t\t\"Content-Type\": \"application/json\"\n\t\t}\n\t\n\t\t// Check if custom headers are set\n\t\tconst customHeaders = schemaDetail.headers // Moved this line up to the loop\n\t\n\t\t// Check if custom headers are set and are of type string\n\t\tif (customHeaders && typeof customHeaders === \"string\") {\n\t\t\tlet parsedCustomHeaders = JSON.parse(customHeaders) as Record<\n\t\t\t\tstring, string\n\t\t\t>\n\t\n\t\t\theaders = {\n\t\t\t\t...headers,\n\t\t\t\t...parsedCustomHeaders\n\t\t\t}\n\t\t}\n\t\n\t\tconst fullUrl = schemaDetail.url + path\n\t\n\t\tconst bodyContent = parsedArgs.requestBody || parsedArgs\n\t\n\t\tconst requestInit = {\n\t\t\tmethod: \"POST\",\n\t\t\theaders,\n\t\t\tbody: JSON.stringify(bodyContent) // Use the extracted requestBody or the entire parsedArgs\n\t\t}\n\t\n\t\tconst response = await fetch(fullUrl, requestInit)\n\t\n\t\tif (!response.ok) {\n\t\t\tdata = {\n\t\t\t\terror: response.statusText\n\t\t\t}\n\t\t} else {\n\t\t\tdata = await response.json()\n\t\t}\n\t\treturn data\n\t}\n\t\n\t// Override the process function\n async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n\t\t//make sure not to include functions if we have no way to run them after.\n\t\tinputs = this.removeInvalidInputs(inputs)\n\n\t\t// Call the parent class's process method to do its job\n\t\tlet outputs = await super.process(inputs, context)\n\n\t\tconst funcCallOutput = outputs['function-call' as PortId] ?? outputs['function-calls' as PortId];\n const funcCalls = funcCallOutput?.type === 'object[]'\n ? funcCallOutput.value\n : undefined // coerceTypeOptional(functionCallOutput, 'string[]');\n\n\t\tif (funcCalls !== undefined) {\n\t\t\tconst messages = outputs['all-messages' as PortId]\n\t\t\tconst toolSchemas = coerceTypeOptional(inputs['toolSchemas' as PortId], 'gpt-function[]')\n\n\t\t\tconst functionCalls: Array<FunctionCall> = funcCalls.map((functionCall) => ({\n\t\t\t\tname: functionCall.name as string,\n\t\t\t\targuments: functionCall.arguments as string,\n\t\t\t\tid: functionCall.id as string,\n\t\t\t}))\n\n\t\t\t//call the tool(s) to get the results to add to the message\n\t\t\tfor (const functionCall of functionCalls) {\n\t\t\t\t// Find the schema detail that contains the function name\n\t\t\t\tconst toolSchema = toolSchemas!.find(detail => detail.name == functionCall.name)\n\t\t\t\tif (!toolSchema) {\n throw new Error(`Function ${functionCall.name} not found in any schema`)\n }\n\n\t\t\t\tconst schemaDetail = this.convertToolSchemaToSchemaDetail(toolSchema)\n\t\t\t\tconst path = this.extractPath(schemaDetail, functionCall.name, functionCall.arguments)\n\n // Determine if the request should be in the body or as a query\n let data = {}\n\n if (schemaDetail.requestInBody) {\n // If the type is set to body\n data = await this.callToolPost(schemaDetail, path, functionCall.arguments, data)\n } else { // If the type is set to query\n data = await this.callToolGet(functionCall.arguments, schemaDetail, path, data)\n }\n\n\t\t\t\t(messages!['value'] as ChatMessage[]).push({\n\t\t\t\t\ttype: \"function\",\n name: functionCall.id,\n message: JSON.stringify(data)\n })\n }\n\t\t\t\n\t\t\tinputs = omit(inputs, ['functions', 'prompt'])\n\t\t\tinputs['prompt' as PortId] = messages as unknown as DataValue\n\t\t\toutputs = await super.process(inputs, context)\n\t\t}\n\n\t\treturn outputs;\n\t}\n}\n\nconst createPluginNodeImpl = (chatNode: ChartNode): PluginNodeImpl<ChatAidonNode> => {\n\tconst impl = new ChatAidonNodeImpl(chatNode as ChatNode)\n\n\treturn {\n\t\tcreate(): ChatAidonNode {\n\t\t\treturn impl.create()\n\t\t},\t\t\n\t\tgetInputDefinitions(data): NodeInputDefinition[] {\n\t\t\timpl.chartNode.data = data // Ensure data is set correctly in the base class\n\t\t\tconst inputs = impl.getInputDefinitions()\n\t\t\tif (data.enableFunctionUse) {\n\t\t\t\tinputs.push({\n\t\t\t\t\tdataType: ['gpt-function', 'gpt-function[]'] as const,\n\t\t\t\t\tid: 'toolSchemas' as PortId,\n\t\t\t\t\ttitle: 'Tool Schemas',\n\t\t\t\t\tdescription: 'The schemas required to run the tool(s) specified in the functions input keyed by function name.',\n\t\t\t\t\tcoerced: true,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn inputs\n\t\t},\n\t\tgetOutputDefinitions(data): NodeOutputDefinition[] {\n\t\t\timpl.chartNode.data = data // Ensure data is set correctly in the base class\n\t\t\tconst outputs: NodeOutputDefinition[] = impl.getOutputDefinitions()\n\t\t\treturn outputs.filter(output => {\n\t\t\t\treturn !(output.id === 'function-calls');\n\t\t\t});\n\t\t},\n\t\tgetEditors(data: ChatNodeData): EditorDefinition<ChatNode>[] {\n\t\t\timpl.chartNode.data = data // Ensure data is set correctly in the base class\n\t\t\treturn impl.getEditors()\n\t\t},\n\t\tgetBody(data): string {\n\t\t\timpl.chartNode.data = data // Ensure data is set correctly in the base class\n\t\t\treturn impl.getBody()\n\t\t},\n\t\tgetUIData(): NodeUIData {\n\t\t\treturn {\n\t\t\t\tinfoBoxBody: dedent`\n\t\t\t\t\tMakes a call to an Aidon chat model. The settings contains many options for tweaking the model's behavior.\n\t\t\t\t`,\n\t\t\t\tinfoBoxTitle: 'Chat (Aidon) Node',\n\t\t\t\tcontextMenuTitle: 'Chat (Aidon)',\n\t\t\t\tgroup: ['AI'],\n\t\t\t};\n\t\t},\n\t\tasync process(\n\t\t\tdata: ChatNodeData,\n\t\t\tinputData: Inputs,\n\t\t\tcontext: InternalProcessContext,\n\t\t): Promise<Outputs> {\n\t\t\timpl.chartNode.data = data // Ensure data is set correctly in the base class\n\t\t\treturn impl.process(inputData, context)\n\t\t},\n\t}\n}\n\nexport function chatAidonNode() {\n\tconst chatNode:ChartNode = registry.create('chat');\n\tconst chatAidonNodeImpl = createPluginNodeImpl(chatNode)\n\treturn pluginNodeDefinition(chatAidonNodeImpl, 'Chat Aidon Node')\n}\n", "import { type RivetPlugin } from '../../index.js';\nimport { chatAidonNode } from './nodes/ChatAidonNode.js';\n\nexport const aidonPlugin: RivetPlugin = {\n\tid: 'aidon',\n\tname: 'Aidon',\n\n register: (register) => {\n register(chatAidonNode());\n },\n};\n", "import { aidonPlugin } from './plugin.js';\n\nexport default aidonPlugin;\n", "// https://github.com/openai/openai-node/issues/18#issuecomment-1518715285\nexport class EventSourceResponse extends Response {\n name: string;\n readonly streams: {\n eventStream: ReadableStream<string>;\n textStream: ReadableStream<string>;\n } | null;\n\n constructor(body: ReadableStream<Uint8Array> | null, init?: ResponseInit) {\n if (body == null) {\n super(null, init);\n this.name = 'EventSourceResponse';\n this.streams = null;\n return;\n }\n\n const [bodyForString, bodyForEvents] = body.tee();\n const streams = createEventStream(bodyForEvents);\n // By passing our transformed stream into the Response constructor, we prevent anyone\n // from accidentally accessing the raw response.body stream.\n super(bodyForString, init);\n this.name = 'EventSourceResponse';\n this.streams = streams;\n }\n\n async *events(): AsyncGenerator<string> {\n if (this.streams == null) {\n return;\n }\n const reader = this.streams.eventStream.getReader();\n\n try {\n while (true) {\n const { done, value } = await this.raceWithTimeout(reader.read());\n if (done) {\n break;\n }\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n }\n\n private async raceWithTimeout<T>(promise: Promise<T>, timeout = 5000): Promise<T> {\n // eslint-disable-next-line no-async-promise-executor -- Error handled correctly\n return new Promise(async (resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new Error('Timeout: API response took too long.'));\n }, timeout);\n\n try {\n const result = await promise;\n clearTimeout(timer);\n resolve(result);\n } catch (error) {\n clearTimeout(timer);\n reject(error);\n }\n });\n }\n}\n\nexport default async function fetchEventSource(url: string, init?: RequestInit): Promise<EventSourceResponse> {\n const headers = {\n ...init?.headers,\n accept: 'text/event-stream',\n };\n\n const response = await fetch(url, {\n ...init,\n headers,\n });\n\n return new EventSourceResponse(response.body, response);\n}\n\nclass LineSplitter implements Transformer<string, string> {\n private buffer = '';\n constructor(readonly separator = /\\n+/) {}\n\n transform(chunk: string, controller: TransformStreamDefaultController<string>): void {\n this.buffer += chunk;\n const lines = this.buffer.split(this.separator);\n this.buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n controller.enqueue(line);\n }\n }\n\n flush(controller: TransformStreamDefaultController<string>): void {\n if (this.buffer.length > 0) {\n controller.enqueue(this.buffer);\n this.buffer = '';\n }\n }\n}\n\nfunction createEventStream(body: ReadableStream<Uint8Array> | null) {\n if (body == null) {\n return null;\n }\n\n const textStream = body.pipeThrough(new TextDecoderStream());\n\n const eventStream = textStream.pipeThrough(new TransformStream(new LineSplitter())).pipeThrough(\n new TransformStream<string, string>({\n transform(line, controller) {\n if (line.startsWith('data: ')) {\n const data = line.slice(6).trim();\n controller.enqueue(data);\n } else if (line.startsWith('event: ')) {\n const event = line.slice(7).trim();\n controller.enqueue(`[${event}]`);\n }\n },\n }),\n );\n return { eventStream, textStream };\n}\n", "import fetchEventSource from './fetchEventSource.js';\n\nexport type AnthropicModel = {\n maxTokens: number;\n cost: {\n prompt: number;\n completion: number;\n };\n displayName: string;\n};\n\nexport const anthropicModels = {\n 'claude-instant-1': {\n maxTokens: 100_000,\n cost: {\n prompt: 0.00163,\n completion: 0.00551,\n },\n displayName: 'Claude Instant',\n },\n 'claude-instant-1.2': {\n maxTokens: 100_000,\n cost: {\n prompt: 0.8e-6,\n completion: 2.4e-6,\n },\n displayName: 'Claude Instant 1.2',\n },\n 'claude-2': {\n maxTokens: 100_000,\n cost: {\n prompt: 8e-6,\n completion: 24e-6,\n },\n displayName: 'Claude 2',\n },\n 'claude-2.1': {\n maxTokens: 200_000,\n cost: {\n prompt: 8e-6,\n completion: 24e-6,\n },\n displayName: 'Claude 2.1',\n },\n 'claude-3-haiku-20240307': {\n maxTokens: 200_000,\n cost: {\n prompt: 0.25e-6,\n completion: 1.25e-6,\n },\n displayName: 'Claude 3 Haiku',\n },\n 'claude-3-sonnet-20240229': {\n maxTokens: 200_000,\n cost: {\n prompt: 3e-6,\n completion: 15e-6,\n },\n displayName: 'Claude 3 Sonnet',\n },\n 'claude-3-opus-20240229': {\n maxTokens: 200_000,\n cost: {\n prompt: 15e-6,\n completion: 75e-6,\n },\n displayName: 'Claude 3 Opus',\n },\n 'claude-3-5-sonnet-20240620': {\n maxTokens: 200_000,\n cost: {\n prompt: 3e-6,\n completion: 15e-6,\n },\n displayName: 'Claude 3.5 Sonnet',\n },\n} satisfies Record<string, AnthropicModel>;\n\nexport type AnthropicModels = keyof typeof anthropicModels;\n\nexport const anthropicModelOptions = Object.entries(anthropicModels).map(([id, { displayName }]) => ({\n value: id,\n label: displayName,\n}));\n\nexport type Claude3ChatMessage = {\n role: 'user' | 'assistant';\n content: string | Claude3ChatMessageContentPart[];\n}\n\nexport type Claude3ChatMessageTextContentPart = {\n type: 'text';\n text: string;\n};\n\nexport type Claude3ChatMessageImageContentPart = {\n type: 'image';\n source: {\n type: 'base64';\n media_type: string;\n data: string;\n };\n};\n\nexport type Claude3ChatMessageToolResultContentPart = {\n type: 'tool_result';\n tool_use_id: string;\n content: string | { type: 'text'; text: string; }[];\n};\n\nexport type Claude3ChatMessageToolUseContentPart = {\n type: 'tool_use';\n id: string;\n name: string;\n input: object;\n}\n\nexport type Claude3ChatMessageContentPart = \n | Claude3ChatMessageTextContentPart\n | Claude3ChatMessageImageContentPart\n | Claude3ChatMessageToolResultContentPart\n | Claude3ChatMessageToolUseContentPart;\n\nexport type ChatMessageOptions = {\n apiKey: string;\n model: AnthropicModels;\n messages: Claude3ChatMessage[];\n system?: string;\n max_tokens: number;\n stop_sequences?: string[];\n temperature?: number;\n top_p?: number;\n top_k?: number;\n signal?: AbortSignal;\n stream?: boolean;\n tools?: {\n name: string;\n description: string;\n input_schema: object;\n }[];\n};\n\nexport type ChatCompletionOptions = {\n apiKey: string;\n model: AnthropicModels;\n prompt: string;\n max_tokens_to_sample: number;\n stop_sequences?: string[];\n temperature?: number;\n top_p?: number;\n top_k?: number;\n signal?: AbortSignal;\n stream?: boolean;\n};\n\nexport type ChatCompletionChunk = {\n completion: string;\n stop_reason: 'stop_sequence' | null;\n model: string;\n};\n\nexport type ChatMessageChunk = {\n type: 'message_start';\n message: {\n id: string;\n type: string;\n role: string;\n content: {\n type: 'text';\n text: string;\n }[];\n model: AnthropicModels;\n stop_reason: string | null;\n stop_sequence: string | null;\n usage: {\n input_tokens: number;\n output_tokens: number;\n };\n };\n} | {\n type: 'content_block_start';\n index: number;\n content_block: {\n type: 'text';\n text: string;\n };\n} | {\n type: 'ping';\n} | {\n type: 'content_block_delta';\n index: number;\n delta: {\n type: 'text_delta';\n text: string;\n }\n} | {\n type: 'message_delta';\n delta: {\n stop_reason: string | null;\n stop_sequence: string | null;\n usage: {\n output_tokens: number;\n }\n }\n} | {\n type: 'message_stop';\n};\n\nexport type ChatMessageResponse = {\n id: string;\n content: ({\n text: string;\n } | {\n id: string;\n name: string;\n input: object;\n })[];\n model: string;\n stop_reason: 'end_turn';\n stop_sequence: string;\n usage: {\n input_tokens: number;\n output_tokens: number;\n };\n};\n\nexport async function* streamChatCompletions({\n apiKey,\n signal,\n ...rest\n}: ChatCompletionOptions): AsyncGenerator<ChatCompletionChunk> {\n const defaultSignal = new AbortController().signal;\n const response = await fetchEventSource('https://api.anthropic.com/v1/complete', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-api-key': apiKey,\n 'anthropic-version': '2023-06-01',\n },\n body: JSON.stringify({\n ...rest,\n stream: true,\n }),\n signal: signal ?? defaultSignal,\n });\n\n let hadChunks = false;\n let nextDataType: string | undefined;\n\n for await (const chunk of response.events()) {\n hadChunks = true;\n\n if (chunk === '[DONE]') {\n return;\n } else if (/\\[\\w+\\]/.test(chunk)) {\n nextDataType = chunk.slice(1, -1);\n continue;\n }\n\n let data: ChatCompletionChunk;\n try {\n data = JSON.parse(chunk);\n } catch (err) {\n console.error('JSON parse failed on chunk: ', chunk);\n throw err;\n }\n\n yield data;\n }\n\n if (!hadChunks) {\n const responseJson = await response.json();\n throw new AnthropicError(`No chunks received. Response: ${JSON.stringify(responseJson)}`, response, responseJson);\n }\n}\n\nexport async function callMessageApi({\n apiKey,\n signal,\n tools,\n ...rest\n}: ChatMessageOptions): Promise<ChatMessageResponse> {\n const defaultSignal = new AbortController().signal;\n const response = await fetch('https://api.anthropic.com/v1/messages', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-api-key': apiKey,\n 'anthropic-version': '2023-06-01',\n 'anthropic-beta': tools ? 'tools-2024-04-04' : 'messages-2023-12-15',\n },\n body: JSON.stringify({\n ...rest,\n tools,\n stream: false,\n }),\n signal: signal ?? defaultSignal,\n });\n const responseJson = await response.json();\n if (response.status !== 200) {\n throw new AnthropicError(responseJson?.error?.message ?? 'Request failed', response, responseJson);\n }\n return responseJson;\n}\n\nexport async function* streamMessageApi({\n apiKey,\n signal,\n ...rest\n}: ChatMessageOptions): AsyncGenerator<ChatMessageChunk> {\n // Use the Messages API for Claude 3 models\n const defaultSignal = new AbortController().signal;\n const response = await fetchEventSource('https://api.anthropic.com/v1/messages', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-api-key': apiKey,\n 'anthropic-version': '2023-06-01',\n 'anthropic-beta': 'messages-2023-12-15',\n },\n body: JSON.stringify({\n ...rest,\n stream: true,\n }),\n signal: signal ?? defaultSignal,\n });\n\n let hadChunks = false;\n let nextDataType: string | undefined;\n\n for await (const chunk of response.events()) {\n hadChunks = true;\n\n if (chunk === '[message_stop]') {\n return;\n } else if (/\\[\\w+\\]/.test(chunk)) {\n nextDataType = chunk.slice(1, -1);\n continue;\n }\n\n let data: ChatMessageChunk;\n try {\n data = JSON.parse(chunk);\n } catch (err) {\n console.error('JSON parse failed on chunk: ', chunk);\n throw err;\n }\n\n yield data;\n }\n\n if (!hadChunks) {\n const responseJson = await response.json();\n throw new AnthropicError(`No chunks received. Response: ${JSON.stringify(responseJson)}`, response, responseJson);\n }\n}\n\nexport class AnthropicError extends Error {\n constructor(\n message: string,\n public readonly response: Response,\n public readonly responseJson: unknown,\n ) {\n super(message);\n }\n}\n", "import {\n uint8ArrayToBase64,\n type ChartNode,\n type ChatMessage,\n type EditorDefinition,\n type Inputs,\n type InternalProcessContext,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type NodeUIData,\n type Outputs,\n type PluginNodeImpl,\n type PortId,\n type ScalarDataValue,\n type ChatMessageMessagePart,\n} from '../../../index.js';\nimport {\n type AnthropicModels,\n type ChatCompletionOptions,\n anthropicModelOptions,\n anthropicModels,\n streamChatCompletions,\n AnthropicError,\n type Claude3ChatMessage,\n type Claude3ChatMessageContentPart,\n streamMessageApi,\n type ChatMessageOptions,\n callMessageApi,\n type Claude3ChatMessageTextContentPart,\n\ttype Claude3ChatMessageToolResultContentPart,\n} from '../anthropic.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport retry from 'p-retry';\nimport { match } from 'ts-pattern';\nimport { coerceType, coerceTypeOptional } from '../../../utils/coerceType.js';\nimport { addWarning } from '../../../utils/outputs.js';\nimport { getError } from '../../../utils/errors.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { getScalarTypeOf, isArrayDataValue } from '../../../model/DataValue.js';\nimport type { TokenizerCallInfo } from '../../../integrations/Tokenizer.js';\nimport { assertNever } from '../../../utils/assertNever.js';\nimport { isNotNull } from '../../../utils/genericUtilFunctions.js';\n\nexport type ChatAnthropicNode = ChartNode<'chatAnthropic', ChatAnthropicNodeData>;\n\nexport type ChatAnthropicNodeConfigData = {\n model: AnthropicModels;\n temperature: number;\n useTopP: boolean;\n top_p?: number;\n top_k?: number;\n maxTokens: number;\n stop?: string;\n enableToolUse?: boolean;\n};\n\nexport type ChatAnthropicNodeData = ChatAnthropicNodeConfigData & {\n useModelInput: boolean;\n useTemperatureInput: boolean;\n useTopPInput: boolean;\n useTopKInput: boolean;\n useUseTopPInput: boolean;\n useMaxTokensInput: boolean;\n useStop: boolean;\n useStopInput: boolean;\n\n /** Given the same set of inputs, return the same output without hitting GPT */\n cache: boolean;\n\n useAsGraphPartialOutput?: boolean;\n};\n\n// Temporary\nconst cache = new Map<string, Outputs>();\n\nexport const ChatAnthropicNodeImpl: PluginNodeImpl<ChatAnthropicNode> = {\n create(): ChatAnthropicNode {\n const chartNode: ChatAnthropicNode = {\n type: 'chatAnthropic',\n title: 'Chat (Anthropic)',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 275,\n },\n data: {\n model: 'claude-3-5-sonnet-20240620',\n useModelInput: false,\n\n temperature: 0.5,\n useTemperatureInput: false,\n\n top_p: 1,\n useTopPInput: false,\n\n top_k: undefined,\n useTopKInput: false,\n\n useTopP: false,\n useUseTopPInput: false,\n\n maxTokens: 1024,\n useMaxTokensInput: false,\n\n useStop: false,\n stop: '',\n useStopInput: false,\n\n cache: false,\n useAsGraphPartialOutput: true,\n\n enableToolUse: false,\n },\n };\n\n return chartNode;\n },\n\n getInputDefinitions(data): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n\n if (data.model.startsWith('claude-3')) {\n inputs.push({\n dataType: 'string',\n id: 'system' as PortId,\n title: 'System Prompt',\n });\n }\n\n if (data.useModelInput) {\n inputs.push({\n id: 'model' as PortId,\n title: 'Model',\n dataType: 'string',\n required: false,\n });\n }\n\n if (data.useTemperatureInput) {\n inputs.push({\n dataType: 'number',\n id: 'temperature' as PortId,\n title: 'Temperature',\n });\n }\n\n if (data.useTopPInput) {\n inputs.push({\n dataType: 'number',\n id: 'top_p' as PortId,\n title: 'Top P',\n });\n }\n\n if (data.useUseTopPInput) {\n inputs.push({\n dataType: 'boolean',\n id: 'useTopP' as PortId,\n title: 'Use Top P',\n });\n }\n\n if (data.useMaxTokensInput) {\n inputs.push({\n dataType: 'number',\n id: 'maxTokens' as PortId,\n title: 'Max Tokens',\n });\n }\n\n if (data.useStopInput) {\n inputs.push({\n dataType: 'string',\n id: 'stop' as PortId,\n title: 'Stop',\n });\n }\n\n inputs.push({\n dataType: ['chat-message', 'chat-message[]'] as const,\n id: 'prompt' as PortId,\n title: 'Prompt',\n });\n\n if (data.enableToolUse) {\n inputs.push({\n dataType: ['gpt-function', 'gpt-function[]'] as const,\n id: 'tools' as PortId,\n title: 'Tools',\n description: 'Tools to use in the model. To connect multiple tools, use an Array node.',\n coerced: false,\n });\n }\n\n return inputs;\n },\n\n getOutputDefinitions(data): NodeOutputDefinition[] {\n const outputs: NodeOutputDefinition[] = [];\n\n outputs.push({\n dataType: 'string',\n id: 'response' as PortId,\n title: 'Response',\n });\n\n if (data.enableToolUse) {\n outputs.push({\n dataType: 'object[]',\n id: 'function-calls' as PortId,\n title: 'Function Calls',\n description: 'The function calls that were made, if any.',\n });\n }\n\n outputs.push({\n dataType: 'chat-message[]',\n id: 'all-messages' as PortId,\n title: 'All Messages',\n description: 'All messages, with the response appended.',\n });\n\n return outputs;\n },\n\n getBody(data): string {\n const modelName = anthropicModels[data.model]?.displayName ?? 'Unknown Model';\n return dedent`\n ${modelName}\n ${\n data.useTopP\n ? `Top P: ${data.useTopPInput ? '(Using Input)' : data.top_p}`\n : `Temperature: ${data.useTemperatureInput ? '(Using Input)' : data.temperature}`\n }\n Max Tokens: ${data.maxTokens}\n ${data.useStop ? `Stop: ${data.useStopInput ? '(Using Input)' : data.stop}` : ''}\n `;\n },\n\n getEditors(): EditorDefinition<ChatAnthropicNode>[] {\n return [\n {\n type: 'dropdown',\n label: 'Model',\n dataKey: 'model',\n useInputToggleDataKey: 'useModelInput',\n options: anthropicModelOptions,\n },\n {\n type: 'number',\n label: 'Temperature',\n dataKey: 'temperature',\n useInputToggleDataKey: 'useTemperatureInput',\n min: 0,\n max: 2,\n step: 0.1,\n },\n {\n type: 'number',\n label: 'Top P',\n dataKey: 'top_p',\n useInputToggleDataKey: 'useTopPInput',\n min: 0,\n max: 1,\n step: 0.1,\n },\n {\n type: 'toggle',\n label: 'Use Top P',\n dataKey: 'useTopP',\n useInputToggleDataKey: 'useUseTopPInput',\n },\n {\n type: 'number',\n label: 'Max Tokens',\n dataKey: 'maxTokens',\n useInputToggleDataKey: 'useMaxTokensInput',\n min: 0,\n max: Number.MAX_SAFE_INTEGER,\n step: 1,\n },\n {\n type: 'string',\n label: 'Stop',\n dataKey: 'stop',\n useInputToggleDataKey: 'useStopInput',\n },\n {\n type: 'toggle',\n label: 'Cache (same inputs, same outputs)',\n dataKey: 'cache',\n },\n {\n type: 'toggle',\n label: 'Use for subgraph partial output',\n dataKey: 'useAsGraphPartialOutput',\n },\n {\n type: 'toggle',\n label: 'Enable Tool Use (disables streaming)',\n dataKey: 'enableToolUse',\n },\n ];\n },\n\n getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Makes a call to an Anthropic chat model. The settings contains many options for tweaking the model's behavior.\n `,\n infoBoxTitle: 'Chat (Anthropic) Node',\n contextMenuTitle: 'Chat (Anthropic)',\n group: ['AI'],\n };\n },\n\n async process(data, inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n if (context.executor === 'browser') {\n throw new Error('This node requires using the Node executor');\n }\n\n const output: Outputs = {};\n const rawModel = data.useModelInput\n ? coerceTypeOptional(inputs['model' as PortId], 'string') ?? data.model\n : data.model;\n const model = rawModel as AnthropicModels;\n const temperature = data.useTemperatureInput\n ? coerceTypeOptional(inputs['temperature' as PortId], 'number') ?? data.temperature\n : data.temperature;\n const topP = data.useTopPInput ? coerceTypeOptional(inputs['top_p' as PortId], 'number') ?? data.top_p : data.top_p;\n const useTopP = data.useUseTopPInput\n ? coerceTypeOptional(inputs['useTopP' as PortId], 'boolean') ?? data.useTopP\n : data.useTopP;\n const stop = data.useStopInput\n ? data.useStop\n ? coerceTypeOptional(inputs['stop' as PortId], 'string') ?? data.stop\n : undefined\n : data.stop;\n const tools = data.enableToolUse\n ? coerceTypeOptional(inputs['tools' as PortId], 'gpt-function[]') ?? []\n : undefined;\n const rivetChatMessages = getChatMessages(inputs);\n const messages = await chatMessagesToClaude3ChatMessages(rivetChatMessages);\n let prompt = messages.reduce((acc, message) => {\n const content =\n typeof message.content === 'string'\n ? message.content\n : message.content\n .filter((c): c is Claude3ChatMessageTextContentPart => c.type === 'text')\n .map((c) => c.text ?? '')\n .join('');\n if (message.role === 'user') {\n return `${acc}\\n\\nHuman: ${content}`;\n } else if (message.role === 'assistant') {\n return `${acc}\\n\\nAssistant: ${content}`;\n }\n return acc;\n }, '');\n prompt += '\\n\\nAssistant:';\n\n // Get the \"System\" prompt input for Claude 3 models\n const system = data.model.startsWith('claude-3') ? getSystemPrompt(inputs) : undefined;\n\n let { maxTokens } = data;\n const tokenizerInfo: TokenizerCallInfo = {\n node: context.node,\n model,\n endpoint: undefined,\n };\n const tokenCountEstimate = await context.tokenizer.getTokenCountForString(prompt, tokenizerInfo);\n const modelInfo = anthropicModels[model] ?? {\n maxTokens: Number.MAX_SAFE_INTEGER,\n cost: {\n prompt: 0,\n completion: 0,\n },\n };\n if (tokenCountEstimate >= modelInfo.maxTokens) {\n throw new Error(\n `The model ${model} can only handle ${modelInfo.maxTokens} tokens, but ${tokenCountEstimate} were provided in the prompts alone.`,\n );\n }\n if (tokenCountEstimate + maxTokens > modelInfo.maxTokens) {\n const message = `The model can only handle a maximum of ${\n modelInfo.maxTokens\n } tokens, but the prompts and max tokens together exceed this limit. The max tokens has been reduced to ${\n modelInfo.maxTokens - tokenCountEstimate\n }.`;\n addWarning(output, message);\n maxTokens = Math.floor((modelInfo.maxTokens - tokenCountEstimate) * 0.95); // reduce max tokens by 5% to be safe, calculation is a little wrong.\n }\n try {\n return await retry(\n async () => {\n const completionOptions: Omit<ChatCompletionOptions, 'apiKey' | 'signal'> = {\n model,\n temperature: useTopP ? undefined : temperature,\n top_p: useTopP ? topP : undefined,\n max_tokens_to_sample: maxTokens ?? modelInfo.maxTokens,\n stop_sequences: stop ? [stop] : undefined,\n prompt,\n };\n const messageOptions: Omit<ChatMessageOptions, 'apiKey' | 'signal'> = {\n model,\n temperature: useTopP ? undefined : temperature,\n top_p: useTopP ? topP : undefined,\n max_tokens: maxTokens ?? modelInfo.maxTokens,\n stop_sequences: stop ? [stop] : undefined,\n system: system,\n messages,\n tools: tools\n ? tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.parameters }))\n : undefined,\n };\n const useMessageApi = model.startsWith('claude-3');\n const cacheKey = JSON.stringify(useMessageApi ? messageOptions : completionOptions);\n if (data.cache) {\n const cached = cache.get(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n const startTime = Date.now();\n const apiKey = context.getPluginConfig('anthropicApiKey');\n\n if (useMessageApi && data.enableToolUse) {\n // Streaming is not supported with tool usage.\n const response = await callMessageApi({\n apiKey: apiKey ?? '',\n ...messageOptions,\n });\n const { input_tokens: requestTokens, output_tokens: responseTokens } = response.usage;\n const responseText = response.content\n .map((c): string | undefined => (c as any).text)\n .filter(isNotNull)\n .join('');\n output['response' as PortId] = {\n type: 'string',\n value: responseText,\n };\n const functionCalls = response.content\n .filter((content) => (content as any).name && (content as any).id)\n .map((functionCall: any) => ({\n name: functionCall.name,\n arguments: functionCall.input, // Matches OpenAI ChatNode\n id: functionCall.id,\n }));\n\n if (functionCalls.length > 0) {\n output['function-calls' as PortId] = {\n type: 'object[]',\n value: functionCalls,\n };\n }\n\n output['all-messages' as PortId] = {\n type: 'chat-message[]',\n value: [\n ...rivetChatMessages,\n {\n type: 'assistant',\n message: responseText,\n function_call:\n functionCalls.length > 0\n ? functionCalls.map((toolCall) => ({\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.arguments),\n id: toolCall.id,\n }))[0]\n : undefined,\n function_calls: functionCalls.map((toolCall) => ({\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.arguments),\n id: toolCall.id,\n })),\n } satisfies ChatMessage,\n ],\n };\n output['requestTokens' as PortId] = { type: 'number', value: requestTokens ?? tokenCountEstimate };\n const responseTokenCount =\n responseTokens ?? context.tokenizer.getTokenCountForString(responseText, tokenizerInfo);\n output['responseTokens' as PortId] = { type: 'number', value: responseTokenCount };\n } else if (useMessageApi) {\n // Use the messages API for Claude 3 models\n const chunks = streamMessageApi({\n apiKey: apiKey ?? '',\n signal: context.signal,\n ...messageOptions,\n });\n\n // Process the response chunks and update the output\n const responseParts: string[] = [];\n let requestTokens: number | undefined = undefined,\n responseTokens: number | undefined = undefined;\n for await (const chunk of chunks) {\n let completion: string = '';\n if (chunk.type === 'content_block_start') {\n completion = chunk.content_block.text;\n } else if (chunk.type === 'content_block_delta') {\n completion = chunk.delta.text;\n } else if (chunk.type === 'message_start' && chunk.message?.usage?.input_tokens) {\n requestTokens = chunk.message.usage.input_tokens;\n } else if (chunk.type === 'message_delta' && chunk.delta?.usage?.output_tokens) {\n responseTokens = chunk.delta.usage.output_tokens;\n }\n if (!completion) {\n continue;\n }\n responseParts.push(completion);\n output['response' as PortId] = {\n type: 'string',\n value: responseParts.join('').trim(),\n };\n output['all-messages' as PortId] = {\n type: 'chat-message[]',\n value: [\n ...rivetChatMessages,\n {\n type: 'assistant',\n message: responseParts.join('').trim(),\n function_call: undefined,\n function_calls: undefined,\n } satisfies ChatMessage,\n ],\n };\n context.onPartialOutputs?.(output);\n }\n\n if (responseParts.length === 0) {\n throw new Error('No response from Anthropic');\n }\n\n output['requestTokens' as PortId] = { type: 'number', value: requestTokens ?? tokenCountEstimate };\n const responseTokenCount =\n responseTokens ?? (await context.tokenizer.getTokenCountForString(responseParts.join(''), tokenizerInfo));\n output['responseTokens' as PortId] = { type: 'number', value: responseTokenCount };\n } else {\n // Use the normal chat completion method for non-Claude 3 models\n const chunks = streamChatCompletions({\n apiKey: apiKey ?? '',\n signal: context.signal,\n ...completionOptions,\n });\n\n // Process the response chunks and update the output\n const responseParts: string[] = [];\n for await (const chunk of chunks) {\n if (!chunk.completion) {\n continue;\n }\n responseParts.push(chunk.completion);\n output['response' as PortId] = {\n type: 'string',\n value: responseParts.join('').trim(),\n };\n context.onPartialOutputs?.(output);\n }\n\n if (responseParts.length === 0) {\n throw new Error('No response from Anthropic');\n }\n\n output['all-messages' as PortId] = {\n type: 'chat-message[]',\n value: [\n ...rivetChatMessages,\n {\n type: 'assistant',\n message: responseParts.join('').trim(),\n function_call: undefined,\n function_calls: undefined,\n } satisfies ChatMessage,\n ],\n };\n output['requestTokens' as PortId] = { type: 'number', value: tokenCountEstimate };\n const responseTokenCount = await context.tokenizer.getTokenCountForString(\n responseParts.join(''),\n tokenizerInfo,\n );\n output['responseTokens' as PortId] = { type: 'number', value: responseTokenCount };\n }\n\n const cost = getCostForTokens(\n {\n requestTokens: output['requestTokens' as PortId]?.value as number,\n responseTokens: output['responseTokens' as PortId]?.value as number,\n },\n model,\n );\n if (cost != null) {\n output['cost' as PortId] = { type: 'number', value: cost };\n }\n\n const endTime = Date.now();\n\n const duration = endTime - startTime;\n output['duration' as PortId] = { type: 'number', value: duration };\n\n Object.freeze(output);\n cache.set(cacheKey, output);\n\n return output;\n },\n {\n forever: true,\n retries: 10000,\n maxRetryTime: 1000 * 60 * 5,\n factor: 2.5,\n minTimeout: 500,\n maxTimeout: 5000,\n randomize: true,\n signal: context.signal,\n onFailedAttempt(err) {\n context.trace(`ChatAnthropicNode failed, retrying: ${err.toString()}`);\n\n if (context.signal.aborted) {\n throw new Error('Aborted');\n }\n\n if (err instanceof AnthropicError) {\n if (err.response.status >= 400 && err.response.status < 500) {\n if ((err.responseJson as any).error?.message) {\n throw new Error((err.responseJson as any).error.message);\n }\n }\n }\n },\n },\n );\n } catch (error) {\n context.trace(getError(error).stack ?? 'Missing stack');\n throw new Error(`Error processing ChatAnthropicNode: ${(error as Error).message}`);\n }\n },\n};\n\nexport const chatAnthropicNode = pluginNodeDefinition(ChatAnthropicNodeImpl, 'Chat');\n\nexport function getSystemPrompt(inputs: Inputs) {\n const system = coerceTypeOptional(inputs['system' as PortId], 'string');\n if (system) {\n return system;\n }\n const prompt = inputs['prompt' as PortId];\n if (prompt && prompt.type === 'chat-message[]') {\n const systemMessage = prompt.value.find((message) => message.type === 'system');\n if (systemMessage) {\n if (typeof systemMessage.message === 'string') {\n return systemMessage.message;\n } else if (Array.isArray(systemMessage.message)) {\n return systemMessage.message.filter((p) => typeof p === 'string').join('');\n }\n }\n }\n}\n\nfunction getChatMessages(inputs: Inputs) {\n const prompt = inputs['prompt' as PortId];\n if (!prompt) {\n throw new Error('Prompt is required');\n }\n\n const chatMessages = match(prompt)\n .with({ type: 'chat-message' }, (p) => [p.value])\n .with({ type: 'chat-message[]' }, (p) => p.value)\n .with({ type: 'string' }, (p): ChatMessage[] => [{ type: 'user', message: p.value }])\n .with({ type: 'string[]' }, (p): ChatMessage[] => p.value.map((v) => ({ type: 'user', message: v })))\n .otherwise((p): ChatMessage[] => {\n if (isArrayDataValue(p)) {\n const stringValues = (p.value as readonly unknown[]).map((v) =>\n coerceType(\n {\n type: getScalarTypeOf(p.type),\n value: v,\n } as ScalarDataValue,\n 'string',\n ),\n );\n\n return stringValues.filter((v) => v != null).map((v) => ({ type: 'user', message: v }));\n }\n\n const coercedMessage = coerceType(p, 'chat-message');\n if (coercedMessage != null) {\n return [coercedMessage];\n }\n\n const coercedString = coerceType(p, 'string');\n return coercedString != null ? [{ type: 'user', message: coerceType(p, 'string') }] : [];\n });\n\n return chatMessages;\n}\n\nexport async function chatMessagesToClaude3ChatMessages(chatMessages: ChatMessage[]): Promise<Claude3ChatMessage[]> {\n const messages: Claude3ChatMessage[] = (await Promise.all(chatMessages.map(chatMessageToClaude3ChatMessage))).filter(\n isNotNull,\n );\n\n // Combine sequential tool_result messages into a single user message with multiple content items\n const combinedMessages = messages.reduce<Claude3ChatMessage[]>((acc, message) => {\n if (\n message.role === 'user' &&\n Array.isArray(message.content) &&\n message.content.length === 1 &&\n message.content[0]!.type === 'tool_result'\n ) {\n const last = acc.at(-1);\n if (last?.role === 'user' && Array.isArray(last.content) && last.content.every((c) => c.type === 'tool_result')) {\n\t\t\t\tconst mc = message.content as Claude3ChatMessageToolResultContentPart[]\n const content = last.content.concat(mc);\n return [...acc.slice(0, -1), { ...last, content }];\n }\n }\n\n return [...acc, message];\n }, []);\n\n return combinedMessages;\n}\n\nasync function chatMessageToClaude3ChatMessage(message: ChatMessage): Promise<Claude3ChatMessage | undefined> {\n if (message.type === 'system') {\n return undefined;\n }\n if (message.type === 'function') {\n // Interpret function messages as user messages with tool_result content items (making Claude API more similar to OpenAI's)\n const content = (Array.isArray(message.message) ? message.message : [message.message])\n .map((m) => (typeof m === 'string' ? { type: 'text' as const, text: m } : undefined))\n .filter(isNotNull);\n return {\n role: 'user',\n content: [\n {\n type: 'tool_result',\n tool_use_id: message.name,\n content: content.length === 1 ? content[0]!.text : content,\n },\n ],\n };\n }\n\n const content = Array.isArray(message.message)\n ? await Promise.all(message.message.map(chatMessageContentToClaude3ChatMessage))\n : [await chatMessageContentToClaude3ChatMessage(message.message)];\n\n if (message.type === 'assistant' && message.function_calls) {\n content.push(\n ...message.function_calls.map((fc) => ({\n type: 'tool_use' as const,\n id: fc.id!,\n name: fc.name,\n input: JSON.parse(fc.arguments),\n })),\n );\n } else if (message.type === 'assistant' && message.function_call) {\n content.push({\n type: 'tool_use',\n id: message.function_call.id!,\n name: message.function_call.name,\n input: JSON.parse(message.function_call.arguments),\n });\n }\n return {\n role: message.type,\n content,\n };\n}\n\nasync function chatMessageContentToClaude3ChatMessage(\n content: ChatMessageMessagePart,\n): Promise<Claude3ChatMessageContentPart> {\n if (typeof content === 'string') {\n return {\n type: 'text',\n text: content,\n };\n }\n switch (content.type) {\n case 'image':\n return {\n type: 'image',\n source: {\n type: 'base64' as const,\n media_type: content.mediaType as string,\n data: (await uint8ArrayToBase64(content.data)) ?? '',\n },\n };\n case 'url':\n throw new Error('unable to convert urls for Claude');\n default:\n assertNever(content);\n }\n}\n\nfunction getCostForTokens(\n tokenCounts: { requestTokens: number; responseTokens: number },\n model: AnthropicModels,\n): number | undefined {\n const modelInfo = anthropicModels[model];\n if (modelInfo == null) {\n return undefined;\n }\n return modelInfo.cost.prompt * tokenCounts.requestTokens + modelInfo.cost.completion * tokenCounts.responseTokens;\n}\n", "export function assertNever(x: never): never {\n throw new Error(`Unexpected object: ${x}`);\n}\n", "import { type RivetPlugin } from '../../index.js';\nimport { chatAnthropicNode } from './nodes/ChatAnthropicNode.js';\n\nexport const anthropicPlugin: RivetPlugin = {\n id: 'anthropic',\n name: 'Anthropic',\n\n register: (register) => {\n register(chatAnthropicNode);\n },\n\n configSpec: {\n anthropicApiKey: {\n type: 'string',\n label: 'Anthropic API Key',\n description: 'The API key for the Anthropic service.',\n pullEnvironmentVariable: 'ANTHROPIC_API_KEY',\n helperText: 'You may also set the ANTHROPIC_API_KEY environment variable.',\n },\n },\n};\n", "import { anthropicPlugin } from './plugin.js';\n\nexport default anthropicPlugin;\n", "import { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport {\n Battle,\n ClosedQA,\n Factuality,\n Humor,\n Possible,\n Security,\n Summary,\n Translation,\n Sql,\n type templates,\n} from 'autoevals';\nimport type {\n ChartNode,\n EditorDefinition,\n Inputs,\n InternalProcessContext,\n NodeId,\n NodeImpl,\n NodeInputDefinition,\n NodeOutputDefinition,\n NodeUIData,\n Outputs,\n PluginNodeImpl,\n PortId,\n} from '../../index.js';\nimport { match } from 'ts-pattern';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { pluginNodeDefinition } from '../../model/NodeDefinition.js';\n\nexport type AutoEvalsNode = ChartNode<'autoevals', AutoEvalsNodeData>;\n\nexport type AutoEvalsNodeData = {\n evaluatorName?: keyof typeof templates;\n};\n\nconst options = [\n { label: 'Factuality', value: 'factuality' },\n { label: 'Humor', value: 'humor' },\n { label: 'Security', value: 'security' },\n { label: 'Possible', value: 'possible' },\n { label: 'Summary', value: 'summary' },\n { label: 'Translation', value: 'translation' },\n { label: 'Battle', value: 'battle' },\n { label: 'Closed Q&A', value: 'closed_q_a' },\n { label: 'SQL', value: 'sql' },\n];\n\nexport const AutoEvalsNodeImpl: PluginNodeImpl<AutoEvalsNode> = {\n create(): AutoEvalsNode {\n const chartNode: AutoEvalsNode = {\n type: 'autoevals',\n title: 'Autoevals',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n evaluatorName: 'factuality',\n },\n };\n\n return chartNode;\n },\n\n getInputDefinitions(data): NodeInputDefinition[] {\n const base: NodeInputDefinition[] = [\n {\n id: 'output' as PortId,\n dataType: 'string',\n title: 'Output',\n },\n {\n id: 'expected' as PortId,\n dataType: 'string',\n title: 'Expected',\n },\n ];\n\n const forEvaluator: NodeInputDefinition[] = match(data.evaluatorName)\n .with('factuality', (): NodeInputDefinition[] => [\n {\n id: 'input' as PortId,\n dataType: 'string',\n title: 'Input',\n },\n ])\n .with('battle', (): NodeInputDefinition[] => [\n {\n id: 'instructions' as PortId,\n dataType: 'string',\n title: 'Instructions',\n },\n ])\n .with('closed_q_a', (): NodeInputDefinition[] => [\n {\n id: 'input' as PortId,\n dataType: 'string',\n title: 'Input',\n },\n {\n id: 'criteria' as PortId,\n dataType: 'string',\n title: 'Criteria',\n },\n ])\n .with('humor', (): NodeInputDefinition[] => [])\n .with('possible', (): NodeInputDefinition[] => [\n {\n id: 'input' as PortId,\n dataType: 'string',\n title: 'Input',\n },\n ])\n .with('security', (): NodeInputDefinition[] => [])\n .with('summary', (): NodeInputDefinition[] => [\n {\n id: 'input' as PortId,\n dataType: 'string',\n title: 'Input',\n },\n ])\n .with('translation', (): NodeInputDefinition[] => [\n {\n id: 'input' as PortId,\n dataType: 'string',\n title: 'Input',\n },\n {\n id: 'language' as PortId,\n dataType: 'string',\n title: 'Language',\n },\n ])\n .with('sql', (): NodeInputDefinition[] => [\n {\n id: 'input' as PortId,\n dataType: 'string',\n title: 'Input',\n },\n ])\n .with(undefined, (): NodeInputDefinition[] => [])\n .exhaustive();\n\n return [...forEvaluator, ...base];\n },\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'number',\n id: 'score' as PortId,\n title: 'Score',\n },\n {\n dataType: 'string',\n id: 'rationale' as PortId,\n title: 'Rationale',\n },\n {\n dataType: 'object',\n id: 'metadata' as PortId,\n title: 'Metadata',\n },\n ];\n },\n\n getEditors(): EditorDefinition<AutoEvalsNode>[] {\n return [\n {\n type: 'dropdown',\n dataKey: 'evaluatorName',\n label: 'Evaluator',\n options,\n },\n ];\n },\n\n getBody(data): string | undefined {\n return options.find((option) => option.value === data.evaluatorName)?.label ?? 'None';\n },\n\n getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Evaluates the validity of a response using the autoevals library.\n `,\n infoBoxTitle: 'Autoevals Node',\n contextMenuTitle: 'Autoevals',\n group: 'Custom',\n };\n },\n\n async process(data, inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const evaluatorName = data.evaluatorName;\n\n const output = coerceType(inputs['output' as PortId], 'string');\n const expected = coerceType(inputs['expected' as PortId], 'string');\n\n const baseArgs = {\n output,\n expected,\n openAiApiKey: context.settings.openAiKey,\n openAiOrganizationId: context.settings.openAiOrganization,\n };\n\n const result = await match(evaluatorName)\n .with('factuality', () => {\n const input = coerceType(inputs['input' as PortId], 'string');\n return Factuality({ ...baseArgs, input });\n })\n .with('battle', () => {\n const instructions = coerceType(inputs['instructions' as PortId], 'string');\n return Battle({ ...baseArgs, instructions });\n })\n .with('closed_q_a', () => {\n const input = coerceType(inputs['input' as PortId], 'string');\n const criteria = coerceType(inputs['criteria' as PortId], 'string');\n return ClosedQA({ ...baseArgs, input, criteria });\n })\n .with('humor', () => {\n return Humor({ ...baseArgs });\n })\n .with('possible', () => {\n const input = coerceType(inputs['input' as PortId], 'string');\n return Possible({ ...baseArgs, input });\n })\n .with('security', () => {\n return Security({ ...baseArgs });\n })\n .with('summary', () => {\n const input = coerceType(inputs['input' as PortId], 'string');\n return Summary({ ...baseArgs, input });\n })\n .with('translation', () => {\n const input = coerceType(inputs['input' as PortId], 'string');\n const language = coerceType(inputs['language' as PortId], 'string');\n return Translation({ ...baseArgs, input, language });\n })\n .with('sql', () => {\n const input = coerceType(inputs['input' as PortId], 'string');\n return Sql({ ...baseArgs, input });\n })\n .with(undefined, () => {\n throw new Error('Evaluator name is undefined');\n })\n .exhaustive();\n\n return {\n ['score' as PortId]: {\n type: 'number',\n value: result.score,\n },\n ['rationale' as PortId]: {\n type: 'string',\n value: (result.metadata?.rationale as string | undefined) ?? '',\n },\n ['metadata' as PortId]: {\n type: 'object',\n value: result.metadata as Record<string, unknown>,\n },\n };\n },\n};\n\nexport const autoEvalsNode = pluginNodeDefinition(AutoEvalsNodeImpl, 'Autoevals');\n", "import type { RivetPlugin } from '../../index.js';\nimport { autoEvalsNode } from './AutoEvalsNode.js';\n\nexport const autoevalsPlugin: RivetPlugin = {\n id: 'autoevals',\n name: 'Autoevals',\n register: (register) => {\n register(autoEvalsNode);\n },\n};\n", "import { autoevalsPlugin } from './plugin.js';\n\nexport default autoevalsPlugin;\n", "import { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport {\n type AnyDataValue,\n type ChartNode,\n type EditorDefinition,\n type Inputs,\n type InternalProcessContext,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type NodeUIData,\n type Outputs,\n type PortId,\n type StringArrayDataValue,\n type StringDataValue,\n type ObjectDataValue,\n type ArrayDataValue,\n type PluginNodeImpl,\n} from '../../index.js';\nimport {\n type LemurNodeData,\n getClient,\n getLemurParams,\n lemurEditorDefinitions,\n lemurInputDefinitions,\n} from './lemurHelpers.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { pluginNodeDefinition } from '../../model/NodeDefinition.js';\nimport { AssemblyAI, type LemurQuestion, type LemurQuestionAnswerParams } from 'assemblyai';\n\nexport type LemurQaNode = ChartNode<'assemblyAiLemurQa', LemurQaNodeData>;\n\nexport type LemurQaNodeData = LemurNodeData & {\n questions_answer_format?: string;\n questions_context?: string;\n questions_answer_options?: string;\n};\n\nexport const LemurQaNodeImpl = {\n create(): LemurQaNode {\n const chartNode: LemurQaNode = {\n type: 'assemblyAiLemurQa',\n title: 'LeMUR Question & Answers',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n final_model: 'default',\n },\n };\n\n return chartNode;\n },\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n ...lemurInputDefinitions,\n {\n id: 'questions' as PortId,\n dataType: ['string', 'string[]', 'object', 'object[]', 'any', 'any[]'],\n title: 'Questions',\n },\n {\n id: 'context' as PortId,\n dataType: 'string',\n title: 'Context',\n },\n ];\n },\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'object[]',\n id: 'response' as PortId,\n title: 'Response',\n },\n ];\n },\n\n getEditors(): EditorDefinition<LemurQaNode>[] {\n return [\n {\n type: 'string',\n label: 'Context',\n dataKey: 'context',\n },\n ...(lemurEditorDefinitions as unknown as EditorDefinition<LemurQaNode>[]),\n {\n type: 'string',\n label: 'Questions Answer Format',\n dataKey: 'questions_answer_format',\n },\n {\n type: 'string',\n label: 'Questions Context',\n dataKey: 'questions_context',\n },\n {\n type: 'string',\n label: 'Questions Answer Options',\n dataKey: 'questions_answer_options',\n },\n ];\n },\n\n getBody(): string | undefined {\n return '';\n },\n\n getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`Use AssemblyAI LeMUR to ask questions about transcripts`,\n infoBoxTitle: 'Use AssemblyAI LeMUR Question & Answer',\n contextMenuTitle: 'LeMUR Q&A',\n group: ['AI', 'AssemblyAI'],\n };\n },\n\n async process(data, inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const client = getClient(context);\n\n const questions = getQuestions(inputs).map((question) => applyQuestionEditors(data, question));\n\n const params: LemurQuestionAnswerParams = {\n questions,\n ...getLemurParams(inputs, data),\n };\n\n const { response } = await client.lemur.questionAnswer(params);\n return {\n ['response' as PortId]: {\n type: 'object[]',\n value: response,\n },\n };\n },\n} satisfies PluginNodeImpl<LemurQaNode>;\n\nfunction getQuestions(inputs: Inputs): LemurQuestion[] {\n const input = inputs['questions' as PortId] as\n | StringDataValue\n | StringArrayDataValue\n | AnyDataValue\n | ObjectDataValue\n | ArrayDataValue<ObjectDataValue>\n | ArrayDataValue<AnyDataValue>;\n\n if (!input) throw new Error('Questions are required.');\n\n if (input.type === 'string') {\n return [\n {\n question: coerceType(input, 'string'),\n },\n ];\n } else if (input.type === 'string[]') {\n return coerceType(input, 'string[]').map((question) => ({ question }));\n } else if (input.type === 'object') {\n return [coerceType(input, 'object')] as LemurQuestion[];\n } else if (input.type === 'object[]') {\n return coerceType(input, 'object[]') as unknown as LemurQuestion[];\n } else if (input.type === 'any' && typeof input.value === 'string') {\n return [\n {\n question: coerceType(input, 'string'),\n },\n ];\n } else if ((input.type === 'any' && Array.isArray(input.value)) || input.type === 'any[]') {\n return (input.value as any[]).map<LemurQuestion>((question: any) => {\n if (typeof question === 'string') {\n return { question };\n } else if (typeof question === 'object') {\n return question as LemurQuestion;\n } else {\n throw new Error('Question must be a string or object.');\n }\n });\n }\n throw new Error('Questions must be a string, string[], a question object, or an array of question objects.');\n}\n\nfunction applyQuestionEditors(data: LemurQaNodeData, question: LemurQuestion): LemurQuestion {\n if (!('answer_format' in question) && data.questions_answer_format) {\n question.answer_format = data.questions_answer_format;\n }\n if (!('answer_options' in question) && data.questions_answer_options) {\n question.answer_options = data.questions_answer_options.split(';');\n }\n if (!('context' in question) && data.questions_context) {\n question.context = data.questions_context;\n }\n\n return question;\n}\n\nexport const lemurQaNode = pluginNodeDefinition(LemurQaNodeImpl, 'LeMUR Q&A');\n", "import { AssemblyAI } from 'assemblyai';\nimport type { LemurBaseParams } from 'assemblyai';\nimport {\n type AnyDataValue,\n type ArrayDataValue,\n type Inputs,\n type InternalProcessContext,\n type PortId,\n type StringArrayDataValue,\n type StringDataValue,\n} from '../../index.js';\nimport { coerceType, coerceTypeOptional } from '../../utils/coerceType.js';\n\nfunction getTranscriptIds(inputs: Inputs): string[] | undefined {\n const input = inputs['transcript_ids' as PortId] as\n | StringDataValue\n | StringArrayDataValue\n | AnyDataValue\n | ArrayDataValue<AnyDataValue>;\n if (!input) return undefined;\n\n if (input.type === 'string' || (input.type === 'any' && typeof input.value === 'string')) {\n return [coerceType(input, 'string')];\n } else if (\n input.type === 'string[]' ||\n input.type === 'any[]' ||\n (input.type === 'any' && Array.isArray(input.value))\n ) {\n return coerceType(input, 'string[]');\n }\n throw new Error('Transcript IDs must be a string or string[] of transcript IDs.');\n}\n\nconst userAgent = {\n integration: {\n name: 'Rivet',\n version: '1.0.1',\n },\n};\nexport function getClient(context: InternalProcessContext): AssemblyAI {\n const apiKey = context.getPluginConfig('assemblyAiApiKey');\n if (!apiKey) {\n throw new Error('AssemblyAI API key not set.');\n }\n return new AssemblyAI({ apiKey, userAgent });\n}\n\nexport function getLemurParams(inputs: Inputs, editorData: LemurNodeData): LemurBaseParams {\n const params: LemurBaseParams = {\n transcript_ids: getTranscriptIds(inputs),\n input_text: coerceTypeOptional(inputs['input_text' as PortId], 'string'),\n context: coerceTypeOptional(inputs['context' as PortId], 'string') || editorData.context || undefined,\n final_model: editorData.final_model && editorData.final_model !== 'default' ? editorData.final_model : undefined,\n max_output_size: editorData.max_output_size,\n temperature: editorData.temperature,\n };\n\n return params;\n}\n\nexport const lemurInputDefinitions = [\n {\n id: 'transcript_ids' as PortId,\n dataType: ['string', 'string[]', 'any', 'any[]'],\n title: 'Transcript IDs',\n },\n {\n id: 'input_text' as PortId,\n dataType: ['string'],\n title: 'Input Text',\n },\n] as const;\n\nexport const lemurEditorDefinitions = [\n {\n type: 'dropdown',\n label: 'Final Model',\n dataKey: 'final_model',\n options: [\n {\n value: 'anthropic/claude-3-5-sonnet',\n label: 'Claude 3.5 Sonnet (on Anthropic)',\n },\n {\n value: 'anthropic/claude-3-opus',\n label: 'Claude 3 Opus (on Anthropic)',\n },\n {\n value: 'anthropic/claude-3-haiku',\n label: 'Claude 3 Haiku (on Anthropic)',\n },\n {\n value: 'anthropic/claude-3-sonnet',\n label: 'Claude 3 Sonnet (on Anthropic)',\n },\n {\n value: 'anthropic/claude-2-1',\n label: 'Claude 2.1 (on Anthropic)',\n },\n {\n value: 'anthropic/claude-2',\n label: 'Claude 2.1 (on Anthropic)',\n },\n {\n value: 'default',\n label: 'Default',\n },\n {\n value: 'anthropic/claude-instant-1-2',\n label: 'Claude Instant 1.2 (on Anthropic)',\n },\n {\n value: 'basic',\n label: 'Basic',\n },\n {\n value: 'assemblyai/mistral-7b',\n label: 'Mistral 7B (hosted by AssemblyAI)',\n },\n ],\n },\n {\n type: 'number',\n label: 'Maximum Output Size',\n dataKey: 'max_output_size',\n },\n {\n type: 'number',\n label: 'Temperature',\n dataKey: 'temperature',\n min: 0,\n max: 1,\n },\n] as const;\n\nexport type FinalModel =\n | 'anthropic/claude-3-5-sonnet'\n | 'anthropic/claude-3-opus'\n | 'anthropic/claude-3-haiku'\n | 'anthropic/claude-3-sonnet'\n | 'anthropic/claude-2-1'\n | 'anthropic/claude-2'\n | 'default'\n | 'anthropic/claude-instant-1-2'\n | 'basic'\n | 'assemblyai/mistral-7b';\n\nexport type LemurNodeData = {\n context?: string;\n final_model?: FinalModel;\n max_output_size?: number;\n temperature?: number;\n};\n", "import { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport type { TranscribeParams, TranscriptParams } from 'assemblyai';\nimport {\n type AnyDataValue,\n type AudioDataValue,\n type ChartNode,\n type EditorDefinition,\n type Inputs,\n type InternalProcessContext,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type NodeUIData,\n type Outputs,\n type PluginNodeImpl,\n type PortId,\n type StringDataValue,\n} from '../../index.js';\nimport { getClient } from './lemurHelpers.js';\nimport { pluginNodeDefinition } from '../../model/NodeDefinition.js';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport type TranscribeAudioNode = ChartNode<'assemblyAiTranscribeAudio', TranscribeAudioNodeData>;\n\nexport type TranscribeAudioNodeData = {\n transcriptParameters?: string;\n};\n\nexport const TranscribeAudioNodeImpl: PluginNodeImpl<TranscribeAudioNode> = {\n create(): TranscribeAudioNode {\n const chartNode: TranscribeAudioNode = {\n type: 'assemblyAiTranscribeAudio',\n title: 'Transcribe Audio',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {},\n };\n\n return chartNode;\n },\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n {\n id: 'audio' as PortId,\n dataType: ['audio', 'string'],\n title: 'Audio',\n },\n ];\n },\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'string',\n id: 'text' as PortId,\n title: 'Transcript text',\n },\n {\n dataType: 'string',\n id: 'id' as PortId,\n title: 'Transcript ID',\n },\n {\n dataType: 'object',\n id: 'transcript' as PortId,\n title: 'Transcript object',\n },\n ];\n },\n\n getEditors(): EditorDefinition<TranscribeAudioNode>[] {\n return [\n {\n type: 'code',\n label: 'Transcript Parameters (JSON)',\n language: 'json',\n dataKey: 'transcriptParameters',\n helperMessage: `Configure additional parameters using a JSON object. This will override any other fields you have set.\n For a detailed list of parameters, see [the AssemblyAI API documentation](https://www.assemblyai.com/docs/api-reference/transcripts/submit?utm_source=rivet).`,\n },\n ];\n },\n\n getBody(): string | undefined {\n return '';\n },\n\n getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`Use AssemblyAI to transcribe audio`,\n infoBoxTitle: 'Transcribe Audio Node',\n contextMenuTitle: 'Transcribe Audio',\n group: ['AI', 'AssemblyAI'],\n };\n },\n\n async process(data, inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const input = inputs['audio' as PortId] as AudioDataValue | StringDataValue | AnyDataValue;\n if (!input) throw new Error('Audio input is required.');\n\n const client = getClient(context);\n\n let audioUrl: string;\n if (input.type === 'audio') {\n const audio = coerceType(inputs['audio' as PortId], 'audio');\n audioUrl = await client.files.upload(audio.data);\n } else if (input.type === 'string' || input.type === 'any') {\n audioUrl = coerceType(inputs['audio' as PortId], 'string');\n } else {\n throw new Error('Audio input must be audio or string containing the audio URL.');\n }\n\n let transcriptParams: TranscribeParams = { audio: audioUrl };\n transcriptParams = { ...transcriptParams, ...getAdditionalParameters(data) };\n const transcript = await client.transcripts.transcribe(transcriptParams);\n\n return {\n ['text' as PortId]: {\n type: 'string',\n value: transcript.text as string,\n },\n ['id' as PortId]: {\n type: 'string',\n value: transcript.id,\n },\n ['transcript' as PortId]: {\n type: 'object',\n value: transcript,\n },\n };\n },\n};\n\nexport const transcribeAudioNode = pluginNodeDefinition(TranscribeAudioNodeImpl, 'Transcribe Audio');\n\nfunction getAdditionalParameters(data: TranscribeAudioNodeData): Partial<TranscriptParams> {\n const transcriptParams: string | null | undefined = data.transcriptParameters?.trim();\n if (!transcriptParams) {\n return {};\n }\n\n let transcriptParamsObj: Array<unknown> | Partial<TranscriptParams>;\n try {\n transcriptParamsObj = JSON.parse(transcriptParams);\n } catch (e) {\n throw new Error('The transcript parameters field has to be a valid JSON object, or empty.'); // This message is surfaced to the user\n }\n\n if (Array.isArray(transcriptParamsObj)) {\n throw new Error('The transcript parameters field should be a JSON object, but is a JSON array'); // This message is surfaced to the user\n }\n\n return transcriptParamsObj;\n}\n", "import { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport { AssemblyAI, type LemurSummaryParams } from 'assemblyai';\nimport {\n type ChartNode,\n type EditorDefinition,\n type Inputs,\n type InternalProcessContext,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type NodeUIData,\n type Outputs,\n type PluginNodeImpl,\n type PortId,\n} from '../../index.js';\nimport {\n type LemurNodeData,\n getClient,\n getLemurParams,\n lemurEditorDefinitions,\n lemurInputDefinitions,\n} from './lemurHelpers.js';\nimport { pluginNodeDefinition } from '../../model/NodeDefinition.js';\n\nexport type LemurSummaryNode = ChartNode<'assemblyAiLemurSummary', LemurSummaryNodeData>;\n\nexport type LemurSummaryNodeData = LemurNodeData & {\n answer_format?: string;\n};\n\nexport const LemurSummaryNodeImpl: PluginNodeImpl<LemurSummaryNode> = {\n create(): LemurSummaryNode {\n const chartNode: LemurSummaryNode = {\n type: 'assemblyAiLemurSummary',\n title: 'LeMUR Summary',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n final_model: 'default',\n },\n };\n\n return chartNode;\n },\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n ...lemurInputDefinitions,\n {\n id: 'context' as PortId,\n dataType: 'string',\n title: 'Context',\n },\n ];\n },\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'string',\n id: 'response' as PortId,\n title: 'Response',\n },\n ];\n },\n\n getEditors(): EditorDefinition<LemurSummaryNode>[] {\n return [\n {\n type: 'string',\n label: 'Context',\n dataKey: 'context',\n },\n ...(lemurEditorDefinitions as unknown as EditorDefinition<LemurSummaryNode>[]),\n ];\n },\n\n getBody(): string | undefined {\n return '';\n },\n\n getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`Use AssemblyAI LeMUR Summary to summarize transcripts`,\n infoBoxTitle: 'Use AssemblyAI LeMUR Summary',\n contextMenuTitle: 'LeMUR Summary',\n group: ['AI', 'AssemblyAI'],\n };\n },\n\n async process(data, inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const client = getClient(context);\n const params: LemurSummaryParams = getLemurParams(inputs, data);\n\n if (data.answer_format) {\n params.answer_format = data.answer_format;\n }\n\n const { response } = await client.lemur.summary(params);\n\n return {\n ['response' as PortId]: {\n type: 'string',\n value: response,\n },\n };\n },\n};\n\nexport const lemurSummaryNode = pluginNodeDefinition(LemurSummaryNodeImpl, 'LeMUR Summary');\n", "import { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport { type LemurTaskParams } from 'assemblyai';\nimport {\n type ChartNode,\n type EditorDefinition,\n type Inputs,\n type InternalProcessContext,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type NodeUIData,\n type Outputs,\n type PluginNodeImpl,\n type PortId,\n} from '../../index.js';\nimport {\n type LemurNodeData,\n getClient,\n getLemurParams,\n lemurEditorDefinitions,\n lemurInputDefinitions,\n} from './lemurHelpers.js';\nimport { pluginNodeDefinition } from '../../model/NodeDefinition.js';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type LemurTaskNode = ChartNode<'assemblyAiLemurTask', LemurTaskNodeData>;\n\nexport type LemurTaskNodeData = LemurNodeData & {\n prompt?: string;\n};\n\nexport const LemurTaskNodeImpl: PluginNodeImpl<LemurTaskNode> = {\n create(): LemurTaskNode {\n const chartNode: LemurTaskNode = {\n type: 'assemblyAiLemurTask',\n title: 'LeMUR Task',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n final_model: 'default',\n },\n };\n\n return chartNode;\n },\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n ...lemurInputDefinitions,\n {\n id: 'prompt' as PortId,\n dataType: 'string',\n title: 'Prompt',\n },\n ];\n },\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'string',\n id: 'response' as PortId,\n title: 'Response',\n },\n ];\n },\n\n getEditors(): EditorDefinition<LemurTaskNode>[] {\n return [\n {\n type: 'string',\n label: 'Prompt',\n dataKey: 'prompt',\n },\n ...(lemurEditorDefinitions as unknown as EditorDefinition<LemurTaskNode>[]),\n ];\n },\n\n getBody(): string | undefined {\n return '';\n },\n\n getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`Use AssemblyAI LeMUR Custom Task to ask anything.`,\n infoBoxTitle: 'Use AssemblyAI LeMUR Custom Task',\n contextMenuTitle: 'LeMUR Custom Task',\n group: ['AI', 'AssemblyAI'],\n };\n },\n\n async process(data, inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const client = getClient(context);\n const params: LemurTaskParams = {\n prompt: coerceTypeOptional(inputs['prompt' as PortId], 'string') || data.prompt || '',\n ...getLemurParams(inputs, data),\n };\n if (!params.prompt) throw new Error('Prompt must be provided.');\n\n const { response } = await client.lemur.task(params);\n\n return {\n ['response' as PortId]: {\n type: 'string',\n value: response,\n },\n };\n },\n};\n\nexport const lemurTaskNode = pluginNodeDefinition(LemurTaskNodeImpl, 'LeMUR Task');\n", "import { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport type { LemurActionItemsParams } from 'assemblyai';\nimport {\n type ChartNode,\n type EditorDefinition,\n type Inputs,\n type InternalProcessContext,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type NodeUIData,\n type Outputs,\n type PluginNodeImpl,\n type PortId,\n} from '../../index.js';\nimport { pluginNodeDefinition } from '../../model/NodeDefinition.js';\nimport {\n type LemurNodeData,\n getClient,\n getLemurParams,\n lemurEditorDefinitions,\n lemurInputDefinitions,\n} from './lemurHelpers.js';\n\nexport type LemurActionItemsNode = ChartNode<'assemblyAiLemurActionItems', LemurActionItemsNodeData>;\n\nexport type LemurActionItemsNodeData = LemurNodeData;\n\nexport const LemurActionItemsNodeImpl: PluginNodeImpl<LemurActionItemsNode> = {\n create(): LemurActionItemsNode {\n const chartNode: LemurActionItemsNode = {\n type: 'assemblyAiLemurActionItems',\n title: 'LeMUR Action Items',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 250,\n },\n data: {\n final_model: 'default',\n },\n };\n\n return chartNode;\n },\n\n getInputDefinitions(): NodeInputDefinition[] {\n return [\n ...lemurInputDefinitions,\n {\n id: 'context' as PortId,\n dataType: 'string',\n title: 'Context',\n },\n ];\n },\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n dataType: 'string',\n id: 'response' as PortId,\n title: 'Response',\n },\n ];\n },\n\n getEditors(): EditorDefinition<LemurActionItemsNode>[] {\n return [\n {\n type: 'string',\n label: 'Context',\n dataKey: 'context',\n },\n ...(lemurEditorDefinitions as unknown as EditorDefinition<LemurActionItemsNode>[]),\n ];\n },\n\n getBody(): string | undefined {\n return '';\n },\n\n getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`Use AssemblyAI LeMUR Action Items to extract action items`,\n infoBoxTitle: 'Use AssemblyAI LeMUR Action Items',\n contextMenuTitle: 'LeMUR Action Items',\n group: ['AI', 'AssemblyAI'],\n };\n },\n\n async process(data, inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const client = getClient(context);\n\n const params: LemurActionItemsParams = getLemurParams(inputs, data);\n\n const { response } = await client.lemur.actionItems(params);\n\n return {\n ['response' as PortId]: {\n type: 'string',\n value: response,\n },\n };\n },\n};\n\nexport const lemurActionItemsNode = pluginNodeDefinition(LemurActionItemsNodeImpl, 'LeMUR Action Items');\n", "import { type RivetPlugin } from '../../index.js';\nimport { lemurQaNode } from './LemurQaNode.js';\nimport { transcribeAudioNode } from './TranscribeAudioNode.js';\nimport { lemurSummaryNode } from './LemurSummaryNode.js';\nimport { lemurTaskNode } from './LemurTaskNode.js';\nimport { lemurActionItemsNode } from './LemurActionItemsNode.js';\n\nexport const assemblyAiPlugin: RivetPlugin = {\n id: 'assemblyAi',\n name: 'AssemblyAI',\n\n register: (register) => {\n register(transcribeAudioNode);\n register(lemurSummaryNode);\n register(lemurQaNode);\n register(lemurTaskNode);\n register(lemurActionItemsNode);\n },\n\n configSpec: {\n assemblyAiApiKey: {\n type: 'secret',\n label: 'AssemblyAI API Key',\n description: 'The API key for the AssemblyAI service.',\n pullEnvironmentVariable: 'ASSEMBLYAI_API_KEY',\n helperText: 'You may also set the ASSEMBLYAI_API_KEY environment variable.',\n },\n },\n\n contextMenuGroups: [\n {\n id: 'add-node-group:assemblyai',\n label: 'AssemblyAI',\n },\n ],\n};\n", "import { assemblyAiPlugin } from './plugin.js';\n\nexport default assemblyAiPlugin;\n", "import { nanoid } from 'nanoid/non-secure';\nimport {\n type ChartNode,\n type EditorDefinition,\n type NodeBodySpec,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type NodeUIData,\n type Outputs,\n type PluginNodeImpl,\n type PortId,\n} from '../../../index.js';\nimport { HfInference, HfInferenceEndpoint } from '@huggingface/inference';\nimport { getInputOrData } from '../../../utils/inputs.js';\nimport { coerceType } from '../../../utils/coerceType.js';\nimport { dedent } from '../../../utils/misc.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\n\nexport type ChatHuggingFaceNode = ChartNode<'chatHuggingFace', ChatHuggingFaceNodeData>;\n\nexport type ChatHuggingFaceNodeData = {\n model: string;\n useModelInput?: boolean;\n\n endpoint?: string;\n useEndpointInput?: boolean;\n\n temperature?: number;\n useTemperatureInput?: boolean;\n\n maxNewTokens: number;\n useMaxNewTokensInput?: boolean;\n\n doSample: boolean;\n useDoSampleInput?: boolean;\n\n maxTime?: number;\n useMaxTimeInput?: boolean;\n\n repetitionPenalty?: number;\n useRepetitionPenaltyInput?: boolean;\n\n topP?: number;\n useTopPInput?: boolean;\n\n topK?: number;\n useTopKInput?: boolean;\n};\n\nexport const ChatHuggingFaceNodeImpl: PluginNodeImpl<ChatHuggingFaceNode> = {\n create(): ChatHuggingFaceNode {\n return {\n id: nanoid() as NodeId,\n type: 'chatHuggingFace',\n data: {\n model: '',\n temperature: 0.5,\n maxNewTokens: 1024,\n doSample: false,\n },\n title: 'Chat (Hugging Face)',\n visualData: {\n x: 0,\n y: 0,\n width: 300,\n },\n };\n },\n\n getUIData(): NodeUIData {\n return {\n group: ['AI', 'Hugging Face'],\n contextMenuTitle: 'Chat (Hugging Face)',\n infoBoxTitle: 'Chat (Hugging Face) Node',\n infoBoxBody: 'Chat, using the hugging face inference API',\n };\n },\n\n getInputDefinitions(data): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n\n inputs.push({\n id: 'prompt' as PortId,\n dataType: 'string',\n title: 'Prompt',\n required: true,\n });\n\n if (data.useModelInput) {\n inputs.push({\n id: 'model' as PortId,\n dataType: 'string',\n title: 'Model',\n });\n }\n\n if (data.useEndpointInput) {\n inputs.push({\n id: 'endpoint' as PortId,\n dataType: 'string',\n title: 'Endpoint',\n });\n }\n\n if (data.useTemperatureInput) {\n inputs.push({\n id: 'temperature' as PortId,\n dataType: 'number',\n title: 'Temperature',\n });\n }\n\n if (data.useMaxNewTokensInput) {\n inputs.push({\n id: 'maxNewTokens' as PortId,\n dataType: 'number',\n title: 'Max New Tokens',\n });\n }\n\n if (data.useDoSampleInput) {\n inputs.push({\n id: 'doSample' as PortId,\n dataType: 'boolean',\n title: 'Do Sample',\n });\n }\n\n if (data.useMaxTimeInput) {\n inputs.push({\n id: 'maxTime' as PortId,\n dataType: 'number',\n title: 'Max Time (s)',\n });\n }\n\n if (data.useRepetitionPenaltyInput) {\n inputs.push({\n id: 'repetitionPenalty' as PortId,\n dataType: 'number',\n title: 'Repetition Penalty',\n });\n }\n\n if (data.useTopPInput) {\n inputs.push({\n id: 'topP' as PortId,\n dataType: 'number',\n title: 'Top P',\n });\n }\n\n if (data.useTopKInput) {\n inputs.push({\n id: 'topK' as PortId,\n dataType: 'number',\n title: 'Top K',\n });\n }\n\n return inputs;\n },\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'output' as PortId,\n dataType: 'string',\n title: 'Output',\n },\n ];\n },\n\n getEditors(): EditorDefinition<ChatHuggingFaceNode>[] {\n return [\n {\n type: 'string',\n label: 'Model',\n dataKey: 'model',\n useInputToggleDataKey: 'useModelInput',\n },\n {\n type: 'string',\n label: 'Endpoint',\n dataKey: 'endpoint',\n useInputToggleDataKey: 'useEndpointInput',\n },\n {\n type: 'number',\n label: 'Temperature (0-100)',\n dataKey: 'temperature',\n useInputToggleDataKey: 'useTemperatureInput',\n min: 0,\n step: 50,\n allowEmpty: true,\n },\n {\n type: 'number',\n label: 'Max New Tokens',\n dataKey: 'maxNewTokens',\n useInputToggleDataKey: 'useMaxNewTokensInput',\n min: 0,\n step: 1,\n },\n {\n type: 'toggle',\n label: 'Do Sample',\n dataKey: 'doSample',\n useInputToggleDataKey: 'useDoSampleInput',\n },\n {\n type: 'number',\n label: 'Max Time (s)',\n dataKey: 'maxTime',\n useInputToggleDataKey: 'useMaxTimeInput',\n allowEmpty: true,\n },\n {\n type: 'number',\n label: 'Repetition Penalty (0-100)',\n dataKey: 'repetitionPenalty',\n useInputToggleDataKey: 'useRepetitionPenaltyInput',\n allowEmpty: true,\n },\n {\n type: 'number',\n label: 'Top P (0-100)',\n dataKey: 'topP',\n useInputToggleDataKey: 'useTopPInput',\n allowEmpty: true,\n },\n {\n type: 'number',\n label: 'Top K (0-100)',\n dataKey: 'topK',\n useInputToggleDataKey: 'useTopKInput',\n allowEmpty: true,\n },\n ];\n },\n\n getBody(data): string | NodeBodySpec | NodeBodySpec[] | undefined {\n return dedent`\n ${\n data.endpoint || data.useEndpointInput\n ? `Endpoint: ${data.useEndpointInput ? '(Using Input)' : 'Yes'}`\n : `Model: ${data.useModelInput ? '(Using Input)' : data.model}`\n }\n ${\n data.useTemperatureInput\n ? 'Temperature: (Using Input)'\n : data.temperature != null\n ? `Temperature: ${data.temperature}`\n : ''\n }\n Max New Tokens: ${data.useMaxNewTokensInput ? '(Using Input)' : data.maxNewTokens}\n `;\n },\n\n async process(data, inputData, context): Promise<Outputs> {\n const accessToken = context.getPluginConfig('huggingFaceAccessToken');\n\n const prompt = coerceType(inputData['prompt' as PortId], 'string');\n const endpoint = getInputOrData(data, inputData, 'endpoint');\n\n const model = getInputOrData(data, inputData, 'model');\n const temperature = getInputOrData(data, inputData, 'temperature', 'number');\n const maxNewTokens = getInputOrData(data, inputData, 'maxNewTokens', 'number');\n const doSample = getInputOrData(data, inputData, 'doSample', 'boolean');\n const maxTime = getInputOrData(data, inputData, 'maxTime', 'number');\n const repetitionPenalty = getInputOrData(data, inputData, 'repetitionPenalty', 'number');\n const topP = getInputOrData(data, inputData, 'topP', 'number');\n const topK = getInputOrData(data, inputData, 'topK', 'number');\n\n const hf = endpoint ? new HfInferenceEndpoint(endpoint, accessToken) : new HfInference(accessToken);\n\n const generationStream = hf.textGenerationStream({\n inputs: prompt,\n model,\n parameters: {\n temperature,\n max_new_tokens: maxNewTokens,\n do_sample: doSample,\n max_time: maxTime,\n repetition_penalty: repetitionPenalty,\n top_p: topP,\n top_k: topK,\n },\n });\n\n const parts = [];\n\n for await (const { token } of generationStream) {\n if (!token.special) {\n parts.push(token.text);\n }\n\n context.onPartialOutputs?.({\n ['output' as PortId]: {\n type: 'string',\n value: parts.join(''),\n },\n });\n }\n\n return {\n ['output' as PortId]: {\n type: 'string',\n value: parts.join(''),\n },\n };\n },\n};\n\nexport const chatHuggingFaceNode = pluginNodeDefinition(ChatHuggingFaceNodeImpl, 'Chat (Hugging Face)');\n", "import { nanoid } from 'nanoid/non-secure';\nimport {\n type ChartNode,\n type EditorDefinition,\n type NodeBodySpec,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type NodeUIData,\n type Outputs,\n type PluginNodeImpl,\n type PortId,\n} from '../../../index.js';\nimport { HfInference, HfInferenceEndpoint } from '@huggingface/inference';\nimport { dedent } from 'ts-dedent';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { getInputOrData } from '../../../utils/inputs.js';\nimport { coerceType } from '../../../utils/coerceType.js';\n\nexport type TextToImageHuggingFaceNode = ChartNode<'textToImageHuggingFace', TextToImageHuggingFaceNodeData>;\n\nexport type TextToImageHuggingFaceNodeData = {\n model: string;\n useModelInput?: boolean;\n\n endpoint?: string;\n useEndpointInput?: boolean;\n\n width: number;\n useWidthInput?: boolean;\n\n height: number;\n useHeightInput?: boolean;\n\n negativePrompt?: string;\n useNegativePromptInput?: boolean;\n\n guidanceScale: number;\n useGuidanceScaleInput?: boolean;\n\n numInferenceSteps: number;\n useNumInferenceStepsInput?: boolean;\n};\n\nexport const TextToImageHuggingFaceNodeImpl: PluginNodeImpl<TextToImageHuggingFaceNode> = {\n create(): TextToImageHuggingFaceNode {\n return {\n id: nanoid() as NodeId,\n type: 'textToImageHuggingFace',\n data: {\n model: '',\n width: 256,\n height: 256,\n negativePrompt: '',\n guidanceScale: 7,\n numInferenceSteps: 3,\n },\n title: 'Text-to-Image (Hugging Face)',\n visualData: {\n x: 0,\n y: 0,\n width: 300,\n },\n };\n },\n\n getUIData(): NodeUIData {\n return {\n group: ['AI', 'Hugging Face'],\n contextMenuTitle: 'Text-to-Image (Hugging Face)',\n infoBoxTitle: 'Text-to-Image (Hugging Face) Node',\n infoBoxBody: 'Use the Hugging Face API to generate an image from text.',\n };\n },\n\n getInputDefinitions(data): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n\n inputs.push({\n id: 'prompt' as PortId,\n dataType: 'string',\n title: 'Prompt',\n required: true,\n });\n\n if (data.useModelInput) {\n inputs.push({\n id: 'model' as PortId,\n dataType: 'string',\n title: 'Model',\n });\n }\n\n if (data.useEndpointInput) {\n inputs.push({\n id: 'endpoint' as PortId,\n dataType: 'string',\n title: 'Endpoint',\n });\n }\n\n if (data.useWidthInput) {\n inputs.push({\n id: 'width' as PortId,\n dataType: 'number',\n title: 'Width',\n });\n }\n\n if (data.useHeightInput) {\n inputs.push({\n id: 'height' as PortId,\n dataType: 'number',\n title: 'Height',\n });\n }\n\n if (data.useNegativePromptInput) {\n inputs.push({\n id: 'negativePrompt' as PortId,\n dataType: 'string',\n title: 'Negative Prompt',\n });\n }\n\n if (data.useGuidanceScaleInput) {\n inputs.push({\n id: 'guidanceScale' as PortId,\n dataType: 'number',\n title: 'Guidance Scale',\n });\n }\n\n if (data.useNumInferenceStepsInput) {\n inputs.push({\n id: 'numInferenceSteps' as PortId,\n dataType: 'number',\n title: 'Num Inference Steps',\n });\n }\n\n return inputs;\n },\n\n getOutputDefinitions(): NodeOutputDefinition[] {\n return [\n {\n id: 'output' as PortId,\n dataType: 'string',\n title: 'Output',\n },\n ];\n },\n\n getEditors(): EditorDefinition<TextToImageHuggingFaceNode>[] {\n return [\n {\n type: 'string',\n label: 'Model',\n dataKey: 'model',\n useInputToggleDataKey: 'useModelInput',\n },\n {\n type: 'number',\n label: 'Width',\n dataKey: 'width',\n useInputToggleDataKey: 'useWidthInput',\n },\n {\n type: 'number',\n label: 'Height',\n dataKey: 'height',\n useInputToggleDataKey: 'useHeightInput',\n },\n {\n type: 'string',\n label: 'Negative Prompt',\n dataKey: 'negativePrompt',\n useInputToggleDataKey: 'useNegativePromptInput',\n },\n {\n type: 'number',\n label: 'Guidance Scale',\n dataKey: 'guidanceScale',\n useInputToggleDataKey: 'useGuidanceScaleInput',\n min: 0,\n max: 20,\n step: 1,\n },\n {\n type: 'number',\n label: 'Num Inference Steps',\n dataKey: 'numInferenceSteps',\n useInputToggleDataKey: 'useNumInferenceStepsInput',\n min: 0,\n max: 20,\n step: 1,\n },\n ];\n },\n\n getBody(data): string | NodeBodySpec | NodeBodySpec[] | undefined {\n return dedent`\n Model: ${data.useModelInput ? '(Using Input)' : data.model}\n `;\n },\n\n async process(data, inputData, context): Promise<Outputs> {\n const accessToken = context.getPluginConfig('huggingFaceAccessToken');\n\n const prompt = coerceType(inputData['prompt' as PortId], 'string');\n const endpoint = getInputOrData(data, inputData, 'endpoint');\n\n const model = getInputOrData(data, inputData, 'model');\n const width = getInputOrData(data, inputData, 'width', 'number');\n const height = getInputOrData(data, inputData, 'height', 'number');\n const negativePrompt = getInputOrData(data, inputData, 'negativePrompt') || undefined;\n const guidanceScale = getInputOrData(data, inputData, 'guidanceScale', 'number');\n const numInferenceSteps = getInputOrData(data, inputData, 'numInferenceSteps', 'number');\n\n const hf = endpoint ? new HfInferenceEndpoint(endpoint, accessToken) : new HfInference(accessToken);\n\n const image = await hf.textToImage({\n inputs: prompt,\n model,\n parameters: {\n width,\n height,\n negative_prompt: negativePrompt,\n guidance_scale: guidanceScale,\n num_inference_steps: numInferenceSteps,\n },\n });\n\n return {\n ['output' as PortId]: {\n type: 'image',\n value: {\n mediaType: 'image/png',\n data: new Uint8Array(await image.arrayBuffer()),\n },\n },\n };\n },\n};\n\nexport const textToImageHuggingFaceNode = pluginNodeDefinition(\n TextToImageHuggingFaceNodeImpl,\n 'Text-to-Image (Hugging Face)',\n);\n", "import { type RivetPlugin } from '../../index.js';\nimport { chatHuggingFaceNode } from './nodes/ChatHuggingFace.js';\nimport { textToImageHuggingFaceNode } from './nodes/TextToImageHuggingFace.js';\n\nexport const huggingFacePlugin: RivetPlugin = {\n id: 'huggingface',\n name: 'Hugging Face',\n\n configSpec: {\n huggingFaceAccessToken: {\n type: 'secret',\n label: 'Hugging Face Access Token',\n description: 'Your access token for the Hugging Face API.',\n pullEnvironmentVariable: 'HUGGING_FACE_ACCESS_TOKEN',\n helperText: 'Create at https://huggingface.co/settings/tokens',\n },\n },\n\n contextMenuGroups: [\n {\n id: 'huggingFace',\n label: 'Hugging Face',\n },\n ],\n\n register(register) {\n register(chatHuggingFaceNode);\n register(textToImageHuggingFaceNode);\n },\n};\n", "import {\n type ArrayDataValue,\n type DataValue,\n type ScalarDataValue,\n type Settings,\n type VectorDataValue,\n type VectorDatabase,\n} from '../../index.js';\nimport * as CryptoJS from 'crypto-js';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport class PineconeVectorDatabase implements VectorDatabase {\n readonly #apiKey;\n\n constructor(settings: Settings) {\n this.#apiKey = settings.pluginSettings?.pinecone?.pineconeApiKey as string | undefined;\n }\n\n async store(collection: DataValue, vector: VectorDataValue, data: DataValue, { id }: { id?: string }): Promise<void> {\n const collectionDetails = getCollection(coerceType(collection, 'string'));\n\n if (!id) {\n id = CryptoJS.SHA256(vector.value.join(',')).toString(CryptoJS.enc.Hex);\n }\n\n let metadata: Record<string, unknown> = {}\n if (data.type === 'object') {\n metadata = data.value;\n }\n else {\n metadata = { data: data.value };\n }\n\n const response = await fetch(`${collectionDetails.host}/vectors/upsert`, {\n method: 'POST',\n body: JSON.stringify({\n vectors: [\n {\n id,\n values: vector.value,\n metadata,\n },\n ],\n ...collectionDetails.options,\n }),\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'api-key': this.#apiKey!,\n },\n });\n\n if (response.status !== 200) {\n throw new Error(`Pinecone error: ${await response.text()}`);\n }\n }\n\n async nearestNeighbors(\n collection: DataValue,\n vector: VectorDataValue,\n k: number,\n ): Promise<ArrayDataValue<ScalarDataValue>> {\n const collectionDetails = getCollection(coerceType(collection, 'string'));\n\n const response = await fetch(`${collectionDetails.host}/query`, {\n method: 'POST',\n body: JSON.stringify({\n vector: vector.value,\n topK: k,\n includeMetadata: true,\n ...collectionDetails.options,\n }),\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'api-key': this.#apiKey!,\n },\n });\n\n if (response.status !== 200) {\n throw new Error(`Pinecone error: ${await response.text()}`);\n }\n\n const responseData = await response.json();\n\n const { matches } = responseData as {\n matches: {\n id: string;\n score: number;\n metadata: { data: unknown };\n }[];\n };\n\n return {\n type: 'object[]',\n value: matches.map(({ id, metadata }) => ({ id, data: metadata.data, metadata })),\n };\n }\n}\n\ninterface CollectionDetails {\n host: string;\n options: { [option: string]: any };\n}\n\nfunction getCollection(collectionString: string): CollectionDetails {\n let collectionURL: URL;\n\n if (!collectionString.startsWith('http://') && !collectionString.startsWith('https://')) {\n collectionString = `https://${collectionString}`;\n }\n\n try {\n collectionURL = new URL(collectionString);\n } catch (error) {\n throw new Error(`Incorrectly formatted Pinecone collection: ${error}`);\n }\n\n const host = `${collectionURL.protocol}//${collectionURL.host}`;\n const options: { [option: string]: any } = {};\n\n if (collectionURL.pathname !== '/') {\n // Chop off the leading slash.\n options.namespace = collectionURL.pathname.slice(1);\n }\n\n return { host, options };\n}\n", "import { type RivetPlugin } from '../../index.js';\nimport { PineconeVectorDatabase } from './PineconeVectorDatabase.js';\nimport { registerIntegration } from '../../integrations/integrations.js';\n\nexport const pineconePlugin: RivetPlugin = {\n id: 'pinecone',\n name: 'Pinecone',\n\n register: () => {\n registerIntegration('vectorDatabase', 'pinecone', (context) => new PineconeVectorDatabase(context.settings));\n },\n\n configSpec: {\n pineconeApiKey: {\n type: 'secret',\n label: 'Pinecone API Key',\n description: 'The API key for the Pinecone service.',\n pullEnvironmentVariable: 'PINECONE_API_KEY',\n helperText: 'You may also set the PINECONE_API_KEY environment variable.',\n },\n },\n};\n", "import { pineconePlugin } from './plugin.js';\n\nexport default pineconePlugin;\n", "import { Pipeline, StepRun, init, runTest, getPipelines } from '@gentrace/core';\n\nimport {\n type GraphId,\n type NativeApi,\n type NodeGraph,\n type Project,\n type Recording,\n type RivetPlugin,\n type SecretPluginConfigurationSpec,\n type Settings,\n} from '../../index.js';\nimport { mapValues } from 'lodash-es';\nimport { ExecutionRecorder } from '../../recording/ExecutionRecorder.js';\nimport { inferType } from '../../utils/coerceType.js';\nimport { GraphProcessor } from '../../model/GraphProcessor.js';\n\nconst apiKeyConfigSpec: SecretPluginConfigurationSpec = {\n type: 'secret',\n label: 'Gentrace API Key',\n description: 'The API key for the Gentrace service.',\n pullEnvironmentVariable: 'GENTRACE_API_KEY',\n helperText: 'Create at https://gentrace.ai/settings/api-keys',\n};\n\nfunction initializeGentrace(gentraceApiKey: string) {\n init({\n apiKey: gentraceApiKey,\n });\n}\n\nexport const runGentraceTests = async (\n gentracePipelineSlug: string,\n settings: Settings,\n project: Omit<Project, 'data'>,\n graph: NodeGraph,\n nativeApi: NativeApi,\n) => {\n const gentraceApiKey = settings.pluginSettings?.gentrace?.gentraceApiKey as string | undefined;\n\n if (!gentraceApiKey) {\n throw new Error('Gentrace API key not set.');\n }\n\n const graphId = graph.metadata?.id;\n\n if (!graphId) {\n throw new Error('Graph ID not set.');\n }\n\n initializeGentrace(gentraceApiKey);\n\n const response = await runTest(gentracePipelineSlug, async (testCase) => {\n const pipeline = new Pipeline({\n slug: gentracePipelineSlug,\n });\n\n const runner = pipeline.start();\n\n const rivetFormattedInputs = mapValues(testCase.inputs, inferType);\n\n const tempProject = {\n ...project,\n graphs: {\n ...project.graphs,\n [graph.metadata!.id!]: graph,\n },\n };\n\n const recorder = new ExecutionRecorder();\n const processor = new GraphProcessor(tempProject, graphId);\n processor.executor = 'browser';\n\n recorder.record(processor);\n await processor.processGraph(\n {\n settings,\n nativeApi,\n },\n rivetFormattedInputs,\n );\n\n const fullRecording = recorder.getRecording();\n\n const stepRuns = convertRecordingToStepRuns(fullRecording, project, graphId);\n\n stepRuns.forEach((stepRun) => {\n runner.addStepRunNode(stepRun);\n });\n\n if (stepRuns.length === 0) {\n throw new Error('No Rivet steps found. You need operations which are not Graph Input or Graph Output nodes.');\n }\n\n return ['', runner];\n });\n\n return response;\n};\n\nexport const runRemoteGentraceTests = async (\n gentracePipelineSlug: string,\n settings: Settings,\n project: Omit<Project, 'data'>,\n graph: NodeGraph,\n runAndRecord: (testCase: Record<string, any>) => Promise<Recording>,\n) => {\n const gentraceApiKey = settings.pluginSettings?.gentrace?.gentraceApiKey as string | undefined;\n\n if (!gentraceApiKey) {\n throw new Error('Gentrace API key not set.');\n }\n\n const graphId = graph.metadata?.id;\n\n if (!graphId) {\n throw new Error('Graph ID not set.');\n }\n\n initializeGentrace(gentraceApiKey);\n\n const response = await runTest(gentracePipelineSlug, async (testCase) => {\n const pipeline = new Pipeline({\n slug: gentracePipelineSlug,\n });\n\n const runner = pipeline.start();\n\n const rivetFormattedInputs = mapValues(testCase.inputs, inferType);\n\n const fullRecording = await runAndRecord(rivetFormattedInputs);\n const stepRuns = convertRecordingToStepRuns(fullRecording, project, graphId);\n\n stepRuns.forEach((stepRun) => {\n runner.addStepRunNode(stepRun);\n });\n\n if (stepRuns.length === 0) {\n throw new Error('No Rivet steps found. You need operations which are not Graph Input or Graph Output nodes.');\n }\n\n return ['', runner];\n });\n\n return response;\n};\n\ntype SimplifiedNode = {\n nodeId: string;\n start: number;\n end: number;\n modelParams: Record<string, any>;\n inputs: Record<string, any>;\n outputs: Record<string, any>;\n};\n\nfunction convertRecordingToStepRuns(recording: Recording, project: Omit<Project, 'data'>, graphId: GraphId): StepRun[] {\n const partialProcessStartEndPairs: {\n [processId: string]: Partial<SimplifiedNode>;\n } = {};\n\n recording.events.forEach((event) => {\n const eventType = event?.type;\n\n if (!eventType) {\n return;\n }\n\n if (eventType === 'nodeStart' || eventType === 'nodeFinish') {\n const processId = event?.data?.processId;\n const nodeId = event?.data?.nodeId;\n\n if (!processId) {\n return;\n }\n\n let existingPair = partialProcessStartEndPairs[processId];\n\n if (!existingPair) {\n existingPair = {};\n partialProcessStartEndPairs[processId] = existingPair;\n }\n\n existingPair.nodeId = nodeId;\n\n if (eventType === 'nodeStart') {\n existingPair.start = event.ts;\n existingPair.inputs = event.data.inputs;\n } else {\n existingPair.end = event.ts;\n existingPair.outputs = event.data.outputs;\n }\n }\n });\n\n const processStartEndPairs = partialProcessStartEndPairs as {\n [processId: string]: SimplifiedNode;\n };\n\n const selectedGraph = project.graphs[graphId];\n\n if (!selectedGraph) {\n return [];\n }\n\n // Convert to step runs\n const stepRuns: StepRun[] = [];\n\n for (const [, pair] of Object.entries(processStartEndPairs)) {\n const { nodeId } = pair;\n\n const relatedNode = selectedGraph.nodes.find((node) => node.id === nodeId);\n\n const nodeType = relatedNode?.type;\n\n if (!nodeType || !relatedNode.data || nodeType === 'graphInput' || nodeType === 'graphOutput') {\n continue;\n }\n\n const nodeData = relatedNode.data as Record<string, any>;\n\n if (relatedNode) {\n pair.modelParams = { ...nodeData, ...{ type: nodeType } };\n }\n\n if (nodeType === 'chat') {\n const modelName = nodeData.model ? nodeData.model : '';\n\n if (modelName.startsWith('gpt')) {\n // Convert to OpenAI Gentrace node\n const gentraceOpenAIInputs: Record<string, any> = { ...pair.inputs };\n\n gentraceOpenAIInputs.messages = [\n {\n content: pair.inputs.prompt.value,\n role: 'user',\n },\n ];\n\n const gentraceOpenAIModelParams: Record<string, any> = { ...pair.modelParams };\n\n gentraceOpenAIModelParams.model = modelName;\n\n gentraceOpenAIModelParams.frequency_penalty = pair.modelParams.frequencyPenalty || null;\n\n gentraceOpenAIModelParams.max_tokens = pair.modelParams.maxTokens || undefined;\n\n gentraceOpenAIModelParams.presence_penalty = pair.modelParams.presencePenalty || null;\n\n gentraceOpenAIModelParams.stop = pair.modelParams.stop || null;\n\n gentraceOpenAIModelParams.temperature = pair.modelParams.temperature || null;\n\n gentraceOpenAIModelParams.top_p = pair.modelParams.top_p || null;\n\n const gentraceOpenAIOutputs: Record<string, any> = { ...pair.outputs };\n\n const outputValues: string[] = Array.isArray(pair.outputs.response.value)\n ? pair.outputs.response.value\n : [pair.outputs.response.value];\n\n gentraceOpenAIOutputs.choices = outputValues.map((outputValue, index) => {\n return {\n index,\n message: {\n content: outputValue,\n role: 'assistant',\n },\n usage: {\n completion_tokens: pair.outputs.responseTokens.value,\n prompt_tokens: pair.outputs.requestTokens.value,\n total_tokens: pair.outputs.responseTokens.value + pair.outputs.requestTokens.value,\n },\n };\n });\n\n stepRuns.push(\n new StepRun(\n 'openai',\n 'openai_createChatCompletion',\n pair.end - pair.start,\n new Date(pair.start).toISOString(),\n new Date(pair.end).toISOString(),\n gentraceOpenAIInputs,\n gentraceOpenAIModelParams,\n gentraceOpenAIOutputs,\n {},\n ),\n );\n\n continue;\n }\n }\n\n stepRuns.push(\n new StepRun(\n 'rivet',\n nodeType ? `rivet_operation_${nodeType}` : 'rivet_operation',\n pair.end - pair.start,\n new Date(pair.start).toISOString(),\n new Date(pair.end).toISOString(),\n pair.inputs,\n pair.modelParams,\n pair.outputs,\n {},\n ),\n );\n }\n\n return stepRuns;\n}\n\nexport const getGentracePipelines = async (gentraceApiKey: string) => {\n initializeGentrace(gentraceApiKey);\n return await getPipelines();\n};\n\nexport const gentracePlugin: RivetPlugin = {\n id: 'gentrace',\n name: 'Gentrace',\n\n configSpec: {\n gentraceApiKey: apiKeyConfigSpec,\n },\n};\n", "import { gentracePlugin } from './plugin.js';\n\nexport default gentracePlugin;\n", "import {\n type ChartNode,\n type PluginNodeImpl,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type EditorDefinition,\n} from '../../../index.js';\nimport type { CreateMessageBody, CreateThreadBody, OpenAIThread } from '../../../utils/openai.js';\nimport { dedent, newId, coerceTypeOptional, getInputOrData } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\n\nexport type CreateThreadNode = ChartNode<'openaiCreateThread', CreateThreadNodeData>;\n\nexport type CreateThreadNodeData = {\n threadId?: string;\n useThreadIdInput?: boolean;\n\n metadata: { key: string; value: string }[];\n useMetadataInput?: boolean;\n};\n\nexport const CreateThreadNodeImpl: PluginNodeImpl<CreateThreadNode> = {\n create() {\n return {\n id: newId<NodeId>(),\n type: 'openaiCreateThread',\n data: {\n metadata: [],\n useMetadataInput: false,\n },\n title: 'Create Thread',\n visualData: {\n x: 0,\n y: 0,\n width: 225,\n },\n };\n },\n\n getUIData() {\n return {\n group: 'OpenAI',\n contextMenuTitle: 'Create Thread',\n infoBoxTitle: 'Create Thread Node',\n infoBoxBody: 'Create a new thread for OpenAI assistants.',\n };\n },\n\n getInputDefinitions(data) {\n const inputs: NodeInputDefinition[] = [];\n\n if (data.useThreadIdInput) {\n inputs.push({\n id: 'threadId' as PortId,\n dataType: 'string',\n title: 'Thread ID',\n coerced: true,\n defaultValue: '',\n description: 'The ID of the thread to modify. If not provided, a new thread will be created.',\n required: true,\n });\n }\n\n inputs.push({\n id: 'messages' as PortId,\n dataType: 'object[]',\n title: 'Messages',\n coerced: true,\n defaultValue: [],\n description: 'A list of user messages to start the thread with.',\n required: false,\n });\n\n if (data.useMetadataInput) {\n inputs.push({\n id: 'metadata' as PortId,\n dataType: 'object',\n title: 'Metadata',\n coerced: true,\n defaultValue: {},\n description: 'Metadata to attach to the thread.',\n required: false,\n });\n }\n\n return inputs;\n },\n\n getOutputDefinitions() {\n return [\n {\n id: 'threadId' as PortId,\n dataType: 'string',\n title: 'Thread ID',\n description: 'The ID of the created thread.',\n },\n {\n id: 'thread' as PortId,\n dataType: 'object',\n title: 'Thread',\n description: 'The full created thread object.',\n },\n ];\n },\n\n getEditors(): EditorDefinition<CreateThreadNode>[] {\n return [\n {\n type: 'keyValuePair',\n dataKey: 'metadata',\n useInputToggleDataKey: 'useMetadataInput',\n label: 'Metadata',\n keyPlaceholder: 'Key',\n valuePlaceholder: 'Value',\n },\n ];\n },\n\n getBody(data) {\n return dedent`\n ${data.threadId ? `Thread ID: ${data.threadId}` : 'Create New Thread'}\n ${\n data.useMetadataInput\n ? '(Metadata From Input)'\n : data.metadata.map(({ key, value }) => `${key}=${value}`).join(', ')\n }\n `;\n },\n\n async process(data, inputData, context) {\n const threadId = getInputOrData(data, inputData, 'threadId') ?? '';\n\n const messages = coerceTypeOptional(inputData['messages' as PortId], 'object[]') ?? [];\n\n let metadata: Record<string, string> = data.metadata.reduce(\n (acc, { key, value }) => {\n acc[key] = value;\n return acc;\n },\n {} as Record<string, string>,\n );\n\n if (data.useMetadataInput && inputData['metadata' as PortId]) {\n metadata = coerceTypeOptional(inputData['metadata' as PortId], 'object') as Record<string, string>;\n }\n\n if (!context.settings.openAiKey) {\n throw new Error('OpenAI key is not set.');\n }\n\n const messagesFormatted = messages.map((message): CreateMessageBody => {\n if (!('role' in message)) {\n throw new Error('Invalid message format.');\n }\n\n if (message.role !== 'user') {\n throw new Error('Only user messages are supported.');\n }\n\n return message as CreateMessageBody;\n });\n\n const url = threadId.trim() ? `https://api.openai.com/v1/threads/${threadId}` : 'https://api.openai.com/v1/threads';\n\n if (threadId && messages.length > 0) {\n throw new Error('Cannot provide messages when modifying an existing thread.');\n }\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n body: JSON.stringify(\n threadId.trim()\n ? { metadata }\n : ({\n messages: messagesFormatted,\n metadata,\n } satisfies CreateThreadBody),\n ),\n });\n\n if (!response.ok) {\n throw new Error('Failed to create thread.');\n }\n\n const body = (await response.json()) as OpenAIThread;\n\n return {\n ['threadId' as PortId]: {\n type: 'string',\n value: body.id,\n },\n ['thread' as PortId]: {\n type: 'object',\n value: body,\n },\n };\n },\n};\n\nexport const createThreadNode = pluginNodeDefinition(CreateThreadNodeImpl, 'Create Thread');\n", "import {\n type ChartNode,\n type PluginNodeImpl,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type EditorDefinition,\n} from '../../../index.js';\nimport type { OpenAIThread } from '../../../utils/openai.js';\nimport { newId, dedent } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\n\nexport type GetThreadNode = ChartNode<'openaiGetThread', GetThreadNodeData>;\n\nexport type GetThreadNodeData = {\n threadId: string;\n useThreadIdInput?: boolean;\n};\n\nexport const GetThreadNodeImpl: PluginNodeImpl<GetThreadNode> = {\n create() {\n return {\n id: newId<NodeId>(),\n type: 'openaiGetThread',\n data: {\n threadId: '',\n useThreadIdInput: true,\n },\n title: 'Get Thread',\n visualData: {\n x: 0,\n y: 0,\n width: 225,\n },\n };\n },\n\n getUIData() {\n return {\n group: 'OpenAI',\n contextMenuTitle: 'Get Thread',\n infoBoxTitle: 'Get Thread Node',\n infoBoxBody: 'Retrieve an existing thread from OpenAI assistants.',\n };\n },\n\n getInputDefinitions(data) {\n const inputs: NodeInputDefinition[] = [];\n\n if (data.useThreadIdInput) {\n inputs.push({\n id: 'threadId' as PortId,\n dataType: 'string',\n title: 'Thread ID',\n description: 'The ID of the thread to retrieve.',\n required: true,\n });\n }\n\n return inputs;\n },\n\n getOutputDefinitions() {\n return [\n {\n id: 'thread' as PortId,\n dataType: 'object',\n title: 'Thread',\n description:\n 'The retrieved thread object. If the thread does not exist, this port will not be ran. You can use an If node to test whether the thread exists.',\n },\n ];\n },\n\n getEditors(): EditorDefinition<GetThreadNode>[] {\n return [\n {\n type: 'string',\n dataKey: 'threadId',\n useInputToggleDataKey: 'useThreadIdInput',\n label: 'Thread ID',\n autoFocus: true,\n },\n ];\n },\n\n getBody(data) {\n return dedent`\n ${data.useThreadIdInput ? '(Thread ID from input)' : `Thread ID: ${data.threadId}`}\n `;\n },\n\n async process(data, inputData, context) {\n let threadId = data.threadId;\n\n if (data.useThreadIdInput) {\n threadId = inputData['threadId' as PortId]?.value as string;\n if (!threadId) {\n throw new Error('Thread ID is required.');\n }\n }\n\n if (!context.settings.openAiKey) {\n throw new Error('OpenAI key is not set.');\n }\n\n const response = await fetch(`https://api.openai.com/v1/threads/${threadId}`, {\n method: 'GET',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n });\n\n if (response.status === 404) {\n return {\n ['thread' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n if (!response.ok) {\n throw new Error('Failed to get thread.');\n }\n\n const body = (await response.json()) as OpenAIThread;\n\n return {\n ['thread' as PortId]: {\n type: 'object',\n value: body,\n },\n };\n },\n};\n\nexport const getThreadNode = pluginNodeDefinition(GetThreadNodeImpl, 'Get Thread');\n", "import {\n type ChartNode,\n type PluginNodeImpl,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n} from '../../../index.js';\nimport { newId, dedent, getInputOrData } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\n\nexport type DeleteThreadNode = ChartNode<'openaiDeleteThread', DeleteThreadNodeData>;\n\nexport type DeleteThreadNodeData = {\n threadId: string;\n useThreadIdInput?: boolean;\n};\n\nexport const DeleteThreadNodeImpl: PluginNodeImpl<DeleteThreadNode> = {\n create() {\n return {\n id: newId<NodeId>(),\n type: 'openaiDeleteThread',\n data: {\n threadId: '',\n useThreadIdInput: true,\n },\n title: 'Delete Thread',\n visualData: {\n x: 0,\n y: 0,\n width: 225,\n },\n };\n },\n\n getUIData() {\n return {\n group: 'OpenAI',\n contextMenuTitle: 'Delete Thread',\n infoBoxTitle: 'Delete Thread Node',\n infoBoxBody: 'Delete an existing thread from OpenAI assistants.',\n };\n },\n\n getInputDefinitions(data) {\n const inputs: NodeInputDefinition[] = [];\n\n if (data.useThreadIdInput) {\n inputs.push({\n id: 'threadId' as PortId,\n dataType: 'string',\n title: 'Thread ID',\n description: 'The ID of the thread to delete.',\n required: true,\n });\n }\n\n return inputs;\n },\n\n getOutputDefinitions() {\n return [\n {\n id: 'threadId' as PortId,\n dataType: 'string',\n title: 'Thread ID',\n description: 'The ID of the deleted thread.',\n },\n ];\n },\n\n getBody(data) {\n return dedent`\n ${data.useThreadIdInput ? '' : `Thread ID: ${data.threadId}`}\n `;\n },\n\n getEditors() {\n return [];\n },\n\n async process(data, inputData, context) {\n const threadId = getInputOrData(data, inputData, 'threadId');\n\n if (!threadId) {\n throw new Error('Thread ID is required.');\n }\n\n if (!context.settings.openAiKey) {\n throw new Error('OpenAI key is not set.');\n }\n\n const response = await fetch(`https://api.openai.com/v1/threads/${threadId}`, {\n method: 'DELETE',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n });\n\n if (response.status === 404) {\n return {\n ['threadId' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n if (!response.ok) {\n throw new Error('Failed to delete thread.');\n }\n\n // Return the threadId as output so that subsequent nodes can use it\n return {\n ['threadId' as PortId]: {\n type: 'string',\n value: threadId,\n },\n };\n },\n};\n\nexport const deleteThreadNode = pluginNodeDefinition(DeleteThreadNodeImpl, 'Delete Thread');\n", "export async function handleOpenAIError(response: Response) {\n if (!response.ok) {\n let errorBody: any;\n try {\n errorBody = await response.json();\n } catch (err) {\n throw new Error(`OpenAI request failed, no JSON body. Status code: ${response.status}`);\n }\n\n if (errorBody?.error?.message) {\n throw new Error(errorBody.error.message);\n } else {\n throw new Error(`OpenAI request failed with body. Status code: ${response.status}: ${JSON.stringify(errorBody)}`);\n }\n }\n}\n", "import {\n type ChartNode,\n type PluginNodeImpl,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type EditorDefinition,\n type GptFunction,\n} from '../../../index.js';\nimport { openAiModelOptions, type CreateAssistantBody, type OpenAIAssistantTool } from '../../../utils/openai.js';\nimport { dedent, newId, coerceTypeOptional, getInputOrData } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\n\nexport type CreateAssistantNode = ChartNode<'openaiCreateAssistant', CreateAssistantNodeData>;\n\nexport type CreateAssistantNodeData = {\n assistantId: string;\n useAssistantIdInput?: boolean;\n\n model?: string;\n useModelInput?: boolean;\n\n name?: string;\n useNameInput?: boolean;\n\n description?: string;\n useDescriptionInput?: boolean;\n\n instructions?: string;\n useInstructionsInput?: boolean;\n\n useCodeInterpreterTool?: boolean;\n useRetrievalTool?: boolean;\n functions?: GptFunction[];\n\n file_ids?: string[];\n useFileIdsInput?: boolean;\n\n metadata: { key: string; value: string }[];\n useMetadataInput?: boolean;\n};\n\nexport const CreateAssistantNodeImpl: PluginNodeImpl<CreateAssistantNode> = {\n create() {\n return {\n id: newId<NodeId>(),\n type: 'openaiCreateAssistant',\n data: {\n assistantId: '',\n useAssistantIdInput: false,\n model: '',\n useModelInput: false,\n name: '',\n useNameInput: false,\n description: '',\n useDescriptionInput: false,\n instructions: '',\n useInstructionsInput: false,\n tools: [],\n file_ids: [],\n useFileIdsInput: false,\n metadata: [],\n useMetadataInput: false,\n },\n title: 'Create Assistant',\n visualData: {\n x: 0,\n y: 0,\n width: 300,\n },\n };\n },\n\n getUIData() {\n return {\n group: 'OpenAI',\n contextMenuTitle: 'Create Assistant',\n infoBoxTitle: 'Create Assistant Node',\n infoBoxBody: 'Create a new assistant for OpenAI.',\n };\n },\n\n getInputDefinitions(data) {\n const inputs: NodeInputDefinition[] = [];\n\n if (data.useAssistantIdInput) {\n inputs.push({\n id: 'assistantId' as PortId,\n dataType: 'string',\n title: 'Assistant ID',\n coerced: true,\n defaultValue: '',\n description: 'The ID of the assistant to modify. Leave empty to create a new assistant.',\n });\n }\n\n if (data.useModelInput) {\n inputs.push({\n id: 'model' as PortId,\n dataType: 'string',\n title: 'Model',\n coerced: true,\n defaultValue: '',\n description: 'ID of the model to use.',\n required: false,\n });\n }\n\n if (data.useNameInput) {\n inputs.push({\n id: 'name' as PortId,\n dataType: 'string',\n title: 'Name',\n coerced: true,\n defaultValue: '',\n description: 'The name of the assistant.',\n required: false,\n });\n }\n\n if (data.useDescriptionInput) {\n inputs.push({\n id: 'description' as PortId,\n dataType: 'string',\n title: 'Description',\n coerced: true,\n defaultValue: '',\n description: 'The description of the assistant.',\n required: false,\n });\n }\n\n if (data.useInstructionsInput) {\n inputs.push({\n id: 'instructions' as PortId,\n dataType: 'string',\n title: 'Instructions',\n coerced: true,\n defaultValue: '',\n description: 'The system instructions that the assistant uses.',\n required: false,\n });\n }\n\n inputs.push({\n id: 'functions' as PortId,\n dataType: 'object[]',\n title: 'Functions',\n coerced: true,\n defaultValue: [],\n description: 'A list of GPT functions enabled on the assistant.',\n required: false,\n });\n\n if (data.useFileIdsInput) {\n inputs.push({\n id: 'file_ids' as PortId,\n dataType: 'string[]',\n title: 'File IDs',\n coerced: true,\n defaultValue: [],\n description: 'A list of file IDs attached to this assistant.',\n required: false,\n });\n }\n\n if (data.useMetadataInput) {\n inputs.push({\n id: 'metadata' as PortId,\n dataType: 'object',\n title: 'Metadata',\n coerced: true,\n defaultValue: {},\n description: 'Metadata to attach to the assistant.',\n required: false,\n });\n }\n\n return inputs;\n },\n\n getOutputDefinitions() {\n return [\n {\n id: 'assistantId' as PortId,\n dataType: 'string',\n title: 'Assistant ID',\n description: 'The ID of the created assistant.',\n },\n {\n id: 'assistant' as PortId,\n dataType: 'object',\n title: 'Assistant',\n description: 'The full created assistant object.',\n },\n ];\n },\n\n getEditors(): EditorDefinition<CreateAssistantNode>[] {\n return [\n {\n type: 'string',\n dataKey: 'assistantId',\n useInputToggleDataKey: 'useAssistantIdInput',\n label: 'Existing Assistant ID',\n placeholder: 'Existing assistant ID',\n helperMessage: 'Leave empty to create a new assistant.',\n },\n {\n type: 'dropdown',\n dataKey: 'model',\n useInputToggleDataKey: 'useModelInput',\n label: 'Model',\n options: openAiModelOptions,\n defaultValue: 'gpt-4-turbo',\n },\n {\n type: 'string',\n dataKey: 'name',\n useInputToggleDataKey: 'useNameInput',\n label: 'Name',\n placeholder: 'Enter assistant name',\n maxLength: 256,\n autoFocus: true,\n },\n {\n type: 'string',\n dataKey: 'description',\n useInputToggleDataKey: 'useDescriptionInput',\n label: 'Description',\n placeholder: 'Enter assistant description',\n maxLength: 512,\n },\n {\n type: 'code',\n dataKey: 'instructions',\n useInputToggleDataKey: 'useInstructionsInput',\n label: 'Instructions',\n language: 'markdown',\n },\n {\n type: 'toggle',\n dataKey: 'useCodeInterpreterTool',\n label: 'Code Interpreter Tool Enabled',\n },\n {\n type: 'toggle',\n dataKey: 'useRetrievalTool',\n label: 'Retrieval Tool Enabled',\n },\n {\n type: 'stringList',\n dataKey: 'file_ids',\n useInputToggleDataKey: 'useFileIdsInput',\n label: 'File IDs',\n },\n {\n type: 'keyValuePair',\n dataKey: 'metadata',\n useInputToggleDataKey: 'useMetadataInput',\n label: 'Metadata',\n keyPlaceholder: 'Key',\n valuePlaceholder: 'Value',\n },\n ];\n },\n\n getBody(data) {\n return dedent`\n Model: ${data.useModelInput ? '(Model From Input)' : data.model}\n Name: ${data.useNameInput ? '(Name From Input)' : data.name}\n Description: ${data.useDescriptionInput ? '(Description From Input)' : data.description}\n File IDs: ${data.useFileIdsInput ? '(File IDs From Input)' : JSON.stringify(data.file_ids)}\n Metadata: ${\n data.useMetadataInput\n ? '(Metadata From Input)'\n : data.metadata.map(({ key, value }) => `${key}=${value}`).join(', ')\n }\n\n ${data.useInstructionsInput ? '(Instructions From Input)' : data.instructions}\n `;\n },\n\n async process(data, inputData, context) {\n const assistantId = getInputOrData(data, inputData, 'assistantId');\n\n let metadata = data.metadata.reduce(\n (acc, { key, value }) => {\n acc[key] = value;\n return acc;\n },\n {} as Record<string, string>,\n );\n if (data.useMetadataInput && inputData['metadata' as PortId]) {\n metadata = coerceTypeOptional(inputData['metadata' as PortId], 'object') as Record<string, string>;\n }\n\n const functionTools = coerceTypeOptional(inputData['functions' as PortId], 'gpt-function[]');\n const tools = [...(functionTools?.map((f): OpenAIAssistantTool => ({ type: 'function', function: f })) ?? [])];\n if (data.useCodeInterpreterTool) {\n tools.push({ type: 'code_interpreter' });\n }\n if (data.useRetrievalTool) {\n tools.push({ type: 'retrieval' });\n }\n\n const requestBody: CreateAssistantBody = {\n model: getInputOrData(data, inputData, 'model'),\n name: getInputOrData(data, inputData, 'name'),\n description: getInputOrData(data, inputData, 'description'),\n instructions: getInputOrData(data, inputData, 'instructions'),\n tools,\n file_ids: getInputOrData(data, inputData, 'file_ids', 'string[]'),\n metadata,\n };\n\n if (!requestBody.model?.trim() || !requestBody.name?.trim()) {\n throw new Error('Model and name are required.');\n }\n\n if (!context.settings.openAiKey) {\n throw new Error('OpenAI key is not set.');\n }\n\n const url = assistantId.trim()\n ? `https://api.openai.com/v1/assistants/${assistantId}`\n : 'https://api.openai.com/v1/assistants';\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n body: JSON.stringify(requestBody),\n });\n\n await handleOpenAIError(response);\n\n const body = await response.json();\n\n return {\n ['assistantId' as PortId]: {\n type: 'string',\n value: body.id,\n },\n ['assistant' as PortId]: {\n type: 'object',\n value: body,\n },\n };\n },\n};\n\nexport const createAssistantNode = pluginNodeDefinition(CreateAssistantNodeImpl, 'Create Assistant');\n", "import {\n type ChartNode,\n type PluginNodeImpl,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type EditorDefinition,\n} from '../../../index.js';\nimport { newId, getInputOrData } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\n\nexport type GetAssistantNode = ChartNode<'openaiGetAssistant', GetAssistantNodeData>;\n\nexport type GetAssistantNodeData = {\n assistantId?: string;\n useAssistantIdInput?: boolean;\n};\n\nexport const GetAssistantNodeImpl: PluginNodeImpl<GetAssistantNode> = {\n create() {\n return {\n id: newId<NodeId>(),\n type: 'openaiGetAssistant',\n data: {\n assistantId: '',\n useAssistantIdInput: true,\n },\n title: 'Get Assistant',\n visualData: {\n x: 0,\n y: 0,\n width: 300,\n },\n };\n },\n\n getUIData() {\n return {\n group: 'OpenAI',\n contextMenuTitle: 'Get Assistant',\n infoBoxTitle: 'Get Assistant Node',\n infoBoxBody: 'Retrieve an assistant by its ID from OpenAI.',\n };\n },\n\n getInputDefinitions(data) {\n const inputs: NodeInputDefinition[] = [];\n\n if (data.useAssistantIdInput) {\n inputs.push({\n id: 'assistantId' as PortId,\n dataType: 'string',\n title: 'Assistant ID',\n coerced: true,\n defaultValue: '',\n description: 'The ID of the assistant to retrieve.',\n required: true,\n });\n }\n\n return inputs;\n },\n\n getOutputDefinitions() {\n return [\n {\n id: 'assistantId' as PortId,\n dataType: 'string',\n title: 'Assistant ID',\n description: 'The ID of the retrieved assistant.',\n },\n {\n id: 'assistant' as PortId,\n dataType: 'object',\n title: 'Assistant',\n description: 'The full retrieved assistant object.',\n },\n ];\n },\n\n getEditors(): EditorDefinition<GetAssistantNode>[] {\n return [\n {\n type: 'string',\n dataKey: 'assistantId',\n useInputToggleDataKey: 'useAssistantIdInput',\n label: 'Assistant ID',\n placeholder: 'Enter assistant ID',\n },\n ];\n },\n\n getBody(data) {\n return `Assistant ID: ${data.useAssistantIdInput ? '(Assistant ID From Input)' : data.assistantId}`;\n },\n\n async process(data, inputData, context) {\n const assistantId = getInputOrData(data, inputData, 'assistantId');\n\n if (!assistantId?.trim()) {\n throw new Error('Assistant ID is required.');\n }\n\n if (!context.settings.openAiKey) {\n throw new Error('OpenAI key is not set.');\n }\n\n const response = await fetch(`https://api.openai.com/v1/assistants/${assistantId}`, {\n method: 'GET',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n });\n\n if (response.status === 404) {\n return {\n ['assistantId' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n ['assistant' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n await handleOpenAIError(response);\n\n const body = await response.json();\n\n return {\n ['assistantId' as PortId]: {\n type: 'string',\n value: body.id,\n },\n ['assistant' as PortId]: {\n type: 'object',\n value: body,\n },\n };\n },\n};\n\nexport const getAssistantNode = pluginNodeDefinition(GetAssistantNodeImpl, 'Get Assistant');\n", "import {\n type ChartNode,\n type PluginNodeImpl,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type EditorDefinition,\n} from '../../../index.js';\nimport { newId, getInputOrData, dedent } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\nimport type { OpenAIAssistant, OpenAIListResponse, OpenAIPaginationQuery } from '../../../utils/openai.js';\n\nexport type ListAssistantsNode = ChartNode<'openaiListAssistants', ListAssistantsNodeData>;\n\nexport type ListAssistantsNodeData = {\n limit?: number;\n useLimitInput?: boolean;\n\n order?: string;\n useOrderInput?: boolean;\n\n after?: string;\n useAfterInput?: boolean;\n\n before?: string;\n useBeforeInput?: boolean;\n};\n\nexport const ListAssistantsNodeImpl: PluginNodeImpl<ListAssistantsNode> = {\n create() {\n return {\n id: newId<NodeId>(),\n type: 'openaiListAssistants',\n data: {\n limit: 20,\n useLimitInput: false,\n order: 'asc',\n useOrderInput: false,\n after: '',\n useAfterInput: false,\n before: '',\n useBeforeInput: false,\n },\n title: 'List Assistants',\n visualData: {\n x: 0,\n y: 0,\n width: 300,\n },\n };\n },\n\n getUIData() {\n return {\n group: 'OpenAI',\n contextMenuTitle: 'List Assistants',\n infoBoxTitle: 'List Assistants Node',\n infoBoxBody: 'List assistants from OpenAI.',\n };\n },\n\n getInputDefinitions(data) {\n const inputs: NodeInputDefinition[] = [];\n\n if (data.useLimitInput) {\n inputs.push({\n id: 'limit' as PortId,\n dataType: 'number',\n title: 'Limit',\n coerced: true,\n defaultValue: 20,\n description: 'A limit on the number of objects to be returned.',\n required: false,\n });\n }\n\n if (data.useOrderInput) {\n inputs.push({\n id: 'order' as PortId,\n dataType: 'string',\n title: 'Order',\n coerced: true,\n defaultValue: 'asc',\n description: 'Sort order by the created_at timestamp of the objects.',\n required: false,\n });\n }\n\n if (data.useAfterInput) {\n inputs.push({\n id: 'after' as PortId,\n dataType: 'string',\n title: 'After',\n coerced: true,\n defaultValue: '',\n description: 'A cursor for use in pagination.',\n required: false,\n });\n }\n\n if (data.useBeforeInput) {\n inputs.push({\n id: 'before' as PortId,\n dataType: 'string',\n title: 'Before',\n coerced: true,\n defaultValue: '',\n description: 'A cursor for use in pagination.',\n required: false,\n });\n }\n\n return inputs;\n },\n\n getOutputDefinitions() {\n return [\n {\n id: 'assistants' as PortId,\n dataType: 'object[]',\n title: 'Assistants',\n description: 'The list of assistants.',\n },\n {\n id: 'first_id' as PortId,\n dataType: 'string',\n title: 'First ID',\n description: 'The ID of the first assistant in the list.',\n },\n {\n id: 'last_id' as PortId,\n dataType: 'string',\n title: 'Last ID',\n description: 'The ID of the last assistant in the list.',\n },\n {\n id: 'has_more' as PortId,\n dataType: 'boolean',\n title: 'Has More',\n description: 'Whether there are more assistants to be retrieved.',\n },\n ];\n },\n\n getEditors(): EditorDefinition<ListAssistantsNode>[] {\n return [\n {\n type: 'number',\n dataKey: 'limit',\n useInputToggleDataKey: 'useLimitInput',\n label: 'Limit',\n defaultValue: 20,\n min: 1,\n max: 100,\n },\n {\n type: 'dropdown',\n dataKey: 'order',\n useInputToggleDataKey: 'useOrderInput',\n label: 'Order',\n options: [\n { value: 'asc', label: 'Ascending' },\n { value: 'desc', label: 'Descending' },\n ],\n defaultValue: 'asc',\n },\n {\n type: 'string',\n dataKey: 'after',\n useInputToggleDataKey: 'useAfterInput',\n label: 'After',\n placeholder: 'Enter after cursor',\n },\n {\n type: 'string',\n dataKey: 'before',\n useInputToggleDataKey: 'useBeforeInput',\n label: 'Before',\n placeholder: 'Enter before cursor',\n },\n ];\n },\n\n getBody(data) {\n return dedent`\n Limit: ${data.useLimitInput ? '(Limit From Input)' : data.limit}, ${\n data.useOrderInput ? '(Order From Input)' : data.order === 'asc' ? 'Ascending' : 'Descending'\n }\n${\n data.useAfterInput || data.after?.trim() ? `After: ${data.useAfterInput ? '(After From Input)' : data.after}\\n` : ''\n}${\n data.useBeforeInput || data.before?.trim()\n ? `Before: ${data.useBeforeInput ? '(Before From Input)' : data.before}\\n`\n : ''\n }\n `;\n },\n\n async process(data, inputData, context) {\n const requestQuery: OpenAIPaginationQuery = {\n limit: getInputOrData(data, inputData, 'limit', 'number').toString(),\n order: getInputOrData(data, inputData, 'order'),\n after: getInputOrData(data, inputData, 'after') || undefined, // Mutually exclusive with before, so set to undefined if empty string\n before: getInputOrData(data, inputData, 'before') || undefined,\n };\n\n const queryParams = Object.entries(requestQuery).filter(([, value]) => value !== undefined) as string[][];\n\n if (!context.settings.openAiKey) {\n throw new Error('OpenAI key is not set.');\n }\n\n const query = new URLSearchParams(queryParams);\n const url = `https://api.openai.com/v1/assistants?${query.toString()}`;\n\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n });\n\n await handleOpenAIError(response);\n\n const body = (await response.json()) as OpenAIListResponse<OpenAIAssistant>;\n\n return {\n ['assistants' as PortId]: {\n type: 'object[]',\n value: body.data,\n },\n ['first_id' as PortId]: {\n type: 'string',\n value: body.first_id,\n },\n ['last_id' as PortId]: {\n type: 'string',\n value: body.last_id,\n },\n ['has_more' as PortId]: {\n type: 'boolean',\n value: body.has_more,\n },\n };\n },\n};\n\nexport const listAssistantsNode = pluginNodeDefinition(ListAssistantsNodeImpl, 'List Assistants');\n", "import {\n type ChartNode,\n type PluginNodeImpl,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n} from '../../../index.js';\nimport { newId, dedent, getInputOrData } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\n\nexport type DeleteAssistantNode = ChartNode<'openaiDeleteAssistant', DeleteAssistantNodeData>;\n\nexport type DeleteAssistantNodeData = {\n assistantId: string;\n useAssistantIdInput?: boolean;\n};\n\nexport const DeleteAssistantNodeImpl: PluginNodeImpl<DeleteAssistantNode> = {\n create() {\n return {\n id: newId<NodeId>(),\n type: 'openaiDeleteAssistant',\n data: {\n assistantId: '',\n useAssistantIdInput: true,\n },\n title: 'Delete Assistant',\n visualData: {\n x: 0,\n y: 0,\n width: 275,\n },\n };\n },\n\n getUIData() {\n return {\n group: 'OpenAI',\n contextMenuTitle: 'Delete Assistant',\n infoBoxTitle: 'Delete Assistant Node',\n infoBoxBody: 'Delete an existing assistant from OpenAI.',\n };\n },\n\n getInputDefinitions(data) {\n const inputs: NodeInputDefinition[] = [];\n\n if (data.useAssistantIdInput) {\n inputs.push({\n id: 'assistantId' as PortId,\n dataType: 'string',\n title: 'Assistant ID',\n description: 'The ID of the assistant to delete.',\n required: true,\n });\n }\n\n return inputs;\n },\n\n getOutputDefinitions() {\n return [\n {\n id: 'assistantId' as PortId,\n dataType: 'string',\n title: 'Assistant ID',\n description: 'The ID of the deleted assistant.',\n },\n ];\n },\n\n getBody(data) {\n return dedent`\n ${data.useAssistantIdInput ? '' : `Assistant ID: ${data.assistantId}`}\n `;\n },\n\n getEditors() {\n return [\n {\n type: 'string',\n dataKey: 'assistantId',\n useInputToggleDataKey: 'useAssistantIdInput',\n label: 'Assistant ID',\n placeholder: 'Enter assistant ID',\n },\n ];\n },\n\n async process(data, inputData, context) {\n const assistantId = getInputOrData(data, inputData, 'assistantId');\n\n if (!assistantId) {\n throw new Error('Assistant ID is required.');\n }\n\n if (!context.settings.openAiKey) {\n throw new Error('OpenAI key is not set.');\n }\n\n const response = await fetch(`https://api.openai.com/v1/assistants/${assistantId}`, {\n method: 'DELETE',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n });\n\n if (response.status === 404) {\n return {\n ['assistantId' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n await handleOpenAIError(response);\n\n // Return the assistantId as output so that subsequent nodes can use it\n return {\n ['assistantId' as PortId]: {\n type: 'string',\n value: assistantId,\n },\n };\n },\n};\n\nexport const deleteAssistantNode = pluginNodeDefinition(DeleteAssistantNodeImpl, 'Delete Assistant');\n", "import {\n type ChartNode,\n type PluginNodeImpl,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type EditorDefinition,\n} from '../../../index.js';\nimport { newId, dedent, getInputOrData, coerceType, coerceTypeOptional } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\nimport { openAIFileUploadPurposeOptions } from '../../../utils/openai.js';\n\nexport type UploadFileNode = ChartNode<'openaiUploadFile', UploadFileNodeData>;\n\nexport type UploadFileNodeData = {\n purpose: 'fine-tune' | 'assistants' | 'assistants_output';\n};\n\nexport const UploadFileNodeImpl: PluginNodeImpl<UploadFileNode> = {\n create() {\n return {\n id: newId<NodeId>(),\n type: 'openaiUploadFile',\n data: {\n purpose: 'assistants',\n },\n title: 'Upload File to OpenAI',\n visualData: {\n x: 0,\n y: 0,\n width: 300,\n },\n };\n },\n\n getUIData() {\n return {\n group: 'OpenAI',\n contextMenuTitle: 'Upload File to OpenAI',\n infoBoxTitle: 'Upload File to OpenAI Node',\n infoBoxBody: 'Upload a file to OpenAI.',\n };\n },\n\n getInputDefinitions() {\n const inputs: NodeInputDefinition[] = [];\n\n inputs.push({\n id: 'data' as PortId,\n dataType: 'binary',\n title: 'Data',\n coerced: true,\n defaultValue: '',\n description: 'The binary data of the file to upload.',\n required: true,\n });\n\n inputs.push({\n id: 'file-name' as PortId,\n dataType: 'string',\n title: 'File Name',\n coerced: true,\n description: 'An optional file name to use for the uploaded file.',\n required: false,\n });\n\n return inputs;\n },\n\n getOutputDefinitions() {\n return [\n {\n id: 'fileId' as PortId,\n dataType: 'string',\n title: 'File ID',\n description: 'The ID of the uploaded file.',\n },\n {\n id: 'file' as PortId,\n dataType: 'object',\n title: 'File',\n description: 'The full uploaded file object.',\n },\n ];\n },\n\n getEditors(): EditorDefinition<UploadFileNode>[] {\n return [\n {\n type: 'dropdown',\n dataKey: 'purpose',\n label: 'Purpose',\n options: openAIFileUploadPurposeOptions,\n defaultValue: 'assistants',\n },\n ];\n },\n\n getBody(data) {\n return dedent`\n Purpose: ${openAIFileUploadPurposeOptions.find(({ value }) => value === data.purpose)?.label ?? 'Unknown'}\n `;\n },\n\n async process(data, inputData, context) {\n const purpose = getInputOrData(data, inputData, 'purpose');\n const fileData = coerceType(inputData['data' as PortId], 'binary');\n const fileName = coerceTypeOptional(inputData['file-name' as PortId], 'string');\n\n if (!fileData) {\n throw new Error('File data is required.');\n }\n\n if (!context.settings.openAiKey) {\n throw new Error('OpenAI key is not set.');\n }\n\n const file = fileName\n ? new File([fileData], fileName, { type: 'application/octet-stream' })\n : new Blob([fileData], { type: 'application/octet-stream' });\n\n const formData = new FormData();\n formData.append('purpose', purpose);\n formData.append('file', file);\n\n const response = await fetch('https://api.openai.com/v1/files', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n body: formData,\n });\n\n await handleOpenAIError(response);\n\n const body = await response.json();\n\n return {\n ['fileId' as PortId]: {\n type: 'string',\n value: body.id,\n },\n ['file' as PortId]: {\n type: 'object',\n value: body,\n },\n };\n },\n};\n\nexport const uploadFileNode = pluginNodeDefinition(UploadFileNodeImpl, 'Upload File to OpenAI');\n", "import {\n type ChartNode,\n type PluginNodeImpl,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type EditorDefinition,\n} from '../../../index.js';\nimport { newId, getInputOrData, dedent } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\nimport { openAIFilePurposeOptions, type OpenAIFile } from '../../../utils/openai.js';\n\nexport type ListOpenAIFilesNode = ChartNode<'openaiListFiles', ListOpenAIFilesNodeData>;\n\nexport type ListOpenAIFilesNodeData = {\n purpose?: 'fine-tune' | 'fine-tune-results' | 'assistants' | 'assistants_output';\n usePurposeInput?: boolean;\n};\n\nexport const ListOpenAIFilesNodeImpl: PluginNodeImpl<ListOpenAIFilesNode> = {\n create() {\n return {\n id: newId<NodeId>(),\n type: 'openaiListFiles',\n data: {\n purpose: 'assistants',\n },\n title: 'List OpenAI Files',\n visualData: {\n x: 0,\n y: 0,\n width: 300,\n },\n };\n },\n\n getUIData() {\n return {\n group: 'OpenAI',\n contextMenuTitle: 'List OpenAI Files',\n infoBoxTitle: 'List OpenAI Files Node',\n infoBoxBody: 'List files from OpenAI.',\n };\n },\n\n getInputDefinitions(data) {\n const inputs: NodeInputDefinition[] = [];\n\n if (data.usePurposeInput) {\n inputs.push({\n id: 'purpose' as PortId,\n dataType: 'string',\n title: 'Purpose',\n coerced: true,\n defaultValue: '',\n description: 'Retrieve only files with the specified purpose.',\n });\n }\n\n return inputs;\n },\n\n getOutputDefinitions() {\n return [\n {\n id: 'files' as PortId,\n dataType: 'object[]',\n title: 'Files',\n description: 'The list of files.',\n },\n ];\n },\n\n getEditors(): EditorDefinition<ListOpenAIFilesNode>[] {\n return [\n {\n type: 'dropdown',\n dataKey: 'purpose',\n useInputToggleDataKey: 'usePurposeInput',\n label: 'Purpose',\n options: openAIFilePurposeOptions,\n defaultValue: 'assistants',\n },\n ];\n },\n\n getBody(data) {\n return dedent`\n Purpose: ${openAIFilePurposeOptions.find(({ value }) => value === data.purpose)?.label ?? 'Unknown'}\n `;\n },\n\n async process(data, inputData, context) {\n const purpose = getInputOrData(data, inputData, 'purpose');\n\n if (!context.settings.openAiKey) {\n throw new Error('OpenAI key is not set.');\n }\n\n const url = `https://api.openai.com/v1/files?purpose=${purpose}`;\n\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n });\n\n await handleOpenAIError(response);\n\n const body = (await response.json()) as {\n object: 'list';\n data: OpenAIFile[];\n };\n\n return {\n ['files' as PortId]: {\n type: 'object[]',\n value: body.data,\n },\n };\n },\n};\n\nexport const listOpenAIFilesNode = pluginNodeDefinition(ListOpenAIFilesNodeImpl, 'List OpenAI Files');\n", "import {\n type ChartNode,\n type PluginNodeImpl,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type EditorDefinition,\n} from '../../../index.js';\nimport { newId, getInputOrData, dedent } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\n\nexport type GetOpenAIFileNode = ChartNode<'openaiGetFile', GetOpenAIFileNodeData>;\n\nexport type GetOpenAIFileNodeData = {\n fileId?: string;\n useFileIdInput?: boolean;\n};\n\nexport const GetOpenAIFileNodeImpl: PluginNodeImpl<GetOpenAIFileNode> = {\n create() {\n return {\n id: newId<NodeId>(),\n type: 'openaiGetFile',\n data: {\n useFileIdInput: true,\n },\n title: 'Get OpenAI File',\n visualData: {\n x: 0,\n y: 0,\n width: 300,\n },\n };\n },\n\n getUIData() {\n return {\n group: 'OpenAI',\n contextMenuTitle: 'Get OpenAI File',\n infoBoxTitle: 'Get OpenAI File Node',\n infoBoxBody: 'Get a specific file from OpenAI.',\n };\n },\n\n getInputDefinitions(data) {\n const inputs: NodeInputDefinition[] = [];\n\n if (data.useFileIdInput) {\n inputs.push({\n id: 'fileId' as PortId,\n dataType: 'string',\n title: 'File ID',\n coerced: true,\n defaultValue: '',\n description: 'The ID of the file to retrieve.',\n required: true,\n });\n }\n\n return inputs;\n },\n\n getOutputDefinitions() {\n return [\n {\n id: 'file' as PortId,\n dataType: 'object',\n title: 'File',\n description: 'The retrieved file object.',\n },\n ];\n },\n\n getEditors(): EditorDefinition<GetOpenAIFileNode>[] {\n return [\n {\n type: 'string',\n dataKey: 'fileId',\n useInputToggleDataKey: 'useFileIdInput',\n label: 'File ID',\n },\n ];\n },\n\n getBody(data) {\n return dedent`\n File ID: ${data.fileId ?? 'Unknown'}\n `;\n },\n\n async process(data, inputData, context) {\n const fileId = getInputOrData(data, inputData, 'fileId');\n\n if (!context.settings.openAiKey) {\n throw new Error('OpenAI key is not set.');\n }\n\n const url = `https://api.openai.com/v1/files/${fileId}`;\n\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n });\n\n if (response.status === 404) {\n return {\n ['file' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n await handleOpenAIError(response);\n\n const body = await response.json();\n\n return {\n ['file' as PortId]: {\n type: 'object',\n value: body,\n },\n };\n },\n};\n\nexport const getOpenAIFileNode = pluginNodeDefinition(GetOpenAIFileNodeImpl, 'Get OpenAI File');\n", "import {\n type ChartNode,\n type PluginNodeImpl,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type EditorDefinition,\n} from '../../../index.js';\nimport type { OpenAIAssistantFile, OpenAIFile } from '../../../utils/openai.js';\nimport { dedent, newId, getInputOrData } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\n\nexport type AttachAssistantFileNode = ChartNode<'openaiAttachAssistantFile', AttachAssistantFileNodeData>;\n\nexport type AttachAssistantFileNodeData = {\n assistantId?: string;\n useAssistantIdInput?: boolean;\n fileId?: string;\n useFileIdInput?: boolean;\n};\n\nexport const AttachAssistantFileNodeImpl: PluginNodeImpl<AttachAssistantFileNode> = {\n create() {\n return {\n id: newId<NodeId>(),\n type: 'openaiAttachAssistantFile',\n data: {\n useAssistantIdInput: true,\n useFileIdInput: true,\n },\n title: 'Attach Assistant File',\n visualData: {\n x: 0,\n y: 0,\n width: 225,\n },\n };\n },\n\n getUIData() {\n return {\n group: 'OpenAI',\n contextMenuTitle: 'Attach Assistant File',\n infoBoxTitle: 'Attach Assistant File Node',\n infoBoxBody: 'Attach a file to an OpenAI assistant.',\n };\n },\n\n getInputDefinitions(data) {\n const inputs: NodeInputDefinition[] = [];\n\n if (data.useAssistantIdInput) {\n inputs.push({\n id: 'assistantId' as PortId,\n dataType: 'string',\n title: 'Assistant ID',\n coerced: true,\n defaultValue: '',\n description: 'The ID of the assistant to attach the file to.',\n required: true,\n });\n }\n\n if (data.useFileIdInput) {\n inputs.push({\n id: 'fileId' as PortId,\n dataType: 'string',\n title: 'File ID',\n coerced: true,\n defaultValue: '',\n description: 'The ID of the file to attach.',\n required: true,\n });\n }\n\n return inputs;\n },\n\n getOutputDefinitions() {\n return [\n {\n id: 'fileId' as PortId,\n dataType: 'string',\n title: 'File ID',\n description: 'The ID of the attached file.',\n },\n ];\n },\n\n getEditors(): EditorDefinition<AttachAssistantFileNode>[] {\n return [\n {\n type: 'string',\n dataKey: 'assistantId',\n useInputToggleDataKey: 'useAssistantIdInput',\n label: 'Assistant ID',\n },\n {\n type: 'string',\n dataKey: 'fileId',\n useInputToggleDataKey: 'useFileIdInput',\n label: 'File ID',\n },\n ];\n },\n\n getBody(data) {\n return dedent`\n Assistant ID: ${data.useAssistantIdInput ? '(From Input)' : data.assistantId}\n File ID: ${data.useFileIdInput ? '(From Input)' : data.fileId}\n `;\n },\n\n async process(data, inputData, context) {\n const assistantId = getInputOrData(data, inputData, 'assistantId');\n const fileId = getInputOrData(data, inputData, 'fileId');\n\n if (!context.settings.openAiKey) {\n throw new Error('OpenAI key is not set.');\n }\n\n const url = `https://api.openai.com/v1/assistants/${assistantId}/files`;\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n body: JSON.stringify({ file_id: fileId }),\n });\n\n if (response.status === 404) {\n return {\n ['fileId' as PortId]: {\n type: 'control-flow-excluded',\n value: undefined,\n },\n };\n }\n\n await handleOpenAIError(response);\n\n const body = (await response.json()) as OpenAIAssistantFile;\n\n return {\n ['fileId' as PortId]: {\n type: 'string',\n value: body.id,\n },\n };\n },\n};\n\nexport const attachAssistantFileNode = pluginNodeDefinition(AttachAssistantFileNodeImpl, 'Attach Assistant File');\n", "import {\n type ChartNode,\n type PluginNodeImpl,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type EditorDefinition,\n} from '../../../index.js';\nimport type { CreateMessageBody, OpenAIThreadMessage } from '../../../utils/openai.js';\nimport { dedent, newId, coerceTypeOptional, getInputOrData } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\n\nexport type CreateThreadMessageNode = ChartNode<'openaiCreateThreadMessage', CreateThreadMessageNodeData>;\n\nexport type CreateThreadMessageNodeData = {\n threadId: string;\n useThreadIdInput?: boolean;\n\n file_ids: string[];\n useFileIdsInput?: boolean;\n\n metadata: { key: string; value: string }[];\n useMetadataInput?: boolean;\n};\n\nexport const CreateThreadMessageNodeImpl: PluginNodeImpl<CreateThreadMessageNode> = {\n create() {\n return {\n id: newId<NodeId>(),\n type: 'openaiCreateThreadMessage',\n data: {\n threadId: '',\n useThreadIdInput: true,\n file_ids: [],\n useFileIdsInput: false,\n metadata: [],\n useMetadataInput: false,\n },\n title: 'Create Thread Message',\n visualData: {\n x: 0,\n y: 0,\n width: 300,\n },\n };\n },\n\n getUIData() {\n return {\n group: 'OpenAI',\n contextMenuTitle: 'Create Thread Message',\n infoBoxTitle: 'Create Thread Message Node',\n infoBoxBody: 'Create a new message for an OpenAI thread.',\n };\n },\n\n getInputDefinitions(data) {\n const inputs: NodeInputDefinition[] = [];\n\n inputs.push({\n id: 'content' as PortId,\n dataType: 'string',\n title: 'Content',\n coerced: true,\n defaultValue: '',\n description: 'The content of the message.',\n });\n\n if (data.useThreadIdInput) {\n inputs.push({\n id: 'threadId' as PortId,\n dataType: 'string',\n title: 'Thread ID',\n coerced: true,\n defaultValue: '',\n description: 'The ID of the thread to post the message to.',\n required: true,\n });\n }\n\n if (data.useFileIdsInput) {\n inputs.push({\n id: 'file_ids' as PortId,\n dataType: 'string[]',\n title: 'File IDs',\n coerced: true,\n defaultValue: [],\n description: 'A list of file IDs attached to this message.',\n required: false,\n });\n }\n\n if (data.useMetadataInput) {\n inputs.push({\n id: 'metadata' as PortId,\n dataType: 'object',\n title: 'Metadata',\n coerced: true,\n defaultValue: {},\n description: 'Metadata to attach to the message.',\n required: false,\n });\n }\n\n return inputs;\n },\n\n getOutputDefinitions() {\n return [\n {\n id: 'messageId' as PortId,\n dataType: 'string',\n title: 'Message ID',\n description: 'The ID of the created message.',\n },\n {\n id: 'message' as PortId,\n dataType: 'object',\n title: 'Message',\n description: 'The full created message object.',\n },\n ];\n },\n\n getEditors(): EditorDefinition<CreateThreadMessageNode>[] {\n return [\n {\n type: 'string',\n dataKey: 'threadId',\n useInputToggleDataKey: 'useThreadIdInput',\n label: 'Thread ID',\n placeholder: 'Enter thread ID',\n helperMessage: 'The ID of the thread to post the message to.',\n },\n {\n type: 'stringList',\n dataKey: 'file_ids',\n useInputToggleDataKey: 'useFileIdsInput',\n label: 'File IDs',\n },\n {\n type: 'keyValuePair',\n dataKey: 'metadata',\n useInputToggleDataKey: 'useMetadataInput',\n label: 'Metadata',\n keyPlaceholder: 'Key',\n valuePlaceholder: 'Value',\n },\n ];\n },\n\n getBody(data) {\n return dedent`\n Thread ID: ${data.useThreadIdInput ? '(Thread ID From Input)' : data.threadId}${\n data.useFileIdsInput || data.file_ids.length > 0\n ? `File IDs: ${data.useFileIdsInput ? '(File IDs From Input)' : JSON.stringify(data.file_ids)}\\n`\n : ''\n }${\n data.useMetadataInput || data.metadata.length > 0\n ? `Metadata: ${\n data.useMetadataInput\n ? '(Metadata From Input)'\n : data.metadata.map(({ key, value }) => `${key}=${value}`).join(', ')\n }\\n`\n : ''\n }\n `;\n },\n\n async process(data, inputData, context) {\n const threadId = getInputOrData(data, inputData, 'threadId');\n const content = coerceTypeOptional(inputData['content' as PortId], 'string') ?? '';\n\n let metadata = data.metadata.reduce(\n (acc, { key, value }) => {\n acc[key] = value;\n return acc;\n },\n {} as Record<string, string>,\n );\n if (data.useMetadataInput && inputData['metadata' as PortId]) {\n metadata = coerceTypeOptional(inputData['metadata' as PortId], 'object') as Record<string, string>;\n }\n\n const requestBody: CreateMessageBody = {\n role: 'user',\n content,\n file_ids: getInputOrData(data, inputData, 'file_ids', 'string[]'),\n metadata,\n };\n\n if (!context.settings.openAiKey) {\n throw new Error('OpenAI key is not set.');\n }\n\n const url = `https://api.openai.com/v1/threads/${threadId}/messages`;\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n body: JSON.stringify(requestBody),\n });\n\n await handleOpenAIError(response);\n\n const body = (await response.json()) as OpenAIThreadMessage;\n\n return {\n ['messageId' as PortId]: {\n type: 'string',\n value: body.id,\n },\n ['message' as PortId]: {\n type: 'object',\n value: body,\n },\n };\n },\n};\n\nexport const createThreadMessageNode = pluginNodeDefinition(CreateThreadMessageNodeImpl, 'Create Thread Message');\n", "import {\n type ChartNode,\n type PluginNodeImpl,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type EditorDefinition,\n} from '../../../index.js';\nimport { newId, getInputOrData, dedent } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\nimport type { ListThreadMessagesQuery, OpenAIListResponse, OpenAIThreadMessage } from '../../../utils/openai.js';\n\nexport type ListThreadMessagesNode = ChartNode<'openaiListThreadMessages', ListThreadMessagesNodeData>;\n\nexport type ListThreadMessagesNodeData = {\n threadId: string;\n useThreadIdInput?: boolean;\n\n limit?: number;\n useLimitInput?: boolean;\n\n order?: string;\n useOrderInput?: boolean;\n\n after?: string;\n useAfterInput?: boolean;\n\n before?: string;\n useBeforeInput?: boolean;\n};\n\nexport const ListThreadMessagesNodeImpl: PluginNodeImpl<ListThreadMessagesNode> = {\n create() {\n return {\n id: newId<NodeId>(),\n type: 'openaiListThreadMessages',\n data: {\n threadId: '',\n useThreadIdInput: true,\n limit: 20,\n useLimitInput: false,\n order: 'asc',\n useOrderInput: false,\n after: '',\n useAfterInput: false,\n before: '',\n useBeforeInput: false,\n },\n title: 'List Thread Messages',\n visualData: {\n x: 0,\n y: 0,\n width: 300,\n },\n };\n },\n\n getUIData() {\n return {\n group: 'OpenAI',\n contextMenuTitle: 'List Thread Messages',\n infoBoxTitle: 'List Thread Messages Node',\n infoBoxBody: 'List messages from a thread in OpenAI.',\n };\n },\n\n getInputDefinitions(data) {\n const inputs: NodeInputDefinition[] = [];\n\n if (data.useThreadIdInput) {\n inputs.push({\n id: 'threadId' as PortId,\n dataType: 'string',\n title: 'Thread ID',\n coerced: true,\n defaultValue: '',\n description: 'The ID of the thread to retrieve messages from.',\n required: true,\n });\n }\n\n if (data.useLimitInput) {\n inputs.push({\n id: 'limit' as PortId,\n dataType: 'number',\n title: 'Limit',\n coerced: true,\n defaultValue: 20,\n description: 'A limit on the number of objects to be returned.',\n required: false,\n });\n }\n\n if (data.useOrderInput) {\n inputs.push({\n id: 'order' as PortId,\n dataType: 'string',\n title: 'Order',\n coerced: true,\n defaultValue: 'asc',\n description: 'Sort order by the created_at timestamp of the objects.',\n required: false,\n });\n }\n\n if (data.useAfterInput) {\n inputs.push({\n id: 'after' as PortId,\n dataType: 'string',\n title: 'After',\n coerced: true,\n defaultValue: '',\n description: 'A cursor for use in pagination.',\n required: false,\n });\n }\n\n if (data.useBeforeInput) {\n inputs.push({\n id: 'before' as PortId,\n dataType: 'string',\n title: 'Before',\n coerced: true,\n defaultValue: '',\n description: 'A cursor for use in pagination.',\n required: false,\n });\n }\n\n return inputs;\n },\n\n getOutputDefinitions() {\n return [\n {\n id: 'messages' as PortId,\n dataType: 'object[]',\n title: 'Messages',\n description: 'The list of messages.',\n },\n {\n id: 'first_id' as PortId,\n dataType: 'string',\n title: 'First ID',\n description: 'The ID of the first message in the list.',\n },\n {\n id: 'last_id' as PortId,\n dataType: 'string',\n title: 'Last ID',\n description: 'The ID of the last message in the list.',\n },\n {\n id: 'has_more' as PortId,\n dataType: 'boolean',\n title: 'Has More',\n description: 'Whether there are more messages to be retrieved.',\n },\n ];\n },\n\n getEditors(): EditorDefinition<ListThreadMessagesNode>[] {\n return [\n {\n type: 'string',\n dataKey: 'threadId',\n useInputToggleDataKey: 'useThreadIdInput',\n label: 'Thread ID',\n placeholder: 'Enter thread ID',\n },\n {\n type: 'number',\n dataKey: 'limit',\n useInputToggleDataKey: 'useLimitInput',\n label: 'Limit',\n defaultValue: 20,\n min: 1,\n max: 100,\n },\n {\n type: 'dropdown',\n dataKey: 'order',\n useInputToggleDataKey: 'useOrderInput',\n label: 'Order',\n options: [\n { value: 'asc', label: 'Ascending' },\n { value: 'desc', label: 'Descending' },\n ],\n defaultValue: 'asc',\n },\n {\n type: 'string',\n dataKey: 'after',\n useInputToggleDataKey: 'useAfterInput',\n label: 'After',\n placeholder: 'Enter after cursor',\n },\n {\n type: 'string',\n dataKey: 'before',\n useInputToggleDataKey: 'useBeforeInput',\n label: 'Before',\n placeholder: 'Enter before cursor',\n },\n ];\n },\n\n getBody(data) {\n return dedent`\n Thread ID: ${data.useThreadIdInput ? '(Thread ID From Input)' : data.threadId}\n Limit: ${data.useLimitInput ? '(Limit From Input)' : data.limit}, ${\n data.useOrderInput ? '(Order From Input)' : data.order === 'asc' ? 'Ascending' : 'Descending'\n }\n${\n data.useAfterInput || data.after?.trim() ? `After: ${data.useAfterInput ? '(After From Input)' : data.after}\\n` : ''\n}${\n data.useBeforeInput || data.before?.trim()\n ? `Before: ${data.useBeforeInput ? '(Before From Input)' : data.before}\\n`\n : ''\n }\n `;\n },\n\n async process(data, inputData, context) {\n const threadId = getInputOrData(data, inputData, 'threadId');\n const requestQuery: ListThreadMessagesQuery = {\n limit: getInputOrData(data, inputData, 'limit', 'number'),\n order: getInputOrData(data, inputData, 'order'),\n after: getInputOrData(data, inputData, 'after') || undefined, // Mutually exclusive with before, so set to undefined if empty string\n before: getInputOrData(data, inputData, 'before') || undefined,\n };\n\n const queryParams = Object.entries(requestQuery).filter(([, value]) => value !== undefined) as string[][];\n\n if (!context.settings.openAiKey) {\n throw new Error('OpenAI key is not set.');\n }\n\n const query = new URLSearchParams(queryParams);\n const url = `https://api.openai.com/v1/threads/${threadId}/messages?${query.toString()}`;\n\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n });\n\n await handleOpenAIError(response);\n\n const body = (await response.json()) as OpenAIListResponse<OpenAIThreadMessage>;\n\n return {\n ['messages' as PortId]: {\n type: 'object[]',\n value: body.data,\n },\n ['first_id' as PortId]: {\n type: 'string',\n value: body.first_id,\n },\n ['last_id' as PortId]: {\n type: 'string',\n value: body.last_id,\n },\n ['has_more' as PortId]: {\n type: 'boolean',\n value: body.has_more,\n },\n };\n },\n};\n\nexport const listThreadMessagesNode = pluginNodeDefinition(ListThreadMessagesNodeImpl, 'List Thread Messages');\n", "import {\n type ChartNode,\n type PluginNodeImpl,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type EditorDefinition,\n type GptFunction,\n type GraphId,\n type GraphInputs,\n type ScalarDataValue,\n isArrayDataValue,\n arrayizeDataValue,\n unwrapDataValue,\n} from '../../../index.js';\nimport {\n openAiModelOptions,\n type CreateRunBody,\n type OpenAIAssistantTool,\n type OpenAIRun,\n type CreateMessageBody,\n type OpenAIRunStep,\n type OpenAIListResponse,\n type OpenAIPaginationQuery,\n type OpenAIThreadMessage,\n} from '../../../utils/openai.js';\nimport { dedent, newId, coerceTypeOptional, getInputOrData } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\nimport { type DataValue } from '../../../model/DataValue.js';\nimport { match } from 'ts-pattern';\n\nexport type RunThreadNode = ChartNode<'openaiRunThread', RunThreadNodeData>;\n\nexport type RunThreadNodeData = {\n createThread: boolean;\n\n threadId: string;\n useThreadIdInput?: boolean;\n\n assistantId: string;\n useAssistantIdInput?: boolean;\n\n model?: string;\n useModelInput?: boolean;\n\n instructions?: string;\n useInstructionsInput?: boolean;\n\n useCodeInterpreterTool?: boolean;\n useRetrievalTool?: boolean;\n functions?: GptFunction[];\n\n metadata: { key: string; value: string }[];\n useMetadataInput?: boolean;\n\n toolCallHandlers: { key: string; value: GraphId }[];\n\n onMessageCreationSubgraphId?: GraphId;\n};\n\nconst POLL_FREQUENCY = 500;\n\nexport const RunThreadNodeImpl: PluginNodeImpl<RunThreadNode> = {\n create() {\n return {\n id: newId<NodeId>(),\n type: 'openaiRunThread',\n data: {\n createThread: true,\n threadId: '',\n useThreadIdInput: false,\n assistantId: '',\n useAssistantIdInput: false,\n model: '',\n useModelInput: false,\n instructions: '',\n useInstructionsInput: false,\n tools: [],\n metadata: [],\n useMetadataInput: false,\n toolCallHandlers: [],\n },\n title: 'Run Thread',\n visualData: {\n x: 0,\n y: 0,\n width: 400,\n },\n };\n },\n\n getUIData() {\n return {\n group: 'OpenAI',\n contextMenuTitle: 'Run Thread',\n infoBoxTitle: 'Run Thread Node',\n infoBoxBody: 'Run a thread for OpenAI.',\n };\n },\n\n getInputDefinitions(data) {\n const inputs: NodeInputDefinition[] = [];\n\n if (!data.createThread && data.useThreadIdInput) {\n inputs.push({\n id: 'threadId' as PortId,\n dataType: 'string',\n title: 'Thread ID',\n coerced: true,\n defaultValue: '',\n description: 'The ID of the thread to run.',\n required: true,\n });\n }\n\n if (data.createThread) {\n inputs.push({\n id: 'messages' as PortId,\n dataType: 'object[]',\n title: 'Messages',\n coerced: true,\n defaultValue: [],\n description: 'A list of user messages to start the thread with.',\n required: false,\n });\n }\n\n if (data.useAssistantIdInput) {\n inputs.push({\n id: 'assistantId' as PortId,\n dataType: 'string',\n title: 'Assistant ID',\n coerced: true,\n defaultValue: '',\n description: 'The ID of the assistant to use.',\n required: true,\n });\n }\n\n if (data.useModelInput) {\n inputs.push({\n id: 'model' as PortId,\n dataType: 'string',\n title: 'Model',\n coerced: true,\n defaultValue: '',\n description: 'ID of the model to use.',\n required: false,\n });\n }\n\n if (data.useInstructionsInput) {\n inputs.push({\n id: 'instructions' as PortId,\n dataType: 'string',\n title: 'Instructions',\n coerced: true,\n defaultValue: '',\n description: 'The system instructions that the assistant uses.',\n required: false,\n });\n }\n\n inputs.push({\n id: 'functions' as PortId,\n dataType: ['gpt-function[]', 'gpt-function'],\n title: 'Functions',\n coerced: true,\n defaultValue: [],\n description: 'A list of GPT functions enabled on the assistant.',\n required: false,\n });\n\n if (data.useMetadataInput) {\n inputs.push({\n id: 'metadata' as PortId,\n dataType: 'object',\n title: 'Metadata',\n coerced: true,\n defaultValue: {},\n description: 'Metadata to attach to the run.',\n required: false,\n });\n }\n\n return inputs;\n },\n\n getOutputDefinitions() {\n return [\n {\n id: 'runId' as PortId,\n dataType: 'string',\n title: 'Run ID',\n description: 'The ID of the run.',\n },\n {\n id: 'run' as PortId,\n dataType: 'object',\n title: 'Run',\n description: 'The full run object.',\n },\n {\n id: 'steps' as PortId,\n dataType: 'object[]',\n title: 'Steps',\n description: 'The list of steps for the run.',\n },\n {\n id: 'last_step' as PortId,\n dataType: 'object',\n title: 'Last Step',\n description: 'The last step for the run.',\n },\n {\n id: 'messages' as PortId,\n dataType: 'object[]',\n title: 'Messages',\n description: 'The list of messages for the thread.',\n },\n {\n id: 'last_message' as PortId,\n dataType: 'object',\n title: 'Last Message',\n description: 'The last message on the thread.',\n },\n {\n id: 'last_assistant_messages' as PortId,\n dataType: 'object[]',\n title: 'Last Assistant Messages',\n description: 'The last messages of type `assistant` for the thread.',\n },\n ];\n },\n\n getEditors(): EditorDefinition<RunThreadNode>[] {\n return [\n {\n type: 'toggle',\n dataKey: 'createThread',\n label: 'Create New Thread',\n },\n {\n type: 'string',\n dataKey: 'threadId',\n useInputToggleDataKey: 'useThreadIdInput',\n label: 'Thread ID',\n placeholder: 'Enter thread ID',\n helperMessage: 'The ID of the thread to run.',\n hideIf: (data) => data.createThread,\n },\n {\n type: 'string',\n dataKey: 'assistantId',\n useInputToggleDataKey: 'useAssistantIdInput',\n label: 'Assistant ID',\n placeholder: 'Enter assistant ID',\n helperMessage: 'The ID of the assistant to use. Required.',\n },\n {\n type: 'dropdown',\n dataKey: 'model',\n useInputToggleDataKey: 'useModelInput',\n label: 'Model',\n options: [\n {\n label: 'Default',\n value: '',\n },\n ...openAiModelOptions,\n ],\n defaultValue: '',\n helperMessage: 'The GPT model to use for the run. If default, the model of the assistant will be used.',\n },\n {\n type: 'code',\n dataKey: 'instructions',\n useInputToggleDataKey: 'useInstructionsInput',\n label: 'Instructions',\n language: 'markdown',\n helperMessage:\n 'The instructions for the assistant to use for the run. If empty, the instructions of the assistant will be used.',\n },\n {\n type: 'toggle',\n dataKey: 'useCodeInterpreterTool',\n label: 'Code Interpreter Tool Enabled',\n helperMessage:\n \"Note: Only enabled if functions are provided. Otherwise, the assistant's settings will be used.\",\n },\n {\n type: 'toggle',\n dataKey: 'useRetrievalTool',\n label: 'Retrieval Tool Enabled',\n helperMessage:\n \"Note: Only enabled if functions are provided. Otherwise, the assistant's settings will be used.\",\n },\n {\n type: 'custom',\n customEditorId: 'ToolCallHandlers',\n label: 'Tool Call Handlers',\n dataKey: 'toolCallHandlers',\n helperMessage:\n 'Handles for each function tool call that the assistant has access to. Make sure you provide a subgraph handler for every possible tool call that can be performed. A special `unknown` handler can be used as a fallback for unconfigured tool calls.',\n },\n {\n type: 'keyValuePair',\n dataKey: 'metadata',\n useInputToggleDataKey: 'useMetadataInput',\n label: 'Metadata',\n keyPlaceholder: 'Key',\n valuePlaceholder: 'Value',\n },\n {\n type: 'graphSelector',\n dataKey: 'onMessageCreationSubgraphId',\n label: 'On Message Creation Subgraph',\n helperMessage:\n 'A subgraph to run when a message is created. The message will be available as `input` or `message` in the subgraph.',\n },\n ];\n },\n\n getBody(data, context) {\n let body = dedent`\n Assistant ID: ${data.useAssistantIdInput ? '(Assistant ID From Input)' : data.assistantId}\n `;\n\n const additional: string[] = [];\n\n if (data.createThread) {\n additional.push('Create New Thread');\n } else {\n additional.push(`Thread ID: ${data.useThreadIdInput ? '(Thread ID From Input)' : data.threadId}`);\n }\n\n if (data.useModelInput || data.model) {\n additional.push(`Model: ${data.useModelInput ? '(Model From Input)' : data.model}`);\n }\n\n if (data.useInstructionsInput || data.instructions?.trim()) {\n additional.push(`Instructions: ${data.useInstructionsInput ? '(Instructions From Input)' : data.instructions}`);\n }\n\n if (data.useMetadataInput || data.metadata.length > 0) {\n additional.push(\n `Metadata: ${\n data.useMetadataInput\n ? '(Metadata From Input)'\n : data.metadata.map(({ key, value }) => `${key}=${value}`).join(', ')\n }`,\n );\n }\n\n if (data.useCodeInterpreterTool) {\n additional.push('Code Interpreter Tool Enabled');\n }\n\n if (data.useRetrievalTool) {\n additional.push('Retrieval Tool Enabled');\n }\n\n if (data.toolCallHandlers.length > 0) {\n additional.push('Tool Call Handlers:');\n\n data.toolCallHandlers.forEach(({ key, value }) => {\n const subgraphName = context.project.graphs[value]?.metadata!.name! ?? 'Unknown Subgraph';\n additional.push(` ${key || '(MISSING!)'} -> ${subgraphName}`);\n });\n }\n\n if (data.onMessageCreationSubgraphId) {\n const subgraphName =\n context.project.graphs[data.onMessageCreationSubgraphId]?.metadata!.name! ?? 'Unknown Subgraph';\n additional.push(`On Message Creation Subgraph: ${subgraphName}`);\n }\n\n body = `${body}\\n${additional.join('\\n')}`;\n\n return body;\n },\n\n async process(data, inputData, context) {\n const threadId = getInputOrData(data, inputData, 'threadId');\n const assistantId = getInputOrData(data, inputData, 'assistantId');\n\n let metadata = data.metadata.reduce(\n (acc, { key, value }) => {\n acc[key] = value;\n return acc;\n },\n {} as Record<string, string>,\n );\n if (data.useMetadataInput && inputData['metadata' as PortId]) {\n metadata = coerceTypeOptional(inputData['metadata' as PortId], 'object') as Record<string, string>;\n }\n\n const functionTools = coerceTypeOptional(inputData['functions' as PortId], 'gpt-function[]');\n const tools = [...(functionTools?.map((f): OpenAIAssistantTool => ({ type: 'function', function: f })) ?? [])];\n\n if (tools.length) {\n if (data.useCodeInterpreterTool) {\n tools.push({ type: 'code_interpreter' });\n }\n if (data.useRetrievalTool) {\n tools.push({ type: 'retrieval' });\n }\n }\n\n const requestBody: CreateRunBody = {\n assistant_id: assistantId,\n model: getInputOrData(data, inputData, 'model'),\n instructions: getInputOrData(data, inputData, 'instructions'),\n tools: tools.length > 0 ? tools : undefined,\n metadata,\n };\n\n if (!context.settings.openAiKey) {\n throw new Error('OpenAI key is not set.');\n }\n\n let response: Response;\n\n const coerceToThreadMessage = (value: DataValue | undefined): CreateMessageBody | undefined => {\n if (!value?.value) {\n return undefined;\n }\n\n if (value.type === 'string' || typeof value.value === 'string') {\n return { role: 'user', content: value.value as string };\n }\n\n if (typeof value.value === 'object') {\n if (!('role' in value.value)) {\n throw new Error('Invalid message format - missing role.');\n }\n\n if (value.value.role !== 'user') {\n throw new Error('Only user messages are supported.');\n }\n\n return value.value as CreateMessageBody;\n }\n\n return { role: 'user', content: coerceTypeOptional(value, 'string') ?? '' };\n };\n\n if (data.createThread) {\n const messagesInput = inputData['messages' as PortId];\n const messages = messagesInput\n ? arrayizeDataValue(unwrapDataValue(messagesInput)).map((message) => coerceToThreadMessage(message))\n : [];\n\n response = await fetch('https://api.openai.com/v1/threads/runs', {\n method: 'POST',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n body: JSON.stringify({\n ...requestBody,\n thread: {\n messages,\n // Thread metadata?\n },\n }),\n });\n } else {\n response = await fetch(`https://api.openai.com/v1/threads/${threadId}/runs`, {\n method: 'POST',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n body: JSON.stringify(requestBody),\n });\n }\n\n await handleOpenAIError(response);\n\n const body = (await response.json()) as OpenAIRun;\n\n const pollController = new AbortController();\n const pollRunSteps = async (onNewStepCompleted: (step: OpenAIRunStep) => Promise<void>) => {\n let lastCompletedAt = 0;\n\n // On poll controller abort, continue so we get the final poll\n const pollControllerAborted = new Promise((resolve) =>\n pollController.signal.addEventListener('abort', () => resolve(undefined)),\n );\n\n // On main controller abort, reject\n const mainGraphAborted = new Promise((_, reject) =>\n context.signal.addEventListener('abort', () => reject(new Error('aborted'))),\n );\n\n while (!pollController.signal.aborted) {\n // Delay at beginning because there won't be anything to start, and also this helps last poll get final data\n await Promise.race([\n // Poll frequency\n new Promise((resolve) => setTimeout(resolve, POLL_FREQUENCY)),\n pollControllerAborted,\n mainGraphAborted,\n ]);\n\n const query = new URLSearchParams({\n limit: '3',\n order: 'desc',\n } satisfies OpenAIPaginationQuery);\n\n const url = `https://api.openai.com/v1/threads/${body.thread_id}/runs/${body.id}/steps?${query.toString()}`;\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n });\n\n await handleOpenAIError(response);\n\n const stepListBody = (await response.json()) as OpenAIListResponse<OpenAIRunStep>;\n\n const newSteps = stepListBody.data.filter(\n (step) => step.completed_at != null && step.completed_at > lastCompletedAt,\n );\n\n if (newSteps.length > 0) {\n lastCompletedAt = newSteps[0]!.completed_at!;\n }\n\n for (const newStep of newSteps) {\n await onNewStepCompleted(newStep);\n }\n }\n };\n\n const pollRunStepsPromise = data.onMessageCreationSubgraphId\n ? pollRunSteps(async (step) => {\n if (step.step_details.type !== 'message_creation') {\n return;\n }\n\n const messageId = step.step_details.message_creation.message_id;\n\n const messageResponse = await fetch(\n `https://api.openai.com/v1/threads/${body.thread_id}/messages/${messageId}`,\n {\n method: 'GET',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n },\n );\n\n await handleOpenAIError(messageResponse);\n\n const messageBody = (await messageResponse.json()) as OpenAIThreadMessage;\n\n const inputs: GraphInputs = {\n input: {\n type: 'object[]',\n value: messageBody.content,\n },\n message: {\n type: 'object',\n value: messageBody,\n },\n message_id: {\n type: 'string',\n value: messageBody.id,\n },\n thread_id: {\n type: 'string',\n value: messageBody.thread_id,\n },\n };\n\n const subprocessor = context.createSubProcessor(data.onMessageCreationSubgraphId!, {\n signal: context.signal,\n });\n\n await subprocessor.processGraph(context, inputs, context.contextValues);\n })\n : Promise.resolve();\n\n let latestBody = body;\n\n try {\n while (\n latestBody.status === 'in_progress' ||\n latestBody.status === 'queued' ||\n latestBody.status === 'requires_action'\n ) {\n const runResponse = await fetch(`https://api.openai.com/v1/threads/${body.thread_id}/runs/${body.id}`, {\n method: 'GET',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n });\n\n await handleOpenAIError(runResponse);\n\n latestBody = (await runResponse.json()) as OpenAIRun;\n\n // Requires action, start calling subgraphs\n if (latestBody.status === 'requires_action') {\n const toolCalls = latestBody.required_action!.submit_tool_outputs.tool_calls;\n\n /** Run one subgraph per tool call requested */\n const toolCallOutputs = await Promise.all(\n toolCalls.map(async (toolCall) => {\n let inputArguments: Record<string, any> = {};\n try {\n inputArguments = JSON.parse(toolCall.function.arguments);\n } catch (err) {\n // Ignore\n }\n\n const inputs: Record<string, DataValue> = {\n run_id: {\n type: 'string',\n value: latestBody.id,\n },\n run: {\n type: 'object',\n value: latestBody,\n },\n tool_call_id: {\n type: 'string',\n value: toolCall.id,\n },\n name: {\n type: 'string',\n value: toolCall.function.name,\n },\n arguments: {\n type: 'object',\n value: inputArguments,\n },\n input: {\n type: 'object',\n value: inputArguments,\n },\n };\n\n let handlerSubgraphId = data.toolCallHandlers.find(({ key }) => key === toolCall.function.name)?.value;\n\n // Fall back to \"unknown\" if it's present\n if (!handlerSubgraphId) {\n handlerSubgraphId = data.toolCallHandlers.find(({ key }) => key === 'unknown')?.value;\n }\n\n if (!handlerSubgraphId) {\n throw new Error(`No handler found for tool call: ${toolCall.function.name}`);\n }\n\n const subprocessor = context.createSubProcessor(handlerSubgraphId, { signal: context.signal });\n\n const outputs = await subprocessor.processGraph(context, inputs, context.contextValues);\n\n const outputString = coerceTypeOptional(outputs.output, 'string');\n\n return outputString ?? '';\n }),\n );\n\n /** Collect all the subgraph outputs, then submit them. All outputs must be submitted in a single request, per documentation. */\n const mappedToolCallOuptuts = toolCalls.map((toolCall, i) => ({\n tool_call_id: toolCall.id,\n output: toolCallOutputs[i],\n }));\n\n const submitResponse = await fetch(\n `https://api.openai.com/v1/threads/${body.thread_id}/runs/${body.id}/submit_tool_outputs`,\n {\n method: 'POST',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n body: JSON.stringify({\n tool_outputs: mappedToolCallOuptuts,\n }),\n },\n );\n\n await handleOpenAIError(submitResponse);\n }\n\n await Promise.race([\n new Promise((resolve) => setTimeout(resolve, POLL_FREQUENCY)),\n new Promise((_, reject) => context.signal.addEventListener('abort', () => reject(new Error('aborted')))),\n ]);\n }\n\n if (\n latestBody.status === 'cancelled' ||\n latestBody.status === 'cancelling' ||\n latestBody.status === 'expired' ||\n latestBody.status === 'failed'\n ) {\n throw new Error(`Run failed with status: ${latestBody.status}`);\n }\n\n const listStepsQuery = new URLSearchParams({\n limit: '20',\n order: 'desc',\n });\n\n const listStepsResponsePromise = await fetch(\n `https://api.openai.com/v1/threads/${body.thread_id}/runs/${body.id}/steps?${listStepsQuery.toString()}`,\n {\n method: 'GET',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n },\n );\n\n const getMessagesQuery = new URLSearchParams({\n limit: '20',\n order: 'desc',\n } satisfies OpenAIPaginationQuery);\n\n const messagesResponsePromise = await fetch(\n `https://api.openai.com/v1/threads/${body.thread_id}/messages?${getMessagesQuery.toString()}`,\n {\n method: 'GET',\n headers: {\n 'OpenAI-Beta': 'assistants=v1',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${context.settings.openAiKey}`,\n 'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n },\n },\n );\n\n const [listStepsResponse, messagesResponse] = await Promise.all([\n listStepsResponsePromise,\n messagesResponsePromise,\n ]);\n\n await handleOpenAIError(listStepsResponse);\n await handleOpenAIError(messagesResponse);\n\n const listStepsBody = (await listStepsResponse.json()) as OpenAIListResponse<OpenAIRunStep>;\n const messagesForThread = (await messagesResponse.json()) as OpenAIListResponse<OpenAIThreadMessage>;\n\n const lastUserMessageIndex = messagesForThread.data.findIndex((message) => message.role === 'user');\n const lastAssistantMessages = messagesForThread.data.slice(0, lastUserMessageIndex);\n\n return {\n ['runId' as PortId]: {\n type: 'string',\n value: latestBody.id,\n },\n ['run' as PortId]: {\n type: 'object',\n value: latestBody,\n },\n ['steps' as PortId]: {\n type: 'object[]',\n value: listStepsBody.data,\n },\n ['last_step' as PortId]: {\n type: 'object',\n value: listStepsBody.data[0]!,\n },\n ['messages' as PortId]: {\n type: 'object[]',\n value: messagesForThread.data,\n },\n ['last_message' as PortId]: {\n type: 'object',\n value: messagesForThread.data[0]!,\n },\n ['last_assistant_messages' as PortId]: {\n type: 'object[]',\n value: lastAssistantMessages,\n },\n };\n } finally {\n pollController.abort();\n await pollRunStepsPromise;\n }\n },\n};\n\nexport const runThreadNode = pluginNodeDefinition(RunThreadNodeImpl, 'Run Thread');\n", "import {\n type ChartNode,\n type NodeId,\n type NodeInputDefinition,\n type PortId,\n type EditorDefinition,\n type PluginNodeImpl,\n} from '../../../index.js';\nimport { dedent, newId, coerceTypeOptional, getInputOrData, coerceType } from '../../../utils/index.js';\nimport { interpolate } from '../../../utils/interpolation.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport type { CreateMessageBody, OpenAIThreadMessage } from '../../../utils/openai.js';\nimport { mapValues } from 'lodash-es';\n\nexport type ThreadMessageNode = ChartNode<'threadMessage', ThreadMessageNodeData>;\n\nexport type ThreadMessageNodeData = {\n text: string;\n\n fileIds?: string[];\n useFileIdsInput?: boolean;\n\n metadata: { key: string; value: string }[];\n useMetadataInput?: boolean;\n};\n\nexport const ThreadMessageNodeImpl: PluginNodeImpl<ThreadMessageNode> = {\n create() {\n return {\n id: newId<NodeId>(),\n type: 'threadMessage',\n data: {\n text: '{{input}}',\n fileIds: [],\n useFileIdsInput: false,\n metadata: [],\n useMetadataInput: false,\n },\n title: 'Thread Message',\n visualData: {\n x: 0,\n y: 0,\n width: 225,\n },\n };\n },\n\n getUIData() {\n return {\n group: 'OpenAI',\n contextMenuTitle: 'Thread Message',\n infoBoxTitle: 'Thread Message Node',\n infoBoxBody: 'Create a new message for a thread.',\n };\n },\n\n getInputDefinitions(data) {\n let inputs: NodeInputDefinition[] = [];\n\n if (data.useFileIdsInput) {\n inputs.push({\n id: 'fileIds' as PortId,\n dataType: 'string[]',\n title: 'File IDs',\n coerced: true,\n defaultValue: [],\n description: 'The IDs of the files to attach to the message.',\n required: false,\n });\n }\n\n if (data.useMetadataInput) {\n inputs.push({\n id: 'metadata' as PortId,\n dataType: 'object',\n title: 'Metadata',\n coerced: true,\n defaultValue: {},\n description: 'Metadata to attach to the message.',\n required: false,\n });\n }\n\n // Extract inputs from promptText, everything like {{input}}\n const inputNames = [...new Set(data.text.match(/\\{\\{([^}]+)\\}\\}/g))];\n inputs = [\n ...inputs,\n ...(inputNames?.map((inputName): NodeInputDefinition => {\n return {\n // id and title should not have the {{ and }}\n id: inputName.slice(2, -2) as PortId,\n title: inputName.slice(2, -2),\n dataType: 'string',\n required: false,\n };\n }) ?? []),\n ];\n\n return inputs;\n },\n\n getOutputDefinitions() {\n return [\n {\n id: 'message' as PortId,\n dataType: 'object',\n title: 'Message',\n description: 'The created message.',\n },\n ];\n },\n\n getEditors(): EditorDefinition<ThreadMessageNode>[] {\n return [\n {\n type: 'code',\n label: 'Text',\n dataKey: 'text',\n language: 'prompt-interpolation-markdown',\n theme: 'prompt-interpolation',\n },\n {\n type: 'keyValuePair',\n dataKey: 'metadata',\n useInputToggleDataKey: 'useMetadataInput',\n label: 'Metadata',\n keyPlaceholder: 'Key',\n valuePlaceholder: 'Value',\n },\n {\n type: 'stringList',\n dataKey: 'fileIds',\n useInputToggleDataKey: 'useFileIdsInput',\n label: 'File IDs',\n placeholder: 'File ID',\n },\n ];\n },\n\n getBody(data) {\n return {\n type: 'colorized',\n text: data.text.split('\\n').slice(0, 15).join('\\n').trim(),\n language: 'prompt-interpolation-markdown',\n theme: 'prompt-interpolation',\n };\n },\n\n async process(data, inputData) {\n const text = getInputOrData(data, inputData, 'text', 'string');\n const fileIds = getInputOrData(data, inputData, 'fileIds', 'string[]') ?? [];\n\n let metadata: Record<string, string> = data.metadata.reduce(\n (acc, { key, value }) => {\n acc[key] = value;\n return acc;\n },\n {} as Record<string, string>,\n );\n\n if (data.useMetadataInput && inputData['metadata' as PortId]) {\n metadata = coerceTypeOptional(inputData['metadata' as PortId], 'object') as Record<string, string>;\n }\n\n const inputMap = mapValues(inputData, (input) => coerceType(input, 'string')) as Record<PortId, string>;\n const interpolated = interpolate(text, inputMap);\n\n // Here you would typically make a call to an API to create the message\n // For the sake of this example, we'll just return the data as is\n\n return {\n ['message' as PortId]: {\n type: 'object',\n value: {\n role: 'user',\n content: interpolated,\n file_ids: fileIds,\n metadata,\n } satisfies CreateMessageBody,\n },\n };\n },\n};\n\nexport const threadMessageNode = pluginNodeDefinition(ThreadMessageNodeImpl, 'Thread Message');\n", "import { type RivetPlugin } from '../../index.js';\nimport { createThreadNode } from './nodes/CreateThreadNode.js';\nimport { getThreadNode } from './nodes/GetThreadNode.js';\nimport { deleteThreadNode } from './nodes/DeleteThreadNode.js';\nimport { createAssistantNode } from './nodes/CreateAssistantNode.js';\nimport { getAssistantNode } from './nodes/GetAssistantNode.js';\nimport { listAssistantsNode } from './nodes/ListAssistantsNode.js';\nimport { deleteAssistantNode } from './nodes/DeleteAssistantNode.js';\nimport { uploadFileNode } from './nodes/UploadFileNode.js';\nimport { listOpenAIFilesNode } from './nodes/ListOpenAIFilesNode.js';\nimport { getOpenAIFileNode } from './nodes/GetOpenAIFileNode.js';\nimport { attachAssistantFileNode } from './nodes/AttachAssistantFileNode.js';\nimport { createThreadMessageNode } from './nodes/CreateThreadMessageNode.js';\nimport { listThreadMessagesNode } from './nodes/ListThreadMessagesNode.js';\nimport { runThreadNode } from './nodes/RunThreadNode.js';\nimport { threadMessageNode } from './nodes/ThreadMessageNode.js';\n\nexport const openAIPlugin: RivetPlugin = {\n id: 'openai',\n name: 'OpenAI',\n\n configSpec: {},\n\n contextMenuGroups: [\n {\n id: 'openai',\n label: 'OpenAI',\n },\n ],\n\n register(register) {\n register(createThreadNode);\n register(getThreadNode);\n register(deleteThreadNode);\n register(createAssistantNode);\n register(getAssistantNode);\n register(listAssistantsNode);\n register(deleteAssistantNode);\n register(uploadFileNode);\n register(listOpenAIFilesNode);\n register(getOpenAIFileNode);\n register(attachAssistantFileNode);\n register(createThreadMessageNode);\n register(listThreadMessagesNode);\n register(runThreadNode);\n register(threadMessageNode);\n },\n};\n", "export type GoogleModel = {\n maxTokens: number;\n cost: {\n prompt: number;\n completion: number;\n };\n displayName: string;\n};\n\nexport const googleModels = {\n 'gemini-pro': {\n maxTokens: 32760,\n cost: {\n prompt: NaN,\n completion: NaN,\n },\n displayName: 'Gemini Pro',\n },\n 'gemini-pro-vision': {\n maxTokens: 16384,\n cost: {\n prompt: NaN,\n completion: NaN,\n },\n displayName: 'Gemini Pro Vision',\n },\n} satisfies Record<string, GoogleModel>;\n\nexport type GoogleModels = keyof typeof googleModels;\n\nexport const googleModelOptions = Object.entries(googleModels).map(([id, { displayName }]) => ({\n value: id,\n label: displayName,\n}));\n\nexport interface GoogleChatMessage {\n role: 'user' | 'assistant';\n parts: (\n | {\n text: string;\n }\n | {\n inline_data: {\n mime_type: string;\n data: string;\n };\n }\n )[];\n}\n\nexport type ChatCompletionOptions = {\n project: string;\n location: string;\n applicationCredentials: string;\n model: GoogleModels;\n prompt: GoogleChatMessage[];\n max_output_tokens: number;\n temperature?: number;\n top_p?: number;\n top_k?: number;\n signal?: AbortSignal;\n};\n\nexport type ChatCompletionChunk = {\n completion: string;\n finish_reason:\n | 'FINISH_REASON_UNSPECIFIED'\n | 'FINISH_REASON_STOP'\n | 'FINISH_REASON_MAX_TOKENS'\n | 'FINISH_REASON_SAFETY'\n | 'FINISH_REASON_RECITATION'\n | 'FINISH_REASON_OTHER'\n | undefined;\n model: string;\n};\n\nexport async function* streamChatCompletions({\n project,\n location,\n applicationCredentials,\n model,\n signal,\n max_output_tokens,\n temperature,\n top_p,\n top_k,\n prompt,\n}: ChatCompletionOptions): AsyncGenerator<ChatCompletionChunk> {\n const defaultSignal = new AbortController().signal;\n\n // If you import normally, the Google auth library throws a fit.\n const { VertexAI } = await import('@google-cloud/vertexai');\n\n // Can't find a way to pass the credentials path in\n process.env['GOOGLE_APPLICATION_CREDENTIALS'] = applicationCredentials;\n const vertexAi = new VertexAI({ project, location });\n const generativeModel = vertexAi.preview.getGenerativeModel({\n model,\n generation_config: {\n max_output_tokens,\n temperature,\n top_p,\n top_k,\n },\n });\n const response = await generativeModel.generateContentStream({\n contents: prompt,\n });\n\n let hadChunks = false;\n\n for await (const chunk of response.stream) {\n console.log('streaming google responses');\n hadChunks = true;\n\n if (!signal?.aborted && chunk.candidates[0]?.content.parts[0]?.text) {\n yield {\n completion: chunk.candidates[0]?.content.parts[0]?.text,\n finish_reason: chunk.candidates[0]?.finishReason as any,\n model,\n };\n } else {\n return;\n }\n }\n\n if (!hadChunks) {\n throw new Error(`No chunks received.`);\n }\n}\n", "import {\n uint8ArrayToBase64,\n type ChartNode,\n type ChatMessage,\n type EditorDefinition,\n type Inputs,\n type InternalProcessContext,\n type NodeId,\n type NodeInputDefinition,\n type NodeOutputDefinition,\n type NodeUIData,\n type Outputs,\n type PluginNodeImpl,\n type PortId,\n type ScalarDataValue,\n} from '../../../index.js';\nimport {\n type GoogleModels,\n type ChatCompletionOptions,\n googleModelOptions,\n googleModels,\n streamChatCompletions,\n type GoogleChatMessage,\n} from '../google.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport retry from 'p-retry';\nimport { match } from 'ts-pattern';\nimport { coerceType, coerceTypeOptional } from '../../../utils/coerceType.js';\nimport { addWarning } from '../../../utils/outputs.js';\nimport { getError } from '../../../utils/errors.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { getScalarTypeOf, isArrayDataValue } from '../../../model/DataValue.js';\nimport type { TokenizerCallInfo } from '../../../integrations/Tokenizer.js';\n\nexport type ChatGoogleNode = ChartNode<'chatGoogle', ChatGoogleNodeData>;\n\nexport type ChatGoogleNodeConfigData = {\n model: GoogleModels;\n temperature: number;\n useTopP: boolean;\n top_p?: number;\n top_k?: number;\n maxTokens: number;\n};\n\nexport type ChatGoogleNodeData = ChatGoogleNodeConfigData & {\n useModelInput: boolean;\n useTemperatureInput: boolean;\n useTopPInput: boolean;\n useTopKInput: boolean;\n useUseTopPInput: boolean;\n useMaxTokensInput: boolean;\n\n /** Given the same set of inputs, return the same output without hitting GPT */\n cache: boolean;\n\n useAsGraphPartialOutput?: boolean;\n};\n\n// Temporary\nconst cache = new Map<string, Outputs>();\n\nexport const ChatGoogleNodeImpl: PluginNodeImpl<ChatGoogleNode> = {\n create(): ChatGoogleNode {\n const chartNode: ChatGoogleNode = {\n type: 'chatGoogle',\n title: 'Chat (Google)',\n id: nanoid() as NodeId,\n visualData: {\n x: 0,\n y: 0,\n width: 275,\n },\n data: {\n model: 'gemini-pro',\n useModelInput: false,\n\n temperature: 0.5,\n useTemperatureInput: false,\n\n top_p: 1,\n useTopPInput: false,\n\n top_k: undefined,\n useTopKInput: false,\n\n useTopP: false,\n useUseTopPInput: false,\n\n maxTokens: 1024,\n useMaxTokensInput: false,\n\n cache: false,\n useAsGraphPartialOutput: true,\n },\n };\n\n return chartNode;\n },\n\n getInputDefinitions(data): NodeInputDefinition[] {\n const inputs: NodeInputDefinition[] = [];\n\n if (data.useModelInput) {\n inputs.push({\n id: 'model' as PortId,\n title: 'Model',\n dataType: 'string',\n required: false,\n });\n }\n\n if (data.useTemperatureInput) {\n inputs.push({\n dataType: 'number',\n id: 'temperature' as PortId,\n title: 'Temperature',\n });\n }\n\n if (data.useTopPInput) {\n inputs.push({\n dataType: 'number',\n id: 'top_p' as PortId,\n title: 'Top P',\n });\n }\n\n if (data.useUseTopPInput) {\n inputs.push({\n dataType: 'boolean',\n id: 'useTopP' as PortId,\n title: 'Use Top P',\n });\n }\n\n if (data.useMaxTokensInput) {\n inputs.push({\n dataType: 'number',\n id: 'maxTokens' as PortId,\n title: 'Max Tokens',\n });\n }\n\n inputs.push({\n dataType: ['chat-message', 'chat-message[]'] as const,\n id: 'prompt' as PortId,\n title: 'Prompt',\n });\n\n return inputs;\n },\n\n getOutputDefinitions(data): NodeOutputDefinition[] {\n const outputs: NodeOutputDefinition[] = [];\n\n outputs.push({\n dataType: 'string',\n id: 'response' as PortId,\n title: 'Response',\n });\n\n outputs.push({\n dataType: 'chat-message[]',\n id: 'in-messages' as PortId,\n title: 'Messages Sent',\n description: 'All messages sent to the model.',\n });\n\n outputs.push({\n dataType: 'chat-message[]',\n id: 'all-messages' as PortId,\n title: 'All Messages',\n description: 'All messages, with the response appended.',\n });\n\n return outputs;\n },\n\n getBody(data): string {\n return dedent`\n ${googleModels[data.model]?.displayName ?? `Google (${data.model})`}\n ${\n data.useTopP\n ? `Top P: ${data.useTopPInput ? '(Using Input)' : data.top_p}`\n : `Temperature: ${data.useTemperatureInput ? '(Using Input)' : data.temperature}`\n }\n Max Tokens: ${data.maxTokens}\n `;\n },\n\n getEditors(): EditorDefinition<ChatGoogleNode>[] {\n return [\n {\n type: 'dropdown',\n label: 'Model',\n dataKey: 'model',\n useInputToggleDataKey: 'useModelInput',\n options: googleModelOptions,\n },\n {\n type: 'number',\n label: 'Temperature',\n dataKey: 'temperature',\n useInputToggleDataKey: 'useTemperatureInput',\n min: 0,\n max: 2,\n step: 0.1,\n },\n {\n type: 'number',\n label: 'Top P',\n dataKey: 'top_p',\n useInputToggleDataKey: 'useTopPInput',\n min: 0,\n max: 1,\n step: 0.1,\n },\n {\n type: 'toggle',\n label: 'Use Top P',\n dataKey: 'useTopP',\n useInputToggleDataKey: 'useUseTopPInput',\n },\n {\n type: 'number',\n label: 'Max Tokens',\n dataKey: 'maxTokens',\n useInputToggleDataKey: 'useMaxTokensInput',\n min: 0,\n max: Number.MAX_SAFE_INTEGER,\n step: 1,\n },\n {\n type: 'toggle',\n label: 'Cache (same inputs, same outputs)',\n dataKey: 'cache',\n },\n {\n type: 'toggle',\n label: 'Use for subgraph partial output',\n dataKey: 'useAsGraphPartialOutput',\n },\n ];\n },\n\n getUIData(): NodeUIData {\n return {\n infoBoxBody: dedent`\n Makes a call to an Google chat model. The settings contains many options for tweaking the model's behavior.\n `,\n infoBoxTitle: 'Chat (Google) Node',\n contextMenuTitle: 'Chat (Google)',\n group: ['AI'],\n };\n },\n\n async process(data, inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n const output: Outputs = {};\n\n const rawModel = data.useModelInput\n ? coerceTypeOptional(inputs['model' as PortId], 'string') ?? data.model\n : data.model;\n\n const model = rawModel as GoogleModels;\n\n const temperature = data.useTemperatureInput\n ? coerceTypeOptional(inputs['temperature' as PortId], 'number') ?? data.temperature\n : data.temperature;\n\n const topP = data.useTopPInput ? coerceTypeOptional(inputs['top_p' as PortId], 'number') ?? data.top_p : data.top_p;\n\n const useTopP = data.useUseTopPInput\n ? coerceTypeOptional(inputs['useTopP' as PortId], 'boolean') ?? data.useTopP\n : data.useTopP;\n\n const { messages } = getChatGoogleNodeMessages(inputs);\n\n const prompt = await Promise.all(\n messages.map(async (message): Promise<GoogleChatMessage> => {\n return {\n role: message.type === 'user' ? 'user' : 'assistant',\n parts: await Promise.all(\n [message.message].flat().map(async (part): Promise<GoogleChatMessage['parts'][0]> => {\n if (typeof part === 'string') {\n return { text: part };\n } else if (part.type === 'image') {\n return {\n inline_data: {\n mime_type: part.mediaType,\n data: (await uint8ArrayToBase64(part.data))!,\n },\n };\n } else {\n throw new Error(`Google Vertex AI does not support message parts of type ${part.type}`);\n }\n }),\n ),\n };\n }),\n );\n\n let { maxTokens } = data;\n\n const tokenizerInfo: TokenizerCallInfo = {\n node: context.node,\n model,\n endpoint: undefined,\n };\n\n // TODO Better token counting for Google models.\n const tokenCount = await context.tokenizer.getTokenCountForMessages(messages, undefined, tokenizerInfo);\n\n if (googleModels[model] && tokenCount >= googleModels[model].maxTokens) {\n throw new Error(\n `The model ${model} can only handle ${googleModels[model].maxTokens} tokens, but ${tokenCount} were provided in the prompts alone.`,\n );\n }\n\n if (googleModels[model] && tokenCount + maxTokens > googleModels[model].maxTokens) {\n const message = `The model can only handle a maximum of ${\n googleModels[model].maxTokens\n } tokens, but the prompts and max tokens together exceed this limit. The max tokens has been reduced to ${\n googleModels[model].maxTokens - tokenCount\n }.`;\n addWarning(output, message);\n maxTokens = Math.floor((googleModels[model].maxTokens - tokenCount) * 0.95); // reduce max tokens by 5% to be safe, calculation is a little wrong.\n }\n\n const project = context.getPluginConfig('googleProjectId');\n const location = context.getPluginConfig('googleRegion');\n const applicationCredentials = context.getPluginConfig('googleApplicationCredentials');\n\n if (project == null) {\n throw new Error('Google Project ID is not defined.');\n }\n if (location == null) {\n throw new Error('Google Region is not defined.');\n }\n if (applicationCredentials == null) {\n throw new Error('Google Application Credentials is not defined.');\n }\n\n try {\n return await retry(\n async () => {\n const options: Omit<ChatCompletionOptions, 'project' | 'location' | 'applicationCredentials' | 'signal'> = {\n prompt,\n model,\n temperature: useTopP ? undefined : temperature,\n top_p: useTopP ? topP : undefined,\n max_output_tokens: maxTokens,\n };\n const cacheKey = JSON.stringify(options);\n\n if (data.cache) {\n const cached = cache.get(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n const startTime = Date.now();\n\n const chunks = streamChatCompletions({\n signal: context.signal,\n project,\n location,\n applicationCredentials,\n ...options,\n });\n\n const responseParts: string[] = [];\n\n for await (const chunk of chunks) {\n if (!chunk.completion) {\n // Could be error for some reason \uD83E\uDD37\u200D\u2642\uFE0F but ignoring has worked for me so far.\n continue;\n }\n\n responseParts.push(chunk.completion);\n\n output['response' as PortId] = {\n type: 'string',\n value: responseParts.join('').trim(),\n };\n\n context.onPartialOutputs?.(output);\n }\n\n const endTime = Date.now();\n\n output['all-messages' as PortId] = {\n type: 'chat-message[]',\n value: [\n ...messages,\n {\n type: 'assistant',\n message: responseParts.join('').trim() ?? '',\n function_call: undefined,\n function_calls: undefined,\n },\n ],\n };\n\n output['in-messages' as PortId] = {\n type: 'chat-message[]',\n value: messages,\n };\n\n if (responseParts.length === 0) {\n throw new Error('No response from Google');\n }\n\n output['requestTokens' as PortId] = { type: 'number', value: tokenCount };\n\n const responseTokenCount = await context.tokenizer.getTokenCountForString(\n responseParts.join(''),\n tokenizerInfo,\n );\n output['responseTokens' as PortId] = { type: 'number', value: responseTokenCount };\n\n // TODO\n // const cost =\n // getCostForPrompt(completionMessages, model) + getCostForTokens(responseTokenCount, 'completion', model);\n\n // output['cost' as PortId] = { type: 'number', value: cost };\n\n const duration = endTime - startTime;\n\n output['duration' as PortId] = { type: 'number', value: duration };\n\n Object.freeze(output);\n cache.set(cacheKey, output);\n\n return output;\n },\n {\n retries: 10,\n maxRetryTime: 1000 * 60 * 5,\n factor: 2.5,\n minTimeout: 500,\n maxTimeout: 5000,\n randomize: true,\n signal: context.signal,\n onFailedAttempt(err) {\n context.trace(`ChatGoogleNode failed, retrying: ${err.toString()}`);\n\n if (context.signal.aborted) {\n throw new Error('Aborted');\n }\n },\n },\n );\n } catch (error) {\n context.trace(getError(error).stack ?? 'Missing stack');\n throw new Error(`Error processing ChatGoogleNode: ${(error as Error).message}`);\n }\n },\n};\n\nexport const chatGoogleNode = pluginNodeDefinition(ChatGoogleNodeImpl, 'Chat');\n\nexport function getChatGoogleNodeMessages(inputs: Inputs) {\n const prompt = inputs['prompt' as PortId];\n if (!prompt) {\n throw new Error('Prompt is required');\n }\n\n const messages: ChatMessage[] = match(prompt)\n .with({ type: 'chat-message' }, (p) => [p.value])\n .with({ type: 'chat-message[]' }, (p) => p.value)\n .with({ type: 'string' }, (p): ChatMessage[] => [{ type: 'user', message: p.value }])\n .with({ type: 'string[]' }, (p): ChatMessage[] => p.value.map((v) => ({ type: 'user', message: v })))\n .otherwise((p): ChatMessage[] => {\n if (isArrayDataValue(p)) {\n const stringValues = (p.value as readonly unknown[]).map((v) =>\n coerceType(\n {\n type: getScalarTypeOf(p.type),\n value: v,\n } as ScalarDataValue,\n 'string',\n ),\n );\n\n return stringValues.filter((v) => v != null).map((v) => ({ type: 'user', message: v }));\n }\n\n const coercedMessage = coerceType(p, 'chat-message');\n if (coercedMessage != null) {\n return [coercedMessage];\n }\n\n const coercedString = coerceType(p, 'string');\n return coercedString != null ? [{ type: 'user', message: coerceType(p, 'string') }] : [];\n });\n return { messages };\n}\n", "import { type RivetPlugin } from '../../index.js';\nimport { chatGoogleNode } from './nodes/ChatGoogleNode.js';\n\nexport const googlePlugin: RivetPlugin = {\n id: 'google',\n name: 'Google',\n\n register: (register) => {\n register(chatGoogleNode);\n },\n\n configSpec: {\n googleProjectId: {\n type: 'string',\n label: 'Google Project ID',\n description: 'The Google project ID.',\n pullEnvironmentVariable: 'GCP_PROJECT',\n helperText: 'You may also set the GCP_PROJECT environment variable.',\n },\n googleRegion: {\n type: 'string',\n label: 'Google Region',\n description: 'The Google region.',\n pullEnvironmentVariable: 'GCP_REGION',\n helperText: 'You may also set the GCP_REGION environment variable.',\n },\n googleApplicationCredentials: {\n type: 'string',\n label: 'Google Application Credentials',\n description: 'The path with the JSON file that contains your credentials.',\n pullEnvironmentVariable: 'GOOGLE_APPLICATION_CREDENTIALS',\n helperText:\n 'You may also set the GOOGLE_APPLICATION_CREDENTIALS environment variable. See https://cloud.google.com/vertex-ai/docs/start/client-libraries for more info.',\n },\n },\n};\n", "import aidonPlugin from './plugins/aidon/index.js';\nimport anthropicPlugin from './plugins/anthropic/index.js';\nimport autoevalsPlugin from './plugins/autoevals/index.js';\nimport assemblyAiPlugin from './plugins/assemblyAi/index.js';\nimport { huggingFacePlugin } from './plugins/huggingface/plugin.js';\nimport pineconePlugin from './plugins/pinecone/index.js';\nimport gentracePlugin from './plugins/gentrace/index.js';\nimport { openAIPlugin } from './plugins/openai/plugin.js';\nimport { googlePlugin } from './plugins/google/plugin.js';\n\nexport {\n\taidonPlugin,\n anthropicPlugin,\n autoevalsPlugin,\n assemblyAiPlugin,\n pineconePlugin,\n huggingFacePlugin,\n gentracePlugin,\n googlePlugin,\n};\n\nexport const plugins = {\n\taidon: aidonPlugin,\n anthropic: anthropicPlugin,\n autoevals: autoevalsPlugin,\n assemblyAi: assemblyAiPlugin,\n pinecone: pineconePlugin,\n huggingFace: huggingFacePlugin,\n gentrace: gentracePlugin,\n openai: openAIPlugin,\n google: googlePlugin,\n};\n", "import { type Dataset, type DatasetId, type DatasetMetadata, type DatasetRow, type ProjectId } from '../index.js';\nimport { cloneDeep } from 'lodash-es';\nimport type { CombinedDataset } from '../utils/index.js';\n\nexport interface DatasetProvider {\n getDatasetMetadata(id: DatasetId): Promise<DatasetMetadata | undefined>;\n\n getDatasetsForProject(projectId: ProjectId): Promise<DatasetMetadata[]>;\n\n getDatasetData(id: DatasetId): Promise<Dataset>;\n\n putDatasetData(id: DatasetId, data: Dataset): Promise<void>;\n\n putDatasetRow(id: DatasetId, row: DatasetRow): Promise<void>;\n\n putDatasetMetadata(metadata: DatasetMetadata): Promise<void>;\n\n clearDatasetData(id: DatasetId): Promise<void>;\n\n deleteDataset(id: DatasetId): Promise<void>;\n\n /** Gets the K nearest neighbor rows to the given vector. */\n knnDatasetRows(datasetId: DatasetId, k: number, vector: number[]): Promise<(DatasetRow & { distance?: number })[]>;\n\n exportDatasetsForProject(projectId: ProjectId): Promise<CombinedDataset[]>;\n}\n\nexport class InMemoryDatasetProvider implements DatasetProvider {\n readonly #datasets;\n\n constructor(datasets: CombinedDataset[]) {\n this.#datasets = datasets;\n }\n\n async getDatasetMetadata(id: DatasetId): Promise<DatasetMetadata | undefined> {\n const dataset = this.#datasets.find((d) => d.meta.id === id);\n return dataset?.meta;\n }\n\n async getDatasetsForProject(projectId: ProjectId): Promise<DatasetMetadata[]> {\n return this.#datasets.map((d) => d.meta);\n }\n\n async getDatasetData(id: DatasetId): Promise<Dataset> {\n const dataset = this.#datasets.find((d) => d.meta.id === id);\n if (!dataset) {\n return { id, rows: [] };\n }\n return dataset.data;\n }\n\n async putDatasetRow(id: DatasetId, row: DatasetRow): Promise<void> {\n const dataset = this.#datasets.find((d) => d.meta.id === id);\n if (!dataset) {\n throw new Error(`Dataset ${id} not found`);\n }\n\n const existingRow = dataset.data.rows.find((r) => r.id === row.id);\n if (existingRow) {\n existingRow.data = row.data;\n existingRow.embedding = row.embedding;\n return;\n }\n\n dataset.data.rows.push(row);\n }\n\n async putDatasetData(id: DatasetId, data: Dataset): Promise<void> {\n const dataset = this.#datasets.find((d) => d.meta.id === id);\n if (!dataset) {\n throw new Error(`Dataset ${id} not found`);\n }\n\n dataset.data = data;\n }\n\n async putDatasetMetadata(metadata: DatasetMetadata): Promise<void> {\n const matchingDataset = this.#datasets.find((d) => d.meta.id === metadata.id);\n\n if (matchingDataset) {\n matchingDataset.meta = metadata;\n return;\n }\n\n this.#datasets.push({\n meta: metadata,\n data: {\n id: metadata.id,\n rows: [],\n },\n });\n }\n\n async clearDatasetData(id: DatasetId): Promise<void> {\n const dataset = this.#datasets.find((d) => d.meta.id === id);\n if (!dataset) {\n return;\n }\n\n dataset.data = {\n id,\n rows: [],\n };\n }\n\n async deleteDataset(id: DatasetId): Promise<void> {\n const index = this.#datasets.findIndex((d) => d.meta.id === id);\n if (index === -1) {\n return;\n }\n\n this.#datasets.splice(index, 1);\n }\n\n async knnDatasetRows(\n datasetId: DatasetId,\n k: number,\n vector: number[],\n ): Promise<(DatasetRow & { distance?: number | undefined })[]> {\n const allRows = await this.getDatasetData(datasetId);\n\n const sorted = allRows.rows\n .filter((row) => row.embedding != null)\n .map((row) => ({\n row,\n similarity: dotProductSimilarity(vector, row.embedding!),\n }))\n .sort((a, b) => b.similarity - a.similarity);\n\n return sorted.slice(0, k).map((r) => ({ ...r.row, distance: r.similarity }));\n }\n\n async exportDatasetsForProject(_projectId: ProjectId): Promise<CombinedDataset[]> {\n // Cloning is safest... but slow\n return cloneDeep(this.#datasets);\n }\n}\n\n/** OpenAI embeddings are already normalized, so this is equivalent to cosine similarity */\nconst dotProductSimilarity = (a: number[], b: number[]): number => {\n return a.reduce((acc, val, i) => acc + val * b[i]!, 0);\n};\n", "import {\n type NodeId,\n type Inputs,\n type Outputs,\n type GraphOutputs,\n type GraphProcessor,\n type PortId,\n} from '../index.js';\nimport { coerceType } from '../utils/coerceType.js';\n\nexport type RivetEventStreamFilterSpec = {\n /** Stream partial output deltas for the specified node IDs or node titles. */\n partialOutputs?: string[] | true;\n\n /** Send the graph output when done? */\n done?: boolean;\n\n /** If the graph errors, send an error event? */\n error?: boolean;\n\n /** Stream node start events for the specified node IDs or node titles. */\n nodeStart?: string[] | true;\n\n /** Stream node finish events for the specified nodeIDs or node titles. */\n nodeFinish?: string[] | true;\n};\n\n/** Map of all possible event names to their data for streaming events. */\nexport type RivetEventStreamEvent = {\n /** Deltas for partial outputs. */\n partialOutput: {\n nodeId: NodeId;\n nodeTitle: string;\n delta: string;\n };\n\n nodeStart: {\n nodeId: NodeId;\n nodeTitle: string;\n inputs: Inputs;\n };\n\n nodeFinish: {\n nodeId: NodeId;\n nodeTitle: string;\n outputs: Outputs;\n };\n\n done: {\n graphOutput: GraphOutputs;\n };\n\n error: {\n error: string;\n };\n};\n\nexport type RivetEventStreamEventInfo = {\n [P in keyof RivetEventStreamEvent]: {\n type: P;\n } & RivetEventStreamEvent[P];\n}[keyof RivetEventStreamEvent];\n\n/** A simplified way to listen and stream processor events, including filtering. */\nexport async function* getProcessorEvents(\n processor: GraphProcessor,\n spec: RivetEventStreamFilterSpec,\n): AsyncGenerator<RivetEventStreamEventInfo, void> {\n const previousIndexes = new Map<NodeId, number>();\n\n for await (const event of processor.events()) {\n if (event.type === 'partialOutput') {\n if (\n spec.partialOutputs === true ||\n spec.partialOutputs?.includes(event.node.id) ||\n spec.partialOutputs?.includes(event.node.title)\n ) {\n const currentOutput = coerceType(event.outputs['response' as PortId], 'string');\n\n const delta = currentOutput.slice(previousIndexes.get(event.node.id) ?? 0);\n\n yield {\n type: 'partialOutput',\n nodeId: event.node.id,\n nodeTitle: event.node.title,\n delta,\n };\n\n previousIndexes.set(event.node.id, currentOutput.length);\n }\n } else if (event.type === 'done') {\n if (spec.done) {\n yield {\n type: 'done',\n graphOutput: event.results,\n };\n }\n } else if (event.type === 'error') {\n if (spec.error) {\n yield {\n type: 'error',\n error: typeof event.error === 'string' ? event.error : event.error.toString(),\n };\n }\n } else if (event.type === 'nodeStart') {\n if (\n spec.nodeStart === true ||\n spec.nodeStart?.includes(event.node.id) ||\n spec.nodeStart?.includes(event.node.title)\n ) {\n yield {\n type: 'nodeStart',\n inputs: event.inputs,\n nodeId: event.node.id,\n nodeTitle: event.node.title,\n };\n }\n } else if (event.type === 'nodeFinish') {\n if (\n spec.nodeFinish === true ||\n spec.nodeFinish?.includes(event.node.id) ||\n spec.nodeFinish?.includes(event.node.title)\n ) {\n yield {\n type: 'nodeFinish',\n outputs: event.outputs,\n nodeId: event.node.id,\n nodeTitle: event.node.title,\n };\n }\n }\n }\n}\n\n/**\n * Creates a ReadableStream for processor events, following the Server-Sent Events protocol.\n * https://developer.mozilla.org/en-US/docs/Web/API/EventSource\n *\n * Includes configuration for what events to send to the client, for example you can stream the partial output deltas\n * for specific nodes, and/or the graph output when done.\n */\nexport function getProcessorSSEStream(\n processor: GraphProcessor,\n\n /** The spec for what you're streaming to the client */\n spec: RivetEventStreamFilterSpec,\n) {\n const encoder = new TextEncoder();\n\n function sendEvent<T extends keyof RivetEventStreamEvent>(\n controller: ReadableStreamDefaultController,\n type: T,\n data: RivetEventStreamEvent[T],\n ) {\n const event = `event: ${type}\\ndata: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(event));\n }\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n try {\n for await (const event of getProcessorEvents(processor, spec)) {\n sendEvent(controller, event.type, event);\n }\n controller.close();\n } catch (err) {\n controller.error(err);\n }\n },\n });\n}\n\nexport function getSingleNodeStream(processor: GraphProcessor, nodeIdOrTitle: string) {\n return new ReadableStream<string>({\n async start(controller) {\n try {\n for await (const event of getProcessorEvents(processor, {\n partialOutputs: [nodeIdOrTitle],\n nodeFinish: [nodeIdOrTitle],\n })) {\n if (event.type === 'partialOutput' && (event.nodeId === nodeIdOrTitle || event.nodeTitle === nodeIdOrTitle)) {\n controller.enqueue(`data: ${JSON.stringify(event.delta)}\\n\\n`);\n } else if (\n event.type === 'nodeFinish' &&\n (event.nodeId === nodeIdOrTitle || event.nodeTitle === nodeIdOrTitle)\n ) {\n controller.close();\n }\n }\n\n controller.close();\n } catch (err) {\n controller.error(err);\n }\n },\n });\n}\n", "import type { PascalCase } from 'type-fest';\nimport {\n type AttachedData,\n type AudioProvider,\n type DataValue,\n type DatasetProvider,\n type ExternalFunction,\n type GraphId,\n type NativeApi,\n type NodeRegistration,\n type ProcessContext,\n type ProcessEvents,\n type Project,\n type RivetEventStreamFilterSpec,\n type Settings,\n} from '../index.js';\nimport { mapValues } from '../utils/typeSafety.js';\nimport { getProcessorEvents, getProcessorSSEStream, getSingleNodeStream } from './streaming.js';\nimport { GraphProcessor } from '../model/GraphProcessor.js';\nimport { deserializeProject } from '../utils/serialization/serialization.js';\nimport { DEFAULT_CHAT_NODE_TIMEOUT } from '../utils/defaults.js';\n\nexport type LooseDataValue = DataValue | string | number | boolean;\n\nexport type RunGraphOptions = {\n graph?: string;\n inputs?: Record<string, LooseDataValue>;\n context?: Record<string, LooseDataValue>;\n nativeApi?: NativeApi;\n datasetProvider?: DatasetProvider;\n audioProvider?: AudioProvider;\n externalFunctions?: {\n [key: string]: ExternalFunction;\n };\n onUserEvent?: {\n [key: string]: (data: DataValue | undefined) => void;\n };\n abortSignal?: AbortSignal;\n registry?: NodeRegistration;\n getChatNodeEndpoint?: ProcessContext['getChatNodeEndpoint'];\n} & {\n [P in keyof ProcessEvents as `on${PascalCase<P>}`]?: (params: ProcessEvents[P]) => void;\n} & Settings;\n\nexport function looseDataValuesToDataValues(values: Record<string, LooseDataValue>): Record<string, DataValue> {\n return mapValues(values, (val) => looseDataValueToDataValue(val));\n}\n\nexport function looseDataValueToDataValue(value: LooseDataValue): DataValue {\n if (typeof value === 'string') {\n return { type: 'string', value };\n }\n\n if (typeof value === 'number') {\n return { type: 'number', value };\n }\n\n if (typeof value === 'boolean') {\n return { type: 'boolean', value };\n }\n\n return value;\n}\n\nexport function coreCreateProcessor(project: Project, options: RunGraphOptions) {\n const { graph, inputs = {}, context = {} } = options;\n\n const graphId = graph\n ? graph in project.graphs\n ? graph\n : Object.values(project.graphs).find((g) => g.metadata?.name === graph)?.metadata?.id\n : project.metadata.mainGraphId;\n\n if (!graphId) {\n throw new Error(`Graph not found, and no main graph specified.`);\n }\n\n const processor = new GraphProcessor(project, graphId as GraphId, options.registry);\n\n if (options.onStart) {\n processor.on('start', options.onStart);\n }\n\n if (options.onNodeStart) {\n processor.on('nodeStart', options.onNodeStart);\n }\n\n if (options.onNodeFinish) {\n processor.on('nodeFinish', options.onNodeFinish);\n }\n\n if (options.onNodeError) {\n processor.on('nodeError', options.onNodeError);\n }\n\n if (options.onNodeExcluded) {\n processor.on('nodeExcluded', options.onNodeExcluded);\n }\n\n if (options.onGraphStart) {\n processor.on('graphStart', options.onGraphStart);\n }\n\n if (options.onGraphError) {\n processor.on('graphError', options.onGraphError);\n }\n\n if (options.onGraphFinish) {\n processor.on('graphFinish', options.onGraphFinish);\n }\n\n if (options.onPartialOutput) {\n processor.on('partialOutput', options.onPartialOutput);\n }\n\n if (options.onUserInput) {\n processor.on('userInput', options.onUserInput);\n }\n\n if (options.onDone) {\n processor.on('done', options.onDone);\n }\n\n if (options.onAbort) {\n processor.on('abort', options.onAbort);\n }\n\n if (options.onGraphAbort) {\n processor.on('graphAbort', options.onGraphAbort);\n }\n\n if (options.onTrace) {\n processor.on('trace', options.onTrace);\n }\n\n if (options.onNodeOutputsCleared) {\n processor.on('nodeOutputsCleared', options.onNodeOutputsCleared);\n }\n\n if (options.externalFunctions) {\n for (const [name, fn] of Object.entries(options.externalFunctions)) {\n processor.setExternalFunction(name, fn);\n }\n }\n\n if (options.onUserEvent) {\n for (const [name, fn] of Object.entries(options.onUserEvent)) {\n processor.onUserEvent(name, fn);\n }\n }\n\n options.abortSignal?.addEventListener('abort', () => {\n processor.abort();\n });\n\n const resolvedInputs = looseDataValuesToDataValues(inputs);\n const resolvedContextValues = looseDataValuesToDataValues(context);\n\n return {\n processor,\n inputs: resolvedInputs,\n contextValues: resolvedContextValues,\n getEvents: (spec: RivetEventStreamFilterSpec) => getProcessorEvents(processor, spec),\n getSSEStream: (spec: RivetEventStreamFilterSpec) => getProcessorSSEStream(processor, spec),\n streamNode: (nodeIdOrTitle: string) => getSingleNodeStream(processor, nodeIdOrTitle),\n async run() {\n const outputs = await processor.processGraph(\n {\n nativeApi: options.nativeApi,\n datasetProvider: options.datasetProvider,\n audioProvider: options.audioProvider,\n settings: {\n openAiKey: options.openAiKey ?? '',\n openAiOrganization: options.openAiOrganization ?? '',\n openAiEndpoint: options.openAiEndpoint ?? '',\n pluginEnv: options.pluginEnv ?? {},\n pluginSettings: options.pluginSettings ?? {},\n recordingPlaybackLatency: 1000,\n chatNodeHeaders: options.chatNodeHeaders ?? {},\n chatNodeTimeout: options.chatNodeTimeout ?? DEFAULT_CHAT_NODE_TIMEOUT,\n } satisfies Required<Settings>,\n getChatNodeEndpoint: options.getChatNodeEndpoint,\n },\n resolvedInputs,\n resolvedContextValues,\n );\n\n return outputs;\n },\n };\n}\n\nexport async function coreRunGraph(project: Project, options: RunGraphOptions): Promise<Record<string, DataValue>> {\n const processorInfo = coreCreateProcessor(project, options);\n return processorInfo.run();\n}\n\nexport function loadProjectFromString(content: string): Project {\n const [project] = deserializeProject(content);\n return project;\n}\n\nexport function loadProjectAndAttachedDataFromString(content: string): [Project, AttachedData] {\n return deserializeProject(content);\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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qC,SAA0C;AAC7F,SAAO,mBAAmB,OAAO;AACnC;;;AnKzMO,IAAME,SAA2B;",
6
+ "names": ["Rivet", "yaml", "import_lodash_es", "import_safe_stable_stringify", "yaml", "mapValues", "fromSerializedProject", "fromSerializedGraph", "stableStringify", "fromSerializedNode", "fromSerializedConnection", "yaml", "err", "import_lodash_es", "import_emittery", "import_non_secure", "import_ts_pattern", "mapValues", "import_non_secure", "import_lodash_es", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "values", "import_non_secure", "import_lodash_es", "init", "import_ts_pattern", "import_ts_dedent", "import_ts_pattern", "message", "retry", "options", "import_non_secure", "import_lodash_es", "import_ts_dedent", "import_ts_pattern", "type", "import_non_secure", "import_ts_dedent", "match", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "match", "import_non_secure", "import_ts_dedent", "value", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_non_secure", "import_ts_dedent", "import_ts_pattern", "import_non_secure", "import_lodash_es", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_lodash_es", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "match", "yaml", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_lodash_es", "import_ts_dedent", "result", "import_non_secure", "import_jsonpath_plus", "import_ts_dedent", "match", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "id", "value", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_yaml", "import_ts_dedent", "yaml", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_pattern", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "value", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_lodash_es", "import_ts_dedent", "include", "import_non_secure", "import_ts_dedent", "values", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_lodash_es", "import_ts_pattern", "import_ts_dedent", "import_non_secure", "import_ts_pattern", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "max", "import_non_secure", "import_lodash_es", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_non_secure", "import_non_secure", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "match", "import_non_secure", "import_lodash_es", "import_ts_pattern", "type", "import_non_secure", "import_non_secure", "import_jsonpath_plus", "import_ts_dedent", "match", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "graph", "import_non_secure", "import_ts_dedent", "import_ts_dedent", "handler", "import_non_secure", "registry", "Emittery", "PQueueImport", "Emittery", "registry", "values", "error", "results", "node", "_a", "connections", "options", "import_openai", "options", "import_non_secure", "import_emittery", "options", "Emittery", "import_lodash_es", "import_ts_dedent", "chatNode", "EventSourceResponse", "init", "createEventStream", "fetchEventSource", "LineSplitter", "streamChatCompletions", "fetchEventSource", "import_non_secure", "import_ts_dedent", "import_p_retry", "import_ts_pattern", "cache", "retry", "streamChatCompletions", "getCostForTokens", "content", "import_non_secure", "import_ts_dedent", "import_ts_pattern", "import_non_secure", "import_ts_dedent", "import_assemblyai", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_assemblyai", "import_non_secure", "import_ts_dedent", "import_assemblyai", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_non_secure", "import_inference", "import_ts_dedent", "options", "import_lodash_es", "import_ts_pattern", "_a", "response", "import_lodash_es", "streamChatCompletions", "import_non_secure", "import_ts_dedent", "import_p_retry", "import_ts_pattern", "cache", "retry", "options", "streamChatCompletions", "import_lodash_es", "values", "mapValues", "options", "_a", "Rivet"]
7
+ }