use-checklist.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import {
  2. useCallback,
  3. useMemo,
  4. useRef,
  5. } from 'react'
  6. import { useTranslation } from 'react-i18next'
  7. import { useStoreApi } from 'reactflow'
  8. import type {
  9. CommonNodeType,
  10. Edge,
  11. Node,
  12. } from '../types'
  13. import { BlockEnum } from '../types'
  14. import { useStore } from '../store'
  15. import {
  16. getToolCheckParams,
  17. getValidTreeNodes,
  18. } from '../utils'
  19. import {
  20. CUSTOM_NODE,
  21. MAX_TREE_DEPTH,
  22. } from '../constants'
  23. import type { ToolNodeType } from '../nodes/tool/types'
  24. import { useIsChatMode } from './use-workflow'
  25. import { useNodesExtraData } from './use-nodes-data'
  26. import { useToastContext } from '@/app/components/base/toast'
  27. import { CollectionType } from '@/app/components/tools/types'
  28. import { useGetLanguage } from '@/context/i18n'
  29. import type { AgentNodeType } from '../nodes/agent/types'
  30. import { useStrategyProviders } from '@/service/use-strategy'
  31. import { canFindTool } from '@/utils'
  32. import { useDatasetsDetailStore } from '../datasets-detail-store/store'
  33. import type { KnowledgeRetrievalNodeType } from '../nodes/knowledge-retrieval/types'
  34. import type { DataSet } from '@/models/datasets'
  35. import { fetchDatasets } from '@/service/datasets'
  36. export const useChecklist = (nodes: Node[], edges: Edge[]) => {
  37. const { t } = useTranslation()
  38. const language = useGetLanguage()
  39. const nodesExtraData = useNodesExtraData()
  40. const isChatMode = useIsChatMode()
  41. const buildInTools = useStore(s => s.buildInTools)
  42. const customTools = useStore(s => s.customTools)
  43. const workflowTools = useStore(s => s.workflowTools)
  44. const { data: strategyProviders } = useStrategyProviders()
  45. const datasetsDetail = useDatasetsDetailStore(s => s.datasetsDetail)
  46. const getCheckData = useCallback((data: CommonNodeType<{}>) => {
  47. let checkData = data
  48. if (data.type === BlockEnum.KnowledgeRetrieval) {
  49. const datasetIds = (data as CommonNodeType<KnowledgeRetrievalNodeType>).dataset_ids
  50. const _datasets = datasetIds.reduce<DataSet[]>((acc, id) => {
  51. if (datasetsDetail[id])
  52. acc.push(datasetsDetail[id])
  53. return acc
  54. }, [])
  55. checkData = {
  56. ...data,
  57. _datasets,
  58. } as CommonNodeType<KnowledgeRetrievalNodeType>
  59. }
  60. return checkData
  61. }, [datasetsDetail])
  62. const needWarningNodes = useMemo(() => {
  63. const list = []
  64. const { validNodes } = getValidTreeNodes(nodes.filter(node => node.type === CUSTOM_NODE), edges)
  65. for (let i = 0; i < nodes.length; i++) {
  66. const node = nodes[i]
  67. let toolIcon
  68. let moreDataForCheckValid
  69. if (node.data.type === BlockEnum.Tool) {
  70. const { provider_type } = node.data
  71. moreDataForCheckValid = getToolCheckParams(node.data as ToolNodeType, buildInTools, customTools, workflowTools, language)
  72. if (provider_type === CollectionType.builtIn)
  73. toolIcon = buildInTools.find(tool => canFindTool(tool.id, node.data.provider_id || ''))?.icon
  74. if (provider_type === CollectionType.custom)
  75. toolIcon = customTools.find(tool => tool.id === node.data.provider_id)?.icon
  76. if (provider_type === CollectionType.workflow)
  77. toolIcon = workflowTools.find(tool => tool.id === node.data.provider_id)?.icon
  78. }
  79. if (node.data.type === BlockEnum.Agent) {
  80. const data = node.data as AgentNodeType
  81. const isReadyForCheckValid = !!strategyProviders
  82. const provider = strategyProviders?.find(provider => provider.declaration.identity.name === data.agent_strategy_provider_name)
  83. const strategy = provider?.declaration.strategies?.find(s => s.identity.name === data.agent_strategy_name)
  84. moreDataForCheckValid = {
  85. provider,
  86. strategy,
  87. language,
  88. isReadyForCheckValid,
  89. }
  90. }
  91. if (node.type === CUSTOM_NODE) {
  92. const checkData = getCheckData(node.data)
  93. const { errorMessage } = nodesExtraData[node.data.type].checkValid(checkData, t, moreDataForCheckValid)
  94. if (errorMessage || !validNodes.find(n => n.id === node.id)) {
  95. list.push({
  96. id: node.id,
  97. type: node.data.type,
  98. title: node.data.title,
  99. toolIcon,
  100. unConnected: !validNodes.find(n => n.id === node.id),
  101. errorMessage,
  102. })
  103. }
  104. }
  105. }
  106. if (isChatMode && !nodes.find(node => node.data.type === BlockEnum.Answer)) {
  107. list.push({
  108. id: 'answer-need-added',
  109. type: BlockEnum.Answer,
  110. title: t('workflow.blocks.answer'),
  111. errorMessage: t('workflow.common.needAnswerNode'),
  112. })
  113. }
  114. if (!isChatMode && !nodes.find(node => node.data.type === BlockEnum.End)) {
  115. list.push({
  116. id: 'end-need-added',
  117. type: BlockEnum.End,
  118. title: t('workflow.blocks.end'),
  119. errorMessage: t('workflow.common.needEndNode'),
  120. })
  121. }
  122. return list
  123. }, [nodes, edges, isChatMode, buildInTools, customTools, workflowTools, language, nodesExtraData, t, strategyProviders, getCheckData])
  124. return needWarningNodes
  125. }
  126. export const useChecklistBeforePublish = () => {
  127. const { t } = useTranslation()
  128. const language = useGetLanguage()
  129. const buildInTools = useStore(s => s.buildInTools)
  130. const customTools = useStore(s => s.customTools)
  131. const workflowTools = useStore(s => s.workflowTools)
  132. const { notify } = useToastContext()
  133. const isChatMode = useIsChatMode()
  134. const store = useStoreApi()
  135. const nodesExtraData = useNodesExtraData()
  136. const { data: strategyProviders } = useStrategyProviders()
  137. const updateDatasetsDetail = useDatasetsDetailStore(s => s.updateDatasetsDetail)
  138. const updateTime = useRef(0)
  139. const getCheckData = useCallback((data: CommonNodeType<{}>, datasets: DataSet[]) => {
  140. let checkData = data
  141. if (data.type === BlockEnum.KnowledgeRetrieval) {
  142. const datasetIds = (data as CommonNodeType<KnowledgeRetrievalNodeType>).dataset_ids
  143. const datasetsDetail = datasets.reduce<Record<string, DataSet>>((acc, dataset) => {
  144. acc[dataset.id] = dataset
  145. return acc
  146. }, {})
  147. const _datasets = datasetIds.reduce<DataSet[]>((acc, id) => {
  148. if (datasetsDetail[id])
  149. acc.push(datasetsDetail[id])
  150. return acc
  151. }, [])
  152. checkData = {
  153. ...data,
  154. _datasets,
  155. } as CommonNodeType<KnowledgeRetrievalNodeType>
  156. }
  157. return checkData
  158. }, [])
  159. const handleCheckBeforePublish = useCallback(async () => {
  160. const {
  161. getNodes,
  162. edges,
  163. } = store.getState()
  164. const nodes = getNodes().filter(node => node.type === CUSTOM_NODE)
  165. const {
  166. validNodes,
  167. maxDepth,
  168. } = getValidTreeNodes(nodes.filter(node => node.type === CUSTOM_NODE), edges)
  169. if (maxDepth > MAX_TREE_DEPTH) {
  170. notify({ type: 'error', message: t('workflow.common.maxTreeDepth', { depth: MAX_TREE_DEPTH }) })
  171. return false
  172. }
  173. // Before publish, we need to fetch datasets detail, in case of the settings of datasets have been changed
  174. const knowledgeRetrievalNodes = nodes.filter(node => node.data.type === BlockEnum.KnowledgeRetrieval)
  175. const allDatasetIds = knowledgeRetrievalNodes.reduce<string[]>((acc, node) => {
  176. return Array.from(new Set([...acc, ...(node.data as CommonNodeType<KnowledgeRetrievalNodeType>).dataset_ids]))
  177. }, [])
  178. let datasets: DataSet[] = []
  179. if (allDatasetIds.length > 0) {
  180. updateTime.current = updateTime.current + 1
  181. const currUpdateTime = updateTime.current
  182. const { data: datasetsDetail } = await fetchDatasets({ url: '/datasets', params: { page: 1, ids: allDatasetIds } })
  183. if (datasetsDetail && datasetsDetail.length > 0) {
  184. // avoid old data to overwrite the new data
  185. if (currUpdateTime < updateTime.current)
  186. return false
  187. datasets = datasetsDetail
  188. updateDatasetsDetail(datasetsDetail)
  189. }
  190. }
  191. for (let i = 0; i < nodes.length; i++) {
  192. const node = nodes[i]
  193. let moreDataForCheckValid
  194. if (node.data.type === BlockEnum.Tool)
  195. moreDataForCheckValid = getToolCheckParams(node.data as ToolNodeType, buildInTools, customTools, workflowTools, language)
  196. if (node.data.type === BlockEnum.Agent) {
  197. const data = node.data as AgentNodeType
  198. const isReadyForCheckValid = !!strategyProviders
  199. const provider = strategyProviders?.find(provider => provider.declaration.identity.name === data.agent_strategy_provider_name)
  200. const strategy = provider?.declaration.strategies?.find(s => s.identity.name === data.agent_strategy_name)
  201. moreDataForCheckValid = {
  202. provider,
  203. strategy,
  204. language,
  205. isReadyForCheckValid,
  206. }
  207. }
  208. const checkData = getCheckData(node.data, datasets)
  209. const { errorMessage } = nodesExtraData[node.data.type as BlockEnum].checkValid(checkData, t, moreDataForCheckValid)
  210. if (errorMessage) {
  211. notify({ type: 'error', message: `[${node.data.title}] ${errorMessage}` })
  212. return false
  213. }
  214. if (!validNodes.find(n => n.id === node.id)) {
  215. notify({ type: 'error', message: `[${node.data.title}] ${t('workflow.common.needConnectTip')}` })
  216. return false
  217. }
  218. }
  219. if (isChatMode && !nodes.find(node => node.data.type === BlockEnum.Answer)) {
  220. notify({ type: 'error', message: t('workflow.common.needAnswerNode') })
  221. return false
  222. }
  223. if (!isChatMode && !nodes.find(node => node.data.type === BlockEnum.End)) {
  224. notify({ type: 'error', message: t('workflow.common.needEndNode') })
  225. return false
  226. }
  227. return true
  228. }, [store, isChatMode, notify, t, buildInTools, customTools, workflowTools, language, nodesExtraData, strategyProviders, updateDatasetsDetail, getCheckData])
  229. return {
  230. handleCheckBeforePublish,
  231. }
  232. }