index.tsx 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import { useState } from 'react'
  2. import useSWR from 'swr'
  3. import { useTranslation } from 'react-i18next'
  4. import { useContext } from 'use-context-selector'
  5. import type {
  6. FormValue,
  7. ProviderConfigModal,
  8. ProviderEnum,
  9. } from './declarations'
  10. import ModelCard from './model-card'
  11. import ModelItem from './model-item'
  12. import ModelModal from './model-modal'
  13. import SystemModel from './system-model'
  14. import config from './configs'
  15. import { ConfigurableProviders } from './utils'
  16. import {
  17. changeModelProviderPriority,
  18. deleteModelProvider,
  19. deleteModelProviderModel,
  20. fetchModelProviders,
  21. setModelProvider,
  22. } from '@/service/common'
  23. import { useToastContext } from '@/app/components/base/toast'
  24. import Confirm from '@/app/components/base/confirm/common'
  25. import { ModelType } from '@/app/components/header/account-setting/model-page/declarations'
  26. import { useEventEmitterContextContext } from '@/context/event-emitter'
  27. import { useProviderContext } from '@/context/provider-context'
  28. import I18n from '@/context/i18n'
  29. import { AlertTriangle } from '@/app/components/base/icons/src/vender/solid/alertsAndFeedback'
  30. const MODEL_CARD_LIST = [
  31. config.openai,
  32. config.anthropic,
  33. ]
  34. type DeleteModel = {
  35. model_name: string
  36. model_type: string
  37. }
  38. const ModelPage = () => {
  39. const { t } = useTranslation()
  40. const { locale } = useContext(I18n)
  41. const {
  42. updateModelList,
  43. textGenerationDefaultModel,
  44. embeddingsDefaultModel,
  45. speech2textDefaultModel,
  46. rerankDefaultModel,
  47. } = useProviderContext()
  48. const { data: providers, mutate: mutateProviders } = useSWR('/workspaces/current/model-providers', fetchModelProviders)
  49. const [showModal, setShowModal] = useState(false)
  50. const { notify } = useToastContext()
  51. const { eventEmitter } = useEventEmitterContextContext()
  52. const [modelModalConfig, setModelModalConfig] = useState<ProviderConfigModal | undefined>(undefined)
  53. const [confirmShow, setConfirmShow] = useState(false)
  54. const [deleteModel, setDeleteModel] = useState<DeleteModel & { providerKey: ProviderEnum }>()
  55. const [modalMode, setModalMode] = useState('add')
  56. let modelList = []
  57. if (locale === 'en') {
  58. modelList = [
  59. config.azure_openai,
  60. config.replicate,
  61. config.huggingface_hub,
  62. config.cohere,
  63. config.zhipuai,
  64. config.baichuan,
  65. config.spark,
  66. config.minimax,
  67. config.tongyi,
  68. config.wenxin,
  69. config.jina,
  70. config.chatglm,
  71. config.xinference,
  72. config.openllm,
  73. config.localai,
  74. ]
  75. }
  76. else {
  77. modelList = [
  78. config.huggingface_hub,
  79. config.cohere,
  80. config.zhipuai,
  81. config.spark,
  82. config.baichuan,
  83. config.minimax,
  84. config.azure_openai,
  85. config.replicate,
  86. config.tongyi,
  87. config.wenxin,
  88. config.jina,
  89. config.chatglm,
  90. config.xinference,
  91. config.openllm,
  92. config.localai,
  93. ]
  94. }
  95. const handleOpenModal = (newModelModalConfig: ProviderConfigModal | undefined, editValue?: FormValue) => {
  96. if (newModelModalConfig) {
  97. setShowModal(true)
  98. const defaultValue = editValue ? { ...newModelModalConfig.defaultValue, ...editValue } : newModelModalConfig.defaultValue
  99. setModelModalConfig({
  100. ...newModelModalConfig,
  101. defaultValue,
  102. })
  103. if (editValue)
  104. setModalMode('edit')
  105. else
  106. setModalMode('add')
  107. }
  108. }
  109. const handleCancelModal = () => {
  110. setShowModal(false)
  111. }
  112. const handleUpdateProvidersAndModelList = () => {
  113. updateModelList(ModelType.textGeneration)
  114. updateModelList(ModelType.embeddings)
  115. updateModelList(ModelType.speech2text)
  116. updateModelList(ModelType.reranking)
  117. mutateProviders()
  118. }
  119. const handleSave = async (originValue?: FormValue) => {
  120. if (originValue && modelModalConfig) {
  121. const v = modelModalConfig.filterValue ? modelModalConfig.filterValue(originValue) : originValue
  122. let body, url
  123. if (ConfigurableProviders.includes(modelModalConfig.key)) {
  124. const { model_name, model_type, ...config } = v
  125. body = {
  126. model_name,
  127. model_type,
  128. config,
  129. }
  130. url = `/workspaces/current/model-providers/${modelModalConfig.key}/models`
  131. }
  132. else {
  133. body = {
  134. config: v,
  135. }
  136. url = `/workspaces/current/model-providers/${modelModalConfig.key}`
  137. }
  138. try {
  139. eventEmitter?.emit('provider-save')
  140. const res = await setModelProvider({ url, body })
  141. if (res.result === 'success') {
  142. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  143. handleUpdateProvidersAndModelList()
  144. handleCancelModal()
  145. }
  146. eventEmitter?.emit('')
  147. }
  148. catch (e) {
  149. eventEmitter?.emit('')
  150. }
  151. }
  152. }
  153. const handleConfirm = (deleteModel: DeleteModel, providerKey: ProviderEnum) => {
  154. setDeleteModel({ ...deleteModel, providerKey })
  155. setConfirmShow(true)
  156. }
  157. const handleOperate = async ({ type, value }: Record<string, any>, provierKey: ProviderEnum) => {
  158. if (type === 'delete') {
  159. if (!value) {
  160. const res = await deleteModelProvider({ url: `/workspaces/current/model-providers/${provierKey}` })
  161. if (res.result === 'success') {
  162. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  163. handleUpdateProvidersAndModelList()
  164. }
  165. }
  166. else {
  167. handleConfirm(value, provierKey)
  168. }
  169. }
  170. if (type === 'priority') {
  171. const res = await changeModelProviderPriority({
  172. url: `/workspaces/current/model-providers/${provierKey}/preferred-provider-type`,
  173. body: {
  174. preferred_provider_type: value,
  175. },
  176. })
  177. if (res.result === 'success') {
  178. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  179. mutateProviders()
  180. }
  181. }
  182. }
  183. const handleDeleteModel = async () => {
  184. const { model_name, model_type, providerKey } = deleteModel || {}
  185. const res = await deleteModelProviderModel({
  186. url: `/workspaces/current/model-providers/${providerKey}/models?model_name=${model_name}&model_type=${model_type}`,
  187. })
  188. if (res.result === 'success') {
  189. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  190. setConfirmShow(false)
  191. handleUpdateProvidersAndModelList()
  192. }
  193. }
  194. const defaultModelNotConfigured = !textGenerationDefaultModel && !embeddingsDefaultModel && !speech2textDefaultModel && !rerankDefaultModel
  195. return (
  196. <div className='relative pt-1 -mt-2'>
  197. <div className={`flex items-center justify-between mb-2 h-8 ${defaultModelNotConfigured && 'px-3 bg-[#FFFAEB] rounded-lg border border-[#FEF0C7]'}`}>
  198. {
  199. defaultModelNotConfigured
  200. ? (
  201. <div className='flex items-center text-xs font-medium text-gray-700'>
  202. <AlertTriangle className='mr-1 w-3 h-3 text-[#F79009]' />
  203. {t('common.modelProvider.notConfigured')}
  204. </div>
  205. )
  206. : <div className='text-sm font-medium text-gray-800'>{t('common.modelProvider.models')}</div>
  207. }
  208. <SystemModel onUpdate={() => mutateProviders()} />
  209. </div>
  210. <div className='grid grid-cols-1 lg:grid-cols-2 gap-4 mb-6'>
  211. {
  212. MODEL_CARD_LIST.map((model, index) => (
  213. <ModelCard
  214. key={index}
  215. modelItem={model.item}
  216. currentProvider={providers?.[model.item.key]}
  217. onOpenModal={editValue => handleOpenModal(model.modal, editValue)}
  218. onOperate={v => handleOperate(v, model.item.key)}
  219. />
  220. ))
  221. }
  222. </div>
  223. {
  224. modelList.map((model, index) => (
  225. <ModelItem
  226. key={index}
  227. modelItem={model.item}
  228. currentProvider={providers?.[model.item.key]}
  229. onOpenModal={editValue => handleOpenModal(model.modal, editValue)}
  230. onOperate={v => handleOperate(v, model.item.key)}
  231. onUpdate={mutateProviders}
  232. />
  233. ))
  234. }
  235. <ModelModal
  236. isShow={showModal}
  237. modelModal={modelModalConfig}
  238. onCancel={handleCancelModal}
  239. onSave={handleSave}
  240. mode={modalMode}
  241. />
  242. <Confirm
  243. isShow={confirmShow}
  244. onCancel={() => setConfirmShow(false)}
  245. title={deleteModel?.model_name || ''}
  246. desc={t('common.modelProvider.item.deleteDesc', { modelName: deleteModel?.model_name }) || ''}
  247. onConfirm={handleDeleteModel}
  248. confirmWrapperClassName='!z-30'
  249. />
  250. </div>
  251. )
  252. }
  253. export default ModelPage