__init__.py 8.9 KB

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