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.

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