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.

__init__.py 11KB

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