__init__.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. from typing import Any, Literal, Optional
  2. from urllib.parse import quote_plus
  3. from pydantic import Field, NonNegativeInt, PositiveFloat, PositiveInt, computed_field
  4. from pydantic_settings import BaseSettings
  5. from .cache.redis_config import RedisConfig
  6. from .storage.aliyun_oss_storage_config import AliyunOSSStorageConfig
  7. from .storage.amazon_s3_storage_config import S3StorageConfig
  8. from .storage.azure_blob_storage_config import AzureBlobStorageConfig
  9. from .storage.baidu_obs_storage_config import BaiduOBSStorageConfig
  10. from .storage.google_cloud_storage_config import GoogleCloudStorageConfig
  11. from .storage.huawei_obs_storage_config import HuaweiCloudOBSStorageConfig
  12. from .storage.oci_storage_config import OCIStorageConfig
  13. from .storage.opendal_storage_config import OpenDALStorageConfig
  14. from .storage.supabase_storage_config import SupabaseStorageConfig
  15. from .storage.tencent_cos_storage_config import TencentCloudCOSStorageConfig
  16. from .storage.volcengine_tos_storage_config import VolcengineTOSStorageConfig
  17. from .vdb.analyticdb_config import AnalyticdbConfig
  18. from .vdb.baidu_vector_config import BaiduVectorDBConfig
  19. from .vdb.chroma_config import ChromaConfig
  20. from .vdb.couchbase_config import CouchbaseConfig
  21. from .vdb.elasticsearch_config import ElasticsearchConfig
  22. from .vdb.lindorm_config import LindormConfig
  23. from .vdb.milvus_config import MilvusConfig
  24. from .vdb.myscale_config import MyScaleConfig
  25. from .vdb.oceanbase_config import OceanBaseVectorConfig
  26. from .vdb.opensearch_config import OpenSearchConfig
  27. from .vdb.oracle_config import OracleConfig
  28. from .vdb.pgvector_config import PGVectorConfig
  29. from .vdb.pgvectors_config import PGVectoRSConfig
  30. from .vdb.qdrant_config import QdrantConfig
  31. from .vdb.relyt_config import RelytConfig
  32. from .vdb.tencent_vector_config import TencentVectorDBConfig
  33. from .vdb.tidb_on_qdrant_config import TidbOnQdrantConfig
  34. from .vdb.tidb_vector_config import TiDBVectorConfig
  35. from .vdb.upstash_config import UpstashConfig
  36. from .vdb.vikingdb_config import VikingDBConfig
  37. from .vdb.weaviate_config import WeaviateConfig
  38. class StorageConfig(BaseSettings):
  39. STORAGE_TYPE: Literal[
  40. "opendal",
  41. "s3",
  42. "aliyun-oss",
  43. "azure-blob",
  44. "baidu-obs",
  45. "google-storage",
  46. "huawei-obs",
  47. "oci-storage",
  48. "tencent-cos",
  49. "volcengine-tos",
  50. "supabase",
  51. "local",
  52. ] = Field(
  53. description="Type of storage to use."
  54. " Options: 'opendal', '(deprecated) local', 's3', 'aliyun-oss', 'azure-blob', 'baidu-obs', 'google-storage', "
  55. "'huawei-obs', 'oci-storage', 'tencent-cos', 'volcengine-tos', 'supabase'. Default is 'opendal'.",
  56. default="opendal",
  57. )
  58. STORAGE_LOCAL_PATH: str = Field(
  59. description="Path for local storage when STORAGE_TYPE is set to 'local'.",
  60. default="storage",
  61. deprecated=True,
  62. )
  63. class VectorStoreConfig(BaseSettings):
  64. VECTOR_STORE: Optional[str] = Field(
  65. description="Type of vector store to use for efficient similarity search."
  66. " Set to None if not using a vector store.",
  67. default=None,
  68. )
  69. VECTOR_STORE_WHITELIST_ENABLE: Optional[bool] = Field(
  70. description="Enable whitelist for vector store.",
  71. default=False,
  72. )
  73. class KeywordStoreConfig(BaseSettings):
  74. KEYWORD_STORE: str = Field(
  75. description="Method for keyword extraction and storage."
  76. " Default is 'jieba', a Chinese text segmentation library.",
  77. default="jieba",
  78. )
  79. class DatabaseConfig(BaseSettings):
  80. DB_HOST: str = Field(
  81. description="Hostname or IP address of the database server.",
  82. default="localhost",
  83. )
  84. DB_PORT: PositiveInt = Field(
  85. description="Port number for database connection.",
  86. default=5432,
  87. )
  88. DB_USERNAME: str = Field(
  89. description="Username for database authentication.",
  90. default="postgres",
  91. )
  92. DB_PASSWORD: str = Field(
  93. description="Password for database authentication.",
  94. default="",
  95. )
  96. DB_DATABASE: str = Field(
  97. description="Name of the database to connect to.",
  98. default="dify",
  99. )
  100. DB_CHARSET: str = Field(
  101. description="Character set for database connection.",
  102. default="",
  103. )
  104. DB_EXTRAS: str = Field(
  105. description="Additional database connection parameters. Example: 'keepalives_idle=60&keepalives=1'",
  106. default="",
  107. )
  108. SQLALCHEMY_DATABASE_URI_SCHEME: str = Field(
  109. description="Database URI scheme for SQLAlchemy connection.",
  110. default="postgresql",
  111. )
  112. @computed_field
  113. def SQLALCHEMY_DATABASE_URI(self) -> str:
  114. db_extras = (
  115. f"{self.DB_EXTRAS}&client_encoding={self.DB_CHARSET}" if self.DB_CHARSET else self.DB_EXTRAS
  116. ).strip("&")
  117. db_extras = f"?{db_extras}" if db_extras else ""
  118. return (
  119. f"{self.SQLALCHEMY_DATABASE_URI_SCHEME}://"
  120. f"{quote_plus(self.DB_USERNAME)}:{quote_plus(self.DB_PASSWORD)}@{self.DB_HOST}:{self.DB_PORT}/{self.DB_DATABASE}"
  121. f"{db_extras}"
  122. )
  123. SQLALCHEMY_POOL_SIZE: NonNegativeInt = Field(
  124. description="Maximum number of database connections in the pool.",
  125. default=30,
  126. )
  127. SQLALCHEMY_MAX_OVERFLOW: NonNegativeInt = Field(
  128. description="Maximum number of connections that can be created beyond the pool_size.",
  129. default=10,
  130. )
  131. SQLALCHEMY_POOL_RECYCLE: NonNegativeInt = Field(
  132. description="Number of seconds after which a connection is automatically recycled.",
  133. default=3600,
  134. )
  135. SQLALCHEMY_POOL_PRE_PING: bool = Field(
  136. description="If True, enables connection pool pre-ping feature to check connections.",
  137. default=False,
  138. )
  139. SQLALCHEMY_ECHO: bool | str = Field(
  140. description="If True, SQLAlchemy will log all SQL statements.",
  141. default=False,
  142. )
  143. @computed_field
  144. def SQLALCHEMY_ENGINE_OPTIONS(self) -> dict[str, Any]:
  145. return {
  146. "pool_size": self.SQLALCHEMY_POOL_SIZE,
  147. "max_overflow": self.SQLALCHEMY_MAX_OVERFLOW,
  148. "pool_recycle": self.SQLALCHEMY_POOL_RECYCLE,
  149. "pool_pre_ping": self.SQLALCHEMY_POOL_PRE_PING,
  150. "connect_args": {"options": "-c timezone=UTC"},
  151. }
  152. class CeleryConfig(DatabaseConfig):
  153. CELERY_BACKEND: str = Field(
  154. description="Backend for Celery task results. Options: 'database', 'redis'.",
  155. default="database",
  156. )
  157. CELERY_BROKER_URL: Optional[str] = Field(
  158. description="URL of the message broker for Celery tasks.",
  159. default=None,
  160. )
  161. CELERY_USE_SENTINEL: Optional[bool] = Field(
  162. description="Whether to use Redis Sentinel for high availability.",
  163. default=False,
  164. )
  165. CELERY_SENTINEL_MASTER_NAME: Optional[str] = Field(
  166. description="Name of the Redis Sentinel master.",
  167. default=None,
  168. )
  169. CELERY_SENTINEL_SOCKET_TIMEOUT: Optional[PositiveFloat] = Field(
  170. description="Timeout for Redis Sentinel socket operations in seconds.",
  171. default=0.1,
  172. )
  173. @computed_field
  174. def CELERY_RESULT_BACKEND(self) -> str | None:
  175. return (
  176. "db+{}".format(self.SQLALCHEMY_DATABASE_URI)
  177. if self.CELERY_BACKEND == "database"
  178. else self.CELERY_BROKER_URL
  179. )
  180. @property
  181. def BROKER_USE_SSL(self) -> bool:
  182. return self.CELERY_BROKER_URL.startswith("rediss://") if self.CELERY_BROKER_URL else False
  183. class InternalTestConfig(BaseSettings):
  184. """
  185. Configuration settings for Internal Test
  186. """
  187. AWS_SECRET_ACCESS_KEY: Optional[str] = Field(
  188. description="Internal test AWS secret access key",
  189. default=None,
  190. )
  191. AWS_ACCESS_KEY_ID: Optional[str] = Field(
  192. description="Internal test AWS access key ID",
  193. default=None,
  194. )
  195. class MiddlewareConfig(
  196. # place the configs in alphabet order
  197. CeleryConfig,
  198. DatabaseConfig,
  199. KeywordStoreConfig,
  200. RedisConfig,
  201. # configs of storage and storage providers
  202. StorageConfig,
  203. AliyunOSSStorageConfig,
  204. AzureBlobStorageConfig,
  205. BaiduOBSStorageConfig,
  206. GoogleCloudStorageConfig,
  207. HuaweiCloudOBSStorageConfig,
  208. OCIStorageConfig,
  209. OpenDALStorageConfig,
  210. S3StorageConfig,
  211. SupabaseStorageConfig,
  212. TencentCloudCOSStorageConfig,
  213. VolcengineTOSStorageConfig,
  214. # configs of vdb and vdb providers
  215. VectorStoreConfig,
  216. AnalyticdbConfig,
  217. ChromaConfig,
  218. MilvusConfig,
  219. MyScaleConfig,
  220. OpenSearchConfig,
  221. OracleConfig,
  222. PGVectorConfig,
  223. PGVectoRSConfig,
  224. QdrantConfig,
  225. RelytConfig,
  226. TencentVectorDBConfig,
  227. TiDBVectorConfig,
  228. WeaviateConfig,
  229. ElasticsearchConfig,
  230. CouchbaseConfig,
  231. InternalTestConfig,
  232. VikingDBConfig,
  233. UpstashConfig,
  234. TidbOnQdrantConfig,
  235. LindormConfig,
  236. OceanBaseVectorConfig,
  237. BaiduVectorDBConfig,
  238. ):
  239. pass