main.py 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892
  1. import asyncio
  2. import inspect
  3. import json
  4. import logging
  5. import mimetypes
  6. import os
  7. import shutil
  8. import sys
  9. import time
  10. import random
  11. from contextlib import asynccontextmanager
  12. from urllib.parse import urlencode, parse_qs, urlparse
  13. from pydantic import BaseModel
  14. from sqlalchemy import text
  15. from typing import Optional
  16. from aiocache import cached
  17. import aiohttp
  18. import requests
  19. from fastapi import (
  20. Depends,
  21. FastAPI,
  22. File,
  23. Form,
  24. HTTPException,
  25. Request,
  26. UploadFile,
  27. status,
  28. )
  29. from fastapi.middleware.cors import CORSMiddleware
  30. from fastapi.responses import JSONResponse, RedirectResponse
  31. from fastapi.staticfiles import StaticFiles
  32. from starlette.exceptions import HTTPException as StarletteHTTPException
  33. from starlette.middleware.base import BaseHTTPMiddleware
  34. from starlette.middleware.sessions import SessionMiddleware
  35. from starlette.responses import Response, StreamingResponse
  36. from open_webui.routers import (
  37. audio,
  38. chat,
  39. images,
  40. ollama,
  41. openai,
  42. retrieval,
  43. pipelines,
  44. tasks,
  45. auths,
  46. chats,
  47. folders,
  48. configs,
  49. groups,
  50. files,
  51. functions,
  52. memories,
  53. models,
  54. knowledge,
  55. prompts,
  56. evaluations,
  57. tools,
  58. users,
  59. utils,
  60. )
  61. from open_webui.retrieval.utils import get_sources_from_files
  62. from open_webui.socket.main import (
  63. app as socket_app,
  64. periodic_usage_pool_cleanup,
  65. get_event_call,
  66. get_event_emitter,
  67. )
  68. from open_webui.internal.db import Session
  69. from backend.open_webui.routers.webui import (
  70. app as webui_app,
  71. generate_function_chat_completion,
  72. get_all_models as get_open_webui_models,
  73. )
  74. from open_webui.models.functions import Functions
  75. from open_webui.models.models import Models
  76. from open_webui.models.users import UserModel, Users
  77. from backend.open_webui.utils.plugin import load_function_module_by_id
  78. from open_webui.constants import TASKS
  79. from open_webui.config import (
  80. # Ollama
  81. ENABLE_OLLAMA_API,
  82. OLLAMA_BASE_URLS,
  83. OLLAMA_API_CONFIGS,
  84. # OpenAI
  85. ENABLE_OPENAI_API,
  86. OPENAI_API_BASE_URLS,
  87. OPENAI_API_KEYS,
  88. OPENAI_API_CONFIGS,
  89. # Image
  90. AUTOMATIC1111_API_AUTH,
  91. AUTOMATIC1111_BASE_URL,
  92. AUTOMATIC1111_CFG_SCALE,
  93. AUTOMATIC1111_SAMPLER,
  94. AUTOMATIC1111_SCHEDULER,
  95. COMFYUI_BASE_URL,
  96. COMFYUI_WORKFLOW,
  97. COMFYUI_WORKFLOW_NODES,
  98. ENABLE_IMAGE_GENERATION,
  99. IMAGE_GENERATION_ENGINE,
  100. IMAGE_GENERATION_MODEL,
  101. IMAGE_SIZE,
  102. IMAGE_STEPS,
  103. IMAGES_OPENAI_API_BASE_URL,
  104. IMAGES_OPENAI_API_KEY,
  105. # Audio
  106. AUDIO_STT_ENGINE,
  107. AUDIO_STT_MODEL,
  108. AUDIO_STT_OPENAI_API_BASE_URL,
  109. AUDIO_STT_OPENAI_API_KEY,
  110. AUDIO_TTS_API_KEY,
  111. AUDIO_TTS_ENGINE,
  112. AUDIO_TTS_MODEL,
  113. AUDIO_TTS_OPENAI_API_BASE_URL,
  114. AUDIO_TTS_OPENAI_API_KEY,
  115. AUDIO_TTS_SPLIT_ON,
  116. AUDIO_TTS_VOICE,
  117. AUDIO_TTS_AZURE_SPEECH_REGION,
  118. AUDIO_TTS_AZURE_SPEECH_OUTPUT_FORMAT,
  119. WHISPER_MODEL,
  120. WHISPER_MODEL_AUTO_UPDATE,
  121. WHISPER_MODEL_DIR,
  122. # Retrieval
  123. RAG_TEMPLATE,
  124. DEFAULT_RAG_TEMPLATE,
  125. RAG_EMBEDDING_MODEL,
  126. RAG_EMBEDDING_MODEL_AUTO_UPDATE,
  127. RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
  128. RAG_RERANKING_MODEL,
  129. RAG_RERANKING_MODEL_AUTO_UPDATE,
  130. RAG_RERANKING_MODEL_TRUST_REMOTE_CODE,
  131. RAG_EMBEDDING_ENGINE,
  132. RAG_EMBEDDING_BATCH_SIZE,
  133. RAG_RELEVANCE_THRESHOLD,
  134. RAG_FILE_MAX_COUNT,
  135. RAG_FILE_MAX_SIZE,
  136. RAG_OPENAI_API_BASE_URL,
  137. RAG_OPENAI_API_KEY,
  138. RAG_OLLAMA_BASE_URL,
  139. RAG_OLLAMA_API_KEY,
  140. CHUNK_OVERLAP,
  141. CHUNK_SIZE,
  142. CONTENT_EXTRACTION_ENGINE,
  143. TIKA_SERVER_URL,
  144. RAG_TOP_K,
  145. RAG_TEXT_SPLITTER,
  146. TIKTOKEN_ENCODING_NAME,
  147. PDF_EXTRACT_IMAGES,
  148. YOUTUBE_LOADER_LANGUAGE,
  149. YOUTUBE_LOADER_PROXY_URL,
  150. # Retrieval (Web Search)
  151. RAG_WEB_SEARCH_ENGINE,
  152. RAG_WEB_SEARCH_RESULT_COUNT,
  153. RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
  154. RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
  155. JINA_API_KEY,
  156. SEARCHAPI_API_KEY,
  157. SEARCHAPI_ENGINE,
  158. SEARXNG_QUERY_URL,
  159. SERPER_API_KEY,
  160. SERPLY_API_KEY,
  161. SERPSTACK_API_KEY,
  162. SERPSTACK_HTTPS,
  163. TAVILY_API_KEY,
  164. BING_SEARCH_V7_ENDPOINT,
  165. BING_SEARCH_V7_SUBSCRIPTION_KEY,
  166. BRAVE_SEARCH_API_KEY,
  167. KAGI_SEARCH_API_KEY,
  168. MOJEEK_SEARCH_API_KEY,
  169. GOOGLE_PSE_API_KEY,
  170. GOOGLE_PSE_ENGINE_ID,
  171. ENABLE_RAG_HYBRID_SEARCH,
  172. ENABLE_RAG_LOCAL_WEB_FETCH,
  173. ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
  174. ENABLE_RAG_WEB_SEARCH,
  175. UPLOAD_DIR,
  176. # WebUI
  177. WEBUI_AUTH,
  178. WEBUI_NAME,
  179. WEBUI_BANNERS,
  180. WEBHOOK_URL,
  181. ADMIN_EMAIL,
  182. SHOW_ADMIN_DETAILS,
  183. JWT_EXPIRES_IN,
  184. ENABLE_SIGNUP,
  185. ENABLE_LOGIN_FORM,
  186. ENABLE_API_KEY,
  187. ENABLE_COMMUNITY_SHARING,
  188. ENABLE_MESSAGE_RATING,
  189. ENABLE_EVALUATION_ARENA_MODELS,
  190. USER_PERMISSIONS,
  191. DEFAULT_USER_ROLE,
  192. DEFAULT_PROMPT_SUGGESTIONS,
  193. DEFAULT_MODELS,
  194. DEFAULT_ARENA_MODEL,
  195. MODEL_ORDER_LIST,
  196. EVALUATION_ARENA_MODELS,
  197. # WebUI (OAuth)
  198. ENABLE_OAUTH_ROLE_MANAGEMENT,
  199. OAUTH_ROLES_CLAIM,
  200. OAUTH_EMAIL_CLAIM,
  201. OAUTH_PICTURE_CLAIM,
  202. OAUTH_USERNAME_CLAIM,
  203. OAUTH_ALLOWED_ROLES,
  204. OAUTH_ADMIN_ROLES,
  205. # WebUI (LDAP)
  206. ENABLE_LDAP,
  207. LDAP_SERVER_LABEL,
  208. LDAP_SERVER_HOST,
  209. LDAP_SERVER_PORT,
  210. LDAP_ATTRIBUTE_FOR_USERNAME,
  211. LDAP_SEARCH_FILTERS,
  212. LDAP_SEARCH_BASE,
  213. LDAP_APP_DN,
  214. LDAP_APP_PASSWORD,
  215. LDAP_USE_TLS,
  216. LDAP_CA_CERT_FILE,
  217. LDAP_CIPHERS,
  218. # Misc
  219. ENV,
  220. CACHE_DIR,
  221. STATIC_DIR,
  222. FRONTEND_BUILD_DIR,
  223. CORS_ALLOW_ORIGIN,
  224. DEFAULT_LOCALE,
  225. OAUTH_PROVIDERS,
  226. # Admin
  227. ENABLE_ADMIN_CHAT_ACCESS,
  228. ENABLE_ADMIN_EXPORT,
  229. # Tasks
  230. TASK_MODEL,
  231. TASK_MODEL_EXTERNAL,
  232. ENABLE_TAGS_GENERATION,
  233. ENABLE_SEARCH_QUERY_GENERATION,
  234. ENABLE_RETRIEVAL_QUERY_GENERATION,
  235. ENABLE_AUTOCOMPLETE_GENERATION,
  236. TITLE_GENERATION_PROMPT_TEMPLATE,
  237. TAGS_GENERATION_PROMPT_TEMPLATE,
  238. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  239. QUERY_GENERATION_PROMPT_TEMPLATE,
  240. AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE,
  241. AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH,
  242. AppConfig,
  243. reset_config,
  244. )
  245. from open_webui.env import (
  246. CHANGELOG,
  247. GLOBAL_LOG_LEVEL,
  248. SAFE_MODE,
  249. SRC_LOG_LEVELS,
  250. VERSION,
  251. WEBUI_URL,
  252. WEBUI_BUILD_HASH,
  253. WEBUI_SECRET_KEY,
  254. WEBUI_SESSION_COOKIE_SAME_SITE,
  255. WEBUI_SESSION_COOKIE_SECURE,
  256. WEBUI_AUTH_TRUSTED_EMAIL_HEADER,
  257. WEBUI_AUTH_TRUSTED_NAME_HEADER,
  258. BYPASS_MODEL_ACCESS_CONTROL,
  259. RESET_CONFIG_ON_START,
  260. OFFLINE_MODE,
  261. )
  262. from open_webui.utils.misc import (
  263. add_or_update_system_message,
  264. get_last_user_message,
  265. prepend_to_first_user_message_content,
  266. )
  267. from open_webui.utils.payload import convert_payload_openai_to_ollama
  268. from open_webui.utils.response import (
  269. convert_response_ollama_to_openai,
  270. convert_streaming_response_ollama_to_openai,
  271. )
  272. from open_webui.utils.task import (
  273. rag_template,
  274. tools_function_calling_generation_template,
  275. )
  276. from open_webui.utils.tools import get_tools
  277. from open_webui.utils.access_control import has_access
  278. from open_webui.utils.auth import (
  279. decode_token,
  280. get_admin_user,
  281. get_current_user,
  282. get_http_authorization_cred,
  283. get_verified_user,
  284. )
  285. from open_webui.utils.oauth import oauth_manager
  286. from open_webui.utils.security_headers import SecurityHeadersMiddleware
  287. if SAFE_MODE:
  288. print("SAFE MODE ENABLED")
  289. Functions.deactivate_all_functions()
  290. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  291. log = logging.getLogger(__name__)
  292. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  293. class SPAStaticFiles(StaticFiles):
  294. async def get_response(self, path: str, scope):
  295. try:
  296. return await super().get_response(path, scope)
  297. except (HTTPException, StarletteHTTPException) as ex:
  298. if ex.status_code == 404:
  299. return await super().get_response("index.html", scope)
  300. else:
  301. raise ex
  302. print(
  303. rf"""
  304. ___ __ __ _ _ _ ___
  305. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  306. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  307. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  308. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  309. |_|
  310. v{VERSION} - building the best open-source AI user interface.
  311. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  312. https://github.com/open-webui/open-webui
  313. """
  314. )
  315. @asynccontextmanager
  316. async def lifespan(app: FastAPI):
  317. if RESET_CONFIG_ON_START:
  318. reset_config()
  319. asyncio.create_task(periodic_usage_pool_cleanup())
  320. yield
  321. app = FastAPI(
  322. docs_url="/docs" if ENV == "dev" else None,
  323. openapi_url="/openapi.json" if ENV == "dev" else None,
  324. redoc_url=None,
  325. lifespan=lifespan,
  326. )
  327. app.state.config = AppConfig()
  328. ########################################
  329. #
  330. # OLLAMA
  331. #
  332. ########################################
  333. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  334. app.state.config.OLLAMA_BASE_URLS = OLLAMA_BASE_URLS
  335. app.state.config.OLLAMA_API_CONFIGS = OLLAMA_API_CONFIGS
  336. app.state.OLLAMA_MODELS = {}
  337. ########################################
  338. #
  339. # OPENAI
  340. #
  341. ########################################
  342. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  343. app.state.config.OPENAI_API_BASE_URLS = OPENAI_API_BASE_URLS
  344. app.state.config.OPENAI_API_KEYS = OPENAI_API_KEYS
  345. app.state.config.OPENAI_API_CONFIGS = OPENAI_API_CONFIGS
  346. app.state.OPENAI_MODELS = {}
  347. ########################################
  348. #
  349. # WEBUI
  350. #
  351. ########################################
  352. app.state.config.ENABLE_SIGNUP = ENABLE_SIGNUP
  353. app.state.config.ENABLE_LOGIN_FORM = ENABLE_LOGIN_FORM
  354. app.state.config.ENABLE_API_KEY = ENABLE_API_KEY
  355. app.state.config.JWT_EXPIRES_IN = JWT_EXPIRES_IN
  356. app.state.config.SHOW_ADMIN_DETAILS = SHOW_ADMIN_DETAILS
  357. app.state.config.ADMIN_EMAIL = ADMIN_EMAIL
  358. app.state.config.DEFAULT_MODELS = DEFAULT_MODELS
  359. app.state.config.DEFAULT_PROMPT_SUGGESTIONS = DEFAULT_PROMPT_SUGGESTIONS
  360. app.state.config.DEFAULT_USER_ROLE = DEFAULT_USER_ROLE
  361. app.state.config.USER_PERMISSIONS = USER_PERMISSIONS
  362. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  363. app.state.config.BANNERS = WEBUI_BANNERS
  364. app.state.config.MODEL_ORDER_LIST = MODEL_ORDER_LIST
  365. app.state.config.ENABLE_COMMUNITY_SHARING = ENABLE_COMMUNITY_SHARING
  366. app.state.config.ENABLE_MESSAGE_RATING = ENABLE_MESSAGE_RATING
  367. app.state.config.ENABLE_EVALUATION_ARENA_MODELS = ENABLE_EVALUATION_ARENA_MODELS
  368. app.state.config.EVALUATION_ARENA_MODELS = EVALUATION_ARENA_MODELS
  369. app.state.config.OAUTH_USERNAME_CLAIM = OAUTH_USERNAME_CLAIM
  370. app.state.config.OAUTH_PICTURE_CLAIM = OAUTH_PICTURE_CLAIM
  371. app.state.config.OAUTH_EMAIL_CLAIM = OAUTH_EMAIL_CLAIM
  372. app.state.config.ENABLE_OAUTH_ROLE_MANAGEMENT = ENABLE_OAUTH_ROLE_MANAGEMENT
  373. app.state.config.OAUTH_ROLES_CLAIM = OAUTH_ROLES_CLAIM
  374. app.state.config.OAUTH_ALLOWED_ROLES = OAUTH_ALLOWED_ROLES
  375. app.state.config.OAUTH_ADMIN_ROLES = OAUTH_ADMIN_ROLES
  376. app.state.config.ENABLE_LDAP = ENABLE_LDAP
  377. app.state.config.LDAP_SERVER_LABEL = LDAP_SERVER_LABEL
  378. app.state.config.LDAP_SERVER_HOST = LDAP_SERVER_HOST
  379. app.state.config.LDAP_SERVER_PORT = LDAP_SERVER_PORT
  380. app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME = LDAP_ATTRIBUTE_FOR_USERNAME
  381. app.state.config.LDAP_APP_DN = LDAP_APP_DN
  382. app.state.config.LDAP_APP_PASSWORD = LDAP_APP_PASSWORD
  383. app.state.config.LDAP_SEARCH_BASE = LDAP_SEARCH_BASE
  384. app.state.config.LDAP_SEARCH_FILTERS = LDAP_SEARCH_FILTERS
  385. app.state.config.LDAP_USE_TLS = LDAP_USE_TLS
  386. app.state.config.LDAP_CA_CERT_FILE = LDAP_CA_CERT_FILE
  387. app.state.config.LDAP_CIPHERS = LDAP_CIPHERS
  388. app.state.AUTH_TRUSTED_EMAIL_HEADER = WEBUI_AUTH_TRUSTED_EMAIL_HEADER
  389. app.state.AUTH_TRUSTED_NAME_HEADER = WEBUI_AUTH_TRUSTED_NAME_HEADER
  390. app.state.TOOLS = {}
  391. app.state.FUNCTIONS = {}
  392. ########################################
  393. #
  394. # RETRIEVAL
  395. #
  396. ########################################
  397. app.state.config.TOP_K = RAG_TOP_K
  398. app.state.config.RELEVANCE_THRESHOLD = RAG_RELEVANCE_THRESHOLD
  399. app.state.config.FILE_MAX_SIZE = RAG_FILE_MAX_SIZE
  400. app.state.config.FILE_MAX_COUNT = RAG_FILE_MAX_COUNT
  401. app.state.config.ENABLE_RAG_HYBRID_SEARCH = ENABLE_RAG_HYBRID_SEARCH
  402. app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION = (
  403. ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION
  404. )
  405. app.state.config.CONTENT_EXTRACTION_ENGINE = CONTENT_EXTRACTION_ENGINE
  406. app.state.config.TIKA_SERVER_URL = TIKA_SERVER_URL
  407. app.state.config.TEXT_SPLITTER = RAG_TEXT_SPLITTER
  408. app.state.config.TIKTOKEN_ENCODING_NAME = TIKTOKEN_ENCODING_NAME
  409. app.state.config.CHUNK_SIZE = CHUNK_SIZE
  410. app.state.config.CHUNK_OVERLAP = CHUNK_OVERLAP
  411. app.state.config.RAG_EMBEDDING_ENGINE = RAG_EMBEDDING_ENGINE
  412. app.state.config.RAG_EMBEDDING_MODEL = RAG_EMBEDDING_MODEL
  413. app.state.config.RAG_EMBEDDING_BATCH_SIZE = RAG_EMBEDDING_BATCH_SIZE
  414. app.state.config.RAG_RERANKING_MODEL = RAG_RERANKING_MODEL
  415. app.state.config.RAG_TEMPLATE = RAG_TEMPLATE
  416. app.state.config.RAG_OPENAI_API_BASE_URL = RAG_OPENAI_API_BASE_URL
  417. app.state.config.RAG_OPENAI_API_KEY = RAG_OPENAI_API_KEY
  418. app.state.config.RAG_OLLAMA_BASE_URL = RAG_OLLAMA_BASE_URL
  419. app.state.config.RAG_OLLAMA_API_KEY = RAG_OLLAMA_API_KEY
  420. app.state.config.PDF_EXTRACT_IMAGES = PDF_EXTRACT_IMAGES
  421. app.state.config.YOUTUBE_LOADER_LANGUAGE = YOUTUBE_LOADER_LANGUAGE
  422. app.state.config.YOUTUBE_LOADER_PROXY_URL = YOUTUBE_LOADER_PROXY_URL
  423. app.state.config.ENABLE_RAG_WEB_SEARCH = ENABLE_RAG_WEB_SEARCH
  424. app.state.config.RAG_WEB_SEARCH_ENGINE = RAG_WEB_SEARCH_ENGINE
  425. app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST = RAG_WEB_SEARCH_DOMAIN_FILTER_LIST
  426. app.state.config.SEARXNG_QUERY_URL = SEARXNG_QUERY_URL
  427. app.state.config.GOOGLE_PSE_API_KEY = GOOGLE_PSE_API_KEY
  428. app.state.config.GOOGLE_PSE_ENGINE_ID = GOOGLE_PSE_ENGINE_ID
  429. app.state.config.BRAVE_SEARCH_API_KEY = BRAVE_SEARCH_API_KEY
  430. app.state.config.KAGI_SEARCH_API_KEY = KAGI_SEARCH_API_KEY
  431. app.state.config.MOJEEK_SEARCH_API_KEY = MOJEEK_SEARCH_API_KEY
  432. app.state.config.SERPSTACK_API_KEY = SERPSTACK_API_KEY
  433. app.state.config.SERPSTACK_HTTPS = SERPSTACK_HTTPS
  434. app.state.config.SERPER_API_KEY = SERPER_API_KEY
  435. app.state.config.SERPLY_API_KEY = SERPLY_API_KEY
  436. app.state.config.TAVILY_API_KEY = TAVILY_API_KEY
  437. app.state.config.SEARCHAPI_API_KEY = SEARCHAPI_API_KEY
  438. app.state.config.SEARCHAPI_ENGINE = SEARCHAPI_ENGINE
  439. app.state.config.JINA_API_KEY = JINA_API_KEY
  440. app.state.config.BING_SEARCH_V7_ENDPOINT = BING_SEARCH_V7_ENDPOINT
  441. app.state.config.BING_SEARCH_V7_SUBSCRIPTION_KEY = BING_SEARCH_V7_SUBSCRIPTION_KEY
  442. app.state.config.RAG_WEB_SEARCH_RESULT_COUNT = RAG_WEB_SEARCH_RESULT_COUNT
  443. app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS = RAG_WEB_SEARCH_CONCURRENT_REQUESTS
  444. app.state.YOUTUBE_LOADER_TRANSLATION = None
  445. app.state.EMBEDDING_FUNCTION = None
  446. ########################################
  447. #
  448. # IMAGES
  449. #
  450. ########################################
  451. app.state.config.IMAGE_GENERATION_ENGINE = IMAGE_GENERATION_ENGINE
  452. app.state.config.ENABLE_IMAGE_GENERATION = ENABLE_IMAGE_GENERATION
  453. app.state.config.IMAGES_OPENAI_API_BASE_URL = IMAGES_OPENAI_API_BASE_URL
  454. app.state.config.IMAGES_OPENAI_API_KEY = IMAGES_OPENAI_API_KEY
  455. app.state.config.IMAGE_GENERATION_MODEL = IMAGE_GENERATION_MODEL
  456. app.state.config.AUTOMATIC1111_BASE_URL = AUTOMATIC1111_BASE_URL
  457. app.state.config.AUTOMATIC1111_API_AUTH = AUTOMATIC1111_API_AUTH
  458. app.state.config.AUTOMATIC1111_CFG_SCALE = AUTOMATIC1111_CFG_SCALE
  459. app.state.config.AUTOMATIC1111_SAMPLER = AUTOMATIC1111_SAMPLER
  460. app.state.config.AUTOMATIC1111_SCHEDULER = AUTOMATIC1111_SCHEDULER
  461. app.state.config.COMFYUI_BASE_URL = COMFYUI_BASE_URL
  462. app.state.config.COMFYUI_WORKFLOW = COMFYUI_WORKFLOW
  463. app.state.config.COMFYUI_WORKFLOW_NODES = COMFYUI_WORKFLOW_NODES
  464. app.state.config.IMAGE_SIZE = IMAGE_SIZE
  465. app.state.config.IMAGE_STEPS = IMAGE_STEPS
  466. ########################################
  467. #
  468. # AUDIO
  469. #
  470. ########################################
  471. app.state.config.STT_OPENAI_API_BASE_URL = AUDIO_STT_OPENAI_API_BASE_URL
  472. app.state.config.STT_OPENAI_API_KEY = AUDIO_STT_OPENAI_API_KEY
  473. app.state.config.STT_ENGINE = AUDIO_STT_ENGINE
  474. app.state.config.STT_MODEL = AUDIO_STT_MODEL
  475. app.state.config.WHISPER_MODEL = WHISPER_MODEL
  476. app.state.config.TTS_OPENAI_API_BASE_URL = AUDIO_TTS_OPENAI_API_BASE_URL
  477. app.state.config.TTS_OPENAI_API_KEY = AUDIO_TTS_OPENAI_API_KEY
  478. app.state.config.TTS_ENGINE = AUDIO_TTS_ENGINE
  479. app.state.config.TTS_MODEL = AUDIO_TTS_MODEL
  480. app.state.config.TTS_VOICE = AUDIO_TTS_VOICE
  481. app.state.config.TTS_API_KEY = AUDIO_TTS_API_KEY
  482. app.state.config.TTS_SPLIT_ON = AUDIO_TTS_SPLIT_ON
  483. app.state.config.TTS_AZURE_SPEECH_REGION = AUDIO_TTS_AZURE_SPEECH_REGION
  484. app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT = AUDIO_TTS_AZURE_SPEECH_OUTPUT_FORMAT
  485. app.state.faster_whisper_model = None
  486. app.state.speech_synthesiser = None
  487. app.state.speech_speaker_embeddings_dataset = None
  488. ########################################
  489. #
  490. # TASKS
  491. #
  492. ########################################
  493. app.state.config.TASK_MODEL = TASK_MODEL
  494. app.state.config.TASK_MODEL_EXTERNAL = TASK_MODEL_EXTERNAL
  495. app.state.config.ENABLE_SEARCH_QUERY_GENERATION = ENABLE_SEARCH_QUERY_GENERATION
  496. app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION = ENABLE_RETRIEVAL_QUERY_GENERATION
  497. app.state.config.ENABLE_AUTOCOMPLETE_GENERATION = ENABLE_AUTOCOMPLETE_GENERATION
  498. app.state.config.ENABLE_TAGS_GENERATION = ENABLE_TAGS_GENERATION
  499. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = TITLE_GENERATION_PROMPT_TEMPLATE
  500. app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE = TAGS_GENERATION_PROMPT_TEMPLATE
  501. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  502. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  503. )
  504. app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE = QUERY_GENERATION_PROMPT_TEMPLATE
  505. app.state.config.AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE = (
  506. AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE
  507. )
  508. app.state.config.AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH = (
  509. AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH
  510. )
  511. ########################################
  512. #
  513. # WEBUI
  514. #
  515. ########################################
  516. app.state.MODELS = {}
  517. ##################################
  518. #
  519. # ChatCompletion Middleware
  520. #
  521. ##################################
  522. def get_filter_function_ids(model):
  523. def get_priority(function_id):
  524. function = Functions.get_function_by_id(function_id)
  525. if function is not None and hasattr(function, "valves"):
  526. # TODO: Fix FunctionModel
  527. return (function.valves if function.valves else {}).get("priority", 0)
  528. return 0
  529. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  530. if "info" in model and "meta" in model["info"]:
  531. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  532. filter_ids = list(set(filter_ids))
  533. enabled_filter_ids = [
  534. function.id
  535. for function in Functions.get_functions_by_type("filter", active_only=True)
  536. ]
  537. filter_ids = [
  538. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  539. ]
  540. filter_ids.sort(key=get_priority)
  541. return filter_ids
  542. async def chat_completion_filter_functions_handler(body, model, extra_params):
  543. skip_files = None
  544. filter_ids = get_filter_function_ids(model)
  545. for filter_id in filter_ids:
  546. filter = Functions.get_function_by_id(filter_id)
  547. if not filter:
  548. continue
  549. if filter_id in webui_app.state.FUNCTIONS:
  550. function_module = webui_app.state.FUNCTIONS[filter_id]
  551. else:
  552. function_module, _, _ = load_function_module_by_id(filter_id)
  553. webui_app.state.FUNCTIONS[filter_id] = function_module
  554. # Check if the function has a file_handler variable
  555. if hasattr(function_module, "file_handler"):
  556. skip_files = function_module.file_handler
  557. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  558. valves = Functions.get_function_valves_by_id(filter_id)
  559. function_module.valves = function_module.Valves(
  560. **(valves if valves else {})
  561. )
  562. if not hasattr(function_module, "inlet"):
  563. continue
  564. try:
  565. inlet = function_module.inlet
  566. # Get the signature of the function
  567. sig = inspect.signature(inlet)
  568. params = {"body": body} | {
  569. k: v
  570. for k, v in {
  571. **extra_params,
  572. "__model__": model,
  573. "__id__": filter_id,
  574. }.items()
  575. if k in sig.parameters
  576. }
  577. if "__user__" in params and hasattr(function_module, "UserValves"):
  578. try:
  579. params["__user__"]["valves"] = function_module.UserValves(
  580. **Functions.get_user_valves_by_id_and_user_id(
  581. filter_id, params["__user__"]["id"]
  582. )
  583. )
  584. except Exception as e:
  585. print(e)
  586. if inspect.iscoroutinefunction(inlet):
  587. body = await inlet(**params)
  588. else:
  589. body = inlet(**params)
  590. except Exception as e:
  591. print(f"Error: {e}")
  592. raise e
  593. if skip_files and "files" in body.get("metadata", {}):
  594. del body["metadata"]["files"]
  595. return body, {}
  596. def get_tools_function_calling_payload(messages, task_model_id, content):
  597. user_message = get_last_user_message(messages)
  598. history = "\n".join(
  599. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  600. for message in messages[::-1][:4]
  601. )
  602. prompt = f"History:\n{history}\nQuery: {user_message}"
  603. return {
  604. "model": task_model_id,
  605. "messages": [
  606. {"role": "system", "content": content},
  607. {"role": "user", "content": f"Query: {prompt}"},
  608. ],
  609. "stream": False,
  610. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  611. }
  612. async def get_content_from_response(response) -> Optional[str]:
  613. content = None
  614. if hasattr(response, "body_iterator"):
  615. async for chunk in response.body_iterator:
  616. data = json.loads(chunk.decode("utf-8"))
  617. content = data["choices"][0]["message"]["content"]
  618. # Cleanup any remaining background tasks if necessary
  619. if response.background is not None:
  620. await response.background()
  621. else:
  622. content = response["choices"][0]["message"]["content"]
  623. return content
  624. def get_task_model_id(
  625. default_model_id: str, task_model: str, task_model_external: str, models
  626. ) -> str:
  627. # Set the task model
  628. task_model_id = default_model_id
  629. # Check if the user has a custom task model and use that model
  630. if models[task_model_id]["owned_by"] == "ollama":
  631. if task_model and task_model in models:
  632. task_model_id = task_model
  633. else:
  634. if task_model_external and task_model_external in models:
  635. task_model_id = task_model_external
  636. return task_model_id
  637. async def chat_completion_tools_handler(
  638. body: dict, user: UserModel, models, extra_params: dict
  639. ) -> tuple[dict, dict]:
  640. # If tool_ids field is present, call the functions
  641. metadata = body.get("metadata", {})
  642. tool_ids = metadata.get("tool_ids", None)
  643. log.debug(f"{tool_ids=}")
  644. if not tool_ids:
  645. return body, {}
  646. skip_files = False
  647. sources = []
  648. task_model_id = get_task_model_id(
  649. body["model"],
  650. app.state.config.TASK_MODEL,
  651. app.state.config.TASK_MODEL_EXTERNAL,
  652. models,
  653. )
  654. tools = get_tools(
  655. webui_app,
  656. tool_ids,
  657. user,
  658. {
  659. **extra_params,
  660. "__model__": models[task_model_id],
  661. "__messages__": body["messages"],
  662. "__files__": metadata.get("files", []),
  663. },
  664. )
  665. log.info(f"{tools=}")
  666. specs = [tool["spec"] for tool in tools.values()]
  667. tools_specs = json.dumps(specs)
  668. if app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE != "":
  669. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  670. else:
  671. template = """Available Tools: {{TOOLS}}\nReturn an empty string if no tools match the query. If a function tool matches, construct and return a JSON object in the format {\"name\": \"functionName\", \"parameters\": {\"requiredFunctionParamKey\": \"requiredFunctionParamValue\"}} using the appropriate tool and its parameters. Only return the object and limit the response to the JSON object without additional text."""
  672. tools_function_calling_prompt = tools_function_calling_generation_template(
  673. template, tools_specs
  674. )
  675. log.info(f"{tools_function_calling_prompt=}")
  676. payload = get_tools_function_calling_payload(
  677. body["messages"], task_model_id, tools_function_calling_prompt
  678. )
  679. try:
  680. payload = filter_pipeline(payload, user, models)
  681. except Exception as e:
  682. raise e
  683. try:
  684. response = await generate_chat_completions(form_data=payload, user=user)
  685. log.debug(f"{response=}")
  686. content = await get_content_from_response(response)
  687. log.debug(f"{content=}")
  688. if not content:
  689. return body, {}
  690. try:
  691. content = content[content.find("{") : content.rfind("}") + 1]
  692. if not content:
  693. raise Exception("No JSON object found in the response")
  694. result = json.loads(content)
  695. tool_function_name = result.get("name", None)
  696. if tool_function_name not in tools:
  697. return body, {}
  698. tool_function_params = result.get("parameters", {})
  699. try:
  700. required_params = (
  701. tools[tool_function_name]
  702. .get("spec", {})
  703. .get("parameters", {})
  704. .get("required", [])
  705. )
  706. tool_function = tools[tool_function_name]["callable"]
  707. tool_function_params = {
  708. k: v
  709. for k, v in tool_function_params.items()
  710. if k in required_params
  711. }
  712. tool_output = await tool_function(**tool_function_params)
  713. except Exception as e:
  714. tool_output = str(e)
  715. if isinstance(tool_output, str):
  716. if tools[tool_function_name]["citation"]:
  717. sources.append(
  718. {
  719. "source": {
  720. "name": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  721. },
  722. "document": [tool_output],
  723. "metadata": [
  724. {
  725. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  726. }
  727. ],
  728. }
  729. )
  730. else:
  731. sources.append(
  732. {
  733. "source": {},
  734. "document": [tool_output],
  735. "metadata": [
  736. {
  737. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  738. }
  739. ],
  740. }
  741. )
  742. if tools[tool_function_name]["file_handler"]:
  743. skip_files = True
  744. except Exception as e:
  745. log.exception(f"Error: {e}")
  746. content = None
  747. except Exception as e:
  748. log.exception(f"Error: {e}")
  749. content = None
  750. log.debug(f"tool_contexts: {sources}")
  751. if skip_files and "files" in body.get("metadata", {}):
  752. del body["metadata"]["files"]
  753. return body, {"sources": sources}
  754. async def chat_completion_files_handler(
  755. body: dict, user: UserModel
  756. ) -> tuple[dict, dict[str, list]]:
  757. sources = []
  758. if files := body.get("metadata", {}).get("files", None):
  759. try:
  760. queries_response = await generate_queries(
  761. {
  762. "model": body["model"],
  763. "messages": body["messages"],
  764. "type": "retrieval",
  765. },
  766. user,
  767. )
  768. queries_response = queries_response["choices"][0]["message"]["content"]
  769. try:
  770. bracket_start = queries_response.find("{")
  771. bracket_end = queries_response.rfind("}") + 1
  772. if bracket_start == -1 or bracket_end == -1:
  773. raise Exception("No JSON object found in the response")
  774. queries_response = queries_response[bracket_start:bracket_end]
  775. queries_response = json.loads(queries_response)
  776. except Exception as e:
  777. queries_response = {"queries": [queries_response]}
  778. queries = queries_response.get("queries", [])
  779. except Exception as e:
  780. queries = []
  781. if len(queries) == 0:
  782. queries = [get_last_user_message(body["messages"])]
  783. sources = get_sources_from_files(
  784. files=files,
  785. queries=queries,
  786. embedding_function=retrieval_app.state.EMBEDDING_FUNCTION,
  787. k=retrieval_app.state.config.TOP_K,
  788. reranking_function=retrieval_app.state.sentence_transformer_rf,
  789. r=retrieval_app.state.config.RELEVANCE_THRESHOLD,
  790. hybrid_search=retrieval_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  791. )
  792. log.debug(f"rag_contexts:sources: {sources}")
  793. return body, {"sources": sources}
  794. async def get_body_and_model_and_user(request, models):
  795. # Read the original request body
  796. body = await request.body()
  797. body_str = body.decode("utf-8")
  798. body = json.loads(body_str) if body_str else {}
  799. model_id = body["model"]
  800. if model_id not in models:
  801. raise Exception("Model not found")
  802. model = models[model_id]
  803. user = get_current_user(
  804. request,
  805. get_http_authorization_cred(request.headers.get("Authorization")),
  806. )
  807. return body, model, user
  808. class ChatCompletionMiddleware(BaseHTTPMiddleware):
  809. async def dispatch(self, request: Request, call_next):
  810. if not request.method == "POST" and any(
  811. endpoint in request.url.path
  812. for endpoint in ["/ollama/api/chat", "/chat/completions"]
  813. ):
  814. return await call_next(request)
  815. log.debug(f"request.url.path: {request.url.path}")
  816. model_list = await get_all_models()
  817. models = {model["id"]: model for model in model_list}
  818. try:
  819. body, model, user = await get_body_and_model_and_user(request, models)
  820. except Exception as e:
  821. return JSONResponse(
  822. status_code=status.HTTP_400_BAD_REQUEST,
  823. content={"detail": str(e)},
  824. )
  825. model_info = Models.get_model_by_id(model["id"])
  826. if user.role == "user" and not BYPASS_MODEL_ACCESS_CONTROL:
  827. if model.get("arena"):
  828. if not has_access(
  829. user.id,
  830. type="read",
  831. access_control=model.get("info", {})
  832. .get("meta", {})
  833. .get("access_control", {}),
  834. ):
  835. raise HTTPException(
  836. status_code=403,
  837. detail="Model not found",
  838. )
  839. else:
  840. if not model_info:
  841. return JSONResponse(
  842. status_code=status.HTTP_404_NOT_FOUND,
  843. content={"detail": "Model not found"},
  844. )
  845. elif not (
  846. user.id == model_info.user_id
  847. or has_access(
  848. user.id, type="read", access_control=model_info.access_control
  849. )
  850. ):
  851. return JSONResponse(
  852. status_code=status.HTTP_403_FORBIDDEN,
  853. content={"detail": "User does not have access to the model"},
  854. )
  855. metadata = {
  856. "chat_id": body.pop("chat_id", None),
  857. "message_id": body.pop("id", None),
  858. "session_id": body.pop("session_id", None),
  859. "tool_ids": body.get("tool_ids", None),
  860. "files": body.get("files", None),
  861. }
  862. body["metadata"] = metadata
  863. extra_params = {
  864. "__event_emitter__": get_event_emitter(metadata),
  865. "__event_call__": get_event_call(metadata),
  866. "__user__": {
  867. "id": user.id,
  868. "email": user.email,
  869. "name": user.name,
  870. "role": user.role,
  871. },
  872. "__metadata__": metadata,
  873. }
  874. # Initialize data_items to store additional data to be sent to the client
  875. # Initialize contexts and citation
  876. data_items = []
  877. sources = []
  878. try:
  879. body, flags = await chat_completion_filter_functions_handler(
  880. body, model, extra_params
  881. )
  882. except Exception as e:
  883. return JSONResponse(
  884. status_code=status.HTTP_400_BAD_REQUEST,
  885. content={"detail": str(e)},
  886. )
  887. tool_ids = body.pop("tool_ids", None)
  888. files = body.pop("files", None)
  889. metadata = {
  890. **metadata,
  891. "tool_ids": tool_ids,
  892. "files": files,
  893. }
  894. body["metadata"] = metadata
  895. try:
  896. body, flags = await chat_completion_tools_handler(
  897. body, user, models, extra_params
  898. )
  899. sources.extend(flags.get("sources", []))
  900. except Exception as e:
  901. log.exception(e)
  902. try:
  903. body, flags = await chat_completion_files_handler(body, user)
  904. sources.extend(flags.get("sources", []))
  905. except Exception as e:
  906. log.exception(e)
  907. # If context is not empty, insert it into the messages
  908. if len(sources) > 0:
  909. context_string = ""
  910. for source_idx, source in enumerate(sources):
  911. source_id = source.get("source", {}).get("name", "")
  912. if "document" in source:
  913. for doc_idx, doc_context in enumerate(source["document"]):
  914. metadata = source.get("metadata")
  915. doc_source_id = None
  916. if metadata:
  917. doc_source_id = metadata[doc_idx].get("source", source_id)
  918. if source_id:
  919. context_string += f"<source><source_id>{doc_source_id if doc_source_id is not None else source_id}</source_id><source_context>{doc_context}</source_context></source>\n"
  920. else:
  921. # If there is no source_id, then do not include the source_id tag
  922. context_string += f"<source><source_context>{doc_context}</source_context></source>\n"
  923. context_string = context_string.strip()
  924. prompt = get_last_user_message(body["messages"])
  925. if prompt is None:
  926. raise Exception("No user message found")
  927. if (
  928. retrieval_app.state.config.RELEVANCE_THRESHOLD == 0
  929. and context_string.strip() == ""
  930. ):
  931. log.debug(
  932. f"With a 0 relevancy threshold for RAG, the context cannot be empty"
  933. )
  934. # Workaround for Ollama 2.0+ system prompt issue
  935. # TODO: replace with add_or_update_system_message
  936. if model["owned_by"] == "ollama":
  937. body["messages"] = prepend_to_first_user_message_content(
  938. rag_template(
  939. retrieval_app.state.config.RAG_TEMPLATE, context_string, prompt
  940. ),
  941. body["messages"],
  942. )
  943. else:
  944. body["messages"] = add_or_update_system_message(
  945. rag_template(
  946. retrieval_app.state.config.RAG_TEMPLATE, context_string, prompt
  947. ),
  948. body["messages"],
  949. )
  950. # If there are citations, add them to the data_items
  951. sources = [
  952. source for source in sources if source.get("source", {}).get("name", "")
  953. ]
  954. if len(sources) > 0:
  955. data_items.append({"sources": sources})
  956. modified_body_bytes = json.dumps(body).encode("utf-8")
  957. # Replace the request body with the modified one
  958. request._body = modified_body_bytes
  959. # Set custom header to ensure content-length matches new body length
  960. request.headers.__dict__["_list"] = [
  961. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  962. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  963. ]
  964. response = await call_next(request)
  965. if not isinstance(response, StreamingResponse):
  966. return response
  967. content_type = response.headers["Content-Type"]
  968. is_openai = "text/event-stream" in content_type
  969. is_ollama = "application/x-ndjson" in content_type
  970. if not is_openai and not is_ollama:
  971. return response
  972. def wrap_item(item):
  973. return f"data: {item}\n\n" if is_openai else f"{item}\n"
  974. async def stream_wrapper(original_generator, data_items):
  975. for item in data_items:
  976. yield wrap_item(json.dumps(item))
  977. async for data in original_generator:
  978. yield data
  979. return StreamingResponse(
  980. stream_wrapper(response.body_iterator, data_items),
  981. headers=dict(response.headers),
  982. )
  983. async def _receive(self, body: bytes):
  984. return {"type": "http.request", "body": body, "more_body": False}
  985. app.add_middleware(ChatCompletionMiddleware)
  986. ##################################
  987. #
  988. # Pipeline Middleware
  989. #
  990. ##################################
  991. def get_sorted_filters(model_id, models):
  992. filters = [
  993. model
  994. for model in models.values()
  995. if "pipeline" in model
  996. and "type" in model["pipeline"]
  997. and model["pipeline"]["type"] == "filter"
  998. and (
  999. model["pipeline"]["pipelines"] == ["*"]
  1000. or any(
  1001. model_id == target_model_id
  1002. for target_model_id in model["pipeline"]["pipelines"]
  1003. )
  1004. )
  1005. ]
  1006. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  1007. return sorted_filters
  1008. def filter_pipeline(payload, user, models):
  1009. user = {"id": user.id, "email": user.email, "name": user.name, "role": user.role}
  1010. model_id = payload["model"]
  1011. sorted_filters = get_sorted_filters(model_id, models)
  1012. model = models[model_id]
  1013. if "pipeline" in model:
  1014. sorted_filters.append(model)
  1015. for filter in sorted_filters:
  1016. r = None
  1017. try:
  1018. urlIdx = filter["urlIdx"]
  1019. url = app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1020. key = app.state.config.OPENAI_API_KEYS[urlIdx]
  1021. if key == "":
  1022. continue
  1023. headers = {"Authorization": f"Bearer {key}"}
  1024. r = requests.post(
  1025. f"{url}/{filter['id']}/filter/inlet",
  1026. headers=headers,
  1027. json={
  1028. "user": user,
  1029. "body": payload,
  1030. },
  1031. )
  1032. r.raise_for_status()
  1033. payload = r.json()
  1034. except Exception as e:
  1035. # Handle connection error here
  1036. print(f"Connection error: {e}")
  1037. if r is not None:
  1038. res = r.json()
  1039. if "detail" in res:
  1040. raise Exception(r.status_code, res["detail"])
  1041. return payload
  1042. class PipelineMiddleware(BaseHTTPMiddleware):
  1043. async def dispatch(self, request: Request, call_next):
  1044. if not request.method == "POST" and any(
  1045. endpoint in request.url.path
  1046. for endpoint in ["/ollama/api/chat", "/chat/completions"]
  1047. ):
  1048. return await call_next(request)
  1049. log.debug(f"request.url.path: {request.url.path}")
  1050. # Read the original request body
  1051. body = await request.body()
  1052. # Decode body to string
  1053. body_str = body.decode("utf-8")
  1054. # Parse string to JSON
  1055. data = json.loads(body_str) if body_str else {}
  1056. try:
  1057. user = get_current_user(
  1058. request,
  1059. get_http_authorization_cred(request.headers["Authorization"]),
  1060. )
  1061. except KeyError as e:
  1062. if len(e.args) > 1:
  1063. return JSONResponse(
  1064. status_code=e.args[0],
  1065. content={"detail": e.args[1]},
  1066. )
  1067. else:
  1068. return JSONResponse(
  1069. status_code=status.HTTP_401_UNAUTHORIZED,
  1070. content={"detail": "Not authenticated"},
  1071. )
  1072. except HTTPException as e:
  1073. return JSONResponse(
  1074. status_code=e.status_code,
  1075. content={"detail": e.detail},
  1076. )
  1077. model_list = await get_all_models()
  1078. models = {model["id"]: model for model in model_list}
  1079. try:
  1080. data = filter_pipeline(data, user, models)
  1081. except Exception as e:
  1082. if len(e.args) > 1:
  1083. return JSONResponse(
  1084. status_code=e.args[0],
  1085. content={"detail": e.args[1]},
  1086. )
  1087. else:
  1088. return JSONResponse(
  1089. status_code=status.HTTP_400_BAD_REQUEST,
  1090. content={"detail": str(e)},
  1091. )
  1092. modified_body_bytes = json.dumps(data).encode("utf-8")
  1093. # Replace the request body with the modified one
  1094. request._body = modified_body_bytes
  1095. # Set custom header to ensure content-length matches new body length
  1096. request.headers.__dict__["_list"] = [
  1097. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  1098. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  1099. ]
  1100. response = await call_next(request)
  1101. return response
  1102. async def _receive(self, body: bytes):
  1103. return {"type": "http.request", "body": body, "more_body": False}
  1104. app.add_middleware(PipelineMiddleware)
  1105. class RedirectMiddleware(BaseHTTPMiddleware):
  1106. async def dispatch(self, request: Request, call_next):
  1107. # Check if the request is a GET request
  1108. if request.method == "GET":
  1109. path = request.url.path
  1110. query_params = dict(parse_qs(urlparse(str(request.url)).query))
  1111. # Check for the specific watch path and the presence of 'v' parameter
  1112. if path.endswith("/watch") and "v" in query_params:
  1113. video_id = query_params["v"][0] # Extract the first 'v' parameter
  1114. encoded_video_id = urlencode({"youtube": video_id})
  1115. redirect_url = f"/?{encoded_video_id}"
  1116. return RedirectResponse(url=redirect_url)
  1117. # Proceed with the normal flow of other requests
  1118. response = await call_next(request)
  1119. return response
  1120. # Add the middleware to the app
  1121. app.add_middleware(RedirectMiddleware)
  1122. app.add_middleware(SecurityHeadersMiddleware)
  1123. @app.middleware("http")
  1124. async def commit_session_after_request(request: Request, call_next):
  1125. response = await call_next(request)
  1126. # log.debug("Commit session after request")
  1127. Session.commit()
  1128. return response
  1129. @app.middleware("http")
  1130. async def check_url(request: Request, call_next):
  1131. start_time = int(time.time())
  1132. request.state.enable_api_key = webui_app.state.config.ENABLE_API_KEY
  1133. response = await call_next(request)
  1134. process_time = int(time.time()) - start_time
  1135. response.headers["X-Process-Time"] = str(process_time)
  1136. return response
  1137. @app.middleware("http")
  1138. async def inspect_websocket(request: Request, call_next):
  1139. if (
  1140. "/ws/socket.io" in request.url.path
  1141. and request.query_params.get("transport") == "websocket"
  1142. ):
  1143. upgrade = (request.headers.get("Upgrade") or "").lower()
  1144. connection = (request.headers.get("Connection") or "").lower().split(",")
  1145. # Check that there's the correct headers for an upgrade, else reject the connection
  1146. # This is to work around this upstream issue: https://github.com/miguelgrinberg/python-engineio/issues/367
  1147. if upgrade != "websocket" or "upgrade" not in connection:
  1148. return JSONResponse(
  1149. status_code=status.HTTP_400_BAD_REQUEST,
  1150. content={"detail": "Invalid WebSocket upgrade request"},
  1151. )
  1152. return await call_next(request)
  1153. app.add_middleware(
  1154. CORSMiddleware,
  1155. allow_origins=CORS_ALLOW_ORIGIN,
  1156. allow_credentials=True,
  1157. allow_methods=["*"],
  1158. allow_headers=["*"],
  1159. )
  1160. app.mount("/ws", socket_app)
  1161. app.include_router(ollama.router, prefix="/ollama")
  1162. app.include_router(openai.router, prefix="/openai")
  1163. app.include_router(images.router, prefix="/api/v1/images")
  1164. app.include_router(audio.router, prefix="/api/v1/audio")
  1165. app.include_router(retrieval.router, prefix="/api/v1/retrieval")
  1166. app.include_router(configs.router, prefix="/api/v1/configs", tags=["configs"])
  1167. app.include_router(auths.router, prefix="/api/v1/auths", tags=["auths"])
  1168. app.include_router(users.router, prefix="/api/v1/users", tags=["users"])
  1169. app.include_router(chats.router, prefix="/api/v1/chats", tags=["chats"])
  1170. app.include_router(models.router, prefix="/api/v1/models", tags=["models"])
  1171. app.include_router(knowledge.router, prefix="/api/v1/knowledge", tags=["knowledge"])
  1172. app.include_router(prompts.router, prefix="/api/v1/prompts", tags=["prompts"])
  1173. app.include_router(tools.router, prefix="/api/v1/tools", tags=["tools"])
  1174. app.include_router(memories.router, prefix="/api/v1/memories", tags=["memories"])
  1175. app.include_router(folders.router, prefix="/api/v1/folders", tags=["folders"])
  1176. app.include_router(groups.router, prefix="/api/v1/groups", tags=["groups"])
  1177. app.include_router(files.router, prefix="/api/v1/files", tags=["files"])
  1178. app.include_router(functions.router, prefix="/api/v1/functions", tags=["functions"])
  1179. app.include_router(
  1180. evaluations.router, prefix="/api/v1/evaluations", tags=["evaluations"]
  1181. )
  1182. app.include_router(utils.router, prefix="/api/v1/utils", tags=["utils"])
  1183. async def get_all_base_models():
  1184. open_webui_models = []
  1185. openai_models = []
  1186. ollama_models = []
  1187. if app.state.config.ENABLE_OPENAI_API:
  1188. openai_models = await openai.get_all_models()
  1189. openai_models = openai_models["data"]
  1190. if app.state.config.ENABLE_OLLAMA_API:
  1191. ollama_models = await ollama.get_all_models()
  1192. ollama_models = [
  1193. {
  1194. "id": model["model"],
  1195. "name": model["name"],
  1196. "object": "model",
  1197. "created": int(time.time()),
  1198. "owned_by": "ollama",
  1199. "ollama": model,
  1200. }
  1201. for model in ollama_models["models"]
  1202. ]
  1203. open_webui_models = await get_open_webui_models()
  1204. models = open_webui_models + openai_models + ollama_models
  1205. return models
  1206. @cached(ttl=3)
  1207. async def get_all_models():
  1208. models = await get_all_base_models()
  1209. # If there are no models, return an empty list
  1210. if len([model for model in models if not model.get("arena", False)]) == 0:
  1211. return []
  1212. global_action_ids = [
  1213. function.id for function in Functions.get_global_action_functions()
  1214. ]
  1215. enabled_action_ids = [
  1216. function.id
  1217. for function in Functions.get_functions_by_type("action", active_only=True)
  1218. ]
  1219. custom_models = Models.get_all_models()
  1220. for custom_model in custom_models:
  1221. if custom_model.base_model_id is None:
  1222. for model in models:
  1223. if (
  1224. custom_model.id == model["id"]
  1225. or custom_model.id == model["id"].split(":")[0]
  1226. ):
  1227. if custom_model.is_active:
  1228. model["name"] = custom_model.name
  1229. model["info"] = custom_model.model_dump()
  1230. action_ids = []
  1231. if "info" in model and "meta" in model["info"]:
  1232. action_ids.extend(
  1233. model["info"]["meta"].get("actionIds", [])
  1234. )
  1235. model["action_ids"] = action_ids
  1236. else:
  1237. models.remove(model)
  1238. elif custom_model.is_active and (
  1239. custom_model.id not in [model["id"] for model in models]
  1240. ):
  1241. owned_by = "openai"
  1242. pipe = None
  1243. action_ids = []
  1244. for model in models:
  1245. if (
  1246. custom_model.base_model_id == model["id"]
  1247. or custom_model.base_model_id == model["id"].split(":")[0]
  1248. ):
  1249. owned_by = model["owned_by"]
  1250. if "pipe" in model:
  1251. pipe = model["pipe"]
  1252. break
  1253. if custom_model.meta:
  1254. meta = custom_model.meta.model_dump()
  1255. if "actionIds" in meta:
  1256. action_ids.extend(meta["actionIds"])
  1257. models.append(
  1258. {
  1259. "id": f"{custom_model.id}",
  1260. "name": custom_model.name,
  1261. "object": "model",
  1262. "created": custom_model.created_at,
  1263. "owned_by": owned_by,
  1264. "info": custom_model.model_dump(),
  1265. "preset": True,
  1266. **({"pipe": pipe} if pipe is not None else {}),
  1267. "action_ids": action_ids,
  1268. }
  1269. )
  1270. # Process action_ids to get the actions
  1271. def get_action_items_from_module(function, module):
  1272. actions = []
  1273. if hasattr(module, "actions"):
  1274. actions = module.actions
  1275. return [
  1276. {
  1277. "id": f"{function.id}.{action['id']}",
  1278. "name": action.get("name", f"{function.name} ({action['id']})"),
  1279. "description": function.meta.description,
  1280. "icon_url": action.get(
  1281. "icon_url", function.meta.manifest.get("icon_url", None)
  1282. ),
  1283. }
  1284. for action in actions
  1285. ]
  1286. else:
  1287. return [
  1288. {
  1289. "id": function.id,
  1290. "name": function.name,
  1291. "description": function.meta.description,
  1292. "icon_url": function.meta.manifest.get("icon_url", None),
  1293. }
  1294. ]
  1295. def get_function_module_by_id(function_id):
  1296. if function_id in webui_app.state.FUNCTIONS:
  1297. function_module = webui_app.state.FUNCTIONS[function_id]
  1298. else:
  1299. function_module, _, _ = load_function_module_by_id(function_id)
  1300. webui_app.state.FUNCTIONS[function_id] = function_module
  1301. for model in models:
  1302. action_ids = [
  1303. action_id
  1304. for action_id in list(set(model.pop("action_ids", []) + global_action_ids))
  1305. if action_id in enabled_action_ids
  1306. ]
  1307. model["actions"] = []
  1308. for action_id in action_ids:
  1309. action_function = Functions.get_function_by_id(action_id)
  1310. if action_function is None:
  1311. raise Exception(f"Action not found: {action_id}")
  1312. function_module = get_function_module_by_id(action_id)
  1313. model["actions"].extend(
  1314. get_action_items_from_module(action_function, function_module)
  1315. )
  1316. log.debug(f"get_all_models() returned {len(models)} models")
  1317. return models
  1318. @app.get("/api/models")
  1319. async def get_models(user=Depends(get_verified_user)):
  1320. models = await get_all_models()
  1321. # Filter out filter pipelines
  1322. models = [
  1323. model
  1324. for model in models
  1325. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  1326. ]
  1327. model_order_list = webui_app.state.config.MODEL_ORDER_LIST
  1328. if model_order_list:
  1329. model_order_dict = {model_id: i for i, model_id in enumerate(model_order_list)}
  1330. # Sort models by order list priority, with fallback for those not in the list
  1331. models.sort(
  1332. key=lambda x: (model_order_dict.get(x["id"], float("inf")), x["name"])
  1333. )
  1334. # Filter out models that the user does not have access to
  1335. if user.role == "user" and not BYPASS_MODEL_ACCESS_CONTROL:
  1336. filtered_models = []
  1337. for model in models:
  1338. if model.get("arena"):
  1339. if has_access(
  1340. user.id,
  1341. type="read",
  1342. access_control=model.get("info", {})
  1343. .get("meta", {})
  1344. .get("access_control", {}),
  1345. ):
  1346. filtered_models.append(model)
  1347. continue
  1348. model_info = Models.get_model_by_id(model["id"])
  1349. if model_info:
  1350. if user.id == model_info.user_id or has_access(
  1351. user.id, type="read", access_control=model_info.access_control
  1352. ):
  1353. filtered_models.append(model)
  1354. models = filtered_models
  1355. log.debug(
  1356. f"/api/models returned filtered models accessible to the user: {json.dumps([model['id'] for model in models])}"
  1357. )
  1358. return {"data": models}
  1359. @app.get("/api/models/base")
  1360. async def get_base_models(user=Depends(get_admin_user)):
  1361. models = await get_all_base_models()
  1362. # Filter out arena models
  1363. models = [model for model in models if not model.get("arena", False)]
  1364. return {"data": models}
  1365. ##################################
  1366. #
  1367. # Config Endpoints
  1368. #
  1369. ##################################
  1370. @app.get("/api/config")
  1371. async def get_app_config(request: Request):
  1372. user = None
  1373. if "token" in request.cookies:
  1374. token = request.cookies.get("token")
  1375. try:
  1376. data = decode_token(token)
  1377. except Exception as e:
  1378. log.debug(e)
  1379. raise HTTPException(
  1380. status_code=status.HTTP_401_UNAUTHORIZED,
  1381. detail="Invalid token",
  1382. )
  1383. if data is not None and "id" in data:
  1384. user = Users.get_user_by_id(data["id"])
  1385. onboarding = False
  1386. if user is None:
  1387. user_count = Users.get_num_users()
  1388. onboarding = user_count == 0
  1389. return {
  1390. **({"onboarding": True} if onboarding else {}),
  1391. "status": True,
  1392. "name": WEBUI_NAME,
  1393. "version": VERSION,
  1394. "default_locale": str(DEFAULT_LOCALE),
  1395. "oauth": {
  1396. "providers": {
  1397. name: config.get("name", name)
  1398. for name, config in OAUTH_PROVIDERS.items()
  1399. }
  1400. },
  1401. "features": {
  1402. "auth": WEBUI_AUTH,
  1403. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1404. "enable_ldap": webui_app.state.config.ENABLE_LDAP,
  1405. "enable_api_key": webui_app.state.config.ENABLE_API_KEY,
  1406. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1407. "enable_login_form": webui_app.state.config.ENABLE_LOGIN_FORM,
  1408. **(
  1409. {
  1410. "enable_web_search": retrieval_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1411. "enable_image_generation": images_app.state.config.ENABLED,
  1412. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1413. "enable_message_rating": webui_app.state.config.ENABLE_MESSAGE_RATING,
  1414. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1415. "enable_admin_chat_access": ENABLE_ADMIN_CHAT_ACCESS,
  1416. }
  1417. if user is not None
  1418. else {}
  1419. ),
  1420. },
  1421. **(
  1422. {
  1423. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1424. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1425. "audio": {
  1426. "tts": {
  1427. "engine": audio_app.state.config.TTS_ENGINE,
  1428. "voice": audio_app.state.config.TTS_VOICE,
  1429. "split_on": audio_app.state.config.TTS_SPLIT_ON,
  1430. },
  1431. "stt": {
  1432. "engine": audio_app.state.config.STT_ENGINE,
  1433. },
  1434. },
  1435. "file": {
  1436. "max_size": retrieval_app.state.config.FILE_MAX_SIZE,
  1437. "max_count": retrieval_app.state.config.FILE_MAX_COUNT,
  1438. },
  1439. "permissions": {**webui_app.state.config.USER_PERMISSIONS},
  1440. }
  1441. if user is not None
  1442. else {}
  1443. ),
  1444. }
  1445. class UrlForm(BaseModel):
  1446. url: str
  1447. @app.get("/api/webhook")
  1448. async def get_webhook_url(user=Depends(get_admin_user)):
  1449. return {
  1450. "url": app.state.config.WEBHOOK_URL,
  1451. }
  1452. @app.post("/api/webhook")
  1453. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1454. app.state.config.WEBHOOK_URL = form_data.url
  1455. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1456. return {"url": app.state.config.WEBHOOK_URL}
  1457. @app.get("/api/version")
  1458. async def get_app_version():
  1459. return {
  1460. "version": VERSION,
  1461. }
  1462. @app.get("/api/version/updates")
  1463. async def get_app_latest_release_version():
  1464. if OFFLINE_MODE:
  1465. log.debug(
  1466. f"Offline mode is enabled, returning current version as latest version"
  1467. )
  1468. return {"current": VERSION, "latest": VERSION}
  1469. try:
  1470. timeout = aiohttp.ClientTimeout(total=1)
  1471. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  1472. async with session.get(
  1473. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1474. ) as response:
  1475. response.raise_for_status()
  1476. data = await response.json()
  1477. latest_version = data["tag_name"]
  1478. return {"current": VERSION, "latest": latest_version[1:]}
  1479. except Exception as e:
  1480. log.debug(e)
  1481. return {"current": VERSION, "latest": VERSION}
  1482. @app.get("/api/changelog")
  1483. async def get_app_changelog():
  1484. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1485. ############################
  1486. # OAuth Login & Callback
  1487. ############################
  1488. # SessionMiddleware is used by authlib for oauth
  1489. if len(OAUTH_PROVIDERS) > 0:
  1490. app.add_middleware(
  1491. SessionMiddleware,
  1492. secret_key=WEBUI_SECRET_KEY,
  1493. session_cookie="oui-session",
  1494. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  1495. https_only=WEBUI_SESSION_COOKIE_SECURE,
  1496. )
  1497. @app.get("/oauth/{provider}/login")
  1498. async def oauth_login(provider: str, request: Request):
  1499. return await oauth_manager.handle_login(provider, request)
  1500. # OAuth login logic is as follows:
  1501. # 1. Attempt to find a user with matching subject ID, tied to the provider
  1502. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  1503. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  1504. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  1505. # - Email addresses are considered unique, so we fail registration if the email address is already taken
  1506. @app.get("/oauth/{provider}/callback")
  1507. async def oauth_callback(provider: str, request: Request, response: Response):
  1508. return await oauth_manager.handle_callback(provider, request, response)
  1509. @app.get("/manifest.json")
  1510. async def get_manifest_json():
  1511. return {
  1512. "name": WEBUI_NAME,
  1513. "short_name": WEBUI_NAME,
  1514. "description": "Open WebUI is an open, extensible, user-friendly interface for AI that adapts to your workflow.",
  1515. "start_url": "/",
  1516. "display": "standalone",
  1517. "background_color": "#343541",
  1518. "orientation": "natural",
  1519. "icons": [
  1520. {
  1521. "src": "/static/logo.png",
  1522. "type": "image/png",
  1523. "sizes": "500x500",
  1524. "purpose": "any",
  1525. },
  1526. {
  1527. "src": "/static/logo.png",
  1528. "type": "image/png",
  1529. "sizes": "500x500",
  1530. "purpose": "maskable",
  1531. },
  1532. ],
  1533. }
  1534. @app.get("/opensearch.xml")
  1535. async def get_opensearch_xml():
  1536. xml_content = rf"""
  1537. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1538. <ShortName>{WEBUI_NAME}</ShortName>
  1539. <Description>Search {WEBUI_NAME}</Description>
  1540. <InputEncoding>UTF-8</InputEncoding>
  1541. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/static/favicon.png</Image>
  1542. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1543. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1544. </OpenSearchDescription>
  1545. """
  1546. return Response(content=xml_content, media_type="application/xml")
  1547. @app.get("/health")
  1548. async def healthcheck():
  1549. return {"status": True}
  1550. @app.get("/health/db")
  1551. async def healthcheck_with_db():
  1552. Session.execute(text("SELECT 1;")).all()
  1553. return {"status": True}
  1554. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  1555. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  1556. if os.path.exists(FRONTEND_BUILD_DIR):
  1557. mimetypes.add_type("text/javascript", ".js")
  1558. app.mount(
  1559. "/",
  1560. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1561. name="spa-static-files",
  1562. )
  1563. else:
  1564. log.warning(
  1565. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1566. )