use-config.ts 10 KB

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