model-load-balancing-configs.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import type { Dispatch, SetStateAction } from 'react'
  2. import { useCallback } from 'react'
  3. import { useTranslation } from 'react-i18next'
  4. import {
  5. RiDeleteBinLine,
  6. } from '@remixicon/react'
  7. import type { ConfigurationMethodEnum, CustomConfigurationModelFixedFields, ModelLoadBalancingConfig, ModelLoadBalancingConfigEntry, ModelProvider } from '../declarations'
  8. import Indicator from '../../../indicator'
  9. import CooldownTimer from './cooldown-timer'
  10. import classNames from '@/utils/classnames'
  11. import Tooltip from '@/app/components/base/tooltip'
  12. import Switch from '@/app/components/base/switch'
  13. import { Balance } from '@/app/components/base/icons/src/vender/line/financeAndECommerce'
  14. import { Edit02, Plus02 } from '@/app/components/base/icons/src/vender/line/general'
  15. import { AlertTriangle } from '@/app/components/base/icons/src/vender/solid/alertsAndFeedback'
  16. import { useModalContextSelector } from '@/context/modal-context'
  17. import UpgradeBtn from '@/app/components/billing/upgrade-btn'
  18. import s from '@/app/components/custom/style.module.css'
  19. import GridMask from '@/app/components/base/grid-mask'
  20. import { useProviderContextSelector } from '@/context/provider-context'
  21. import { IS_CE_EDITION } from '@/config'
  22. export type ModelLoadBalancingConfigsProps = {
  23. draftConfig?: ModelLoadBalancingConfig
  24. setDraftConfig: Dispatch<SetStateAction<ModelLoadBalancingConfig | undefined>>
  25. provider: ModelProvider
  26. configurationMethod: ConfigurationMethodEnum
  27. currentCustomConfigurationModelFixedFields?: CustomConfigurationModelFixedFields
  28. withSwitch?: boolean
  29. className?: string
  30. }
  31. const ModelLoadBalancingConfigs = ({
  32. draftConfig,
  33. setDraftConfig,
  34. provider,
  35. configurationMethod,
  36. currentCustomConfigurationModelFixedFields,
  37. withSwitch = false,
  38. className,
  39. }: ModelLoadBalancingConfigsProps) => {
  40. const { t } = useTranslation()
  41. const modelLoadBalancingEnabled = useProviderContextSelector(state => state.modelLoadBalancingEnabled)
  42. const updateConfigEntry = useCallback(
  43. (
  44. index: number,
  45. modifier: (entry: ModelLoadBalancingConfigEntry) => ModelLoadBalancingConfigEntry | undefined,
  46. ) => {
  47. setDraftConfig((prev) => {
  48. if (!prev)
  49. return prev
  50. const newConfigs = [...prev.configs]
  51. const modifiedConfig = modifier(newConfigs[index])
  52. if (modifiedConfig)
  53. newConfigs[index] = modifiedConfig
  54. else
  55. newConfigs.splice(index, 1)
  56. return {
  57. ...prev,
  58. configs: newConfigs,
  59. }
  60. })
  61. },
  62. [setDraftConfig],
  63. )
  64. const toggleModalBalancing = useCallback((enabled: boolean) => {
  65. if ((modelLoadBalancingEnabled || !enabled) && draftConfig) {
  66. setDraftConfig({
  67. ...draftConfig,
  68. enabled,
  69. })
  70. }
  71. }, [draftConfig, modelLoadBalancingEnabled, setDraftConfig])
  72. const toggleConfigEntryEnabled = useCallback((index: number, state?: boolean) => {
  73. updateConfigEntry(index, entry => ({
  74. ...entry,
  75. enabled: typeof state === 'boolean' ? state : !entry.enabled,
  76. }))
  77. }, [updateConfigEntry])
  78. const setShowModelLoadBalancingEntryModal = useModalContextSelector(state => state.setShowModelLoadBalancingEntryModal)
  79. const toggleEntryModal = useCallback((index?: number, entry?: ModelLoadBalancingConfigEntry) => {
  80. setShowModelLoadBalancingEntryModal({
  81. payload: {
  82. currentProvider: provider,
  83. currentConfigurationMethod: configurationMethod,
  84. currentCustomConfigurationModelFixedFields,
  85. entry,
  86. index,
  87. },
  88. onSaveCallback: ({ entry: result }) => {
  89. if (entry) {
  90. // edit
  91. setDraftConfig(prev => ({
  92. ...prev,
  93. enabled: !!prev?.enabled,
  94. configs: prev?.configs.map((config, i) => i === index ? result! : config) || [],
  95. }))
  96. }
  97. else {
  98. // add
  99. setDraftConfig(prev => ({
  100. ...prev,
  101. enabled: !!prev?.enabled,
  102. configs: (prev?.configs || []).concat([{ ...result!, enabled: true }]),
  103. }))
  104. }
  105. },
  106. onRemoveCallback: ({ index }) => {
  107. if (index !== undefined && (draftConfig?.configs?.length ?? 0) > index) {
  108. setDraftConfig(prev => ({
  109. ...prev,
  110. enabled: !!prev?.enabled,
  111. configs: prev?.configs.filter((_, i) => i !== index) || [],
  112. }))
  113. }
  114. },
  115. })
  116. }, [
  117. configurationMethod,
  118. currentCustomConfigurationModelFixedFields,
  119. draftConfig?.configs?.length,
  120. provider,
  121. setDraftConfig,
  122. setShowModelLoadBalancingEntryModal,
  123. ])
  124. const clearCountdown = useCallback((index: number) => {
  125. updateConfigEntry(index, ({ ttl: _, ...entry }) => {
  126. return {
  127. ...entry,
  128. in_cooldown: false,
  129. }
  130. })
  131. }, [updateConfigEntry])
  132. if (!draftConfig)
  133. return null
  134. return (
  135. <>
  136. <div
  137. className={classNames(
  138. 'min-h-16 bg-gray-50 border rounded-xl transition-colors',
  139. (withSwitch || !draftConfig.enabled) ? 'border-gray-200' : 'border-primary-400',
  140. (withSwitch || draftConfig.enabled) ? 'cursor-default' : 'cursor-pointer',
  141. className,
  142. )}
  143. onClick={(!withSwitch && !draftConfig.enabled) ? () => toggleModalBalancing(true) : undefined}
  144. >
  145. <div className='flex items-center px-[15px] py-3 gap-2 select-none'>
  146. <div className='grow-0 shrink-0 flex items-center justify-center w-8 h-8 text-primary-600 bg-indigo-50 border border-indigo-100 rounded-lg'>
  147. <Balance className='w-4 h-4' />
  148. </div>
  149. <div className='grow'>
  150. <div className='flex items-center gap-1 text-sm'>
  151. {t('common.modelProvider.loadBalancing')}
  152. <Tooltip
  153. popupContent={t('common.modelProvider.loadBalancingInfo')}
  154. popupClassName='max-w-[300px]'
  155. triggerClassName='w-3 h-3'
  156. />
  157. </div>
  158. <div className='text-xs text-gray-500'>{t('common.modelProvider.loadBalancingDescription')}</div>
  159. </div>
  160. {
  161. withSwitch && (
  162. <Switch
  163. defaultValue={Boolean(draftConfig.enabled)}
  164. size='l'
  165. className='ml-3 justify-self-end'
  166. disabled={!modelLoadBalancingEnabled && !draftConfig.enabled}
  167. onChange={value => toggleModalBalancing(value)}
  168. />
  169. )
  170. }
  171. </div>
  172. {draftConfig.enabled && (
  173. <div className='flex flex-col gap-1 px-3 pb-3'>
  174. {draftConfig.configs.map((config, index) => {
  175. const isProviderManaged = config.name === '__inherit__'
  176. return (
  177. <div key={config.id || index} className='group flex items-center px-3 h-10 bg-white border border-gray-200 rounded-lg shadow-xs'>
  178. <div className='grow flex items-center'>
  179. <div className='flex items-center justify-center mr-2 w-3 h-3'>
  180. {(config.in_cooldown && Boolean(config.ttl))
  181. ? (
  182. <CooldownTimer secondsRemaining={config.ttl} onFinish={() => clearCountdown(index)} />
  183. )
  184. : (
  185. <Tooltip popupContent={t('common.modelProvider.apiKeyStatusNormal')}>
  186. <Indicator color='green' />
  187. </Tooltip>
  188. )}
  189. </div>
  190. <div className='text-[13px] mr-1'>
  191. {isProviderManaged ? t('common.modelProvider.defaultConfig') : config.name}
  192. </div>
  193. {isProviderManaged && (
  194. <span className='px-1 text-2xs uppercase text-gray-500 border border-black/8 rounded-[5px]'>{t('common.modelProvider.providerManaged')}</span>
  195. )}
  196. </div>
  197. <div className='flex items-center gap-1'>
  198. {!isProviderManaged && (
  199. <>
  200. <div className='flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100'>
  201. <span
  202. className='flex items-center justify-center w-8 h-8 text-gray-500 bg-white rounded-lg transition-colors cursor-pointer hover:bg-black/5'
  203. onClick={() => toggleEntryModal(index, config)}
  204. >
  205. <Edit02 className='w-4 h-4' />
  206. </span>
  207. <span
  208. className='flex items-center justify-center w-8 h-8 text-gray-500 bg-white rounded-lg transition-colors cursor-pointer hover:bg-black/5'
  209. onClick={() => updateConfigEntry(index, () => undefined)}
  210. >
  211. <RiDeleteBinLine className='w-4 h-4' />
  212. </span>
  213. <span className='mr-2 h-3 border-r border-r-gray-100' />
  214. </div>
  215. </>
  216. )}
  217. <Switch
  218. defaultValue={Boolean(config.enabled)}
  219. size='md'
  220. className='justify-self-end'
  221. onChange={value => toggleConfigEntryEnabled(index, value)}
  222. />
  223. </div>
  224. </div>
  225. )
  226. })}
  227. <div
  228. className='flex items-center px-3 mt-1 h-8 text-[13px] font-medium text-primary-600'
  229. onClick={() => toggleEntryModal()}
  230. >
  231. <div className='flex items-center cursor-pointer'>
  232. <Plus02 className='mr-2 w-3 h-3' />{t('common.modelProvider.addConfig')}
  233. </div>
  234. </div>
  235. </div>
  236. )}
  237. {
  238. draftConfig.enabled && draftConfig.configs.length < 2 && (
  239. <div className='flex items-center px-6 h-[34px] text-xs text-gray-700 bg-black/2 border-t border-t-black/5'>
  240. <AlertTriangle className='mr-1 w-3 h-3 text-[#f79009]' />
  241. {t('common.modelProvider.loadBalancingLeastKeyWarning')}
  242. </div>
  243. )
  244. }
  245. </div>
  246. {!modelLoadBalancingEnabled && !IS_CE_EDITION && (
  247. <GridMask canvasClassName='!rounded-xl'>
  248. <div className='flex items-center justify-between mt-2 px-4 h-14 border-[0.5px] border-gray-200 rounded-xl shadow-md'>
  249. <div
  250. className={classNames('text-sm font-semibold leading-tight text-gradient', s.textGradient)}
  251. >
  252. {t('common.modelProvider.upgradeForLoadBalancing')}
  253. </div>
  254. <UpgradeBtn />
  255. </div>
  256. </GridMask>
  257. )}
  258. </>
  259. )
  260. }
  261. export default ModelLoadBalancingConfigs