use-one-step-run.ts 15 KB

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