__init__.py 9.0 KB

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