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 9.4KB

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