config.py 10 KB

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