model-load-balancing-entry-modal.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. CredentialFormSchemaTextInput,
  18. CustomConfigurationModelFixedFields,
  19. FormValue,
  20. ModelLoadBalancingConfigEntry,
  21. ModelProvider,
  22. } from '../declarations'
  23. import {
  24. ConfigurationMethodEnum,
  25. FormTypeEnum,
  26. } from '../declarations'
  27. import {
  28. useLanguage,
  29. } from '../hooks'
  30. import { useValidate } from '../../key-validator/hooks'
  31. import { ValidatedStatus } from '../../key-validator/declarations'
  32. import { validateLoadBalancingCredentials } from '../utils'
  33. import Form from './Form'
  34. import Button from '@/app/components/base/button'
  35. import { Lock01 } from '@/app/components/base/icons/src/vender/solid/security'
  36. import { LinkExternal02 } from '@/app/components/base/icons/src/vender/line/general'
  37. import {
  38. PortalToFollowElem,
  39. PortalToFollowElemContent,
  40. } from '@/app/components/base/portal-to-follow-elem'
  41. import { useToastContext } from '@/app/components/base/toast'
  42. import Confirm from '@/app/components/base/confirm'
  43. type ModelModalProps = {
  44. provider: ModelProvider
  45. configurationMethod: ConfigurationMethodEnum
  46. currentCustomConfigurationModelFixedFields?: CustomConfigurationModelFixedFields
  47. entry?: ModelLoadBalancingConfigEntry
  48. onCancel: () => void
  49. onSave: (entry: ModelLoadBalancingConfigEntry) => void
  50. onRemove: () => void
  51. }
  52. const ModelLoadBalancingEntryModal: FC<ModelModalProps> = ({
  53. provider,
  54. configurationMethod,
  55. currentCustomConfigurationModelFixedFields,
  56. entry,
  57. onCancel,
  58. onSave,
  59. onRemove,
  60. }) => {
  61. const providerFormSchemaPredefined = configurationMethod === ConfigurationMethodEnum.predefinedModel
  62. // const { credentials: formSchemasValue } = useProviderCredentialsAndLoadBalancing(
  63. // provider.provider,
  64. // configurationMethod,
  65. // providerFormSchemaPredefined && provider.custom_configuration.status === CustomConfigurationStatusEnum.active,
  66. // currentCustomConfigurationModelFixedFields,
  67. // )
  68. const isEditMode = !!entry
  69. const { t } = useTranslation()
  70. const { notify } = useToastContext()
  71. const language = useLanguage()
  72. const [loading, setLoading] = useState(false)
  73. const [showConfirm, setShowConfirm] = useState(false)
  74. const formSchemas = useMemo(() => {
  75. return [
  76. {
  77. type: FormTypeEnum.textInput,
  78. label: {
  79. en_US: 'Config Name',
  80. zh_Hans: '配置名称',
  81. },
  82. variable: 'name',
  83. required: true,
  84. show_on: [],
  85. placeholder: {
  86. en_US: 'Enter your Config Name here',
  87. zh_Hans: '输入配置名称',
  88. },
  89. } as CredentialFormSchemaTextInput,
  90. ...(
  91. providerFormSchemaPredefined
  92. ? provider.provider_credential_schema.credential_form_schemas
  93. : provider.model_credential_schema.credential_form_schemas
  94. ),
  95. ]
  96. }, [
  97. providerFormSchemaPredefined,
  98. provider.provider_credential_schema?.credential_form_schemas,
  99. provider.model_credential_schema?.credential_form_schemas,
  100. ])
  101. const [
  102. requiredFormSchemas,
  103. secretFormSchemas,
  104. defaultFormSchemaValue,
  105. showOnVariableMap,
  106. ] = useMemo(() => {
  107. const requiredFormSchemas: CredentialFormSchema[] = []
  108. const secretFormSchemas: CredentialFormSchema[] = []
  109. const defaultFormSchemaValue: Record<string, string | number> = {}
  110. const showOnVariableMap: Record<string, string[]> = {}
  111. formSchemas.forEach((formSchema) => {
  112. if (formSchema.required)
  113. requiredFormSchemas.push(formSchema)
  114. if (formSchema.type === FormTypeEnum.secretInput)
  115. secretFormSchemas.push(formSchema)
  116. if (formSchema.default)
  117. defaultFormSchemaValue[formSchema.variable] = formSchema.default
  118. if (formSchema.show_on.length) {
  119. formSchema.show_on.forEach((showOnItem) => {
  120. if (!showOnVariableMap[showOnItem.variable])
  121. showOnVariableMap[showOnItem.variable] = []
  122. if (!showOnVariableMap[showOnItem.variable].includes(formSchema.variable))
  123. showOnVariableMap[showOnItem.variable].push(formSchema.variable)
  124. })
  125. }
  126. if (formSchema.type === FormTypeEnum.select || formSchema.type === FormTypeEnum.radio) {
  127. (formSchema as (CredentialFormSchemaRadio | CredentialFormSchemaSelect)).options.forEach((option) => {
  128. if (option.show_on.length) {
  129. option.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. })
  137. }
  138. })
  139. return [
  140. requiredFormSchemas,
  141. secretFormSchemas,
  142. defaultFormSchemaValue,
  143. showOnVariableMap,
  144. ]
  145. }, [formSchemas])
  146. const [initialValue, setInitialValue] = useState<ModelLoadBalancingConfigEntry['credentials']>()
  147. useEffect(() => {
  148. if (entry && !initialValue) {
  149. setInitialValue({
  150. ...defaultFormSchemaValue,
  151. ...entry.credentials,
  152. id: entry.id,
  153. name: entry.name,
  154. } as Record<string, string | undefined | boolean>)
  155. }
  156. }, [entry, defaultFormSchemaValue, initialValue])
  157. const formSchemasValue = useMemo(() => ({
  158. ...currentCustomConfigurationModelFixedFields,
  159. ...initialValue,
  160. }), [currentCustomConfigurationModelFixedFields, initialValue])
  161. const initialFormSchemasValue: Record<string, string | number> = useMemo(() => {
  162. return {
  163. ...defaultFormSchemaValue,
  164. ...formSchemasValue,
  165. } as Record<string, string | number>
  166. }, [formSchemasValue, defaultFormSchemaValue])
  167. const [value, setValue] = useState(initialFormSchemasValue)
  168. useEffect(() => {
  169. setValue(initialFormSchemasValue)
  170. }, [initialFormSchemasValue])
  171. const [_, validating, validatedStatusState] = useValidate(value)
  172. const filteredRequiredFormSchemas = requiredFormSchemas.filter((requiredFormSchema) => {
  173. if (requiredFormSchema.show_on.length && requiredFormSchema.show_on.every(showOnItem => value[showOnItem.variable] === showOnItem.value))
  174. return true
  175. if (!requiredFormSchema.show_on.length)
  176. return true
  177. return false
  178. })
  179. const getSecretValues = useCallback((v: FormValue) => {
  180. return secretFormSchemas.reduce((prev, next) => {
  181. if (isEditMode && v[next.variable] && v[next.variable] === initialFormSchemasValue[next.variable])
  182. prev[next.variable] = '[__HIDDEN__]'
  183. return prev
  184. }, {} as Record<string, string>)
  185. }, [initialFormSchemasValue, isEditMode, secretFormSchemas])
  186. // const handleValueChange = ({ __model_type, __model_name, ...v }: FormValue) => {
  187. const handleValueChange = (v: FormValue) => {
  188. setValue(v)
  189. }
  190. const handleSave = async () => {
  191. try {
  192. setLoading(true)
  193. const res = await validateLoadBalancingCredentials(
  194. providerFormSchemaPredefined,
  195. provider.provider,
  196. {
  197. ...value,
  198. ...getSecretValues(value),
  199. },
  200. entry?.id,
  201. )
  202. if (res.status === ValidatedStatus.Success) {
  203. // notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  204. const { __model_type, __model_name, name, ...credentials } = value
  205. onSave({
  206. ...(entry || {}),
  207. name: name as string,
  208. credentials: credentials as Record<string, string | boolean | undefined>,
  209. })
  210. // onCancel()
  211. }
  212. else {
  213. notify({ type: 'error', message: res.message || '' })
  214. }
  215. }
  216. finally {
  217. setLoading(false)
  218. }
  219. }
  220. const handleRemove = () => {
  221. onRemove?.()
  222. }
  223. return (
  224. <PortalToFollowElem open>
  225. <PortalToFollowElemContent className='w-full h-full z-[60]'>
  226. <div className='fixed inset-0 flex items-center justify-center bg-black/[.25]'>
  227. <div className='mx-2 w-[640px] max-h-[calc(100vh-120px)] bg-white shadow-xl rounded-2xl overflow-y-auto'>
  228. <div className='px-8 pt-8'>
  229. <div className='flex justify-between items-center mb-2'>
  230. <div className='text-xl font-semibold text-gray-900'>{t(isEditMode ? 'common.modelProvider.editConfig' : 'common.modelProvider.addConfig')}</div>
  231. </div>
  232. <Form
  233. value={value}
  234. onChange={handleValueChange}
  235. formSchemas={formSchemas}
  236. validating={validating}
  237. validatedSuccess={validatedStatusState.status === ValidatedStatus.Success}
  238. showOnVariableMap={showOnVariableMap}
  239. isEditMode={isEditMode}
  240. />
  241. <div className='sticky bottom-0 flex justify-between items-center py-6 flex-wrap gap-y-2 bg-white'>
  242. {
  243. (provider.help && (provider.help.title || provider.help.url))
  244. ? (
  245. <a
  246. href={provider.help?.url[language] || provider.help?.url.en_US}
  247. target='_blank' rel='noopener noreferrer'
  248. className='inline-flex items-center text-xs text-primary-600'
  249. onClick={e => !provider.help.url && e.preventDefault()}
  250. >
  251. {provider.help.title?.[language] || provider.help.url[language] || provider.help.title?.en_US || provider.help.url.en_US}
  252. <LinkExternal02 className='ml-1 w-3 h-3' />
  253. </a>
  254. )
  255. : <div />
  256. }
  257. <div>
  258. {
  259. isEditMode && (
  260. <Button
  261. size='large'
  262. className='mr-2 text-[#D92D20]'
  263. onClick={() => setShowConfirm(true)}
  264. >
  265. {t('common.operation.remove')}
  266. </Button>
  267. )
  268. }
  269. <Button
  270. size='large'
  271. className='mr-2'
  272. onClick={onCancel}
  273. >
  274. {t('common.operation.cancel')}
  275. </Button>
  276. <Button
  277. size='large'
  278. variant='primary'
  279. onClick={handleSave}
  280. disabled={loading || filteredRequiredFormSchemas.some(item => value[item.variable] === undefined)}
  281. >
  282. {t('common.operation.save')}
  283. </Button>
  284. </div>
  285. </div>
  286. </div>
  287. <div className='border-t-[0.5px] border-t-black/5'>
  288. {
  289. (validatedStatusState.status === ValidatedStatus.Error && validatedStatusState.message)
  290. ? (
  291. <div className='flex px-[10px] py-3 bg-[#FEF3F2] text-xs text-[#D92D20]'>
  292. <RiErrorWarningFill className='mt-[1px] mr-2 w-[14px] h-[14px]' />
  293. {validatedStatusState.message}
  294. </div>
  295. )
  296. : (
  297. <div className='flex justify-center items-center py-3 bg-gray-50 text-xs text-gray-500'>
  298. <Lock01 className='mr-1 w-3 h-3 text-gray-500' />
  299. {t('common.modelProvider.encrypted.front')}
  300. <a
  301. className='text-primary-600 mx-1'
  302. target='_blank' rel='noopener noreferrer'
  303. href='https://pycryptodome.readthedocs.io/en/latest/src/cipher/oaep.html'
  304. >
  305. PKCS1_OAEP
  306. </a>
  307. {t('common.modelProvider.encrypted.back')}
  308. </div>
  309. )
  310. }
  311. </div>
  312. </div>
  313. {
  314. showConfirm && (
  315. <Confirm
  316. title={t('common.modelProvider.confirmDelete')}
  317. isShow={showConfirm}
  318. onCancel={() => setShowConfirm(false)}
  319. onConfirm={handleRemove}
  320. />
  321. )
  322. }
  323. </div>
  324. </PortalToFollowElemContent>
  325. </PortalToFollowElem>
  326. )
  327. }
  328. export default memo(ModelLoadBalancingEntryModal)