use-one-step-run.ts 13 KB

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