use-config.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import { useCallback, useEffect, useMemo, useState } from 'react'
  2. import { useTranslation } from 'react-i18next'
  3. import produce from 'immer'
  4. import { useBoolean } from 'ahooks'
  5. import { useStore } from '../../store'
  6. import { type ToolNodeType, type ToolVarInputs, VarType } from './types'
  7. import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'
  8. import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'
  9. import { CollectionType } from '@/app/components/tools/types'
  10. import { updateBuiltInToolCredential } from '@/service/tools'
  11. import { addDefaultValue, toolParametersToFormSchemas } from '@/app/components/tools/utils/to-form-schema'
  12. import Toast from '@/app/components/base/toast'
  13. import type { Props as FormProps } from '@/app/components/workflow/nodes/_base/components/before-run-form/form'
  14. import { VarType as VarVarType } from '@/app/components/workflow/types'
  15. import type { InputVar, ValueSelector, Var } from '@/app/components/workflow/types'
  16. import useOneStepRun from '@/app/components/workflow/nodes/_base/hooks/use-one-step-run'
  17. import {
  18. useFetchToolsData,
  19. useNodesReadOnly,
  20. } from '@/app/components/workflow/hooks'
  21. const useConfig = (id: string, payload: ToolNodeType) => {
  22. const { nodesReadOnly: readOnly } = useNodesReadOnly()
  23. const { handleFetchAllTools } = useFetchToolsData()
  24. const { t } = useTranslation()
  25. const language = useLanguage()
  26. const { inputs, setInputs: doSetInputs } = useNodeCrud<ToolNodeType>(id, payload)
  27. /*
  28. * tool_configurations: tool setting, not dynamic setting
  29. * tool_parameters: tool dynamic setting(by user)
  30. */
  31. const { provider_id, provider_type, tool_name, tool_configurations } = inputs
  32. const isBuiltIn = provider_type === CollectionType.builtIn
  33. const buildInTools = useStore(s => s.buildInTools)
  34. const customTools = useStore(s => s.customTools)
  35. const workflowTools = useStore(s => s.workflowTools)
  36. const currentTools = (() => {
  37. switch (provider_type) {
  38. case CollectionType.builtIn:
  39. return buildInTools
  40. case CollectionType.custom:
  41. return customTools
  42. case CollectionType.workflow:
  43. return workflowTools
  44. default:
  45. return []
  46. }
  47. })()
  48. const currCollection = currentTools.find(item => item.id === provider_id)
  49. // Auth
  50. const needAuth = !!currCollection?.allow_delete
  51. const isAuthed = !!currCollection?.is_team_authorization
  52. const isShowAuthBtn = isBuiltIn && needAuth && !isAuthed
  53. const [showSetAuth, {
  54. setTrue: showSetAuthModal,
  55. setFalse: hideSetAuthModal,
  56. }] = useBoolean(false)
  57. const handleSaveAuth = useCallback(async (value: any) => {
  58. await updateBuiltInToolCredential(currCollection?.name as string, value)
  59. Toast.notify({
  60. type: 'success',
  61. message: t('common.api.actionSuccess'),
  62. })
  63. handleFetchAllTools(provider_type)
  64. hideSetAuthModal()
  65. }, [currCollection?.name, hideSetAuthModal, t, handleFetchAllTools, provider_type])
  66. const currTool = currCollection?.tools.find(tool => tool.name === tool_name)
  67. const formSchemas = useMemo(() => {
  68. return currTool ? toolParametersToFormSchemas(currTool.parameters) : []
  69. }, [currTool])
  70. const toolInputVarSchema = formSchemas.filter((item: any) => item.form === 'llm')
  71. // use setting
  72. const toolSettingSchema = formSchemas.filter((item: any) => item.form !== 'llm')
  73. const hasShouldTransferTypeSettingInput = toolSettingSchema.some(item => item.type === 'boolean' || item.type === 'number-input')
  74. const setInputs = useCallback((value: ToolNodeType) => {
  75. if (!hasShouldTransferTypeSettingInput) {
  76. doSetInputs(value)
  77. return
  78. }
  79. const newInputs = produce(value, (draft) => {
  80. const newConfig = { ...draft.tool_configurations }
  81. Object.keys(draft.tool_configurations).forEach((key) => {
  82. const schema = formSchemas.find(item => item.variable === key)
  83. const value = newConfig[key]
  84. if (schema?.type === 'boolean') {
  85. if (typeof value === 'string')
  86. newConfig[key] = parseInt(value, 10)
  87. if (typeof value === 'boolean')
  88. newConfig[key] = value ? 1 : 0
  89. }
  90. if (schema?.type === 'number-input') {
  91. if (typeof value === 'string' && value !== '')
  92. newConfig[key] = parseFloat(value)
  93. }
  94. })
  95. draft.tool_configurations = newConfig
  96. })
  97. doSetInputs(newInputs)
  98. }, [doSetInputs, formSchemas, hasShouldTransferTypeSettingInput])
  99. const [notSetDefaultValue, setNotSetDefaultValue] = useState(false)
  100. const toolSettingValue = (() => {
  101. if (notSetDefaultValue)
  102. return tool_configurations
  103. return addDefaultValue(tool_configurations, toolSettingSchema)
  104. })()
  105. const setToolSettingValue = useCallback((value: Record<string, any>) => {
  106. setNotSetDefaultValue(true)
  107. setInputs({
  108. ...inputs,
  109. tool_configurations: value,
  110. })
  111. }, [inputs, setInputs])
  112. useEffect(() => {
  113. if (!currTool)
  114. return
  115. const inputsWithDefaultValue = produce(inputs, (draft) => {
  116. if (!draft.tool_configurations || Object.keys(draft.tool_configurations).length === 0)
  117. draft.tool_configurations = addDefaultValue(tool_configurations, toolSettingSchema)
  118. if (!draft.tool_parameters)
  119. draft.tool_parameters = {}
  120. })
  121. setInputs(inputsWithDefaultValue)
  122. // eslint-disable-next-line react-hooks/exhaustive-deps
  123. }, [currTool])
  124. // setting when call
  125. const setInputVar = useCallback((value: ToolVarInputs) => {
  126. setInputs({
  127. ...inputs,
  128. tool_parameters: value,
  129. })
  130. }, [inputs, setInputs])
  131. const [currVarIndex, setCurrVarIndex] = useState(-1)
  132. const currVarType = toolInputVarSchema[currVarIndex]?._type
  133. const handleOnVarOpen = useCallback((index: number) => {
  134. setCurrVarIndex(index)
  135. }, [])
  136. const filterVar = useCallback((varPayload: Var) => {
  137. if (currVarType)
  138. return varPayload.type === currVarType
  139. return varPayload.type !== VarVarType.arrayFile
  140. }, [currVarType])
  141. const isLoading = currTool && (isBuiltIn ? !currCollection : false)
  142. // single run
  143. const [inputVarValues, doSetInputVarValues] = useState<Record<string, any>>({})
  144. const setInputVarValues = (value: Record<string, any>) => {
  145. doSetInputVarValues(value)
  146. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  147. setRunInputData(value)
  148. }
  149. // fill single run form variable with constant value first time
  150. const inputVarValuesWithConstantValue = () => {
  151. const res = produce(inputVarValues, (draft) => {
  152. Object.keys(inputs.tool_parameters).forEach((key: string) => {
  153. const { type, value } = inputs.tool_parameters[key]
  154. if (type === VarType.constant && (value === undefined || value === null))
  155. draft.tool_parameters[key].value = value
  156. })
  157. })
  158. return res
  159. }
  160. const {
  161. isShowSingleRun,
  162. hideSingleRun,
  163. getInputVars,
  164. runningStatus,
  165. setRunInputData,
  166. handleRun: doHandleRun,
  167. handleStop,
  168. runResult,
  169. } = useOneStepRun<ToolNodeType>({
  170. id,
  171. data: inputs,
  172. defaultRunInputData: {},
  173. moreDataForCheckValid: {
  174. toolInputsSchema: (() => {
  175. const formInputs: InputVar[] = []
  176. toolInputVarSchema.forEach((item: any) => {
  177. formInputs.push({
  178. label: item.label[language] || item.label.en_US,
  179. variable: item.variable,
  180. type: item.type,
  181. required: item.required,
  182. })
  183. })
  184. return formInputs
  185. })(),
  186. notAuthed: isShowAuthBtn,
  187. toolSettingSchema,
  188. language,
  189. },
  190. })
  191. const hadVarParams = Object.keys(inputs.tool_parameters)
  192. .filter(key => inputs.tool_parameters[key].type !== VarType.constant)
  193. .map(k => inputs.tool_parameters[k])
  194. const varInputs = getInputVars(hadVarParams.map((p) => {
  195. if (p.type === VarType.variable)
  196. return `{{#${(p.value as ValueSelector).join('.')}#}}`
  197. return p.value as string
  198. }))
  199. const singleRunForms = (() => {
  200. const forms: FormProps[] = [{
  201. inputs: varInputs,
  202. values: inputVarValuesWithConstantValue(),
  203. onChange: setInputVarValues,
  204. }]
  205. return forms
  206. })()
  207. const handleRun = (submitData: Record<string, any>) => {
  208. const varTypeInputKeys = Object.keys(inputs.tool_parameters)
  209. .filter(key => inputs.tool_parameters[key].type === VarType.variable)
  210. const shouldAdd = varTypeInputKeys.length > 0
  211. if (!shouldAdd) {
  212. doHandleRun(submitData)
  213. return
  214. }
  215. const addMissedVarData = { ...submitData }
  216. Object.keys(submitData).forEach((key) => {
  217. const value = submitData[key]
  218. varTypeInputKeys.forEach((inputKey) => {
  219. const inputValue = inputs.tool_parameters[inputKey].value as ValueSelector
  220. if (`#${inputValue.join('.')}#` === key)
  221. addMissedVarData[inputKey] = value
  222. })
  223. })
  224. doHandleRun(addMissedVarData)
  225. }
  226. return {
  227. readOnly,
  228. inputs,
  229. currTool,
  230. toolSettingSchema,
  231. toolSettingValue,
  232. setToolSettingValue,
  233. toolInputVarSchema,
  234. setInputVar,
  235. handleOnVarOpen,
  236. filterVar,
  237. currCollection,
  238. isShowAuthBtn,
  239. showSetAuth,
  240. showSetAuthModal,
  241. hideSetAuthModal,
  242. handleSaveAuth,
  243. isLoading,
  244. isShowSingleRun,
  245. hideSingleRun,
  246. inputVarValues,
  247. varInputs,
  248. setInputVarValues,
  249. singleRunForms,
  250. runningStatus,
  251. handleRun,
  252. handleStop,
  253. runResult,
  254. }
  255. }
  256. export default useConfig