index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. import type { FC } from 'react'
  2. import {
  3. memo,
  4. useCallback,
  5. useEffect,
  6. useMemo,
  7. useState,
  8. } from 'react'
  9. import { useTranslation } from 'react-i18next'
  10. import type {
  11. CredentialFormSchema,
  12. CredentialFormSchemaRadio,
  13. CredentialFormSchemaSelect,
  14. CustomConfigurationModelFixedFields,
  15. FormValue,
  16. ModelLoadBalancingConfig,
  17. ModelLoadBalancingConfigEntry,
  18. ModelProvider,
  19. } from '../declarations'
  20. import {
  21. ConfigurationMethodEnum,
  22. CustomConfigurationStatusEnum,
  23. FormTypeEnum,
  24. } from '../declarations'
  25. import {
  26. genModelNameFormSchema,
  27. genModelTypeFormSchema,
  28. removeCredentials,
  29. saveCredentials,
  30. } from '../utils'
  31. import {
  32. useLanguage,
  33. useProviderCredentialsAndLoadBalancing,
  34. } from '../hooks'
  35. import ProviderIcon from '../provider-icon'
  36. import { useValidate } from '../../key-validator/hooks'
  37. import { ValidatedStatus } from '../../key-validator/declarations'
  38. import ModelLoadBalancingConfigs from '../provider-added-card/model-load-balancing-configs'
  39. import Form from './Form'
  40. import Button from '@/app/components/base/button'
  41. import { Lock01 } from '@/app/components/base/icons/src/vender/solid/security'
  42. import { LinkExternal02 } from '@/app/components/base/icons/src/vender/line/general'
  43. import { AlertCircle } from '@/app/components/base/icons/src/vender/solid/alertsAndFeedback'
  44. import {
  45. PortalToFollowElem,
  46. PortalToFollowElemContent,
  47. } from '@/app/components/base/portal-to-follow-elem'
  48. import { useToastContext } from '@/app/components/base/toast'
  49. import ConfirmCommon from '@/app/components/base/confirm/common'
  50. import { useAppContext } from '@/context/app-context'
  51. type ModelModalProps = {
  52. provider: ModelProvider
  53. configurateMethod: ConfigurationMethodEnum
  54. currentCustomConfigurationModelFixedFields?: CustomConfigurationModelFixedFields
  55. onCancel: () => void
  56. onSave: () => void
  57. }
  58. const ModelModal: FC<ModelModalProps> = ({
  59. provider,
  60. configurateMethod,
  61. currentCustomConfigurationModelFixedFields,
  62. onCancel,
  63. onSave,
  64. }) => {
  65. const providerFormSchemaPredefined = configurateMethod === ConfigurationMethodEnum.predefinedModel
  66. const {
  67. credentials: formSchemasValue,
  68. loadBalancing: originalConfig,
  69. mutate,
  70. } = useProviderCredentialsAndLoadBalancing(
  71. provider.provider,
  72. configurateMethod,
  73. providerFormSchemaPredefined && provider.custom_configuration.status === CustomConfigurationStatusEnum.active,
  74. currentCustomConfigurationModelFixedFields,
  75. )
  76. const { isCurrentWorkspaceManager } = useAppContext()
  77. const isEditMode = !!formSchemasValue && isCurrentWorkspaceManager
  78. const { t } = useTranslation()
  79. const { notify } = useToastContext()
  80. const language = useLanguage()
  81. const [loading, setLoading] = useState(false)
  82. const [showConfirm, setShowConfirm] = useState(false)
  83. const [draftConfig, setDraftConfig] = useState<ModelLoadBalancingConfig>()
  84. const originalConfigMap = useMemo(() => {
  85. if (!originalConfig)
  86. return {}
  87. return originalConfig?.configs.reduce((prev, config) => {
  88. if (config.id)
  89. prev[config.id] = config
  90. return prev
  91. }, {} as Record<string, ModelLoadBalancingConfigEntry>)
  92. }, [originalConfig])
  93. useEffect(() => {
  94. if (originalConfig && !draftConfig)
  95. setDraftConfig(originalConfig)
  96. }, [draftConfig, originalConfig])
  97. const formSchemas = useMemo(() => {
  98. return providerFormSchemaPredefined
  99. ? provider.provider_credential_schema.credential_form_schemas
  100. : [
  101. genModelTypeFormSchema(provider.supported_model_types),
  102. genModelNameFormSchema(provider.model_credential_schema?.model),
  103. ...(draftConfig?.enabled ? [] : provider.model_credential_schema.credential_form_schemas),
  104. ]
  105. }, [
  106. providerFormSchemaPredefined,
  107. provider.provider_credential_schema?.credential_form_schemas,
  108. provider.supported_model_types,
  109. provider.model_credential_schema?.credential_form_schemas,
  110. provider.model_credential_schema?.model,
  111. draftConfig?.enabled,
  112. ])
  113. const [
  114. requiredFormSchemas,
  115. defaultFormSchemaValue,
  116. showOnVariableMap,
  117. ] = useMemo(() => {
  118. const requiredFormSchemas: CredentialFormSchema[] = []
  119. const defaultFormSchemaValue: Record<string, string | number> = {}
  120. const showOnVariableMap: Record<string, string[]> = {}
  121. formSchemas.forEach((formSchema) => {
  122. if (formSchema.required)
  123. requiredFormSchemas.push(formSchema)
  124. if (formSchema.default)
  125. defaultFormSchemaValue[formSchema.variable] = formSchema.default
  126. if (formSchema.show_on.length) {
  127. formSchema.show_on.forEach((showOnItem) => {
  128. if (!showOnVariableMap[showOnItem.variable])
  129. showOnVariableMap[showOnItem.variable] = []
  130. if (!showOnVariableMap[showOnItem.variable].includes(formSchema.variable))
  131. showOnVariableMap[showOnItem.variable].push(formSchema.variable)
  132. })
  133. }
  134. if (formSchema.type === FormTypeEnum.select || formSchema.type === FormTypeEnum.radio) {
  135. (formSchema as (CredentialFormSchemaRadio | CredentialFormSchemaSelect)).options.forEach((option) => {
  136. if (option.show_on.length) {
  137. option.show_on.forEach((showOnItem) => {
  138. if (!showOnVariableMap[showOnItem.variable])
  139. showOnVariableMap[showOnItem.variable] = []
  140. if (!showOnVariableMap[showOnItem.variable].includes(formSchema.variable))
  141. showOnVariableMap[showOnItem.variable].push(formSchema.variable)
  142. })
  143. }
  144. })
  145. }
  146. })
  147. return [
  148. requiredFormSchemas,
  149. defaultFormSchemaValue,
  150. showOnVariableMap,
  151. ]
  152. }, [formSchemas])
  153. const initialFormSchemasValue: Record<string, string | number> = useMemo(() => {
  154. return {
  155. ...defaultFormSchemaValue,
  156. ...formSchemasValue,
  157. } as unknown as Record<string, string | number>
  158. }, [formSchemasValue, defaultFormSchemaValue])
  159. const [value, setValue] = useState(initialFormSchemasValue)
  160. useEffect(() => {
  161. setValue(initialFormSchemasValue)
  162. }, [initialFormSchemasValue])
  163. const [_, validating, validatedStatusState] = useValidate(value)
  164. const filteredRequiredFormSchemas = requiredFormSchemas.filter((requiredFormSchema) => {
  165. if (requiredFormSchema.show_on.length && requiredFormSchema.show_on.every(showOnItem => value[showOnItem.variable] === showOnItem.value))
  166. return true
  167. if (!requiredFormSchema.show_on.length)
  168. return true
  169. return false
  170. })
  171. const handleValueChange = (v: FormValue) => {
  172. setValue(v)
  173. }
  174. const extendedSecretFormSchemas = useMemo(
  175. () =>
  176. (providerFormSchemaPredefined
  177. ? provider.provider_credential_schema.credential_form_schemas
  178. : [
  179. genModelTypeFormSchema(provider.supported_model_types),
  180. genModelNameFormSchema(provider.model_credential_schema?.model),
  181. ...provider.model_credential_schema.credential_form_schemas,
  182. ]).filter(({ type }) => type === FormTypeEnum.secretInput),
  183. [
  184. provider.model_credential_schema?.credential_form_schemas,
  185. provider.model_credential_schema?.model,
  186. provider.provider_credential_schema?.credential_form_schemas,
  187. provider.supported_model_types,
  188. providerFormSchemaPredefined,
  189. ],
  190. )
  191. const encodeSecretValues = useCallback((v: FormValue) => {
  192. const result = { ...v }
  193. extendedSecretFormSchemas.forEach(({ variable }) => {
  194. if (result[variable] === formSchemasValue?.[variable] && result[variable] !== undefined)
  195. result[variable] = '[__HIDDEN__]'
  196. })
  197. return result
  198. }, [extendedSecretFormSchemas, formSchemasValue])
  199. const encodeConfigEntrySecretValues = useCallback((entry: ModelLoadBalancingConfigEntry) => {
  200. const result = { ...entry }
  201. extendedSecretFormSchemas.forEach(({ variable }) => {
  202. if (entry.id && result.credentials[variable] === originalConfigMap[entry.id]?.credentials?.[variable])
  203. result.credentials[variable] = '[__HIDDEN__]'
  204. })
  205. return result
  206. }, [extendedSecretFormSchemas, originalConfigMap])
  207. const handleSave = async () => {
  208. try {
  209. setLoading(true)
  210. const res = await saveCredentials(
  211. providerFormSchemaPredefined,
  212. provider.provider,
  213. encodeSecretValues(value),
  214. {
  215. ...draftConfig,
  216. enabled: Boolean(draftConfig?.enabled),
  217. configs: draftConfig?.configs.map(encodeConfigEntrySecretValues) || [],
  218. },
  219. )
  220. if (res.result === 'success') {
  221. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  222. mutate()
  223. onSave()
  224. onCancel()
  225. }
  226. }
  227. finally {
  228. setLoading(false)
  229. }
  230. }
  231. const handleRemove = async () => {
  232. try {
  233. setLoading(true)
  234. const res = await removeCredentials(
  235. providerFormSchemaPredefined,
  236. provider.provider,
  237. value,
  238. )
  239. if (res.result === 'success') {
  240. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  241. mutate()
  242. onSave()
  243. onCancel()
  244. }
  245. }
  246. finally {
  247. setLoading(false)
  248. }
  249. }
  250. const renderTitlePrefix = () => {
  251. const prefix = configurateMethod === ConfigurationMethodEnum.customizableModel ? t('common.operation.add') : t('common.operation.setup')
  252. return `${prefix} ${provider.label[language] || provider.label.en_US}`
  253. }
  254. return (
  255. <PortalToFollowElem open>
  256. <PortalToFollowElemContent className='w-full h-full z-[60]'>
  257. <div className='fixed inset-0 flex items-center justify-center bg-black/[.25]'>
  258. <div className='mx-2 w-[640px] max-h-[calc(100vh-120px)] bg-white shadow-xl rounded-2xl overflow-y-auto'>
  259. <div className='px-8 pt-8'>
  260. <div className='flex justify-between items-center mb-2'>
  261. <div className='text-xl font-semibold text-gray-900'>{renderTitlePrefix()}</div>
  262. <ProviderIcon provider={provider} />
  263. </div>
  264. <Form
  265. value={value}
  266. onChange={handleValueChange}
  267. formSchemas={formSchemas}
  268. validating={validating}
  269. validatedSuccess={validatedStatusState.status === ValidatedStatus.Success}
  270. showOnVariableMap={showOnVariableMap}
  271. isEditMode={isEditMode}
  272. />
  273. <div className='mt-1 mb-4 border-t-[0.5px] border-t-gray-100' />
  274. <ModelLoadBalancingConfigs withSwitch {...{
  275. draftConfig,
  276. setDraftConfig,
  277. provider,
  278. currentCustomConfigurationModelFixedFields,
  279. configurationMethod: configurateMethod,
  280. }} />
  281. <div className='sticky bottom-0 flex justify-between items-center mt-2 -mx-2 pt-4 px-2 pb-6 flex-wrap gap-y-2 bg-white'>
  282. {
  283. (provider.help && (provider.help.title || provider.help.url))
  284. ? (
  285. <a
  286. href={provider.help?.url[language] || provider.help?.url.en_US}
  287. target='_blank' rel='noopener noreferrer'
  288. className='inline-flex items-center text-xs text-primary-600'
  289. onClick={e => !provider.help.url && e.preventDefault()}
  290. >
  291. {provider.help.title?.[language] || provider.help.url[language] || provider.help.title?.en_US || provider.help.url.en_US}
  292. <LinkExternal02 className='ml-1 w-3 h-3' />
  293. </a>
  294. )
  295. : <div />
  296. }
  297. <div>
  298. {
  299. isEditMode && (
  300. <Button
  301. className='mr-2 h-9 text-sm font-medium text-[#D92D20]'
  302. onClick={() => setShowConfirm(true)}
  303. >
  304. {t('common.operation.remove')}
  305. </Button>
  306. )
  307. }
  308. <Button
  309. className='mr-2 h-9 text-sm font-medium text-gray-700'
  310. onClick={onCancel}
  311. >
  312. {t('common.operation.cancel')}
  313. </Button>
  314. <Button
  315. className='h-9 text-sm font-medium'
  316. type='primary'
  317. onClick={handleSave}
  318. disabled={
  319. loading
  320. || filteredRequiredFormSchemas.some(item => value[item.variable] === undefined)
  321. || (draftConfig?.enabled && (draftConfig?.configs.filter(config => config.enabled).length ?? 0) < 2)
  322. }
  323. >
  324. {t('common.operation.save')}
  325. </Button>
  326. </div>
  327. </div>
  328. </div>
  329. <div className='border-t-[0.5px] border-t-black/5'>
  330. {
  331. (validatedStatusState.status === ValidatedStatus.Error && validatedStatusState.message)
  332. ? (
  333. <div className='flex px-[10px] py-3 bg-[#FEF3F2] text-xs text-[#D92D20]'>
  334. <AlertCircle className='mt-[1px] mr-2 w-[14px] h-[14px]' />
  335. {validatedStatusState.message}
  336. </div>
  337. )
  338. : (
  339. <div className='flex justify-center items-center py-3 bg-gray-50 text-xs text-gray-500'>
  340. <Lock01 className='mr-1 w-3 h-3 text-gray-500' />
  341. {t('common.modelProvider.encrypted.front')}
  342. <a
  343. className='text-primary-600 mx-1'
  344. target='_blank' rel='noopener noreferrer'
  345. href='https://pycryptodome.readthedocs.io/en/latest/src/cipher/oaep.html'
  346. >
  347. PKCS1_OAEP
  348. </a>
  349. {t('common.modelProvider.encrypted.back')}
  350. </div>
  351. )
  352. }
  353. </div>
  354. </div>
  355. {
  356. showConfirm && (
  357. <ConfirmCommon
  358. title={t('common.modelProvider.confirmDelete')}
  359. isShow={showConfirm}
  360. onCancel={() => setShowConfirm(false)}
  361. onConfirm={handleRemove}
  362. confirmWrapperClassName='z-[70]'
  363. />
  364. )
  365. }
  366. </div>
  367. </PortalToFollowElemContent>
  368. </PortalToFollowElem>
  369. )
  370. }
  371. export default memo(ModelModal)