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