use-one-step-run.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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 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 iterationTimes = iteratorInputKey ? runInputData[iteratorInputKey].length : 0
  129. const [runResult, setRunResult] = useState<any>(null)
  130. const { handleNodeDataUpdate }: { handleNodeDataUpdate: (data: any) => void } = useNodeDataUpdate()
  131. const [canShowSingleRun, setCanShowSingleRun] = useState(false)
  132. const isShowSingleRun = data._isSingleRun && canShowSingleRun
  133. const [iterationRunResult, setIterationRunResult] = useState<NodeTracing[]>([])
  134. useEffect(() => {
  135. if (!checkValid) {
  136. setCanShowSingleRun(true)
  137. return
  138. }
  139. if (data._isSingleRun) {
  140. const { isValid, errorMessage } = checkValid(data, t, moreDataForCheckValid)
  141. setCanShowSingleRun(isValid)
  142. if (!isValid) {
  143. handleNodeDataUpdate({
  144. id,
  145. data: {
  146. ...data,
  147. _isSingleRun: false,
  148. },
  149. })
  150. Toast.notify({
  151. type: 'error',
  152. message: errorMessage,
  153. })
  154. }
  155. }
  156. // eslint-disable-next-line react-hooks/exhaustive-deps
  157. }, [data._isSingleRun])
  158. const workflowStore = useWorkflowStore()
  159. useEffect(() => {
  160. workflowStore.getState().setShowSingleRunPanel(!!isShowSingleRun)
  161. }, [isShowSingleRun, workflowStore])
  162. const hideSingleRun = () => {
  163. handleNodeDataUpdate({
  164. id,
  165. data: {
  166. ...data,
  167. _isSingleRun: false,
  168. },
  169. })
  170. }
  171. const showSingleRun = () => {
  172. handleNodeDataUpdate({
  173. id,
  174. data: {
  175. ...data,
  176. _isSingleRun: true,
  177. },
  178. })
  179. }
  180. const runningStatus = data._singleRunningStatus || NodeRunningStatus.NotStart
  181. const isCompleted = runningStatus === NodeRunningStatus.Succeeded || runningStatus === NodeRunningStatus.Failed
  182. const handleRun = async (submitData: Record<string, any>) => {
  183. handleNodeDataUpdate({
  184. id,
  185. data: {
  186. ...data,
  187. _singleRunningStatus: NodeRunningStatus.Running,
  188. },
  189. })
  190. let res: any
  191. try {
  192. if (!isIteration) {
  193. res = await singleNodeRun(appId!, id, { inputs: submitData }) as any
  194. }
  195. else {
  196. setIterationRunResult([])
  197. let _iterationResult: NodeTracing[] = []
  198. let _runResult: any = null
  199. ssePost(
  200. getIterationSingleNodeRunUrl(isChatMode, appId!, id),
  201. { body: { inputs: submitData } },
  202. {
  203. onWorkflowStarted: () => {
  204. },
  205. onWorkflowFinished: (params) => {
  206. handleNodeDataUpdate({
  207. id,
  208. data: {
  209. ...data,
  210. _singleRunningStatus: NodeRunningStatus.Succeeded,
  211. },
  212. })
  213. const { data: iterationData } = params
  214. _runResult.created_by = iterationData.created_by.name
  215. setRunResult(_runResult)
  216. },
  217. onIterationStart: (params) => {
  218. const newIterationRunResult = produce(_iterationResult, (draft) => {
  219. draft.push({
  220. ...params.data,
  221. status: NodeRunningStatus.Running,
  222. })
  223. })
  224. _iterationResult = newIterationRunResult
  225. setIterationRunResult(newIterationRunResult)
  226. },
  227. onIterationNext: () => {
  228. // iteration next trigger time is triggered one more time than iterationTimes
  229. if (_iterationResult.length >= iterationTimes!)
  230. return _iterationResult.length >= iterationTimes!
  231. },
  232. onIterationFinish: (params) => {
  233. _runResult = params.data
  234. setRunResult(_runResult)
  235. const iterationRunResult = _iterationResult
  236. const currentIndex = iterationRunResult.findIndex(trace => trace.id === params.data.id)
  237. const newIterationRunResult = produce(iterationRunResult, (draft) => {
  238. if (currentIndex > -1) {
  239. draft[currentIndex] = {
  240. ...draft[currentIndex],
  241. ...data,
  242. }
  243. }
  244. })
  245. _iterationResult = newIterationRunResult
  246. setIterationRunResult(newIterationRunResult)
  247. },
  248. onNodeStarted: (params) => {
  249. const newIterationRunResult = produce(_iterationResult, (draft) => {
  250. draft.push({
  251. ...params.data,
  252. status: NodeRunningStatus.Running,
  253. })
  254. })
  255. _iterationResult = newIterationRunResult
  256. setIterationRunResult(newIterationRunResult)
  257. },
  258. onNodeFinished: (params) => {
  259. const iterationRunResult = _iterationResult
  260. const { data } = params
  261. const currentIndex = iterationRunResult.findIndex(trace => trace.id === data.id)
  262. const newIterationRunResult = produce(iterationRunResult, (draft) => {
  263. if (currentIndex > -1) {
  264. draft[currentIndex] = {
  265. ...draft[currentIndex],
  266. ...data,
  267. }
  268. }
  269. })
  270. _iterationResult = newIterationRunResult
  271. setIterationRunResult(newIterationRunResult)
  272. },
  273. onNodeRetry: (params) => {
  274. const newIterationRunResult = produce(_iterationResult, (draft) => {
  275. draft.push(params.data)
  276. })
  277. _iterationResult = newIterationRunResult
  278. setIterationRunResult(newIterationRunResult)
  279. },
  280. onError: () => {
  281. handleNodeDataUpdate({
  282. id,
  283. data: {
  284. ...data,
  285. _singleRunningStatus: NodeRunningStatus.Failed,
  286. },
  287. })
  288. },
  289. },
  290. )
  291. }
  292. if (res.error)
  293. throw new Error(res.error)
  294. }
  295. catch (e: any) {
  296. if (!isIteration) {
  297. handleNodeDataUpdate({
  298. id,
  299. data: {
  300. ...data,
  301. _singleRunningStatus: NodeRunningStatus.Failed,
  302. },
  303. })
  304. return false
  305. }
  306. }
  307. finally {
  308. if (!isIteration) {
  309. setRunResult({
  310. ...res,
  311. total_tokens: res.execution_metadata?.total_tokens || 0,
  312. created_by: res.created_by_account?.name || '',
  313. })
  314. }
  315. }
  316. if (!isIteration) {
  317. handleNodeDataUpdate({
  318. id,
  319. data: {
  320. ...data,
  321. _singleRunningStatus: NodeRunningStatus.Succeeded,
  322. },
  323. })
  324. }
  325. }
  326. const handleStop = () => {
  327. handleNodeDataUpdate({
  328. id,
  329. data: {
  330. ...data,
  331. _singleRunningStatus: NodeRunningStatus.NotStart,
  332. },
  333. })
  334. }
  335. const toVarInputs = (variables: Variable[]): InputVar[] => {
  336. if (!variables)
  337. return []
  338. const varInputs = variables.filter(item => !isENV(item.value_selector)).map((item) => {
  339. const originalVar = getVar(item.value_selector)
  340. if (!originalVar) {
  341. return {
  342. label: item.label || item.variable,
  343. variable: item.variable,
  344. type: InputVarType.textInput,
  345. required: true,
  346. value_selector: item.value_selector,
  347. }
  348. }
  349. return {
  350. label: item.label || item.variable,
  351. variable: item.variable,
  352. type: varTypeToInputVarType(originalVar.type, {
  353. isSelect: !!originalVar.isSelect,
  354. isParagraph: !!originalVar.isParagraph,
  355. }),
  356. required: item.required !== false,
  357. options: originalVar.options,
  358. }
  359. })
  360. return varInputs
  361. }
  362. const getInputVars = (textList: string[]) => {
  363. const valueSelectors: ValueSelector[] = []
  364. textList.forEach((text) => {
  365. valueSelectors.push(...doGetInputVars(text))
  366. })
  367. const variables = unionBy(valueSelectors, item => item.join('.')).map((item) => {
  368. const varInfo = getNodeInfoById(availableNodesIncludeParent, item[0])?.data
  369. return {
  370. label: {
  371. nodeType: varInfo?.type,
  372. nodeName: varInfo?.title || availableNodesIncludeParent[0]?.data.title, // default start node title
  373. variable: isSystemVar(item) ? item.join('.') : item[item.length - 1],
  374. isChatVar: isConversationVar(item),
  375. },
  376. variable: `#${item.join('.')}#`,
  377. value_selector: item,
  378. }
  379. })
  380. const varInputs = toVarInputs(variables)
  381. return varInputs
  382. }
  383. return {
  384. isShowSingleRun,
  385. hideSingleRun,
  386. showSingleRun,
  387. toVarInputs,
  388. getInputVars,
  389. runningStatus,
  390. isCompleted,
  391. handleRun,
  392. handleStop,
  393. runInputData,
  394. setRunInputData,
  395. runResult,
  396. iterationRunResult,
  397. }
  398. }
  399. export default useOneStepRun