use-one-step-run.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. import { useEffect, useState } from 'react'
  2. import { useTranslation } from 'react-i18next'
  3. import { unionBy } from 'lodash-es'
  4. import produce from 'immer'
  5. import {
  6. useIsChatMode,
  7. useNodeDataUpdate,
  8. useWorkflow,
  9. } from '@/app/components/workflow/hooks'
  10. import { getNodeInfoById, isConversationVar, isENV, isSystemVar, toNodeOutputVars } from '@/app/components/workflow/nodes/_base/components/variable/utils'
  11. import type { CommonNodeType, InputVar, ValueSelector, Var, Variable } from '@/app/components/workflow/types'
  12. import { BlockEnum, InputVarType, NodeRunningStatus, VarType } from '@/app/components/workflow/types'
  13. import { useStore as useAppStore } from '@/app/components/app/store'
  14. import { useStore, useWorkflowStore } from '@/app/components/workflow/store'
  15. import { getIterationSingleNodeRunUrl, singleNodeRun } from '@/service/workflow'
  16. import Toast from '@/app/components/base/toast'
  17. import LLMDefault from '@/app/components/workflow/nodes/llm/default'
  18. import KnowledgeRetrievalDefault from '@/app/components/workflow/nodes/knowledge-retrieval/default'
  19. import IfElseDefault from '@/app/components/workflow/nodes/if-else/default'
  20. import CodeDefault from '@/app/components/workflow/nodes/code/default'
  21. import TemplateTransformDefault from '@/app/components/workflow/nodes/template-transform/default'
  22. import QuestionClassifyDefault from '@/app/components/workflow/nodes/question-classifier/default'
  23. import HTTPDefault from '@/app/components/workflow/nodes/http/default'
  24. import ToolDefault from '@/app/components/workflow/nodes/tool/default'
  25. import VariableAssigner from '@/app/components/workflow/nodes/variable-assigner/default'
  26. import ParameterExtractorDefault from '@/app/components/workflow/nodes/parameter-extractor/default'
  27. import IterationDefault from '@/app/components/workflow/nodes/iteration/default'
  28. import { ssePost } from '@/service/base'
  29. import { getInputVars as doGetInputVars } from '@/app/components/base/prompt-editor/constants'
  30. import type { NodeTracing } from '@/types/workflow'
  31. const { checkValid: checkLLMValid } = LLMDefault
  32. const { checkValid: checkKnowledgeRetrievalValid } = KnowledgeRetrievalDefault
  33. const { checkValid: checkIfElseValid } = IfElseDefault
  34. const { checkValid: checkCodeValid } = CodeDefault
  35. const { checkValid: checkTemplateTransformValid } = TemplateTransformDefault
  36. const { checkValid: checkQuestionClassifyValid } = QuestionClassifyDefault
  37. const { checkValid: checkHttpValid } = HTTPDefault
  38. const { checkValid: checkToolValid } = ToolDefault
  39. const { checkValid: checkVariableAssignerValid } = VariableAssigner
  40. const { checkValid: checkParameterExtractorValid } = ParameterExtractorDefault
  41. const { checkValid: checkIterationValid } = IterationDefault
  42. const checkValidFns: Record<BlockEnum, Function> = {
  43. [BlockEnum.LLM]: checkLLMValid,
  44. [BlockEnum.KnowledgeRetrieval]: checkKnowledgeRetrievalValid,
  45. [BlockEnum.IfElse]: checkIfElseValid,
  46. [BlockEnum.Code]: checkCodeValid,
  47. [BlockEnum.TemplateTransform]: checkTemplateTransformValid,
  48. [BlockEnum.QuestionClassifier]: checkQuestionClassifyValid,
  49. [BlockEnum.HttpRequest]: checkHttpValid,
  50. [BlockEnum.Tool]: checkToolValid,
  51. [BlockEnum.VariableAssigner]: checkVariableAssignerValid,
  52. [BlockEnum.VariableAggregator]: checkVariableAssignerValid,
  53. [BlockEnum.ParameterExtractor]: checkParameterExtractorValid,
  54. [BlockEnum.Iteration]: checkIterationValid,
  55. } as any
  56. type Params<T> = {
  57. id: string
  58. data: CommonNodeType<T>
  59. defaultRunInputData: Record<string, any>
  60. moreDataForCheckValid?: any
  61. iteratorInputKey?: string
  62. }
  63. const varTypeToInputVarType = (type: VarType, {
  64. isSelect,
  65. isParagraph,
  66. }: {
  67. isSelect: boolean
  68. isParagraph: boolean
  69. }) => {
  70. if (isSelect)
  71. return InputVarType.select
  72. if (isParagraph)
  73. return InputVarType.paragraph
  74. if (type === VarType.number)
  75. return InputVarType.number
  76. if ([VarType.object, VarType.array, VarType.arrayNumber, VarType.arrayString, VarType.arrayObject].includes(type))
  77. return InputVarType.json
  78. if (type === VarType.file)
  79. return InputVarType.singleFile
  80. if (type === VarType.arrayFile)
  81. return InputVarType.multiFiles
  82. return InputVarType.textInput
  83. }
  84. const useOneStepRun = <T>({
  85. id,
  86. data,
  87. defaultRunInputData,
  88. moreDataForCheckValid,
  89. iteratorInputKey,
  90. }: Params<T>) => {
  91. const { t } = useTranslation()
  92. const { getBeforeNodesInSameBranch, getBeforeNodesInSameBranchIncludeParent } = useWorkflow() as any
  93. const conversationVariables = useStore(s => s.conversationVariables)
  94. const isChatMode = useIsChatMode()
  95. const isIteration = data.type === BlockEnum.Iteration
  96. const availableNodes = getBeforeNodesInSameBranch(id)
  97. const availableNodesIncludeParent = getBeforeNodesInSameBranchIncludeParent(id)
  98. const allOutputVars = toNodeOutputVars(availableNodes, isChatMode, undefined, undefined, conversationVariables)
  99. const getVar = (valueSelector: ValueSelector): Var | undefined => {
  100. const isSystem = valueSelector[0] === 'sys'
  101. const targetVar = allOutputVars.find(item => isSystem ? !!item.isStartNode : item.nodeId === valueSelector[0])
  102. if (!targetVar)
  103. return undefined
  104. if (isSystem)
  105. return targetVar.vars.find(item => item.variable.split('.')[1] === valueSelector[1])
  106. let curr: any = targetVar.vars
  107. for (let i = 1; i < valueSelector.length; i++) {
  108. const key = valueSelector[i]
  109. const isLast = i === valueSelector.length - 1
  110. if (Array.isArray(curr))
  111. curr = curr.find((v: any) => v.variable.replace('conversation.', '') === key)
  112. if (isLast)
  113. return curr
  114. else if (curr?.type === VarType.object || curr?.type === VarType.file)
  115. curr = curr.children
  116. }
  117. return undefined
  118. }
  119. const checkValid = checkValidFns[data.type]
  120. const appId = useAppStore.getState().appDetail?.id
  121. const [runInputData, setRunInputData] = useState<Record<string, any>>(defaultRunInputData || {})
  122. const iterationTimes = iteratorInputKey ? runInputData[iteratorInputKey].length : 0
  123. const [runResult, setRunResult] = useState<any>(null)
  124. const { handleNodeDataUpdate }: { handleNodeDataUpdate: (data: any) => void } = useNodeDataUpdate()
  125. const [canShowSingleRun, setCanShowSingleRun] = useState(false)
  126. const isShowSingleRun = data._isSingleRun && canShowSingleRun
  127. const [iterationRunResult, setIterationRunResult] = useState<NodeTracing[][]>([])
  128. useEffect(() => {
  129. if (!checkValid) {
  130. setCanShowSingleRun(true)
  131. return
  132. }
  133. if (data._isSingleRun) {
  134. const { isValid, errorMessage } = checkValid(data, t, moreDataForCheckValid)
  135. setCanShowSingleRun(isValid)
  136. if (!isValid) {
  137. handleNodeDataUpdate({
  138. id,
  139. data: {
  140. ...data,
  141. _isSingleRun: false,
  142. },
  143. })
  144. Toast.notify({
  145. type: 'error',
  146. message: errorMessage,
  147. })
  148. }
  149. }
  150. // eslint-disable-next-line react-hooks/exhaustive-deps
  151. }, [data._isSingleRun])
  152. const workflowStore = useWorkflowStore()
  153. useEffect(() => {
  154. workflowStore.getState().setShowSingleRunPanel(!!isShowSingleRun)
  155. }, [isShowSingleRun])
  156. const hideSingleRun = () => {
  157. handleNodeDataUpdate({
  158. id,
  159. data: {
  160. ...data,
  161. _isSingleRun: false,
  162. },
  163. })
  164. }
  165. const showSingleRun = () => {
  166. handleNodeDataUpdate({
  167. id,
  168. data: {
  169. ...data,
  170. _isSingleRun: true,
  171. },
  172. })
  173. }
  174. const runningStatus = data._singleRunningStatus || NodeRunningStatus.NotStart
  175. const isCompleted = runningStatus === NodeRunningStatus.Succeeded || runningStatus === NodeRunningStatus.Failed
  176. const handleRun = async (submitData: Record<string, any>) => {
  177. handleNodeDataUpdate({
  178. id,
  179. data: {
  180. ...data,
  181. _singleRunningStatus: NodeRunningStatus.Running,
  182. },
  183. })
  184. let res: any
  185. try {
  186. if (!isIteration) {
  187. res = await singleNodeRun(appId!, id, { inputs: submitData }) as any
  188. }
  189. else {
  190. setIterationRunResult([])
  191. let _iterationResult: NodeTracing[][] = []
  192. let _runResult: any = null
  193. ssePost(
  194. getIterationSingleNodeRunUrl(isChatMode, appId!, id),
  195. { body: { inputs: submitData } },
  196. {
  197. onWorkflowStarted: () => {
  198. },
  199. onWorkflowFinished: (params) => {
  200. handleNodeDataUpdate({
  201. id,
  202. data: {
  203. ...data,
  204. _singleRunningStatus: NodeRunningStatus.Succeeded,
  205. },
  206. })
  207. const { data: iterationData } = params
  208. _runResult.created_by = iterationData.created_by.name
  209. setRunResult(_runResult)
  210. },
  211. onIterationNext: () => {
  212. // iteration next trigger time is triggered one more time than iterationTimes
  213. if (_iterationResult.length >= iterationTimes!)
  214. return
  215. const newIterationRunResult = produce(_iterationResult, (draft) => {
  216. draft.push([])
  217. })
  218. _iterationResult = newIterationRunResult
  219. setIterationRunResult(newIterationRunResult)
  220. },
  221. onIterationFinish: (params) => {
  222. _runResult = params.data
  223. setRunResult(_runResult)
  224. },
  225. onNodeStarted: (params) => {
  226. const newIterationRunResult = produce(_iterationResult, (draft) => {
  227. draft[draft.length - 1].push({
  228. ...params.data,
  229. status: NodeRunningStatus.Running,
  230. } as NodeTracing)
  231. })
  232. _iterationResult = newIterationRunResult
  233. setIterationRunResult(newIterationRunResult)
  234. },
  235. onNodeFinished: (params) => {
  236. const iterationRunResult = _iterationResult
  237. const { data } = params
  238. const currentIndex = iterationRunResult[iterationRunResult.length - 1].findIndex(trace => trace.node_id === data.node_id)
  239. const newIterationRunResult = produce(iterationRunResult, (draft) => {
  240. if (currentIndex > -1) {
  241. draft[draft.length - 1][currentIndex] = {
  242. ...data,
  243. status: NodeRunningStatus.Succeeded,
  244. } as NodeTracing
  245. }
  246. })
  247. _iterationResult = newIterationRunResult
  248. setIterationRunResult(newIterationRunResult)
  249. },
  250. onError: () => {
  251. handleNodeDataUpdate({
  252. id,
  253. data: {
  254. ...data,
  255. _singleRunningStatus: NodeRunningStatus.Failed,
  256. },
  257. })
  258. },
  259. },
  260. )
  261. }
  262. if (res.error)
  263. throw new Error(res.error)
  264. }
  265. catch (e: any) {
  266. if (!isIteration) {
  267. handleNodeDataUpdate({
  268. id,
  269. data: {
  270. ...data,
  271. _singleRunningStatus: NodeRunningStatus.Failed,
  272. },
  273. })
  274. return false
  275. }
  276. }
  277. finally {
  278. if (!isIteration) {
  279. setRunResult({
  280. ...res,
  281. total_tokens: res.execution_metadata?.total_tokens || 0,
  282. created_by: res.created_by_account?.name || '',
  283. })
  284. }
  285. }
  286. if (!isIteration) {
  287. handleNodeDataUpdate({
  288. id,
  289. data: {
  290. ...data,
  291. _singleRunningStatus: NodeRunningStatus.Succeeded,
  292. },
  293. })
  294. }
  295. }
  296. const handleStop = () => {
  297. handleNodeDataUpdate({
  298. id,
  299. data: {
  300. ...data,
  301. _singleRunningStatus: NodeRunningStatus.NotStart,
  302. },
  303. })
  304. }
  305. const toVarInputs = (variables: Variable[]): InputVar[] => {
  306. if (!variables)
  307. return []
  308. const varInputs = variables.filter(item => !isENV(item.value_selector)).map((item) => {
  309. const originalVar = getVar(item.value_selector)
  310. if (!originalVar) {
  311. return {
  312. label: item.label || item.variable,
  313. variable: item.variable,
  314. type: InputVarType.textInput,
  315. required: true,
  316. value_selector: item.value_selector,
  317. }
  318. }
  319. return {
  320. label: item.label || item.variable,
  321. variable: item.variable,
  322. type: varTypeToInputVarType(originalVar.type, {
  323. isSelect: !!originalVar.isSelect,
  324. isParagraph: !!originalVar.isParagraph,
  325. }),
  326. required: item.required !== false,
  327. options: originalVar.options,
  328. }
  329. })
  330. return varInputs
  331. }
  332. const getInputVars = (textList: string[]) => {
  333. const valueSelectors: ValueSelector[] = []
  334. textList.forEach((text) => {
  335. valueSelectors.push(...doGetInputVars(text))
  336. })
  337. const variables = unionBy(valueSelectors, item => item.join('.')).map((item) => {
  338. const varInfo = getNodeInfoById(availableNodesIncludeParent, item[0])?.data
  339. return {
  340. label: {
  341. nodeType: varInfo?.type,
  342. nodeName: varInfo?.title || availableNodesIncludeParent[0]?.data.title, // default start node title
  343. variable: isSystemVar(item) ? item.join('.') : item[item.length - 1],
  344. isChatVar: isConversationVar(item),
  345. },
  346. variable: `#${item.join('.')}#`,
  347. value_selector: item,
  348. }
  349. })
  350. const varInputs = toVarInputs(variables)
  351. return varInputs
  352. }
  353. return {
  354. isShowSingleRun,
  355. hideSingleRun,
  356. showSingleRun,
  357. toVarInputs,
  358. getInputVars,
  359. runningStatus,
  360. isCompleted,
  361. handleRun,
  362. handleStop,
  363. runInputData,
  364. setRunInputData,
  365. runResult,
  366. iterationRunResult,
  367. }
  368. }
  369. export default useOneStepRun