use-config.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. import { useCallback, useEffect, 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 } = 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 currentTools = isBuiltIn ? buildInTools : customTools
  36. const currCollection = currentTools.find(item => item.id === provider_id)
  37. // Auth
  38. const needAuth = !!currCollection?.allow_delete
  39. const isAuthed = !!currCollection?.is_team_authorization
  40. const isShowAuthBtn = isBuiltIn && needAuth && !isAuthed
  41. const [showSetAuth, {
  42. setTrue: showSetAuthModal,
  43. setFalse: hideSetAuthModal,
  44. }] = useBoolean(false)
  45. const handleSaveAuth = useCallback(async (value: any) => {
  46. await updateBuiltInToolCredential(currCollection?.name as string, value)
  47. Toast.notify({
  48. type: 'success',
  49. message: t('common.api.actionSuccess'),
  50. })
  51. handleFetchAllTools(provider_type)
  52. hideSetAuthModal()
  53. }, [currCollection?.name, hideSetAuthModal, t, handleFetchAllTools, provider_type])
  54. const currTool = currCollection?.tools.find(tool => tool.name === tool_name)
  55. const formSchemas = currTool ? toolParametersToFormSchemas(currTool.parameters) : []
  56. const toolInputVarSchema = formSchemas.filter((item: any) => item.form === 'llm')
  57. // use setting
  58. const toolSettingSchema = formSchemas.filter((item: any) => item.form !== 'llm')
  59. const [notSetDefaultValue, setNotSetDefaultValue] = useState(false)
  60. const toolSettingValue = (() => {
  61. if (notSetDefaultValue)
  62. return tool_configurations
  63. return addDefaultValue(tool_configurations, toolSettingSchema)
  64. })()
  65. const setToolSettingValue = useCallback((value: Record<string, any>) => {
  66. setNotSetDefaultValue(true)
  67. setInputs({
  68. ...inputs,
  69. tool_configurations: value,
  70. })
  71. }, [inputs, setInputs])
  72. useEffect(() => {
  73. if (!currTool)
  74. return
  75. const inputsWithDefaultValue = produce(inputs, (draft) => {
  76. if (!draft.tool_configurations || Object.keys(draft.tool_configurations).length === 0)
  77. draft.tool_configurations = addDefaultValue(tool_configurations, toolSettingSchema)
  78. if (!draft.tool_parameters)
  79. draft.tool_parameters = {}
  80. })
  81. setInputs(inputsWithDefaultValue)
  82. // eslint-disable-next-line react-hooks/exhaustive-deps
  83. }, [currTool])
  84. // setting when call
  85. const setInputVar = useCallback((value: ToolVarInputs) => {
  86. setInputs({
  87. ...inputs,
  88. tool_parameters: value,
  89. })
  90. }, [inputs, setInputs])
  91. const [currVarIndex, setCurrVarIndex] = useState(-1)
  92. const currVarType = toolInputVarSchema[currVarIndex]?._type
  93. const handleOnVarOpen = useCallback((index: number) => {
  94. setCurrVarIndex(index)
  95. }, [])
  96. const filterVar = useCallback((varPayload: Var) => {
  97. if (currVarType)
  98. return varPayload.type === currVarType
  99. return varPayload.type !== VarVarType.arrayFile
  100. }, [currVarType])
  101. const isLoading = currTool && (isBuiltIn ? !currCollection : false)
  102. // single run
  103. const [inputVarValues, doSetInputVarValues] = useState<Record<string, any>>({})
  104. const setInputVarValues = (value: Record<string, any>) => {
  105. doSetInputVarValues(value)
  106. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  107. setRunInputData(value)
  108. }
  109. // fill single run form variable with constant value first time
  110. const inputVarValuesWithConstantValue = () => {
  111. const res = produce(inputVarValues, (draft) => {
  112. Object.keys(inputs.tool_parameters).forEach((key: string) => {
  113. const { type, value } = inputs.tool_parameters[key]
  114. if (type === VarType.constant && (value === undefined || value === null))
  115. draft.tool_parameters[key].value = value
  116. })
  117. })
  118. return res
  119. }
  120. const {
  121. isShowSingleRun,
  122. hideSingleRun,
  123. getInputVars,
  124. runningStatus,
  125. setRunInputData,
  126. handleRun: doHandleRun,
  127. handleStop,
  128. runResult,
  129. } = useOneStepRun<ToolNodeType>({
  130. id,
  131. data: inputs,
  132. defaultRunInputData: {},
  133. moreDataForCheckValid: {
  134. toolInputsSchema: (() => {
  135. const formInputs: InputVar[] = []
  136. toolInputVarSchema.forEach((item: any) => {
  137. formInputs.push({
  138. label: item.label[language] || item.label.en_US,
  139. variable: item.variable,
  140. type: item.type,
  141. required: item.required,
  142. })
  143. })
  144. return formInputs
  145. })(),
  146. notAuthed: isShowAuthBtn,
  147. toolSettingSchema,
  148. language,
  149. },
  150. })
  151. const hadVarParams = Object.keys(inputs.tool_parameters)
  152. .filter(key => inputs.tool_parameters[key].type !== VarType.constant)
  153. .map(k => inputs.tool_parameters[k])
  154. const varInputs = getInputVars(hadVarParams.map((p) => {
  155. if (p.type === VarType.variable)
  156. return `{{#${(p.value as ValueSelector).join('.')}#}}`
  157. return p.value as string
  158. }))
  159. const singleRunForms = (() => {
  160. const forms: FormProps[] = [{
  161. inputs: varInputs,
  162. values: inputVarValuesWithConstantValue(),
  163. onChange: setInputVarValues,
  164. }]
  165. return forms
  166. })()
  167. const handleRun = (submitData: Record<string, any>) => {
  168. const varTypeInputKeys = Object.keys(inputs.tool_parameters)
  169. .filter(key => inputs.tool_parameters[key].type === VarType.variable)
  170. const shouldAdd = varTypeInputKeys.length > 0
  171. if (!shouldAdd) {
  172. doHandleRun(submitData)
  173. return
  174. }
  175. const addMissedVarData = { ...submitData }
  176. Object.keys(submitData).forEach((key) => {
  177. const value = submitData[key]
  178. varTypeInputKeys.forEach((inputKey) => {
  179. const inputValue = inputs.tool_parameters[inputKey].value as ValueSelector
  180. if (`#${inputValue.join('.')}#` === key)
  181. addMissedVarData[inputKey] = value
  182. })
  183. })
  184. doHandleRun(addMissedVarData)
  185. }
  186. return {
  187. readOnly,
  188. inputs,
  189. currTool,
  190. toolSettingSchema,
  191. toolSettingValue,
  192. setToolSettingValue,
  193. toolInputVarSchema,
  194. setInputVar,
  195. handleOnVarOpen,
  196. filterVar,
  197. currCollection,
  198. isShowAuthBtn,
  199. showSetAuth,
  200. showSetAuthModal,
  201. hideSetAuthModal,
  202. handleSaveAuth,
  203. isLoading,
  204. isShowSingleRun,
  205. hideSingleRun,
  206. inputVarValues,
  207. varInputs,
  208. setInputVarValues,
  209. singleRunForms,
  210. runningStatus,
  211. handleRun,
  212. handleStop,
  213. runResult,
  214. }
  215. }
  216. export default useConfig