index.tsx 14 KB

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