config.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. import os
  2. import sys
  3. import logging
  4. import chromadb
  5. from chromadb import Settings
  6. from base64 import b64encode
  7. from bs4 import BeautifulSoup
  8. from pathlib import Path
  9. import json
  10. import yaml
  11. import markdown
  12. import requests
  13. import shutil
  14. from secrets import token_bytes
  15. from constants import ERROR_MESSAGES
  16. ####################################
  17. # LOGGING
  18. ####################################
  19. log_levels = ["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"]
  20. GLOBAL_LOG_LEVEL = os.environ.get("GLOBAL_LOG_LEVEL", "").upper()
  21. if GLOBAL_LOG_LEVEL in log_levels:
  22. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL, force=True)
  23. else:
  24. GLOBAL_LOG_LEVEL = "INFO"
  25. log = logging.getLogger(__name__)
  26. log.info(f"GLOBAL_LOG_LEVEL: {GLOBAL_LOG_LEVEL}")
  27. log_sources = [
  28. "AUDIO",
  29. "COMFYUI",
  30. "CONFIG",
  31. "DB",
  32. "IMAGES",
  33. "LITELLM",
  34. "MAIN",
  35. "MODELS",
  36. "OLLAMA",
  37. "OPENAI",
  38. "RAG",
  39. "WEBHOOK",
  40. ]
  41. SRC_LOG_LEVELS = {}
  42. for source in log_sources:
  43. log_env_var = source + "_LOG_LEVEL"
  44. SRC_LOG_LEVELS[source] = os.environ.get(log_env_var, "").upper()
  45. if SRC_LOG_LEVELS[source] not in log_levels:
  46. SRC_LOG_LEVELS[source] = GLOBAL_LOG_LEVEL
  47. log.info(f"{log_env_var}: {SRC_LOG_LEVELS[source]}")
  48. log.setLevel(SRC_LOG_LEVELS["CONFIG"])
  49. ####################################
  50. # Load .env file
  51. ####################################
  52. try:
  53. from dotenv import load_dotenv, find_dotenv
  54. load_dotenv(find_dotenv("../.env"))
  55. except ImportError:
  56. log.warning("dotenv not installed, skipping...")
  57. WEBUI_NAME = os.environ.get("WEBUI_NAME", "Open WebUI")
  58. if WEBUI_NAME != "Open WebUI":
  59. WEBUI_NAME += " (Open WebUI)"
  60. WEBUI_FAVICON_URL = "https://openwebui.com/favicon.png"
  61. ####################################
  62. # ENV (dev,test,prod)
  63. ####################################
  64. ENV = os.environ.get("ENV", "dev")
  65. try:
  66. with open(f"../package.json", "r") as f:
  67. PACKAGE_DATA = json.load(f)
  68. except:
  69. PACKAGE_DATA = {"version": "0.0.0"}
  70. VERSION = PACKAGE_DATA["version"]
  71. # Function to parse each section
  72. def parse_section(section):
  73. items = []
  74. for li in section.find_all("li"):
  75. # Extract raw HTML string
  76. raw_html = str(li)
  77. # Extract text without HTML tags
  78. text = li.get_text(separator=" ", strip=True)
  79. # Split into title and content
  80. parts = text.split(": ", 1)
  81. title = parts[0].strip() if len(parts) > 1 else ""
  82. content = parts[1].strip() if len(parts) > 1 else text
  83. items.append({"title": title, "content": content, "raw": raw_html})
  84. return items
  85. try:
  86. with open("../CHANGELOG.md", "r") as file:
  87. changelog_content = file.read()
  88. except:
  89. changelog_content = ""
  90. # Convert markdown content to HTML
  91. html_content = markdown.markdown(changelog_content)
  92. # Parse the HTML content
  93. soup = BeautifulSoup(html_content, "html.parser")
  94. # Initialize JSON structure
  95. changelog_json = {}
  96. # Iterate over each version
  97. for version in soup.find_all("h2"):
  98. version_number = version.get_text().strip().split(" - ")[0][1:-1] # Remove brackets
  99. date = version.get_text().strip().split(" - ")[1]
  100. version_data = {"date": date}
  101. # Find the next sibling that is a h3 tag (section title)
  102. current = version.find_next_sibling()
  103. while current and current.name != "h2":
  104. if current.name == "h3":
  105. section_title = current.get_text().lower() # e.g., "added", "fixed"
  106. section_items = parse_section(current.find_next_sibling("ul"))
  107. version_data[section_title] = section_items
  108. # Move to the next element
  109. current = current.find_next_sibling()
  110. changelog_json[version_number] = version_data
  111. CHANGELOG = changelog_json
  112. ####################################
  113. # DATA/FRONTEND BUILD DIR
  114. ####################################
  115. DATA_DIR = str(Path(os.getenv("DATA_DIR", "./data")).resolve())
  116. FRONTEND_BUILD_DIR = str(Path(os.getenv("FRONTEND_BUILD_DIR", "../build")))
  117. try:
  118. with open(f"{DATA_DIR}/config.json", "r") as f:
  119. CONFIG_DATA = json.load(f)
  120. except:
  121. CONFIG_DATA = {}
  122. ####################################
  123. # Static DIR
  124. ####################################
  125. STATIC_DIR = str(Path(os.getenv("STATIC_DIR", "./static")).resolve())
  126. shutil.copyfile(f"{FRONTEND_BUILD_DIR}/favicon.png", f"{STATIC_DIR}/favicon.png")
  127. ####################################
  128. # CUSTOM_NAME
  129. ####################################
  130. CUSTOM_NAME = os.environ.get("CUSTOM_NAME", "")
  131. if CUSTOM_NAME:
  132. try:
  133. r = requests.get(f"https://api.openwebui.com/api/v1/custom/{CUSTOM_NAME}")
  134. data = r.json()
  135. if r.ok:
  136. if "logo" in data:
  137. WEBUI_FAVICON_URL = url = (
  138. f"https://api.openwebui.com{data['logo']}"
  139. if data["logo"][0] == "/"
  140. else data["logo"]
  141. )
  142. r = requests.get(url, stream=True)
  143. if r.status_code == 200:
  144. with open(f"{STATIC_DIR}/favicon.png", "wb") as f:
  145. r.raw.decode_content = True
  146. shutil.copyfileobj(r.raw, f)
  147. WEBUI_NAME = data["name"]
  148. except Exception as e:
  149. log.exception(e)
  150. pass
  151. ####################################
  152. # File Upload DIR
  153. ####################################
  154. UPLOAD_DIR = f"{DATA_DIR}/uploads"
  155. Path(UPLOAD_DIR).mkdir(parents=True, exist_ok=True)
  156. ####################################
  157. # Cache DIR
  158. ####################################
  159. CACHE_DIR = f"{DATA_DIR}/cache"
  160. Path(CACHE_DIR).mkdir(parents=True, exist_ok=True)
  161. ####################################
  162. # Docs DIR
  163. ####################################
  164. DOCS_DIR = os.getenv("DOCS_DIR", f"{DATA_DIR}/docs")
  165. Path(DOCS_DIR).mkdir(parents=True, exist_ok=True)
  166. ####################################
  167. # LITELLM_CONFIG
  168. ####################################
  169. def create_config_file(file_path):
  170. directory = os.path.dirname(file_path)
  171. # Check if directory exists, if not, create it
  172. if not os.path.exists(directory):
  173. os.makedirs(directory)
  174. # Data to write into the YAML file
  175. config_data = {
  176. "general_settings": {},
  177. "litellm_settings": {},
  178. "model_list": [],
  179. "router_settings": {},
  180. }
  181. # Write data to YAML file
  182. with open(file_path, "w") as file:
  183. yaml.dump(config_data, file)
  184. LITELLM_CONFIG_PATH = f"{DATA_DIR}/litellm/config.yaml"
  185. if not os.path.exists(LITELLM_CONFIG_PATH):
  186. log.info("Config file doesn't exist. Creating...")
  187. create_config_file(LITELLM_CONFIG_PATH)
  188. log.info("Config file created successfully.")
  189. ####################################
  190. # OLLAMA_BASE_URL
  191. ####################################
  192. OLLAMA_API_BASE_URL = os.environ.get(
  193. "OLLAMA_API_BASE_URL", "http://localhost:11434/api"
  194. )
  195. OLLAMA_BASE_URL = os.environ.get("OLLAMA_BASE_URL", "")
  196. K8S_FLAG = os.environ.get("K8S_FLAG", "")
  197. USE_OLLAMA_DOCKER = os.environ.get("USE_OLLAMA_DOCKER", "false")
  198. if OLLAMA_BASE_URL == "" and OLLAMA_API_BASE_URL != "":
  199. OLLAMA_BASE_URL = (
  200. OLLAMA_API_BASE_URL[:-4]
  201. if OLLAMA_API_BASE_URL.endswith("/api")
  202. else OLLAMA_API_BASE_URL
  203. )
  204. if ENV == "prod":
  205. if OLLAMA_BASE_URL == "/ollama" and not K8S_FLAG:
  206. if USE_OLLAMA_DOCKER.lower() == "true":
  207. # if you use all-in-one docker container (Open WebUI + Ollama)
  208. # with the docker build arg USE_OLLAMA=true (--build-arg="USE_OLLAMA=true") this only works with http://localhost:11434
  209. OLLAMA_BASE_URL = "http://localhost:11434"
  210. else:
  211. OLLAMA_BASE_URL = "http://host.docker.internal:11434"
  212. elif K8S_FLAG:
  213. OLLAMA_BASE_URL = "http://ollama-service.open-webui.svc.cluster.local:11434"
  214. OLLAMA_BASE_URLS = os.environ.get("OLLAMA_BASE_URLS", "")
  215. OLLAMA_BASE_URLS = OLLAMA_BASE_URLS if OLLAMA_BASE_URLS != "" else OLLAMA_BASE_URL
  216. OLLAMA_BASE_URLS = [url.strip() for url in OLLAMA_BASE_URLS.split(";")]
  217. ####################################
  218. # OPENAI_API
  219. ####################################
  220. OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")
  221. OPENAI_API_BASE_URL = os.environ.get("OPENAI_API_BASE_URL", "")
  222. if OPENAI_API_BASE_URL == "":
  223. OPENAI_API_BASE_URL = "https://api.openai.com/v1"
  224. OPENAI_API_KEYS = os.environ.get("OPENAI_API_KEYS", "")
  225. OPENAI_API_KEYS = OPENAI_API_KEYS if OPENAI_API_KEYS != "" else OPENAI_API_KEY
  226. OPENAI_API_KEYS = [url.strip() for url in OPENAI_API_KEYS.split(";")]
  227. OPENAI_API_BASE_URLS = os.environ.get("OPENAI_API_BASE_URLS", "")
  228. OPENAI_API_BASE_URLS = (
  229. OPENAI_API_BASE_URLS if OPENAI_API_BASE_URLS != "" else OPENAI_API_BASE_URL
  230. )
  231. OPENAI_API_BASE_URLS = [
  232. url.strip() if url != "" else "https://api.openai.com/v1"
  233. for url in OPENAI_API_BASE_URLS.split(";")
  234. ]
  235. OPENAI_API_KEY = ""
  236. try:
  237. OPENAI_API_KEY = OPENAI_API_KEYS[
  238. OPENAI_API_BASE_URLS.index("https://api.openai.com/v1")
  239. ]
  240. except:
  241. pass
  242. OPENAI_API_BASE_URL = "https://api.openai.com/v1"
  243. ####################################
  244. # WEBUI
  245. ####################################
  246. ENABLE_SIGNUP = os.environ.get("ENABLE_SIGNUP", "True").lower() == "true"
  247. DEFAULT_MODELS = os.environ.get("DEFAULT_MODELS", None)
  248. DEFAULT_PROMPT_SUGGESTIONS = (
  249. CONFIG_DATA["ui"]["prompt_suggestions"]
  250. if "ui" in CONFIG_DATA
  251. and "prompt_suggestions" in CONFIG_DATA["ui"]
  252. and type(CONFIG_DATA["ui"]["prompt_suggestions"]) is list
  253. else [
  254. {
  255. "title": ["Help me study", "vocabulary for a college entrance exam"],
  256. "content": "Help me study vocabulary: write a sentence for me to fill in the blank, and I'll try to pick the correct option.",
  257. },
  258. {
  259. "title": ["Give me ideas", "for what to do with my kids' art"],
  260. "content": "What are 5 creative things I could do with my kids' art? I don't want to throw them away, but it's also so much clutter.",
  261. },
  262. {
  263. "title": ["Tell me a fun fact", "about the Roman Empire"],
  264. "content": "Tell me a random fun fact about the Roman Empire",
  265. },
  266. {
  267. "title": ["Show me a code snippet", "of a website's sticky header"],
  268. "content": "Show me a code snippet of a website's sticky header in CSS and JavaScript.",
  269. },
  270. ]
  271. )
  272. DEFAULT_USER_ROLE = os.getenv("DEFAULT_USER_ROLE", "pending")
  273. USER_PERMISSIONS_CHAT_DELETION = (
  274. os.environ.get("USER_PERMISSIONS_CHAT_DELETION", "True").lower() == "true"
  275. )
  276. USER_PERMISSIONS = {"chat": {"deletion": USER_PERMISSIONS_CHAT_DELETION}}
  277. ENABLE_MODEL_FILTER = os.environ.get("ENABLE_MODEL_FILTER", "False").lower() == "true"
  278. MODEL_FILTER_LIST = os.environ.get("MODEL_FILTER_LIST", "")
  279. MODEL_FILTER_LIST = [model.strip() for model in MODEL_FILTER_LIST.split(";")]
  280. WEBHOOK_URL = os.environ.get("WEBHOOK_URL", "")
  281. ENABLE_ADMIN_EXPORT = os.environ.get("ENABLE_ADMIN_EXPORT", "True").lower() == "true"
  282. ####################################
  283. # WEBUI_VERSION
  284. ####################################
  285. WEBUI_VERSION = os.environ.get("WEBUI_VERSION", "v1.0.0-alpha.100")
  286. ####################################
  287. # WEBUI_AUTH (Required for security)
  288. ####################################
  289. WEBUI_AUTH = True
  290. WEBUI_AUTH_TRUSTED_EMAIL_HEADER = os.environ.get(
  291. "WEBUI_AUTH_TRUSTED_EMAIL_HEADER", None
  292. )
  293. ####################################
  294. # WEBUI_SECRET_KEY
  295. ####################################
  296. WEBUI_SECRET_KEY = os.environ.get(
  297. "WEBUI_SECRET_KEY",
  298. os.environ.get(
  299. "WEBUI_JWT_SECRET_KEY", "t0p-s3cr3t"
  300. ), # DEPRECATED: remove at next major version
  301. )
  302. if WEBUI_AUTH and WEBUI_SECRET_KEY == "":
  303. raise ValueError(ERROR_MESSAGES.ENV_VAR_NOT_FOUND)
  304. ####################################
  305. # RAG
  306. ####################################
  307. CHROMA_DATA_PATH = f"{DATA_DIR}/vector_db"
  308. CHROMA_TENANT = os.environ.get("CHROMA_TENANT", chromadb.DEFAULT_TENANT)
  309. CHROMA_DATABASE = os.environ.get("CHROMA_DATABASE", chromadb.DEFAULT_DATABASE)
  310. CHROMA_HTTP_HOST = os.environ.get("CHROMA_HTTP_HOST", "")
  311. CHROMA_HTTP_PORT = int(os.environ.get("CHROMA_HTTP_PORT", "8000"))
  312. # Comma-separated list of header=value pairs
  313. CHROMA_HTTP_HEADERS = os.environ.get("CHROMA_HTTP_HEADERS", "")
  314. if CHROMA_HTTP_HEADERS:
  315. CHROMA_HTTP_HEADERS = dict(
  316. [pair.split("=") for pair in CHROMA_HTTP_HEADERS.split(",")]
  317. )
  318. else:
  319. CHROMA_HTTP_HEADERS = None
  320. CHROMA_HTTP_SSL = os.environ.get("CHROMA_HTTP_SSL", "false").lower() == "true"
  321. # this uses the model defined in the Dockerfile ENV variable. If you dont use docker or docker based deployments such as k8s, the default embedding model will be used (sentence-transformers/all-MiniLM-L6-v2)
  322. RAG_TOP_K = int(os.environ.get("RAG_TOP_K", "5"))
  323. RAG_RELEVANCE_THRESHOLD = float(os.environ.get("RAG_RELEVANCE_THRESHOLD", "0.0"))
  324. ENABLE_RAG_HYBRID_SEARCH = (
  325. os.environ.get("ENABLE_RAG_HYBRID_SEARCH", "").lower() == "true"
  326. )
  327. RAG_EMBEDDING_ENGINE = os.environ.get("RAG_EMBEDDING_ENGINE", "")
  328. PDF_EXTRACT_IMAGES = os.environ.get("PDF_EXTRACT_IMAGES", "False").lower() == "true"
  329. RAG_EMBEDDING_MODEL = os.environ.get(
  330. "RAG_EMBEDDING_MODEL", "sentence-transformers/all-MiniLM-L6-v2"
  331. )
  332. log.info(f"Embedding model set: {RAG_EMBEDDING_MODEL}"),
  333. RAG_EMBEDDING_MODEL_AUTO_UPDATE = (
  334. os.environ.get("RAG_EMBEDDING_MODEL_AUTO_UPDATE", "").lower() == "true"
  335. )
  336. RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE = (
  337. os.environ.get("RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE", "").lower() == "true"
  338. )
  339. RAG_RERANKING_MODEL = os.environ.get("RAG_RERANKING_MODEL", "")
  340. if not RAG_RERANKING_MODEL == "":
  341. log.info(f"Reranking model set: {RAG_RERANKING_MODEL}"),
  342. RAG_RERANKING_MODEL_AUTO_UPDATE = (
  343. os.environ.get("RAG_RERANKING_MODEL_AUTO_UPDATE", "").lower() == "true"
  344. )
  345. RAG_RERANKING_MODEL_TRUST_REMOTE_CODE = (
  346. os.environ.get("RAG_RERANKING_MODEL_TRUST_REMOTE_CODE", "").lower() == "true"
  347. )
  348. # device type embedding models - "cpu" (default), "cuda" (nvidia gpu required) or "mps" (apple silicon) - choosing this right can lead to better performance
  349. USE_CUDA = os.environ.get("USE_CUDA_DOCKER", "false")
  350. if USE_CUDA.lower() == "true":
  351. DEVICE_TYPE = "cuda"
  352. else:
  353. DEVICE_TYPE = "cpu"
  354. if CHROMA_HTTP_HOST != "":
  355. CHROMA_CLIENT = chromadb.HttpClient(
  356. host=CHROMA_HTTP_HOST,
  357. port=CHROMA_HTTP_PORT,
  358. headers=CHROMA_HTTP_HEADERS,
  359. ssl=CHROMA_HTTP_SSL,
  360. tenant=CHROMA_TENANT,
  361. database=CHROMA_DATABASE,
  362. settings=Settings(allow_reset=True, anonymized_telemetry=False),
  363. )
  364. else:
  365. CHROMA_CLIENT = chromadb.PersistentClient(
  366. path=CHROMA_DATA_PATH,
  367. settings=Settings(allow_reset=True, anonymized_telemetry=False),
  368. tenant=CHROMA_TENANT,
  369. database=CHROMA_DATABASE,
  370. )
  371. CHUNK_SIZE = int(os.environ.get("CHUNK_SIZE", "1500"))
  372. CHUNK_OVERLAP = int(os.environ.get("CHUNK_OVERLAP", "100"))
  373. DEFAULT_RAG_TEMPLATE = """Use the following context as your learned knowledge, inside <context></context> XML tags.
  374. <context>
  375. [context]
  376. </context>
  377. When answer to user:
  378. - If you don't know, just say that you don't know.
  379. - If you don't know when you are not sure, ask for clarification.
  380. Avoid mentioning that you obtained the information from the context.
  381. And answer according to the language of the user's question.
  382. Given the context information, answer the query.
  383. Query: [query]"""
  384. RAG_TEMPLATE = os.environ.get("RAG_TEMPLATE", DEFAULT_RAG_TEMPLATE)
  385. RAG_OPENAI_API_BASE_URL = os.getenv("RAG_OPENAI_API_BASE_URL", OPENAI_API_BASE_URL)
  386. RAG_OPENAI_API_KEY = os.getenv("RAG_OPENAI_API_KEY", OPENAI_API_KEY)
  387. ####################################
  388. # Transcribe
  389. ####################################
  390. WHISPER_MODEL = os.getenv("WHISPER_MODEL", "base")
  391. WHISPER_MODEL_DIR = os.getenv("WHISPER_MODEL_DIR", f"{CACHE_DIR}/whisper/models")
  392. WHISPER_MODEL_AUTO_UPDATE = (
  393. os.environ.get("WHISPER_MODEL_AUTO_UPDATE", "").lower() == "true"
  394. )
  395. ####################################
  396. # Images
  397. ####################################
  398. IMAGES_GENERATION_ENGINE = os.getenv("IMAGES_GENERATION_ENGINE", "")
  399. ENABLE_IMAGE_GENERATION = (
  400. os.environ.get("ENABLE_IMAGE_GENERATION", "").lower() == "true"
  401. )
  402. AUTOMATIC1111_BASE_URL = os.getenv("AUTOMATIC1111_BASE_URL", "")
  403. COMFYUI_BASE_URL = os.getenv("COMFYUI_BASE_URL", "")
  404. IMAGES_OPENAI_API_BASE_URL = os.getenv(
  405. "IMAGES_OPENAI_API_BASE_URL", OPENAI_API_BASE_URL
  406. )
  407. IMAGES_OPENAI_API_KEY = os.getenv("IMAGES_OPENAI_API_KEY", OPENAI_API_KEY)
  408. IMAGE_SIZE = os.getenv("IMAGE_SIZE", "512x512")
  409. IMAGE_STEPS = int(os.getenv("IMAGE_STEPS", 50))
  410. IMAGES_MODEL = os.getenv("IMAGES_MODEL", "")
  411. ####################################
  412. # Audio
  413. ####################################
  414. AUDIO_OPENAI_API_BASE_URL = os.getenv("AUDIO_OPENAI_API_BASE_URL", OPENAI_API_BASE_URL)
  415. AUDIO_OPENAI_API_KEY = os.getenv("AUDIO_OPENAI_API_KEY", OPENAI_API_KEY)
  416. ####################################
  417. # LiteLLM
  418. ####################################
  419. ENABLE_LITELLM = os.environ.get("ENABLE_LITELLM", "True").lower() == "true"
  420. LITELLM_PROXY_PORT = int(os.getenv("LITELLM_PROXY_PORT", "14365"))
  421. if LITELLM_PROXY_PORT < 0 or LITELLM_PROXY_PORT > 65535:
  422. raise ValueError("Invalid port number for LITELLM_PROXY_PORT")
  423. LITELLM_PROXY_HOST = os.getenv("LITELLM_PROXY_HOST", "127.0.0.1")
  424. ####################################
  425. # Database
  426. ####################################
  427. DATABASE_URL = os.environ.get("DATABASE_URL", f"sqlite:///{DATA_DIR}/webui.db")