use-one-step-run.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. import { useCallback, useEffect, useRef, 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, getLoopSingleNodeRunUrl, 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 Assigner from '@/app/components/workflow/nodes/assigner/default'
  27. import ParameterExtractorDefault from '@/app/components/workflow/nodes/parameter-extractor/default'
  28. import IterationDefault from '@/app/components/workflow/nodes/iteration/default'
  29. import DocumentExtractorDefault from '@/app/components/workflow/nodes/document-extractor/default'
  30. import LoopDefault from '@/app/components/workflow/nodes/loop/default'
  31. import { ssePost } from '@/service/base'
  32. import { getInputVars as doGetInputVars } from '@/app/components/base/prompt-editor/constants'
  33. import type { NodeTracing } from '@/types/workflow'
  34. const { checkValid: checkLLMValid } = LLMDefault
  35. const { checkValid: checkKnowledgeRetrievalValid } = KnowledgeRetrievalDefault
  36. const { checkValid: checkIfElseValid } = IfElseDefault
  37. const { checkValid: checkCodeValid } = CodeDefault
  38. const { checkValid: checkTemplateTransformValid } = TemplateTransformDefault
  39. const { checkValid: checkQuestionClassifyValid } = QuestionClassifyDefault
  40. const { checkValid: checkHttpValid } = HTTPDefault
  41. const { checkValid: checkToolValid } = ToolDefault
  42. const { checkValid: checkVariableAssignerValid } = VariableAssigner
  43. const { checkValid: checkAssignerValid } = Assigner
  44. const { checkValid: checkParameterExtractorValid } = ParameterExtractorDefault
  45. const { checkValid: checkIterationValid } = IterationDefault
  46. const { checkValid: checkDocumentExtractorValid } = DocumentExtractorDefault
  47. const { checkValid: checkLoopValid } = LoopDefault
  48. // eslint-disable-next-line ts/no-unsafe-function-type
  49. const checkValidFns: Record<BlockEnum, Function> = {
  50. [BlockEnum.LLM]: checkLLMValid,
  51. [BlockEnum.KnowledgeRetrieval]: checkKnowledgeRetrievalValid,
  52. [BlockEnum.IfElse]: checkIfElseValid,
  53. [BlockEnum.Code]: checkCodeValid,
  54. [BlockEnum.TemplateTransform]: checkTemplateTransformValid,
  55. [BlockEnum.QuestionClassifier]: checkQuestionClassifyValid,
  56. [BlockEnum.HttpRequest]: checkHttpValid,
  57. [BlockEnum.Tool]: checkToolValid,
  58. [BlockEnum.VariableAssigner]: checkAssignerValid,
  59. [BlockEnum.VariableAggregator]: checkVariableAssignerValid,
  60. [BlockEnum.ParameterExtractor]: checkParameterExtractorValid,
  61. [BlockEnum.Iteration]: checkIterationValid,
  62. [BlockEnum.DocExtractor]: checkDocumentExtractorValid,
  63. [BlockEnum.Loop]: checkLoopValid,
  64. } as any
  65. type Params<T> = {
  66. id: string
  67. data: CommonNodeType<T>
  68. defaultRunInputData: Record<string, any>
  69. moreDataForCheckValid?: any
  70. iteratorInputKey?: string
  71. loopInputKey?: string
  72. }
  73. const varTypeToInputVarType = (type: VarType, {
  74. isSelect,
  75. isParagraph,
  76. }: {
  77. isSelect: boolean
  78. isParagraph: boolean
  79. }) => {
  80. if (isSelect)
  81. return InputVarType.select
  82. if (isParagraph)
  83. return InputVarType.paragraph
  84. if (type === VarType.number)
  85. return InputVarType.number
  86. if ([VarType.object, VarType.array, VarType.arrayNumber, VarType.arrayString, VarType.arrayObject].includes(type))
  87. return InputVarType.json
  88. if (type === VarType.file)
  89. return InputVarType.singleFile
  90. if (type === VarType.arrayFile)
  91. return InputVarType.multiFiles
  92. return InputVarType.textInput
  93. }
  94. const useOneStepRun = <T>({
  95. id,
  96. data,
  97. defaultRunInputData,
  98. moreDataForCheckValid,
  99. iteratorInputKey,
  100. loopInputKey,
  101. }: Params<T>) => {
  102. const { t } = useTranslation()
  103. const { getBeforeNodesInSameBranch, getBeforeNodesInSameBranchIncludeParent } = useWorkflow() as any
  104. const conversationVariables = useStore(s => s.conversationVariables)
  105. const isChatMode = useIsChatMode()
  106. const isIteration = data.type === BlockEnum.Iteration
  107. const isLoop = data.type === BlockEnum.Loop
  108. const availableNodes = getBeforeNodesInSameBranch(id)
  109. const availableNodesIncludeParent = getBeforeNodesInSameBranchIncludeParent(id)
  110. const allOutputVars = toNodeOutputVars(availableNodes, isChatMode, undefined, undefined, conversationVariables)
  111. const getVar = (valueSelector: ValueSelector): Var | undefined => {
  112. const isSystem = valueSelector[0] === 'sys'
  113. const targetVar = allOutputVars.find(item => isSystem ? !!item.isStartNode : item.nodeId === valueSelector[0])
  114. if (!targetVar)
  115. return undefined
  116. if (isSystem)
  117. return targetVar.vars.find(item => item.variable.split('.')[1] === valueSelector[1])
  118. let curr: any = targetVar.vars
  119. for (let i = 1; i < valueSelector.length; i++) {
  120. const key = valueSelector[i]
  121. const isLast = i === valueSelector.length - 1
  122. if (Array.isArray(curr))
  123. curr = curr.find((v: any) => v.variable.replace('conversation.', '') === key)
  124. if (isLast)
  125. return curr
  126. else if (curr?.type === VarType.object || curr?.type === VarType.file)
  127. curr = curr.children
  128. }
  129. return undefined
  130. }
  131. const checkValid = checkValidFns[data.type]
  132. const appId = useAppStore.getState().appDetail?.id
  133. const [runInputData, setRunInputData] = useState<Record<string, any>>(defaultRunInputData || {})
  134. const runInputDataRef = useRef(runInputData)
  135. const handleSetRunInputData = useCallback((data: Record<string, any>) => {
  136. runInputDataRef.current = data
  137. setRunInputData(data)
  138. }, [])
  139. const iterationTimes = iteratorInputKey ? runInputData[iteratorInputKey].length : 0
  140. const loopTimes = loopInputKey ? runInputData[loopInputKey].length : 0
  141. const [runResult, setRunResult] = useState<any>(null)
  142. const { handleNodeDataUpdate }: { handleNodeDataUpdate: (data: any) => void } = useNodeDataUpdate()
  143. const [canShowSingleRun, setCanShowSingleRun] = useState(false)
  144. const isShowSingleRun = data._isSingleRun && canShowSingleRun
  145. const [iterationRunResult, setIterationRunResult] = useState<NodeTracing[]>([])
  146. const [loopRunResult, setLoopRunResult] = useState<NodeTracing[]>([])
  147. useEffect(() => {
  148. if (!checkValid) {
  149. setCanShowSingleRun(true)
  150. return
  151. }
  152. if (data._isSingleRun) {
  153. const { isValid, errorMessage } = checkValid(data, t, moreDataForCheckValid)
  154. setCanShowSingleRun(isValid)
  155. if (!isValid) {
  156. handleNodeDataUpdate({
  157. id,
  158. data: {
  159. ...data,
  160. _isSingleRun: false,
  161. },
  162. })
  163. Toast.notify({
  164. type: 'error',
  165. message: errorMessage,
  166. })
  167. }
  168. }
  169. // eslint-disable-next-line react-hooks/exhaustive-deps
  170. }, [data._isSingleRun])
  171. const workflowStore = useWorkflowStore()
  172. useEffect(() => {
  173. workflowStore.getState().setShowSingleRunPanel(!!isShowSingleRun)
  174. }, [isShowSingleRun, workflowStore])
  175. const hideSingleRun = () => {
  176. handleNodeDataUpdate({
  177. id,
  178. data: {
  179. ...data,
  180. _isSingleRun: false,
  181. },
  182. })
  183. }
  184. const showSingleRun = () => {
  185. handleNodeDataUpdate({
  186. id,
  187. data: {
  188. ...data,
  189. _isSingleRun: true,
  190. },
  191. })
  192. }
  193. const runningStatus = data._singleRunningStatus || NodeRunningStatus.NotStart
  194. const isCompleted = runningStatus === NodeRunningStatus.Succeeded || runningStatus === NodeRunningStatus.Failed
  195. const handleRun = async (submitData: Record<string, any>) => {
  196. handleNodeDataUpdate({
  197. id,
  198. data: {
  199. ...data,
  200. _singleRunningStatus: NodeRunningStatus.Running,
  201. },
  202. })
  203. let res: any
  204. try {
  205. if (!isIteration && !isLoop) {
  206. res = await singleNodeRun(appId!, id, { inputs: submitData }) as any
  207. }
  208. else if (isIteration) {
  209. setIterationRunResult([])
  210. let _iterationResult: NodeTracing[] = []
  211. let _runResult: any = null
  212. ssePost(
  213. getIterationSingleNodeRunUrl(isChatMode, appId!, id),
  214. { body: { inputs: submitData } },
  215. {
  216. onWorkflowStarted: () => {
  217. },
  218. onWorkflowFinished: (params) => {
  219. handleNodeDataUpdate({
  220. id,
  221. data: {
  222. ...data,
  223. _singleRunningStatus: NodeRunningStatus.Succeeded,
  224. },
  225. })
  226. const { data: iterationData } = params
  227. _runResult.created_by = iterationData.created_by.name
  228. setRunResult(_runResult)
  229. },
  230. onIterationStart: (params) => {
  231. const newIterationRunResult = produce(_iterationResult, (draft) => {
  232. draft.push({
  233. ...params.data,
  234. status: NodeRunningStatus.Running,
  235. })
  236. })
  237. _iterationResult = newIterationRunResult
  238. setIterationRunResult(newIterationRunResult)
  239. },
  240. onIterationNext: () => {
  241. // iteration next trigger time is triggered one more time than iterationTimes
  242. if (_iterationResult.length >= iterationTimes!)
  243. return _iterationResult.length >= iterationTimes!
  244. },
  245. onIterationFinish: (params) => {
  246. _runResult = params.data
  247. setRunResult(_runResult)
  248. const iterationRunResult = _iterationResult
  249. const currentIndex = iterationRunResult.findIndex(trace => trace.id === params.data.id)
  250. const newIterationRunResult = produce(iterationRunResult, (draft) => {
  251. if (currentIndex > -1) {
  252. draft[currentIndex] = {
  253. ...draft[currentIndex],
  254. ...data,
  255. }
  256. }
  257. })
  258. _iterationResult = newIterationRunResult
  259. setIterationRunResult(newIterationRunResult)
  260. },
  261. onNodeStarted: (params) => {
  262. const newIterationRunResult = produce(_iterationResult, (draft) => {
  263. draft.push({
  264. ...params.data,
  265. status: NodeRunningStatus.Running,
  266. })
  267. })
  268. _iterationResult = newIterationRunResult
  269. setIterationRunResult(newIterationRunResult)
  270. },
  271. onNodeFinished: (params) => {
  272. const iterationRunResult = _iterationResult
  273. const { data } = params
  274. const currentIndex = iterationRunResult.findIndex(trace => trace.id === data.id)
  275. const newIterationRunResult = produce(iterationRunResult, (draft) => {
  276. if (currentIndex > -1) {
  277. draft[currentIndex] = {
  278. ...draft[currentIndex],
  279. ...data,
  280. }
  281. }
  282. })
  283. _iterationResult = newIterationRunResult
  284. setIterationRunResult(newIterationRunResult)
  285. },
  286. onNodeRetry: (params) => {
  287. const newIterationRunResult = produce(_iterationResult, (draft) => {
  288. draft.push(params.data)
  289. })
  290. _iterationResult = newIterationRunResult
  291. setIterationRunResult(newIterationRunResult)
  292. },
  293. onError: () => {
  294. handleNodeDataUpdate({
  295. id,
  296. data: {
  297. ...data,
  298. _singleRunningStatus: NodeRunningStatus.Failed,
  299. },
  300. })
  301. },
  302. },
  303. )
  304. }
  305. else if (isLoop) {
  306. setLoopRunResult([])
  307. let _loopResult: NodeTracing[] = []
  308. let _runResult: any = null
  309. ssePost(
  310. getLoopSingleNodeRunUrl(isChatMode, appId!, id),
  311. { body: { inputs: submitData } },
  312. {
  313. onWorkflowStarted: () => {
  314. },
  315. onWorkflowFinished: (params) => {
  316. handleNodeDataUpdate({
  317. id,
  318. data: {
  319. ...data,
  320. _singleRunningStatus: NodeRunningStatus.Succeeded,
  321. },
  322. })
  323. const { data: loopData } = params
  324. _runResult.created_by = loopData.created_by.name
  325. setRunResult(_runResult)
  326. },
  327. onLoopStart: (params) => {
  328. const newLoopRunResult = produce(_loopResult, (draft) => {
  329. draft.push({
  330. ...params.data,
  331. status: NodeRunningStatus.Running,
  332. })
  333. })
  334. _loopResult = newLoopRunResult
  335. setLoopRunResult(newLoopRunResult)
  336. },
  337. onLoopNext: () => {
  338. // loop next trigger time is triggered one more time than loopTimes
  339. if (_loopResult.length >= loopTimes!)
  340. return _loopResult.length >= loopTimes!
  341. },
  342. onLoopFinish: (params) => {
  343. _runResult = params.data
  344. setRunResult(_runResult)
  345. const loopRunResult = _loopResult
  346. const currentIndex = loopRunResult.findIndex(trace => trace.id === params.data.id)
  347. const newLoopRunResult = produce(loopRunResult, (draft) => {
  348. if (currentIndex > -1) {
  349. draft[currentIndex] = {
  350. ...draft[currentIndex],
  351. ...data,
  352. }
  353. }
  354. })
  355. _loopResult = newLoopRunResult
  356. setLoopRunResult(newLoopRunResult)
  357. },
  358. onNodeStarted: (params) => {
  359. const newLoopRunResult = produce(_loopResult, (draft) => {
  360. draft.push({
  361. ...params.data,
  362. status: NodeRunningStatus.Running,
  363. })
  364. })
  365. _loopResult = newLoopRunResult
  366. setLoopRunResult(newLoopRunResult)
  367. },
  368. onNodeFinished: (params) => {
  369. const loopRunResult = _loopResult
  370. const { data } = params
  371. const currentIndex = loopRunResult.findIndex(trace => trace.id === data.id)
  372. const newLoopRunResult = produce(loopRunResult, (draft) => {
  373. if (currentIndex > -1) {
  374. draft[currentIndex] = {
  375. ...draft[currentIndex],
  376. ...data,
  377. }
  378. }
  379. })
  380. _loopResult = newLoopRunResult
  381. setLoopRunResult(newLoopRunResult)
  382. },
  383. onNodeRetry: (params) => {
  384. const newLoopRunResult = produce(_loopResult, (draft) => {
  385. draft.push(params.data)
  386. })
  387. _loopResult = newLoopRunResult
  388. setLoopRunResult(newLoopRunResult)
  389. },
  390. onError: () => {
  391. handleNodeDataUpdate({
  392. id,
  393. data: {
  394. ...data,
  395. _singleRunningStatus: NodeRunningStatus.Failed,
  396. },
  397. })
  398. },
  399. },
  400. )
  401. }
  402. if (res && res.error)
  403. throw new Error(res.error)
  404. }
  405. catch (e: any) {
  406. console.error(e)
  407. if (!isIteration && !isLoop) {
  408. handleNodeDataUpdate({
  409. id,
  410. data: {
  411. ...data,
  412. _singleRunningStatus: NodeRunningStatus.Failed,
  413. },
  414. })
  415. return false
  416. }
  417. }
  418. finally {
  419. if (!isIteration && !isLoop) {
  420. setRunResult({
  421. ...res,
  422. total_tokens: res.execution_metadata?.total_tokens || 0,
  423. created_by: res.created_by_account?.name || '',
  424. })
  425. }
  426. }
  427. if (!isIteration && !isLoop) {
  428. handleNodeDataUpdate({
  429. id,
  430. data: {
  431. ...data,
  432. _singleRunningStatus: NodeRunningStatus.Succeeded,
  433. },
  434. })
  435. }
  436. }
  437. const handleStop = () => {
  438. handleNodeDataUpdate({
  439. id,
  440. data: {
  441. ...data,
  442. _singleRunningStatus: NodeRunningStatus.NotStart,
  443. },
  444. })
  445. }
  446. const toVarInputs = (variables: Variable[]): InputVar[] => {
  447. if (!variables)
  448. return []
  449. const varInputs = variables.filter(item => !isENV(item.value_selector)).map((item) => {
  450. const originalVar = getVar(item.value_selector)
  451. if (!originalVar) {
  452. return {
  453. label: item.label || item.variable,
  454. variable: item.variable,
  455. type: InputVarType.textInput,
  456. required: true,
  457. value_selector: item.value_selector,
  458. }
  459. }
  460. return {
  461. label: item.label || item.variable,
  462. variable: item.variable,
  463. type: varTypeToInputVarType(originalVar.type, {
  464. isSelect: !!originalVar.isSelect,
  465. isParagraph: !!originalVar.isParagraph,
  466. }),
  467. required: item.required !== false,
  468. options: originalVar.options,
  469. }
  470. })
  471. return varInputs
  472. }
  473. const getInputVars = (textList: string[]) => {
  474. const valueSelectors: ValueSelector[] = []
  475. textList.forEach((text) => {
  476. valueSelectors.push(...doGetInputVars(text))
  477. })
  478. const variables = unionBy(valueSelectors, item => item.join('.')).map((item) => {
  479. const varInfo = getNodeInfoById(availableNodesIncludeParent, item[0])?.data
  480. return {
  481. label: {
  482. nodeType: varInfo?.type,
  483. nodeName: varInfo?.title || availableNodesIncludeParent[0]?.data.title, // default start node title
  484. variable: isSystemVar(item) ? item.join('.') : item[item.length - 1],
  485. isChatVar: isConversationVar(item),
  486. },
  487. variable: `#${item.join('.')}#`,
  488. value_selector: item,
  489. }
  490. })
  491. const varInputs = toVarInputs(variables)
  492. return varInputs
  493. }
  494. return {
  495. isShowSingleRun,
  496. hideSingleRun,
  497. showSingleRun,
  498. toVarInputs,
  499. getInputVars,
  500. runningStatus,
  501. isCompleted,
  502. handleRun,
  503. handleStop,
  504. runInputData,
  505. runInputDataRef,
  506. setRunInputData: handleSetRunInputData,
  507. runResult,
  508. iterationRunResult,
  509. loopRunResult,
  510. }
  511. }
  512. export default useOneStepRun