config.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. import json
  2. import os
  3. import shutil
  4. from base64 import b64encode
  5. from pathlib import Path
  6. from secrets import token_bytes
  7. import chromadb
  8. import markdown
  9. import requests
  10. import yaml
  11. from bs4 import BeautifulSoup
  12. from chromadb import Settings
  13. from constants import ERROR_MESSAGES
  14. try:
  15. from dotenv import find_dotenv, load_dotenv
  16. load_dotenv(find_dotenv("../.env"))
  17. except ImportError:
  18. print("dotenv not installed, skipping...")
  19. WEBUI_NAME = "Open WebUI"
  20. WEBUI_FAVICON_URL = "https://openwebui.com/favicon.png"
  21. shutil.copyfile("../build/favicon.png", "./static/favicon.png")
  22. ####################################
  23. # ENV (dev,test,prod)
  24. ####################################
  25. ENV = os.environ.get("ENV", "dev")
  26. try:
  27. with open(f"../package.json", "r") as f:
  28. PACKAGE_DATA = json.load(f)
  29. except:
  30. PACKAGE_DATA = {"version": "0.0.0"}
  31. VERSION = PACKAGE_DATA["version"]
  32. # Function to parse each section
  33. def parse_section(section):
  34. items = []
  35. for li in section.find_all("li"):
  36. # Extract raw HTML string
  37. raw_html = str(li)
  38. # Extract text without HTML tags
  39. text = li.get_text(separator=" ", strip=True)
  40. # Split into title and content
  41. parts = text.split(": ", 1)
  42. title = parts[0].strip() if len(parts) > 1 else ""
  43. content = parts[1].strip() if len(parts) > 1 else text
  44. items.append({"title": title, "content": content, "raw": raw_html})
  45. return items
  46. try:
  47. with open("../CHANGELOG.md", "r") as file:
  48. changelog_content = file.read()
  49. except:
  50. changelog_content = ""
  51. # Convert markdown content to HTML
  52. html_content = markdown.markdown(changelog_content)
  53. # Parse the HTML content
  54. soup = BeautifulSoup(html_content, "html.parser")
  55. # Initialize JSON structure
  56. changelog_json = {}
  57. # Iterate over each version
  58. for version in soup.find_all("h2"):
  59. version_number = version.get_text().strip().split(" - ")[0][1:-1] # Remove brackets
  60. date = version.get_text().strip().split(" - ")[1]
  61. version_data = {"date": date}
  62. # Find the next sibling that is a h3 tag (section title)
  63. current = version.find_next_sibling()
  64. while current and current.name != "h2":
  65. if current.name == "h3":
  66. section_title = current.get_text().lower() # e.g., "added", "fixed"
  67. section_items = parse_section(current.find_next_sibling("ul"))
  68. version_data[section_title] = section_items
  69. # Move to the next element
  70. current = current.find_next_sibling()
  71. changelog_json[version_number] = version_data
  72. CHANGELOG = changelog_json
  73. ####################################
  74. # CUSTOM_NAME
  75. ####################################
  76. CUSTOM_NAME = os.environ.get("CUSTOM_NAME", "")
  77. if CUSTOM_NAME:
  78. try:
  79. r = requests.get(f"https://api.openwebui.com/api/v1/custom/{CUSTOM_NAME}")
  80. data = r.json()
  81. if r.ok:
  82. if "logo" in data:
  83. WEBUI_FAVICON_URL = url = (
  84. f"https://api.openwebui.com{data['logo']}"
  85. if data["logo"][0] == "/"
  86. else data["logo"]
  87. )
  88. r = requests.get(url, stream=True)
  89. if r.status_code == 200:
  90. with open("./static/favicon.png", "wb") as f:
  91. r.raw.decode_content = True
  92. shutil.copyfileobj(r.raw, f)
  93. WEBUI_NAME = data["name"]
  94. except Exception as e:
  95. print(e)
  96. pass
  97. ####################################
  98. # DATA/FRONTEND BUILD DIR
  99. ####################################
  100. DATA_DIR = str(Path(os.getenv("DATA_DIR", "./data")).resolve())
  101. FRONTEND_BUILD_DIR = str(Path(os.getenv("FRONTEND_BUILD_DIR", "../build")))
  102. try:
  103. with open(f"{DATA_DIR}/config.json", "r") as f:
  104. CONFIG_DATA = json.load(f)
  105. except:
  106. CONFIG_DATA = {}
  107. ####################################
  108. # File Upload DIR
  109. ####################################
  110. UPLOAD_DIR = f"{DATA_DIR}/uploads"
  111. Path(UPLOAD_DIR).mkdir(parents=True, exist_ok=True)
  112. ####################################
  113. # Cache DIR
  114. ####################################
  115. CACHE_DIR = f"{DATA_DIR}/cache"
  116. Path(CACHE_DIR).mkdir(parents=True, exist_ok=True)
  117. ####################################
  118. # Docs DIR
  119. ####################################
  120. DOCS_DIR = f"{DATA_DIR}/docs"
  121. Path(DOCS_DIR).mkdir(parents=True, exist_ok=True)
  122. ####################################
  123. # LITELLM_CONFIG
  124. ####################################
  125. def create_config_file(file_path):
  126. directory = os.path.dirname(file_path)
  127. # Check if directory exists, if not, create it
  128. if not os.path.exists(directory):
  129. os.makedirs(directory)
  130. # Data to write into the YAML file
  131. config_data = {
  132. "general_settings": {},
  133. "litellm_settings": {},
  134. "model_list": [],
  135. "router_settings": {},
  136. }
  137. # Write data to YAML file
  138. with open(file_path, "w") as file:
  139. yaml.dump(config_data, file)
  140. LITELLM_CONFIG_PATH = f"{DATA_DIR}/litellm/config.yaml"
  141. if not os.path.exists(LITELLM_CONFIG_PATH):
  142. print("Config file doesn't exist. Creating...")
  143. create_config_file(LITELLM_CONFIG_PATH)
  144. print("Config file created successfully.")
  145. ####################################
  146. # OLLAMA_BASE_URL
  147. ####################################
  148. OLLAMA_API_BASE_URL = os.environ.get(
  149. "OLLAMA_API_BASE_URL", "http://localhost:11434/api"
  150. )
  151. OLLAMA_BASE_URL = os.environ.get("OLLAMA_BASE_URL", "")
  152. if OLLAMA_BASE_URL == "" and OLLAMA_API_BASE_URL != "":
  153. OLLAMA_BASE_URL = (
  154. OLLAMA_API_BASE_URL[:-4]
  155. if OLLAMA_API_BASE_URL.endswith("/api")
  156. else OLLAMA_API_BASE_URL
  157. )
  158. if ENV == "prod":
  159. if OLLAMA_BASE_URL == "/ollama":
  160. OLLAMA_BASE_URL = "http://host.docker.internal:11434"
  161. OLLAMA_BASE_URLS = os.environ.get("OLLAMA_BASE_URLS", "")
  162. OLLAMA_BASE_URLS = OLLAMA_BASE_URLS if OLLAMA_BASE_URLS != "" else OLLAMA_BASE_URL
  163. OLLAMA_BASE_URLS = [url.strip() for url in OLLAMA_BASE_URLS.split(";")]
  164. ####################################
  165. # OPENAI_API
  166. ####################################
  167. OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")
  168. OPENAI_API_BASE_URL = os.environ.get("OPENAI_API_BASE_URL", "")
  169. if OPENAI_API_BASE_URL == "":
  170. OPENAI_API_BASE_URL = "https://api.openai.com/v1"
  171. OPENAI_API_KEYS = os.environ.get("OPENAI_API_KEYS", "")
  172. OPENAI_API_KEYS = OPENAI_API_KEYS if OPENAI_API_KEYS != "" else OPENAI_API_KEY
  173. OPENAI_API_KEYS = [url.strip() for url in OPENAI_API_KEYS.split(";")]
  174. OPENAI_API_BASE_URLS = os.environ.get("OPENAI_API_BASE_URLS", "")
  175. OPENAI_API_BASE_URLS = (
  176. OPENAI_API_BASE_URLS if OPENAI_API_BASE_URLS != "" else OPENAI_API_BASE_URL
  177. )
  178. OPENAI_API_BASE_URLS = [
  179. url.strip() if url != "" else "https://api.openai.com/v1"
  180. for url in OPENAI_API_BASE_URLS.split(";")
  181. ]
  182. ####################################
  183. # WEBUI
  184. ####################################
  185. ENABLE_SIGNUP = os.environ.get("ENABLE_SIGNUP", "True").lower() == "true"
  186. DEFAULT_MODELS = os.environ.get("DEFAULT_MODELS", None)
  187. DEFAULT_PROMPT_SUGGESTIONS = (
  188. CONFIG_DATA["ui"]["prompt_suggestions"]
  189. if "ui" in CONFIG_DATA
  190. and "prompt_suggestions" in CONFIG_DATA["ui"]
  191. and type(CONFIG_DATA["ui"]["prompt_suggestions"]) is list
  192. else [
  193. {
  194. "title": ["Help me study", "vocabulary for a college entrance exam"],
  195. "content": "Help me study vocabulary: write a sentence for me to fill in the blank, and I'll try to pick the correct option.",
  196. },
  197. {
  198. "title": ["Give me ideas", "for what to do with my kids' art"],
  199. "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.",
  200. },
  201. {
  202. "title": ["Tell me a fun fact", "about the Roman Empire"],
  203. "content": "Tell me a random fun fact about the Roman Empire",
  204. },
  205. {
  206. "title": ["Show me a code snippet", "of a website's sticky header"],
  207. "content": "Show me a code snippet of a website's sticky header in CSS and JavaScript.",
  208. },
  209. ]
  210. )
  211. DEFAULT_USER_ROLE = os.getenv("DEFAULT_USER_ROLE", "pending")
  212. USER_PERMISSIONS_CHAT_DELETION = (
  213. os.environ.get("USER_PERMISSIONS_CHAT_DELETION", "True").lower() == "true"
  214. )
  215. USER_PERMISSIONS = {"chat": {"deletion": USER_PERMISSIONS_CHAT_DELETION}}
  216. MODEL_FILTER_ENABLED = os.environ.get("MODEL_FILTER_ENABLED", "False").lower() == "true"
  217. MODEL_FILTER_LIST = os.environ.get("MODEL_FILTER_LIST", "")
  218. MODEL_FILTER_LIST = [model.strip() for model in MODEL_FILTER_LIST.split(";")]
  219. WEBHOOK_URL = os.environ.get("WEBHOOK_URL", "")
  220. ####################################
  221. # WEBUI_VERSION
  222. ####################################
  223. WEBUI_VERSION = os.environ.get("WEBUI_VERSION", "v1.0.0-alpha.100")
  224. ####################################
  225. # WEBUI_AUTH (Required for security)
  226. ####################################
  227. WEBUI_AUTH = True
  228. ####################################
  229. # WEBUI_SECRET_KEY
  230. ####################################
  231. WEBUI_SECRET_KEY = os.environ.get(
  232. "WEBUI_SECRET_KEY",
  233. os.environ.get(
  234. "WEBUI_JWT_SECRET_KEY", "t0p-s3cr3t"
  235. ), # DEPRECATED: remove at next major version
  236. )
  237. if WEBUI_AUTH and WEBUI_SECRET_KEY == "":
  238. raise ValueError(ERROR_MESSAGES.ENV_VAR_NOT_FOUND)
  239. ####################################
  240. # RAG
  241. ####################################
  242. CHROMA_DATA_PATH = f"{DATA_DIR}/vector_db"
  243. # 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 (all-MiniLM-L6-v2)
  244. RAG_EMBEDDING_MODEL = os.environ.get("RAG_EMBEDDING_MODEL", "all-MiniLM-L6-v2")
  245. # device type ebbeding models - "cpu" (default), "cuda" (nvidia gpu required) or "mps" (apple silicon) - choosing this right can lead to better performance
  246. RAG_EMBEDDING_MODEL_DEVICE_TYPE = os.environ.get(
  247. "RAG_EMBEDDING_MODEL_DEVICE_TYPE", "cpu"
  248. )
  249. CHROMA_CLIENT = chromadb.PersistentClient(
  250. path=CHROMA_DATA_PATH,
  251. settings=Settings(allow_reset=True, anonymized_telemetry=False),
  252. )
  253. CHUNK_SIZE = 1500
  254. CHUNK_OVERLAP = 100
  255. RAG_TEMPLATE = """Use the following context as your learned knowledge, inside <context></context> XML tags.
  256. <context>
  257. [context]
  258. </context>
  259. When answer to user:
  260. - If you don't know, just say that you don't know.
  261. - If you don't know when you are not sure, ask for clarification.
  262. Avoid mentioning that you obtained the information from the context.
  263. And answer according to the language of the user's question.
  264. Given the context information, answer the query.
  265. Query: [query]"""
  266. ####################################
  267. # Transcribe
  268. ####################################
  269. WHISPER_MODEL = os.getenv("WHISPER_MODEL", "base")
  270. WHISPER_MODEL_DIR = os.getenv("WHISPER_MODEL_DIR", f"{CACHE_DIR}/whisper/models")
  271. ####################################
  272. # Images
  273. ####################################
  274. AUTOMATIC1111_BASE_URL = os.getenv("AUTOMATIC1111_BASE_URL", "")
  275. COMFYUI_BASE_URL = os.getenv("COMFYUI_BASE_URL", "")