您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

provider-context.tsx 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. 'use client'
  2. import { createContext, useContext, useContextSelector } from 'use-context-selector'
  3. import useSWR from 'swr'
  4. import { useEffect, useState } from 'react'
  5. import dayjs from 'dayjs'
  6. import { useTranslation } from 'react-i18next'
  7. import {
  8. fetchModelList,
  9. fetchModelProviders,
  10. fetchSupportRetrievalMethods,
  11. } from '@/service/common'
  12. import {
  13. CurrentSystemQuotaTypeEnum,
  14. ModelStatusEnum,
  15. ModelTypeEnum,
  16. } from '@/app/components/header/account-setting/model-provider-page/declarations'
  17. import type { Model, ModelProvider } from '@/app/components/header/account-setting/model-provider-page/declarations'
  18. import type { RETRIEVE_METHOD } from '@/types/app'
  19. import type { BasicPlan } from '@/app/components/billing/type'
  20. import { Plan, type UsagePlanInfo } from '@/app/components/billing/type'
  21. import { fetchCurrentPlanInfo } from '@/service/billing'
  22. import { parseCurrentPlan } from '@/app/components/billing/utils'
  23. import { defaultPlan } from '@/app/components/billing/config'
  24. import Toast from '@/app/components/base/toast'
  25. import {
  26. useEducationStatus,
  27. } from '@/service/use-education'
  28. import { noop } from 'lodash-es'
  29. type ProviderContextState = {
  30. modelProviders: ModelProvider[]
  31. refreshModelProviders: () => void
  32. textGenerationModelList: Model[]
  33. supportRetrievalMethods: RETRIEVE_METHOD[]
  34. isAPIKeySet: boolean
  35. plan: {
  36. type: BasicPlan
  37. usage: UsagePlanInfo
  38. total: UsagePlanInfo
  39. }
  40. isFetchedPlan: boolean
  41. enableBilling: boolean
  42. onPlanInfoChanged: () => void
  43. enableReplaceWebAppLogo: boolean
  44. modelLoadBalancingEnabled: boolean
  45. datasetOperatorEnabled: boolean
  46. enableEducationPlan: boolean
  47. isEducationWorkspace: boolean
  48. isEducationAccount: boolean
  49. allowRefreshEducationVerify: boolean
  50. educationAccountExpireAt: number | null
  51. isLoadingEducationAccountInfo: boolean
  52. isFetchingEducationAccountInfo: boolean
  53. webappCopyrightEnabled: boolean
  54. licenseLimit: {
  55. workspace_members: {
  56. size: number
  57. limit: number
  58. }
  59. },
  60. refreshLicenseLimit: () => void
  61. isAllowTransferWorkspace: boolean
  62. isAllowPublishAsKnowledgePipeline: boolean
  63. }
  64. const ProviderContext = createContext<ProviderContextState>({
  65. modelProviders: [],
  66. refreshModelProviders: noop,
  67. textGenerationModelList: [],
  68. supportRetrievalMethods: [],
  69. isAPIKeySet: true,
  70. plan: {
  71. type: Plan.sandbox,
  72. usage: {
  73. vectorSpace: 32,
  74. buildApps: 12,
  75. teamMembers: 1,
  76. annotatedResponse: 1,
  77. documentsUploadQuota: 50,
  78. },
  79. total: {
  80. vectorSpace: 200,
  81. buildApps: 50,
  82. teamMembers: 1,
  83. annotatedResponse: 10,
  84. documentsUploadQuota: 500,
  85. },
  86. },
  87. isFetchedPlan: false,
  88. enableBilling: false,
  89. onPlanInfoChanged: noop,
  90. enableReplaceWebAppLogo: false,
  91. modelLoadBalancingEnabled: false,
  92. datasetOperatorEnabled: false,
  93. enableEducationPlan: false,
  94. isEducationWorkspace: false,
  95. isEducationAccount: false,
  96. allowRefreshEducationVerify: false,
  97. educationAccountExpireAt: null,
  98. isLoadingEducationAccountInfo: false,
  99. isFetchingEducationAccountInfo: false,
  100. webappCopyrightEnabled: false,
  101. licenseLimit: {
  102. workspace_members: {
  103. size: 0,
  104. limit: 0,
  105. },
  106. },
  107. refreshLicenseLimit: noop,
  108. isAllowTransferWorkspace: false,
  109. isAllowPublishAsKnowledgePipeline: false,
  110. })
  111. export const useProviderContext = () => useContext(ProviderContext)
  112. // Adding a dangling comma to avoid the generic parsing issue in tsx, see:
  113. // https://github.com/microsoft/TypeScript/issues/15713
  114. export const useProviderContextSelector = <T,>(selector: (state: ProviderContextState) => T): T =>
  115. useContextSelector(ProviderContext, selector)
  116. type ProviderContextProviderProps = {
  117. children: React.ReactNode
  118. }
  119. export const ProviderContextProvider = ({
  120. children,
  121. }: ProviderContextProviderProps) => {
  122. const { data: providersData, mutate: refreshModelProviders } = useSWR('/workspaces/current/model-providers', fetchModelProviders)
  123. const fetchModelListUrlPrefix = '/workspaces/current/models/model-types/'
  124. const { data: textGenerationModelList } = useSWR(`${fetchModelListUrlPrefix}${ModelTypeEnum.textGeneration}`, fetchModelList)
  125. const { data: supportRetrievalMethods } = useSWR('/datasets/retrieval-setting', fetchSupportRetrievalMethods)
  126. const [plan, setPlan] = useState(defaultPlan)
  127. const [isFetchedPlan, setIsFetchedPlan] = useState(false)
  128. const [enableBilling, setEnableBilling] = useState(true)
  129. const [enableReplaceWebAppLogo, setEnableReplaceWebAppLogo] = useState(false)
  130. const [modelLoadBalancingEnabled, setModelLoadBalancingEnabled] = useState(false)
  131. const [datasetOperatorEnabled, setDatasetOperatorEnabled] = useState(false)
  132. const [webappCopyrightEnabled, setWebappCopyrightEnabled] = useState(false)
  133. const [licenseLimit, setLicenseLimit] = useState({
  134. workspace_members: {
  135. size: 0,
  136. limit: 0,
  137. },
  138. })
  139. const [enableEducationPlan, setEnableEducationPlan] = useState(false)
  140. const [isEducationWorkspace, setIsEducationWorkspace] = useState(false)
  141. const { data: educationAccountInfo, isLoading: isLoadingEducationAccountInfo, isFetching: isFetchingEducationAccountInfo } = useEducationStatus(!enableEducationPlan)
  142. const [isAllowTransferWorkspace, setIsAllowTransferWorkspace] = useState(false)
  143. const [isAllowPublishAsKnowledgePipeline, setIsAllowPublishAsKnowledgePipeline] = useState(false)
  144. const fetchPlan = async () => {
  145. try {
  146. const data = await fetchCurrentPlanInfo()
  147. if (!data) {
  148. console.error('Failed to fetch plan info: data is undefined')
  149. return
  150. }
  151. // set default value to avoid undefined error
  152. setEnableBilling(data.billing?.enabled ?? false)
  153. setEnableEducationPlan(data.education?.enabled ?? false)
  154. setIsEducationWorkspace(data.education?.activated ?? false)
  155. setEnableReplaceWebAppLogo(data.can_replace_logo ?? false)
  156. if (data.billing?.enabled) {
  157. setPlan(parseCurrentPlan(data) as any)
  158. setIsFetchedPlan(true)
  159. }
  160. if (data.model_load_balancing_enabled)
  161. setModelLoadBalancingEnabled(true)
  162. if (data.dataset_operator_enabled)
  163. setDatasetOperatorEnabled(true)
  164. if (data.webapp_copyright_enabled)
  165. setWebappCopyrightEnabled(true)
  166. if (data.workspace_members)
  167. setLicenseLimit({ workspace_members: data.workspace_members })
  168. if (data.is_allow_transfer_workspace)
  169. setIsAllowTransferWorkspace(data.is_allow_transfer_workspace)
  170. if (data.knowledge_pipeline?.publish_enabled)
  171. setIsAllowPublishAsKnowledgePipeline(data.knowledge_pipeline?.publish_enabled)
  172. }
  173. catch (error) {
  174. console.error('Failed to fetch plan info:', error)
  175. // set default value to avoid undefined error
  176. setEnableBilling(false)
  177. setEnableEducationPlan(false)
  178. setIsEducationWorkspace(false)
  179. setEnableReplaceWebAppLogo(false)
  180. }
  181. }
  182. useEffect(() => {
  183. fetchPlan()
  184. }, [])
  185. const { t } = useTranslation()
  186. useEffect(() => {
  187. if (localStorage.getItem('anthropic_quota_notice') === 'true')
  188. return
  189. if (dayjs().isAfter(dayjs('2025-03-17')))
  190. return
  191. if (providersData?.data && providersData.data.length > 0) {
  192. const anthropic = providersData.data.find(provider => provider.provider === 'anthropic')
  193. if (anthropic && anthropic.system_configuration.current_quota_type === CurrentSystemQuotaTypeEnum.trial) {
  194. const quota = anthropic.system_configuration.quota_configurations.find(item => item.quota_type === anthropic.system_configuration.current_quota_type)
  195. if (quota && quota.is_valid && quota.quota_used < quota.quota_limit) {
  196. Toast.notify({
  197. type: 'info',
  198. message: t('common.provider.anthropicHosted.trialQuotaTip'),
  199. duration: 60000,
  200. onClose: () => {
  201. localStorage.setItem('anthropic_quota_notice', 'true')
  202. },
  203. })
  204. }
  205. }
  206. }
  207. }, [providersData, t])
  208. return (
  209. <ProviderContext.Provider value={{
  210. modelProviders: providersData?.data || [],
  211. refreshModelProviders,
  212. textGenerationModelList: textGenerationModelList?.data || [],
  213. isAPIKeySet: !!textGenerationModelList?.data.some(model => model.status === ModelStatusEnum.active),
  214. supportRetrievalMethods: supportRetrievalMethods?.retrieval_method || [],
  215. plan,
  216. isFetchedPlan,
  217. enableBilling,
  218. onPlanInfoChanged: fetchPlan,
  219. enableReplaceWebAppLogo,
  220. modelLoadBalancingEnabled,
  221. datasetOperatorEnabled,
  222. enableEducationPlan,
  223. isEducationWorkspace,
  224. isEducationAccount: educationAccountInfo?.is_student || false,
  225. allowRefreshEducationVerify: educationAccountInfo?.allow_refresh || false,
  226. educationAccountExpireAt: educationAccountInfo?.expire_at || null,
  227. isLoadingEducationAccountInfo,
  228. isFetchingEducationAccountInfo,
  229. webappCopyrightEnabled,
  230. licenseLimit,
  231. refreshLicenseLimit: fetchPlan,
  232. isAllowTransferWorkspace,
  233. isAllowPublishAsKnowledgePipeline,
  234. }}>
  235. {children}
  236. </ProviderContext.Provider>
  237. )
  238. }
  239. export default ProviderContext