use-one-step-run.ts 13 KB

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