Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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