hosting_configuration.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. from typing import Optional
  2. from flask import Flask
  3. from pydantic import BaseModel
  4. from configs import dify_config
  5. from core.entities import DEFAULT_PLUGIN_ID
  6. from core.entities.provider_entities import ProviderQuotaType, QuotaUnit, RestrictModel
  7. from core.model_runtime.entities.model_entities import ModelType
  8. class HostingQuota(BaseModel):
  9. quota_type: ProviderQuotaType
  10. restrict_models: list[RestrictModel] = []
  11. class TrialHostingQuota(HostingQuota):
  12. quota_type: ProviderQuotaType = ProviderQuotaType.TRIAL
  13. quota_limit: int = 0
  14. """Quota limit for the hosting provider models. -1 means unlimited."""
  15. class PaidHostingQuota(HostingQuota):
  16. quota_type: ProviderQuotaType = ProviderQuotaType.PAID
  17. class FreeHostingQuota(HostingQuota):
  18. quota_type: ProviderQuotaType = ProviderQuotaType.FREE
  19. class HostingProvider(BaseModel):
  20. enabled: bool = False
  21. credentials: Optional[dict] = None
  22. quota_unit: Optional[QuotaUnit] = None
  23. quotas: list[HostingQuota] = []
  24. class HostedModerationConfig(BaseModel):
  25. enabled: bool = False
  26. providers: list[str] = []
  27. class HostingConfiguration:
  28. provider_map: dict[str, HostingProvider]
  29. moderation_config: Optional[HostedModerationConfig] = None
  30. def __init__(self) -> None:
  31. self.provider_map = {}
  32. self.moderation_config = None
  33. def init_app(self, app: Flask) -> None:
  34. if dify_config.EDITION != "CLOUD":
  35. return
  36. self.provider_map["azure_openai"] = self.init_azure_openai()
  37. self.provider_map["openai"] = self.init_openai()
  38. self.provider_map["anthropic"] = self.init_anthropic()
  39. self.provider_map["minimax"] = self.init_minimax()
  40. self.provider_map["spark"] = self.init_spark()
  41. self.provider_map["zhipuai"] = self.init_zhipuai()
  42. # NOTE: We need to use the new name format after the data migration.
  43. # self.provider_map[f"{DEFAULT_PLUGIN_ID}/azure_openai/azure_openai"] = self.init_azure_openai()
  44. # self.provider_map[f"{DEFAULT_PLUGIN_ID}/openai/openai"] = self.init_openai()
  45. # self.provider_map[f"{DEFAULT_PLUGIN_ID}/anthropic/anthropic"] = self.init_anthropic()
  46. # self.provider_map[f"{DEFAULT_PLUGIN_ID}/minimax/minimax"] = self.init_minimax()
  47. # self.provider_map[f"{DEFAULT_PLUGIN_ID}/spark/spark"] = self.init_spark()
  48. # self.provider_map[f"{DEFAULT_PLUGIN_ID}/zhipuai/zhipuai"] = self.init_zhipuai()
  49. self.moderation_config = self.init_moderation_config()
  50. @staticmethod
  51. def init_azure_openai() -> HostingProvider:
  52. quota_unit = QuotaUnit.TIMES
  53. if dify_config.HOSTED_AZURE_OPENAI_ENABLED:
  54. credentials = {
  55. "openai_api_key": dify_config.HOSTED_AZURE_OPENAI_API_KEY,
  56. "openai_api_base": dify_config.HOSTED_AZURE_OPENAI_API_BASE,
  57. "base_model_name": "gpt-35-turbo",
  58. }
  59. quotas: list[HostingQuota] = []
  60. hosted_quota_limit = dify_config.HOSTED_AZURE_OPENAI_QUOTA_LIMIT
  61. trial_quota = TrialHostingQuota(
  62. quota_limit=hosted_quota_limit,
  63. restrict_models=[
  64. RestrictModel(model="gpt-4", base_model_name="gpt-4", model_type=ModelType.LLM),
  65. RestrictModel(model="gpt-4o", base_model_name="gpt-4o", model_type=ModelType.LLM),
  66. RestrictModel(model="gpt-4o-mini", base_model_name="gpt-4o-mini", model_type=ModelType.LLM),
  67. RestrictModel(model="gpt-4-32k", base_model_name="gpt-4-32k", model_type=ModelType.LLM),
  68. RestrictModel(
  69. model="gpt-4-1106-preview", base_model_name="gpt-4-1106-preview", model_type=ModelType.LLM
  70. ),
  71. RestrictModel(
  72. model="gpt-4-vision-preview", base_model_name="gpt-4-vision-preview", model_type=ModelType.LLM
  73. ),
  74. RestrictModel(model="gpt-35-turbo", base_model_name="gpt-35-turbo", model_type=ModelType.LLM),
  75. RestrictModel(
  76. model="gpt-35-turbo-1106", base_model_name="gpt-35-turbo-1106", model_type=ModelType.LLM
  77. ),
  78. RestrictModel(
  79. model="gpt-35-turbo-instruct", base_model_name="gpt-35-turbo-instruct", model_type=ModelType.LLM
  80. ),
  81. RestrictModel(
  82. model="gpt-35-turbo-16k", base_model_name="gpt-35-turbo-16k", model_type=ModelType.LLM
  83. ),
  84. RestrictModel(
  85. model="text-davinci-003", base_model_name="text-davinci-003", model_type=ModelType.LLM
  86. ),
  87. RestrictModel(
  88. model="text-embedding-ada-002",
  89. base_model_name="text-embedding-ada-002",
  90. model_type=ModelType.TEXT_EMBEDDING,
  91. ),
  92. RestrictModel(
  93. model="text-embedding-3-small",
  94. base_model_name="text-embedding-3-small",
  95. model_type=ModelType.TEXT_EMBEDDING,
  96. ),
  97. RestrictModel(
  98. model="text-embedding-3-large",
  99. base_model_name="text-embedding-3-large",
  100. model_type=ModelType.TEXT_EMBEDDING,
  101. ),
  102. ],
  103. )
  104. quotas.append(trial_quota)
  105. return HostingProvider(enabled=True, credentials=credentials, quota_unit=quota_unit, quotas=quotas)
  106. return HostingProvider(
  107. enabled=False,
  108. quota_unit=quota_unit,
  109. )
  110. def init_openai(self) -> HostingProvider:
  111. quota_unit = QuotaUnit.CREDITS
  112. quotas: list[HostingQuota] = []
  113. if dify_config.HOSTED_OPENAI_TRIAL_ENABLED:
  114. hosted_quota_limit = dify_config.HOSTED_OPENAI_QUOTA_LIMIT
  115. trial_models = self.parse_restrict_models_from_env("HOSTED_OPENAI_TRIAL_MODELS")
  116. trial_quota = TrialHostingQuota(quota_limit=hosted_quota_limit, restrict_models=trial_models)
  117. quotas.append(trial_quota)
  118. if dify_config.HOSTED_OPENAI_PAID_ENABLED:
  119. paid_models = self.parse_restrict_models_from_env("HOSTED_OPENAI_PAID_MODELS")
  120. paid_quota = PaidHostingQuota(restrict_models=paid_models)
  121. quotas.append(paid_quota)
  122. if len(quotas) > 0:
  123. credentials = {
  124. "openai_api_key": dify_config.HOSTED_OPENAI_API_KEY,
  125. }
  126. if dify_config.HOSTED_OPENAI_API_BASE:
  127. credentials["openai_api_base"] = dify_config.HOSTED_OPENAI_API_BASE
  128. if dify_config.HOSTED_OPENAI_API_ORGANIZATION:
  129. credentials["openai_organization"] = dify_config.HOSTED_OPENAI_API_ORGANIZATION
  130. return HostingProvider(enabled=True, credentials=credentials, quota_unit=quota_unit, quotas=quotas)
  131. return HostingProvider(
  132. enabled=False,
  133. quota_unit=quota_unit,
  134. )
  135. @staticmethod
  136. def init_anthropic() -> HostingProvider:
  137. quota_unit = QuotaUnit.TOKENS
  138. quotas: list[HostingQuota] = []
  139. if dify_config.HOSTED_ANTHROPIC_TRIAL_ENABLED:
  140. hosted_quota_limit = dify_config.HOSTED_ANTHROPIC_QUOTA_LIMIT
  141. trial_quota = TrialHostingQuota(quota_limit=hosted_quota_limit)
  142. quotas.append(trial_quota)
  143. if dify_config.HOSTED_ANTHROPIC_PAID_ENABLED:
  144. paid_quota = PaidHostingQuota()
  145. quotas.append(paid_quota)
  146. if len(quotas) > 0:
  147. credentials = {
  148. "anthropic_api_key": dify_config.HOSTED_ANTHROPIC_API_KEY,
  149. }
  150. if dify_config.HOSTED_ANTHROPIC_API_BASE:
  151. credentials["anthropic_api_url"] = dify_config.HOSTED_ANTHROPIC_API_BASE
  152. return HostingProvider(enabled=True, credentials=credentials, quota_unit=quota_unit, quotas=quotas)
  153. return HostingProvider(
  154. enabled=False,
  155. quota_unit=quota_unit,
  156. )
  157. @staticmethod
  158. def init_minimax() -> HostingProvider:
  159. quota_unit = QuotaUnit.TOKENS
  160. if dify_config.HOSTED_MINIMAX_ENABLED:
  161. quotas: list[HostingQuota] = [FreeHostingQuota()]
  162. return HostingProvider(
  163. enabled=True,
  164. credentials=None, # use credentials from the provider
  165. quota_unit=quota_unit,
  166. quotas=quotas,
  167. )
  168. return HostingProvider(
  169. enabled=False,
  170. quota_unit=quota_unit,
  171. )
  172. @staticmethod
  173. def init_spark() -> HostingProvider:
  174. quota_unit = QuotaUnit.TOKENS
  175. if dify_config.HOSTED_SPARK_ENABLED:
  176. quotas: list[HostingQuota] = [FreeHostingQuota()]
  177. return HostingProvider(
  178. enabled=True,
  179. credentials=None, # use credentials from the provider
  180. quota_unit=quota_unit,
  181. quotas=quotas,
  182. )
  183. return HostingProvider(
  184. enabled=False,
  185. quota_unit=quota_unit,
  186. )
  187. @staticmethod
  188. def init_zhipuai() -> HostingProvider:
  189. quota_unit = QuotaUnit.TOKENS
  190. if dify_config.HOSTED_ZHIPUAI_ENABLED:
  191. quotas: list[HostingQuota] = [FreeHostingQuota()]
  192. return HostingProvider(
  193. enabled=True,
  194. credentials=None, # use credentials from the provider
  195. quota_unit=quota_unit,
  196. quotas=quotas,
  197. )
  198. return HostingProvider(
  199. enabled=False,
  200. quota_unit=quota_unit,
  201. )
  202. @staticmethod
  203. def init_moderation_config() -> HostedModerationConfig:
  204. if dify_config.HOSTED_MODERATION_ENABLED and dify_config.HOSTED_MODERATION_PROVIDERS:
  205. providers = dify_config.HOSTED_MODERATION_PROVIDERS.split(",")
  206. hosted_providers = []
  207. for provider in providers:
  208. if "/" not in provider:
  209. provider = f"{DEFAULT_PLUGIN_ID}/{provider}/{provider}"
  210. hosted_providers.append(provider)
  211. return HostedModerationConfig(enabled=True, providers=hosted_providers)
  212. return HostedModerationConfig(enabled=False)
  213. @staticmethod
  214. def parse_restrict_models_from_env(env_var: str) -> list[RestrictModel]:
  215. models_str = dify_config.model_dump().get(env_var)
  216. models_list = models_str.split(",") if models_str else []
  217. return [
  218. RestrictModel(model=model_name.strip(), model_type=ModelType.LLM)
  219. for model_name in models_list
  220. if model_name.strip()
  221. ]