use-one-step-run.ts 13 KB

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