index.tsx 14 KB

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