use-one-step-run.ts 14 KB

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