You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

provider-context.tsx 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. }
  63. const ProviderContext = createContext<ProviderContextState>({
  64. modelProviders: [],
  65. refreshModelProviders: noop,
  66. textGenerationModelList: [],
  67. supportRetrievalMethods: [],
  68. isAPIKeySet: true,
  69. plan: {
  70. type: Plan.sandbox,
  71. usage: {
  72. vectorSpace: 32,
  73. buildApps: 12,
  74. teamMembers: 1,
  75. annotatedResponse: 1,
  76. documentsUploadQuota: 50,
  77. },
  78. total: {
  79. vectorSpace: 200,
  80. buildApps: 50,
  81. teamMembers: 1,
  82. annotatedResponse: 10,
  83. documentsUploadQuota: 500,
  84. },
  85. },
  86. isFetchedPlan: false,
  87. enableBilling: false,
  88. onPlanInfoChanged: noop,
  89. enableReplaceWebAppLogo: false,
  90. modelLoadBalancingEnabled: false,
  91. datasetOperatorEnabled: false,
  92. enableEducationPlan: false,
  93. isEducationWorkspace: false,
  94. isEducationAccount: false,
  95. allowRefreshEducationVerify: false,
  96. educationAccountExpireAt: null,
  97. isLoadingEducationAccountInfo: false,
  98. isFetchingEducationAccountInfo: false,
  99. webappCopyrightEnabled: false,
  100. licenseLimit: {
  101. workspace_members: {
  102. size: 0,
  103. limit: 0,
  104. },
  105. },
  106. refreshLicenseLimit: noop,
  107. isAllowTransferWorkspace: false,
  108. })
  109. export const useProviderContext = () => useContext(ProviderContext)
  110. // Adding a dangling comma to avoid the generic parsing issue in tsx, see:
  111. // https://github.com/microsoft/TypeScript/issues/15713
  112. export const useProviderContextSelector = <T,>(selector: (state: ProviderContextState) => T): T =>
  113. useContextSelector(ProviderContext, selector)
  114. type ProviderContextProviderProps = {
  115. children: React.ReactNode
  116. }
  117. export const ProviderContextProvider = ({
  118. children,
  119. }: ProviderContextProviderProps) => {
  120. const { data: providersData, mutate: refreshModelProviders } = useSWR('/workspaces/current/model-providers', fetchModelProviders)
  121. const fetchModelListUrlPrefix = '/workspaces/current/models/model-types/'
  122. const { data: textGenerationModelList } = useSWR(`${fetchModelListUrlPrefix}${ModelTypeEnum.textGeneration}`, fetchModelList)
  123. const { data: supportRetrievalMethods } = useSWR('/datasets/retrieval-setting', fetchSupportRetrievalMethods)
  124. const [plan, setPlan] = useState(defaultPlan)
  125. const [isFetchedPlan, setIsFetchedPlan] = useState(false)
  126. const [enableBilling, setEnableBilling] = useState(true)
  127. const [enableReplaceWebAppLogo, setEnableReplaceWebAppLogo] = useState(false)
  128. const [modelLoadBalancingEnabled, setModelLoadBalancingEnabled] = useState(false)
  129. const [datasetOperatorEnabled, setDatasetOperatorEnabled] = useState(false)
  130. const [webappCopyrightEnabled, setWebappCopyrightEnabled] = useState(false)
  131. const [licenseLimit, setLicenseLimit] = useState({
  132. workspace_members: {
  133. size: 0,
  134. limit: 0,
  135. },
  136. })
  137. const [enableEducationPlan, setEnableEducationPlan] = useState(false)
  138. const [isEducationWorkspace, setIsEducationWorkspace] = useState(false)
  139. const { data: educationAccountInfo, isLoading: isLoadingEducationAccountInfo, isFetching: isFetchingEducationAccountInfo } = useEducationStatus(!enableEducationPlan)
  140. const [isAllowTransferWorkspace, setIsAllowTransferWorkspace] = useState(false)
  141. const fetchPlan = async () => {
  142. try {
  143. const data = await fetchCurrentPlanInfo()
  144. if (!data) {
  145. console.error('Failed to fetch plan info: data is undefined')
  146. return
  147. }
  148. // set default value to avoid undefined error
  149. setEnableBilling(data.billing?.enabled ?? false)
  150. setEnableEducationPlan(data.education?.enabled ?? false)
  151. setIsEducationWorkspace(data.education?.activated ?? false)
  152. setEnableReplaceWebAppLogo(data.can_replace_logo ?? false)
  153. if (data.billing?.enabled) {
  154. setPlan(parseCurrentPlan(data) as any)
  155. setIsFetchedPlan(true)
  156. }
  157. if (data.model_load_balancing_enabled)
  158. setModelLoadBalancingEnabled(true)
  159. if (data.dataset_operator_enabled)
  160. setDatasetOperatorEnabled(true)
  161. if (data.webapp_copyright_enabled)
  162. setWebappCopyrightEnabled(true)
  163. if (data.workspace_members)
  164. setLicenseLimit({ workspace_members: data.workspace_members })
  165. if (data.is_allow_transfer_workspace)
  166. setIsAllowTransferWorkspace(data.is_allow_transfer_workspace)
  167. }
  168. catch (error) {
  169. console.error('Failed to fetch plan info:', error)
  170. // set default value to avoid undefined error
  171. setEnableBilling(false)
  172. setEnableEducationPlan(false)
  173. setIsEducationWorkspace(false)
  174. setEnableReplaceWebAppLogo(false)
  175. }
  176. }
  177. useEffect(() => {
  178. fetchPlan()
  179. }, [])
  180. const { t } = useTranslation()
  181. useEffect(() => {
  182. if (localStorage.getItem('anthropic_quota_notice') === 'true')
  183. return
  184. if (dayjs().isAfter(dayjs('2025-03-17')))
  185. return
  186. if (providersData?.data && providersData.data.length > 0) {
  187. const anthropic = providersData.data.find(provider => provider.provider === 'anthropic')
  188. if (anthropic && anthropic.system_configuration.current_quota_type === CurrentSystemQuotaTypeEnum.trial) {
  189. const quota = anthropic.system_configuration.quota_configurations.find(item => item.quota_type === anthropic.system_configuration.current_quota_type)
  190. if (quota && quota.is_valid && quota.quota_used < quota.quota_limit) {
  191. Toast.notify({
  192. type: 'info',
  193. message: t('common.provider.anthropicHosted.trialQuotaTip'),
  194. duration: 60000,
  195. onClose: () => {
  196. localStorage.setItem('anthropic_quota_notice', 'true')
  197. },
  198. })
  199. }
  200. }
  201. }
  202. }, [providersData, t])
  203. return (
  204. <ProviderContext.Provider value={{
  205. modelProviders: providersData?.data || [],
  206. refreshModelProviders,
  207. textGenerationModelList: textGenerationModelList?.data || [],
  208. isAPIKeySet: !!textGenerationModelList?.data.some(model => model.status === ModelStatusEnum.active),
  209. supportRetrievalMethods: supportRetrievalMethods?.retrieval_method || [],
  210. plan,
  211. isFetchedPlan,
  212. enableBilling,
  213. onPlanInfoChanged: fetchPlan,
  214. enableReplaceWebAppLogo,
  215. modelLoadBalancingEnabled,
  216. datasetOperatorEnabled,
  217. enableEducationPlan,
  218. isEducationWorkspace,
  219. isEducationAccount: educationAccountInfo?.is_student || false,
  220. allowRefreshEducationVerify: educationAccountInfo?.allow_refresh || false,
  221. educationAccountExpireAt: educationAccountInfo?.expire_at || null,
  222. isLoadingEducationAccountInfo,
  223. isFetchingEducationAccountInfo,
  224. webappCopyrightEnabled,
  225. licenseLimit,
  226. refreshLicenseLimit: fetchPlan,
  227. isAllowTransferWorkspace,
  228. }}>
  229. {children}
  230. </ProviderContext.Provider>
  231. )
  232. }
  233. export default ProviderContext