main.py 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309
  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.EMBEDDING_FUNCTION = None
  445. app.state.sentence_transformer_ef = None
  446. app.state.sentence_transformer_rf = None
  447. app.state.YOUTUBE_LOADER_TRANSLATION = None
  448. ########################################
  449. #
  450. # IMAGES
  451. #
  452. ########################################
  453. app.state.config.IMAGE_GENERATION_ENGINE = IMAGE_GENERATION_ENGINE
  454. app.state.config.ENABLE_IMAGE_GENERATION = ENABLE_IMAGE_GENERATION
  455. app.state.config.IMAGES_OPENAI_API_BASE_URL = IMAGES_OPENAI_API_BASE_URL
  456. app.state.config.IMAGES_OPENAI_API_KEY = IMAGES_OPENAI_API_KEY
  457. app.state.config.IMAGE_GENERATION_MODEL = IMAGE_GENERATION_MODEL
  458. app.state.config.AUTOMATIC1111_BASE_URL = AUTOMATIC1111_BASE_URL
  459. app.state.config.AUTOMATIC1111_API_AUTH = AUTOMATIC1111_API_AUTH
  460. app.state.config.AUTOMATIC1111_CFG_SCALE = AUTOMATIC1111_CFG_SCALE
  461. app.state.config.AUTOMATIC1111_SAMPLER = AUTOMATIC1111_SAMPLER
  462. app.state.config.AUTOMATIC1111_SCHEDULER = AUTOMATIC1111_SCHEDULER
  463. app.state.config.COMFYUI_BASE_URL = COMFYUI_BASE_URL
  464. app.state.config.COMFYUI_WORKFLOW = COMFYUI_WORKFLOW
  465. app.state.config.COMFYUI_WORKFLOW_NODES = COMFYUI_WORKFLOW_NODES
  466. app.state.config.IMAGE_SIZE = IMAGE_SIZE
  467. app.state.config.IMAGE_STEPS = IMAGE_STEPS
  468. ########################################
  469. #
  470. # AUDIO
  471. #
  472. ########################################
  473. app.state.config.STT_OPENAI_API_BASE_URL = AUDIO_STT_OPENAI_API_BASE_URL
  474. app.state.config.STT_OPENAI_API_KEY = AUDIO_STT_OPENAI_API_KEY
  475. app.state.config.STT_ENGINE = AUDIO_STT_ENGINE
  476. app.state.config.STT_MODEL = AUDIO_STT_MODEL
  477. app.state.config.WHISPER_MODEL = WHISPER_MODEL
  478. app.state.config.TTS_OPENAI_API_BASE_URL = AUDIO_TTS_OPENAI_API_BASE_URL
  479. app.state.config.TTS_OPENAI_API_KEY = AUDIO_TTS_OPENAI_API_KEY
  480. app.state.config.TTS_ENGINE = AUDIO_TTS_ENGINE
  481. app.state.config.TTS_MODEL = AUDIO_TTS_MODEL
  482. app.state.config.TTS_VOICE = AUDIO_TTS_VOICE
  483. app.state.config.TTS_API_KEY = AUDIO_TTS_API_KEY
  484. app.state.config.TTS_SPLIT_ON = AUDIO_TTS_SPLIT_ON
  485. app.state.config.TTS_AZURE_SPEECH_REGION = AUDIO_TTS_AZURE_SPEECH_REGION
  486. app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT = AUDIO_TTS_AZURE_SPEECH_OUTPUT_FORMAT
  487. app.state.faster_whisper_model = None
  488. app.state.speech_synthesiser = None
  489. app.state.speech_speaker_embeddings_dataset = None
  490. ########################################
  491. #
  492. # TASKS
  493. #
  494. ########################################
  495. app.state.config.TASK_MODEL = TASK_MODEL
  496. app.state.config.TASK_MODEL_EXTERNAL = TASK_MODEL_EXTERNAL
  497. app.state.config.ENABLE_SEARCH_QUERY_GENERATION = ENABLE_SEARCH_QUERY_GENERATION
  498. app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION = ENABLE_RETRIEVAL_QUERY_GENERATION
  499. app.state.config.ENABLE_AUTOCOMPLETE_GENERATION = ENABLE_AUTOCOMPLETE_GENERATION
  500. app.state.config.ENABLE_TAGS_GENERATION = ENABLE_TAGS_GENERATION
  501. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = TITLE_GENERATION_PROMPT_TEMPLATE
  502. app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE = TAGS_GENERATION_PROMPT_TEMPLATE
  503. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  504. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  505. )
  506. app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE = QUERY_GENERATION_PROMPT_TEMPLATE
  507. app.state.config.AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE = (
  508. AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE
  509. )
  510. app.state.config.AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH = (
  511. AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH
  512. )
  513. ########################################
  514. #
  515. # WEBUI
  516. #
  517. ########################################
  518. app.state.MODELS = {}
  519. ##################################
  520. #
  521. # ChatCompletion Middleware
  522. #
  523. ##################################
  524. def get_filter_function_ids(model):
  525. def get_priority(function_id):
  526. function = Functions.get_function_by_id(function_id)
  527. if function is not None and hasattr(function, "valves"):
  528. # TODO: Fix FunctionModel
  529. return (function.valves if function.valves else {}).get("priority", 0)
  530. return 0
  531. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  532. if "info" in model and "meta" in model["info"]:
  533. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  534. filter_ids = list(set(filter_ids))
  535. enabled_filter_ids = [
  536. function.id
  537. for function in Functions.get_functions_by_type("filter", active_only=True)
  538. ]
  539. filter_ids = [
  540. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  541. ]
  542. filter_ids.sort(key=get_priority)
  543. return filter_ids
  544. async def chat_completion_filter_functions_handler(body, model, extra_params):
  545. skip_files = None
  546. filter_ids = get_filter_function_ids(model)
  547. for filter_id in filter_ids:
  548. filter = Functions.get_function_by_id(filter_id)
  549. if not filter:
  550. continue
  551. if filter_id in webui_app.state.FUNCTIONS:
  552. function_module = webui_app.state.FUNCTIONS[filter_id]
  553. else:
  554. function_module, _, _ = load_function_module_by_id(filter_id)
  555. webui_app.state.FUNCTIONS[filter_id] = function_module
  556. # Check if the function has a file_handler variable
  557. if hasattr(function_module, "file_handler"):
  558. skip_files = function_module.file_handler
  559. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  560. valves = Functions.get_function_valves_by_id(filter_id)
  561. function_module.valves = function_module.Valves(
  562. **(valves if valves else {})
  563. )
  564. if not hasattr(function_module, "inlet"):
  565. continue
  566. try:
  567. inlet = function_module.inlet
  568. # Get the signature of the function
  569. sig = inspect.signature(inlet)
  570. params = {"body": body} | {
  571. k: v
  572. for k, v in {
  573. **extra_params,
  574. "__model__": model,
  575. "__id__": filter_id,
  576. }.items()
  577. if k in sig.parameters
  578. }
  579. if "__user__" in params and hasattr(function_module, "UserValves"):
  580. try:
  581. params["__user__"]["valves"] = function_module.UserValves(
  582. **Functions.get_user_valves_by_id_and_user_id(
  583. filter_id, params["__user__"]["id"]
  584. )
  585. )
  586. except Exception as e:
  587. print(e)
  588. if inspect.iscoroutinefunction(inlet):
  589. body = await inlet(**params)
  590. else:
  591. body = inlet(**params)
  592. except Exception as e:
  593. print(f"Error: {e}")
  594. raise e
  595. if skip_files and "files" in body.get("metadata", {}):
  596. del body["metadata"]["files"]
  597. return body, {}
  598. def get_tools_function_calling_payload(messages, task_model_id, content):
  599. user_message = get_last_user_message(messages)
  600. history = "\n".join(
  601. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  602. for message in messages[::-1][:4]
  603. )
  604. prompt = f"History:\n{history}\nQuery: {user_message}"
  605. return {
  606. "model": task_model_id,
  607. "messages": [
  608. {"role": "system", "content": content},
  609. {"role": "user", "content": f"Query: {prompt}"},
  610. ],
  611. "stream": False,
  612. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  613. }
  614. async def get_content_from_response(response) -> Optional[str]:
  615. content = None
  616. if hasattr(response, "body_iterator"):
  617. async for chunk in response.body_iterator:
  618. data = json.loads(chunk.decode("utf-8"))
  619. content = data["choices"][0]["message"]["content"]
  620. # Cleanup any remaining background tasks if necessary
  621. if response.background is not None:
  622. await response.background()
  623. else:
  624. content = response["choices"][0]["message"]["content"]
  625. return content
  626. def get_task_model_id(
  627. default_model_id: str, task_model: str, task_model_external: str, models
  628. ) -> str:
  629. # Set the task model
  630. task_model_id = default_model_id
  631. # Check if the user has a custom task model and use that model
  632. if models[task_model_id]["owned_by"] == "ollama":
  633. if task_model and task_model in models:
  634. task_model_id = task_model
  635. else:
  636. if task_model_external and task_model_external in models:
  637. task_model_id = task_model_external
  638. return task_model_id
  639. async def chat_completion_tools_handler(
  640. body: dict, user: UserModel, models, extra_params: dict
  641. ) -> tuple[dict, dict]:
  642. # If tool_ids field is present, call the functions
  643. metadata = body.get("metadata", {})
  644. tool_ids = metadata.get("tool_ids", None)
  645. log.debug(f"{tool_ids=}")
  646. if not tool_ids:
  647. return body, {}
  648. skip_files = False
  649. sources = []
  650. task_model_id = get_task_model_id(
  651. body["model"],
  652. app.state.config.TASK_MODEL,
  653. app.state.config.TASK_MODEL_EXTERNAL,
  654. models,
  655. )
  656. tools = get_tools(
  657. webui_app,
  658. tool_ids,
  659. user,
  660. {
  661. **extra_params,
  662. "__model__": models[task_model_id],
  663. "__messages__": body["messages"],
  664. "__files__": metadata.get("files", []),
  665. },
  666. )
  667. log.info(f"{tools=}")
  668. specs = [tool["spec"] for tool in tools.values()]
  669. tools_specs = json.dumps(specs)
  670. if app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE != "":
  671. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  672. else:
  673. 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."""
  674. tools_function_calling_prompt = tools_function_calling_generation_template(
  675. template, tools_specs
  676. )
  677. log.info(f"{tools_function_calling_prompt=}")
  678. payload = get_tools_function_calling_payload(
  679. body["messages"], task_model_id, tools_function_calling_prompt
  680. )
  681. try:
  682. payload = filter_pipeline(payload, user, models)
  683. except Exception as e:
  684. raise e
  685. try:
  686. response = await generate_chat_completions(form_data=payload, user=user)
  687. log.debug(f"{response=}")
  688. content = await get_content_from_response(response)
  689. log.debug(f"{content=}")
  690. if not content:
  691. return body, {}
  692. try:
  693. content = content[content.find("{") : content.rfind("}") + 1]
  694. if not content:
  695. raise Exception("No JSON object found in the response")
  696. result = json.loads(content)
  697. tool_function_name = result.get("name", None)
  698. if tool_function_name not in tools:
  699. return body, {}
  700. tool_function_params = result.get("parameters", {})
  701. try:
  702. required_params = (
  703. tools[tool_function_name]
  704. .get("spec", {})
  705. .get("parameters", {})
  706. .get("required", [])
  707. )
  708. tool_function = tools[tool_function_name]["callable"]
  709. tool_function_params = {
  710. k: v
  711. for k, v in tool_function_params.items()
  712. if k in required_params
  713. }
  714. tool_output = await tool_function(**tool_function_params)
  715. except Exception as e:
  716. tool_output = str(e)
  717. if isinstance(tool_output, str):
  718. if tools[tool_function_name]["citation"]:
  719. sources.append(
  720. {
  721. "source": {
  722. "name": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  723. },
  724. "document": [tool_output],
  725. "metadata": [
  726. {
  727. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  728. }
  729. ],
  730. }
  731. )
  732. else:
  733. sources.append(
  734. {
  735. "source": {},
  736. "document": [tool_output],
  737. "metadata": [
  738. {
  739. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  740. }
  741. ],
  742. }
  743. )
  744. if tools[tool_function_name]["file_handler"]:
  745. skip_files = True
  746. except Exception as e:
  747. log.exception(f"Error: {e}")
  748. content = None
  749. except Exception as e:
  750. log.exception(f"Error: {e}")
  751. content = None
  752. log.debug(f"tool_contexts: {sources}")
  753. if skip_files and "files" in body.get("metadata", {}):
  754. del body["metadata"]["files"]
  755. return body, {"sources": sources}
  756. async def chat_completion_files_handler(
  757. body: dict, user: UserModel
  758. ) -> tuple[dict, dict[str, list]]:
  759. sources = []
  760. if files := body.get("metadata", {}).get("files", None):
  761. try:
  762. queries_response = await generate_queries(
  763. {
  764. "model": body["model"],
  765. "messages": body["messages"],
  766. "type": "retrieval",
  767. },
  768. user,
  769. )
  770. queries_response = queries_response["choices"][0]["message"]["content"]
  771. try:
  772. bracket_start = queries_response.find("{")
  773. bracket_end = queries_response.rfind("}") + 1
  774. if bracket_start == -1 or bracket_end == -1:
  775. raise Exception("No JSON object found in the response")
  776. queries_response = queries_response[bracket_start:bracket_end]
  777. queries_response = json.loads(queries_response)
  778. except Exception as e:
  779. queries_response = {"queries": [queries_response]}
  780. queries = queries_response.get("queries", [])
  781. except Exception as e:
  782. queries = []
  783. if len(queries) == 0:
  784. queries = [get_last_user_message(body["messages"])]
  785. sources = get_sources_from_files(
  786. files=files,
  787. queries=queries,
  788. embedding_function=retrieval_app.state.EMBEDDING_FUNCTION,
  789. k=retrieval_app.state.config.TOP_K,
  790. reranking_function=retrieval_app.state.sentence_transformer_rf,
  791. r=retrieval_app.state.config.RELEVANCE_THRESHOLD,
  792. hybrid_search=retrieval_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  793. )
  794. log.debug(f"rag_contexts:sources: {sources}")
  795. return body, {"sources": sources}
  796. async def get_body_and_model_and_user(request, models):
  797. # Read the original request body
  798. body = await request.body()
  799. body_str = body.decode("utf-8")
  800. body = json.loads(body_str) if body_str else {}
  801. model_id = body["model"]
  802. if model_id not in models:
  803. raise Exception("Model not found")
  804. model = models[model_id]
  805. user = get_current_user(
  806. request,
  807. get_http_authorization_cred(request.headers.get("Authorization")),
  808. )
  809. return body, model, user
  810. class ChatCompletionMiddleware(BaseHTTPMiddleware):
  811. async def dispatch(self, request: Request, call_next):
  812. if not request.method == "POST" and any(
  813. endpoint in request.url.path
  814. for endpoint in ["/ollama/api/chat", "/chat/completions"]
  815. ):
  816. return await call_next(request)
  817. log.debug(f"request.url.path: {request.url.path}")
  818. model_list = await get_all_models()
  819. models = {model["id"]: model for model in model_list}
  820. try:
  821. body, model, user = await get_body_and_model_and_user(request, models)
  822. except Exception as e:
  823. return JSONResponse(
  824. status_code=status.HTTP_400_BAD_REQUEST,
  825. content={"detail": str(e)},
  826. )
  827. model_info = Models.get_model_by_id(model["id"])
  828. if user.role == "user" and not BYPASS_MODEL_ACCESS_CONTROL:
  829. if model.get("arena"):
  830. if not has_access(
  831. user.id,
  832. type="read",
  833. access_control=model.get("info", {})
  834. .get("meta", {})
  835. .get("access_control", {}),
  836. ):
  837. raise HTTPException(
  838. status_code=403,
  839. detail="Model not found",
  840. )
  841. else:
  842. if not model_info:
  843. return JSONResponse(
  844. status_code=status.HTTP_404_NOT_FOUND,
  845. content={"detail": "Model not found"},
  846. )
  847. elif not (
  848. user.id == model_info.user_id
  849. or has_access(
  850. user.id, type="read", access_control=model_info.access_control
  851. )
  852. ):
  853. return JSONResponse(
  854. status_code=status.HTTP_403_FORBIDDEN,
  855. content={"detail": "User does not have access to the model"},
  856. )
  857. metadata = {
  858. "chat_id": body.pop("chat_id", None),
  859. "message_id": body.pop("id", None),
  860. "session_id": body.pop("session_id", None),
  861. "tool_ids": body.get("tool_ids", None),
  862. "files": body.get("files", None),
  863. }
  864. body["metadata"] = metadata
  865. extra_params = {
  866. "__event_emitter__": get_event_emitter(metadata),
  867. "__event_call__": get_event_call(metadata),
  868. "__user__": {
  869. "id": user.id,
  870. "email": user.email,
  871. "name": user.name,
  872. "role": user.role,
  873. },
  874. "__metadata__": metadata,
  875. }
  876. # Initialize data_items to store additional data to be sent to the client
  877. # Initialize contexts and citation
  878. data_items = []
  879. sources = []
  880. try:
  881. body, flags = await chat_completion_filter_functions_handler(
  882. body, model, extra_params
  883. )
  884. except Exception as e:
  885. return JSONResponse(
  886. status_code=status.HTTP_400_BAD_REQUEST,
  887. content={"detail": str(e)},
  888. )
  889. tool_ids = body.pop("tool_ids", None)
  890. files = body.pop("files", None)
  891. metadata = {
  892. **metadata,
  893. "tool_ids": tool_ids,
  894. "files": files,
  895. }
  896. body["metadata"] = metadata
  897. try:
  898. body, flags = await chat_completion_tools_handler(
  899. body, user, models, extra_params
  900. )
  901. sources.extend(flags.get("sources", []))
  902. except Exception as e:
  903. log.exception(e)
  904. try:
  905. body, flags = await chat_completion_files_handler(body, user)
  906. sources.extend(flags.get("sources", []))
  907. except Exception as e:
  908. log.exception(e)
  909. # If context is not empty, insert it into the messages
  910. if len(sources) > 0:
  911. context_string = ""
  912. for source_idx, source in enumerate(sources):
  913. source_id = source.get("source", {}).get("name", "")
  914. if "document" in source:
  915. for doc_idx, doc_context in enumerate(source["document"]):
  916. metadata = source.get("metadata")
  917. doc_source_id = None
  918. if metadata:
  919. doc_source_id = metadata[doc_idx].get("source", source_id)
  920. if source_id:
  921. 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"
  922. else:
  923. # If there is no source_id, then do not include the source_id tag
  924. context_string += f"<source><source_context>{doc_context}</source_context></source>\n"
  925. context_string = context_string.strip()
  926. prompt = get_last_user_message(body["messages"])
  927. if prompt is None:
  928. raise Exception("No user message found")
  929. if (
  930. retrieval_app.state.config.RELEVANCE_THRESHOLD == 0
  931. and context_string.strip() == ""
  932. ):
  933. log.debug(
  934. f"With a 0 relevancy threshold for RAG, the context cannot be empty"
  935. )
  936. # Workaround for Ollama 2.0+ system prompt issue
  937. # TODO: replace with add_or_update_system_message
  938. if model["owned_by"] == "ollama":
  939. body["messages"] = prepend_to_first_user_message_content(
  940. rag_template(
  941. retrieval_app.state.config.RAG_TEMPLATE, context_string, prompt
  942. ),
  943. body["messages"],
  944. )
  945. else:
  946. body["messages"] = add_or_update_system_message(
  947. rag_template(
  948. retrieval_app.state.config.RAG_TEMPLATE, context_string, prompt
  949. ),
  950. body["messages"],
  951. )
  952. # If there are citations, add them to the data_items
  953. sources = [
  954. source for source in sources if source.get("source", {}).get("name", "")
  955. ]
  956. if len(sources) > 0:
  957. data_items.append({"sources": sources})
  958. modified_body_bytes = json.dumps(body).encode("utf-8")
  959. # Replace the request body with the modified one
  960. request._body = modified_body_bytes
  961. # Set custom header to ensure content-length matches new body length
  962. request.headers.__dict__["_list"] = [
  963. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  964. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  965. ]
  966. response = await call_next(request)
  967. if not isinstance(response, StreamingResponse):
  968. return response
  969. content_type = response.headers["Content-Type"]
  970. is_openai = "text/event-stream" in content_type
  971. is_ollama = "application/x-ndjson" in content_type
  972. if not is_openai and not is_ollama:
  973. return response
  974. def wrap_item(item):
  975. return f"data: {item}\n\n" if is_openai else f"{item}\n"
  976. async def stream_wrapper(original_generator, data_items):
  977. for item in data_items:
  978. yield wrap_item(json.dumps(item))
  979. async for data in original_generator:
  980. yield data
  981. return StreamingResponse(
  982. stream_wrapper(response.body_iterator, data_items),
  983. headers=dict(response.headers),
  984. )
  985. async def _receive(self, body: bytes):
  986. return {"type": "http.request", "body": body, "more_body": False}
  987. app.add_middleware(ChatCompletionMiddleware)
  988. ##################################
  989. #
  990. # Pipeline Middleware
  991. #
  992. ##################################
  993. def get_sorted_filters(model_id, models):
  994. filters = [
  995. model
  996. for model in models.values()
  997. if "pipeline" in model
  998. and "type" in model["pipeline"]
  999. and model["pipeline"]["type"] == "filter"
  1000. and (
  1001. model["pipeline"]["pipelines"] == ["*"]
  1002. or any(
  1003. model_id == target_model_id
  1004. for target_model_id in model["pipeline"]["pipelines"]
  1005. )
  1006. )
  1007. ]
  1008. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  1009. return sorted_filters
  1010. def filter_pipeline(payload, user, models):
  1011. user = {"id": user.id, "email": user.email, "name": user.name, "role": user.role}
  1012. model_id = payload["model"]
  1013. sorted_filters = get_sorted_filters(model_id, models)
  1014. model = models[model_id]
  1015. if "pipeline" in model:
  1016. sorted_filters.append(model)
  1017. for filter in sorted_filters:
  1018. r = None
  1019. try:
  1020. urlIdx = filter["urlIdx"]
  1021. url = app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1022. key = app.state.config.OPENAI_API_KEYS[urlIdx]
  1023. if key == "":
  1024. continue
  1025. headers = {"Authorization": f"Bearer {key}"}
  1026. r = requests.post(
  1027. f"{url}/{filter['id']}/filter/inlet",
  1028. headers=headers,
  1029. json={
  1030. "user": user,
  1031. "body": payload,
  1032. },
  1033. )
  1034. r.raise_for_status()
  1035. payload = r.json()
  1036. except Exception as e:
  1037. # Handle connection error here
  1038. print(f"Connection error: {e}")
  1039. if r is not None:
  1040. res = r.json()
  1041. if "detail" in res:
  1042. raise Exception(r.status_code, res["detail"])
  1043. return payload
  1044. class PipelineMiddleware(BaseHTTPMiddleware):
  1045. async def dispatch(self, request: Request, call_next):
  1046. if not request.method == "POST" and any(
  1047. endpoint in request.url.path
  1048. for endpoint in ["/ollama/api/chat", "/chat/completions"]
  1049. ):
  1050. return await call_next(request)
  1051. log.debug(f"request.url.path: {request.url.path}")
  1052. # Read the original request body
  1053. body = await request.body()
  1054. # Decode body to string
  1055. body_str = body.decode("utf-8")
  1056. # Parse string to JSON
  1057. data = json.loads(body_str) if body_str else {}
  1058. try:
  1059. user = get_current_user(
  1060. request,
  1061. get_http_authorization_cred(request.headers["Authorization"]),
  1062. )
  1063. except KeyError as e:
  1064. if len(e.args) > 1:
  1065. return JSONResponse(
  1066. status_code=e.args[0],
  1067. content={"detail": e.args[1]},
  1068. )
  1069. else:
  1070. return JSONResponse(
  1071. status_code=status.HTTP_401_UNAUTHORIZED,
  1072. content={"detail": "Not authenticated"},
  1073. )
  1074. except HTTPException as e:
  1075. return JSONResponse(
  1076. status_code=e.status_code,
  1077. content={"detail": e.detail},
  1078. )
  1079. model_list = await get_all_models()
  1080. models = {model["id"]: model for model in model_list}
  1081. try:
  1082. data = filter_pipeline(data, user, models)
  1083. except Exception as e:
  1084. if len(e.args) > 1:
  1085. return JSONResponse(
  1086. status_code=e.args[0],
  1087. content={"detail": e.args[1]},
  1088. )
  1089. else:
  1090. return JSONResponse(
  1091. status_code=status.HTTP_400_BAD_REQUEST,
  1092. content={"detail": str(e)},
  1093. )
  1094. modified_body_bytes = json.dumps(data).encode("utf-8")
  1095. # Replace the request body with the modified one
  1096. request._body = modified_body_bytes
  1097. # Set custom header to ensure content-length matches new body length
  1098. request.headers.__dict__["_list"] = [
  1099. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  1100. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  1101. ]
  1102. response = await call_next(request)
  1103. return response
  1104. async def _receive(self, body: bytes):
  1105. return {"type": "http.request", "body": body, "more_body": False}
  1106. app.add_middleware(PipelineMiddleware)
  1107. class RedirectMiddleware(BaseHTTPMiddleware):
  1108. async def dispatch(self, request: Request, call_next):
  1109. # Check if the request is a GET request
  1110. if request.method == "GET":
  1111. path = request.url.path
  1112. query_params = dict(parse_qs(urlparse(str(request.url)).query))
  1113. # Check for the specific watch path and the presence of 'v' parameter
  1114. if path.endswith("/watch") and "v" in query_params:
  1115. video_id = query_params["v"][0] # Extract the first 'v' parameter
  1116. encoded_video_id = urlencode({"youtube": video_id})
  1117. redirect_url = f"/?{encoded_video_id}"
  1118. return RedirectResponse(url=redirect_url)
  1119. # Proceed with the normal flow of other requests
  1120. response = await call_next(request)
  1121. return response
  1122. # Add the middleware to the app
  1123. app.add_middleware(RedirectMiddleware)
  1124. app.add_middleware(SecurityHeadersMiddleware)
  1125. @app.middleware("http")
  1126. async def commit_session_after_request(request: Request, call_next):
  1127. response = await call_next(request)
  1128. # log.debug("Commit session after request")
  1129. Session.commit()
  1130. return response
  1131. @app.middleware("http")
  1132. async def check_url(request: Request, call_next):
  1133. start_time = int(time.time())
  1134. request.state.enable_api_key = webui_app.state.config.ENABLE_API_KEY
  1135. response = await call_next(request)
  1136. process_time = int(time.time()) - start_time
  1137. response.headers["X-Process-Time"] = str(process_time)
  1138. return response
  1139. @app.middleware("http")
  1140. async def inspect_websocket(request: Request, call_next):
  1141. if (
  1142. "/ws/socket.io" in request.url.path
  1143. and request.query_params.get("transport") == "websocket"
  1144. ):
  1145. upgrade = (request.headers.get("Upgrade") or "").lower()
  1146. connection = (request.headers.get("Connection") or "").lower().split(",")
  1147. # Check that there's the correct headers for an upgrade, else reject the connection
  1148. # This is to work around this upstream issue: https://github.com/miguelgrinberg/python-engineio/issues/367
  1149. if upgrade != "websocket" or "upgrade" not in connection:
  1150. return JSONResponse(
  1151. status_code=status.HTTP_400_BAD_REQUEST,
  1152. content={"detail": "Invalid WebSocket upgrade request"},
  1153. )
  1154. return await call_next(request)
  1155. app.add_middleware(
  1156. CORSMiddleware,
  1157. allow_origins=CORS_ALLOW_ORIGIN,
  1158. allow_credentials=True,
  1159. allow_methods=["*"],
  1160. allow_headers=["*"],
  1161. )
  1162. app.mount("/ws", socket_app)
  1163. app.include_router(ollama.router, prefix="/ollama")
  1164. app.include_router(openai.router, prefix="/openai")
  1165. app.include_router(images.router, prefix="/api/v1/images", tags=["images"])
  1166. app.include_router(audio.router, prefix="/api/v1/audio", tags=["audio"])
  1167. app.include_router(retrieval.router, prefix="/api/v1/retrieval", tags=["retrieval"])
  1168. app.include_router(configs.router, prefix="/api/v1/configs", tags=["configs"])
  1169. app.include_router(auths.router, prefix="/api/v1/auths", tags=["auths"])
  1170. app.include_router(users.router, prefix="/api/v1/users", tags=["users"])
  1171. app.include_router(chats.router, prefix="/api/v1/chats", tags=["chats"])
  1172. app.include_router(models.router, prefix="/api/v1/models", tags=["models"])
  1173. app.include_router(knowledge.router, prefix="/api/v1/knowledge", tags=["knowledge"])
  1174. app.include_router(prompts.router, prefix="/api/v1/prompts", tags=["prompts"])
  1175. app.include_router(tools.router, prefix="/api/v1/tools", tags=["tools"])
  1176. app.include_router(memories.router, prefix="/api/v1/memories", tags=["memories"])
  1177. app.include_router(folders.router, prefix="/api/v1/folders", tags=["folders"])
  1178. app.include_router(groups.router, prefix="/api/v1/groups", tags=["groups"])
  1179. app.include_router(files.router, prefix="/api/v1/files", tags=["files"])
  1180. app.include_router(functions.router, prefix="/api/v1/functions", tags=["functions"])
  1181. app.include_router(
  1182. evaluations.router, prefix="/api/v1/evaluations", tags=["evaluations"]
  1183. )
  1184. app.include_router(utils.router, prefix="/api/v1/utils", tags=["utils"])
  1185. async def get_all_base_models():
  1186. open_webui_models = []
  1187. openai_models = []
  1188. ollama_models = []
  1189. if app.state.config.ENABLE_OPENAI_API:
  1190. openai_models = await openai.get_all_models()
  1191. openai_models = openai_models["data"]
  1192. if app.state.config.ENABLE_OLLAMA_API:
  1193. ollama_models = await ollama.get_all_models()
  1194. ollama_models = [
  1195. {
  1196. "id": model["model"],
  1197. "name": model["name"],
  1198. "object": "model",
  1199. "created": int(time.time()),
  1200. "owned_by": "ollama",
  1201. "ollama": model,
  1202. }
  1203. for model in ollama_models["models"]
  1204. ]
  1205. open_webui_models = await get_open_webui_models()
  1206. models = open_webui_models + openai_models + ollama_models
  1207. return models
  1208. @cached(ttl=3)
  1209. async def get_all_models():
  1210. models = await get_all_base_models()
  1211. # If there are no models, return an empty list
  1212. if len([model for model in models if not model.get("arena", False)]) == 0:
  1213. return []
  1214. global_action_ids = [
  1215. function.id for function in Functions.get_global_action_functions()
  1216. ]
  1217. enabled_action_ids = [
  1218. function.id
  1219. for function in Functions.get_functions_by_type("action", active_only=True)
  1220. ]
  1221. custom_models = Models.get_all_models()
  1222. for custom_model in custom_models:
  1223. if custom_model.base_model_id is None:
  1224. for model in models:
  1225. if (
  1226. custom_model.id == model["id"]
  1227. or custom_model.id == model["id"].split(":")[0]
  1228. ):
  1229. if custom_model.is_active:
  1230. model["name"] = custom_model.name
  1231. model["info"] = custom_model.model_dump()
  1232. action_ids = []
  1233. if "info" in model and "meta" in model["info"]:
  1234. action_ids.extend(
  1235. model["info"]["meta"].get("actionIds", [])
  1236. )
  1237. model["action_ids"] = action_ids
  1238. else:
  1239. models.remove(model)
  1240. elif custom_model.is_active and (
  1241. custom_model.id not in [model["id"] for model in models]
  1242. ):
  1243. owned_by = "openai"
  1244. pipe = None
  1245. action_ids = []
  1246. for model in models:
  1247. if (
  1248. custom_model.base_model_id == model["id"]
  1249. or custom_model.base_model_id == model["id"].split(":")[0]
  1250. ):
  1251. owned_by = model["owned_by"]
  1252. if "pipe" in model:
  1253. pipe = model["pipe"]
  1254. break
  1255. if custom_model.meta:
  1256. meta = custom_model.meta.model_dump()
  1257. if "actionIds" in meta:
  1258. action_ids.extend(meta["actionIds"])
  1259. models.append(
  1260. {
  1261. "id": f"{custom_model.id}",
  1262. "name": custom_model.name,
  1263. "object": "model",
  1264. "created": custom_model.created_at,
  1265. "owned_by": owned_by,
  1266. "info": custom_model.model_dump(),
  1267. "preset": True,
  1268. **({"pipe": pipe} if pipe is not None else {}),
  1269. "action_ids": action_ids,
  1270. }
  1271. )
  1272. # Process action_ids to get the actions
  1273. def get_action_items_from_module(function, module):
  1274. actions = []
  1275. if hasattr(module, "actions"):
  1276. actions = module.actions
  1277. return [
  1278. {
  1279. "id": f"{function.id}.{action['id']}",
  1280. "name": action.get("name", f"{function.name} ({action['id']})"),
  1281. "description": function.meta.description,
  1282. "icon_url": action.get(
  1283. "icon_url", function.meta.manifest.get("icon_url", None)
  1284. ),
  1285. }
  1286. for action in actions
  1287. ]
  1288. else:
  1289. return [
  1290. {
  1291. "id": function.id,
  1292. "name": function.name,
  1293. "description": function.meta.description,
  1294. "icon_url": function.meta.manifest.get("icon_url", None),
  1295. }
  1296. ]
  1297. def get_function_module_by_id(function_id):
  1298. if function_id in webui_app.state.FUNCTIONS:
  1299. function_module = webui_app.state.FUNCTIONS[function_id]
  1300. else:
  1301. function_module, _, _ = load_function_module_by_id(function_id)
  1302. webui_app.state.FUNCTIONS[function_id] = function_module
  1303. for model in models:
  1304. action_ids = [
  1305. action_id
  1306. for action_id in list(set(model.pop("action_ids", []) + global_action_ids))
  1307. if action_id in enabled_action_ids
  1308. ]
  1309. model["actions"] = []
  1310. for action_id in action_ids:
  1311. action_function = Functions.get_function_by_id(action_id)
  1312. if action_function is None:
  1313. raise Exception(f"Action not found: {action_id}")
  1314. function_module = get_function_module_by_id(action_id)
  1315. model["actions"].extend(
  1316. get_action_items_from_module(action_function, function_module)
  1317. )
  1318. log.debug(f"get_all_models() returned {len(models)} models")
  1319. return models
  1320. @app.get("/api/models")
  1321. async def get_models(user=Depends(get_verified_user)):
  1322. models = await get_all_models()
  1323. # Filter out filter pipelines
  1324. models = [
  1325. model
  1326. for model in models
  1327. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  1328. ]
  1329. model_order_list = webui_app.state.config.MODEL_ORDER_LIST
  1330. if model_order_list:
  1331. model_order_dict = {model_id: i for i, model_id in enumerate(model_order_list)}
  1332. # Sort models by order list priority, with fallback for those not in the list
  1333. models.sort(
  1334. key=lambda x: (model_order_dict.get(x["id"], float("inf")), x["name"])
  1335. )
  1336. # Filter out models that the user does not have access to
  1337. if user.role == "user" and not BYPASS_MODEL_ACCESS_CONTROL:
  1338. filtered_models = []
  1339. for model in models:
  1340. if model.get("arena"):
  1341. if has_access(
  1342. user.id,
  1343. type="read",
  1344. access_control=model.get("info", {})
  1345. .get("meta", {})
  1346. .get("access_control", {}),
  1347. ):
  1348. filtered_models.append(model)
  1349. continue
  1350. model_info = Models.get_model_by_id(model["id"])
  1351. if model_info:
  1352. if user.id == model_info.user_id or has_access(
  1353. user.id, type="read", access_control=model_info.access_control
  1354. ):
  1355. filtered_models.append(model)
  1356. models = filtered_models
  1357. log.debug(
  1358. f"/api/models returned filtered models accessible to the user: {json.dumps([model['id'] for model in models])}"
  1359. )
  1360. return {"data": models}
  1361. @app.get("/api/models/base")
  1362. async def get_base_models(user=Depends(get_admin_user)):
  1363. models = await get_all_base_models()
  1364. # Filter out arena models
  1365. models = [model for model in models if not model.get("arena", False)]
  1366. return {"data": models}
  1367. ##################################
  1368. #
  1369. # Chat Endpoints
  1370. #
  1371. ##################################
  1372. @app.post("/api/chat/completions")
  1373. async def generate_chat_completions(
  1374. request: Request,
  1375. form_data: dict,
  1376. user=Depends(get_verified_user),
  1377. bypass_filter: bool = False,
  1378. ):
  1379. if BYPASS_MODEL_ACCESS_CONTROL:
  1380. bypass_filter = True
  1381. model_list = request.state.models
  1382. models = {model["id"]: model for model in model_list}
  1383. model_id = form_data["model"]
  1384. if model_id not in models:
  1385. raise HTTPException(
  1386. status_code=status.HTTP_404_NOT_FOUND,
  1387. detail="Model not found",
  1388. )
  1389. model = models[model_id]
  1390. # Check if user has access to the model
  1391. if not bypass_filter and user.role == "user":
  1392. if model.get("arena"):
  1393. if not has_access(
  1394. user.id,
  1395. type="read",
  1396. access_control=model.get("info", {})
  1397. .get("meta", {})
  1398. .get("access_control", {}),
  1399. ):
  1400. raise HTTPException(
  1401. status_code=403,
  1402. detail="Model not found",
  1403. )
  1404. else:
  1405. model_info = Models.get_model_by_id(model_id)
  1406. if not model_info:
  1407. raise HTTPException(
  1408. status_code=404,
  1409. detail="Model not found",
  1410. )
  1411. elif not (
  1412. user.id == model_info.user_id
  1413. or has_access(
  1414. user.id, type="read", access_control=model_info.access_control
  1415. )
  1416. ):
  1417. raise HTTPException(
  1418. status_code=403,
  1419. detail="Model not found",
  1420. )
  1421. if model["owned_by"] == "arena":
  1422. model_ids = model.get("info", {}).get("meta", {}).get("model_ids")
  1423. filter_mode = model.get("info", {}).get("meta", {}).get("filter_mode")
  1424. if model_ids and filter_mode == "exclude":
  1425. model_ids = [
  1426. model["id"]
  1427. for model in await get_all_models()
  1428. if model.get("owned_by") != "arena" and model["id"] not in model_ids
  1429. ]
  1430. selected_model_id = None
  1431. if isinstance(model_ids, list) and model_ids:
  1432. selected_model_id = random.choice(model_ids)
  1433. else:
  1434. model_ids = [
  1435. model["id"]
  1436. for model in await get_all_models()
  1437. if model.get("owned_by") != "arena"
  1438. ]
  1439. selected_model_id = random.choice(model_ids)
  1440. form_data["model"] = selected_model_id
  1441. if form_data.get("stream") == True:
  1442. async def stream_wrapper(stream):
  1443. yield f"data: {json.dumps({'selected_model_id': selected_model_id})}\n\n"
  1444. async for chunk in stream:
  1445. yield chunk
  1446. response = await generate_chat_completions(
  1447. form_data, user, bypass_filter=True
  1448. )
  1449. return StreamingResponse(
  1450. stream_wrapper(response.body_iterator), media_type="text/event-stream"
  1451. )
  1452. else:
  1453. return {
  1454. **(
  1455. await generate_chat_completions(form_data, user, bypass_filter=True)
  1456. ),
  1457. "selected_model_id": selected_model_id,
  1458. }
  1459. if model.get("pipe"):
  1460. # Below does not require bypass_filter because this is the only route the uses this function and it is already bypassing the filter
  1461. return await generate_function_chat_completion(
  1462. form_data, user=user, models=models
  1463. )
  1464. if model["owned_by"] == "ollama":
  1465. # Using /ollama/api/chat endpoint
  1466. form_data = convert_payload_openai_to_ollama(form_data)
  1467. form_data = GenerateChatCompletionForm(**form_data)
  1468. response = await generate_ollama_chat_completion(
  1469. form_data=form_data, user=user, bypass_filter=bypass_filter
  1470. )
  1471. if form_data.stream:
  1472. response.headers["content-type"] = "text/event-stream"
  1473. return StreamingResponse(
  1474. convert_streaming_response_ollama_to_openai(response),
  1475. headers=dict(response.headers),
  1476. )
  1477. else:
  1478. return convert_response_ollama_to_openai(response)
  1479. else:
  1480. return await generate_openai_chat_completion(
  1481. form_data, user=user, bypass_filter=bypass_filter
  1482. )
  1483. @app.post("/api/chat/completed")
  1484. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  1485. model_list = await get_all_models()
  1486. models = {model["id"]: model for model in model_list}
  1487. data = form_data
  1488. model_id = data["model"]
  1489. if model_id not in models:
  1490. raise HTTPException(
  1491. status_code=status.HTTP_404_NOT_FOUND,
  1492. detail="Model not found",
  1493. )
  1494. model = models[model_id]
  1495. sorted_filters = get_sorted_filters(model_id, models)
  1496. if "pipeline" in model:
  1497. sorted_filters = [model] + sorted_filters
  1498. for filter in sorted_filters:
  1499. r = None
  1500. try:
  1501. urlIdx = filter["urlIdx"]
  1502. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1503. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1504. if key != "":
  1505. headers = {"Authorization": f"Bearer {key}"}
  1506. r = requests.post(
  1507. f"{url}/{filter['id']}/filter/outlet",
  1508. headers=headers,
  1509. json={
  1510. "user": {
  1511. "id": user.id,
  1512. "name": user.name,
  1513. "email": user.email,
  1514. "role": user.role,
  1515. },
  1516. "body": data,
  1517. },
  1518. )
  1519. r.raise_for_status()
  1520. data = r.json()
  1521. except Exception as e:
  1522. # Handle connection error here
  1523. print(f"Connection error: {e}")
  1524. if r is not None:
  1525. try:
  1526. res = r.json()
  1527. if "detail" in res:
  1528. return JSONResponse(
  1529. status_code=r.status_code,
  1530. content=res,
  1531. )
  1532. except Exception:
  1533. pass
  1534. else:
  1535. pass
  1536. __event_emitter__ = get_event_emitter(
  1537. {
  1538. "chat_id": data["chat_id"],
  1539. "message_id": data["id"],
  1540. "session_id": data["session_id"],
  1541. }
  1542. )
  1543. __event_call__ = get_event_call(
  1544. {
  1545. "chat_id": data["chat_id"],
  1546. "message_id": data["id"],
  1547. "session_id": data["session_id"],
  1548. }
  1549. )
  1550. def get_priority(function_id):
  1551. function = Functions.get_function_by_id(function_id)
  1552. if function is not None and hasattr(function, "valves"):
  1553. # TODO: Fix FunctionModel to include vavles
  1554. return (function.valves if function.valves else {}).get("priority", 0)
  1555. return 0
  1556. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  1557. if "info" in model and "meta" in model["info"]:
  1558. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  1559. filter_ids = list(set(filter_ids))
  1560. enabled_filter_ids = [
  1561. function.id
  1562. for function in Functions.get_functions_by_type("filter", active_only=True)
  1563. ]
  1564. filter_ids = [
  1565. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  1566. ]
  1567. # Sort filter_ids by priority, using the get_priority function
  1568. filter_ids.sort(key=get_priority)
  1569. for filter_id in filter_ids:
  1570. filter = Functions.get_function_by_id(filter_id)
  1571. if not filter:
  1572. continue
  1573. if filter_id in webui_app.state.FUNCTIONS:
  1574. function_module = webui_app.state.FUNCTIONS[filter_id]
  1575. else:
  1576. function_module, _, _ = load_function_module_by_id(filter_id)
  1577. webui_app.state.FUNCTIONS[filter_id] = function_module
  1578. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1579. valves = Functions.get_function_valves_by_id(filter_id)
  1580. function_module.valves = function_module.Valves(
  1581. **(valves if valves else {})
  1582. )
  1583. if not hasattr(function_module, "outlet"):
  1584. continue
  1585. try:
  1586. outlet = function_module.outlet
  1587. # Get the signature of the function
  1588. sig = inspect.signature(outlet)
  1589. params = {"body": data}
  1590. # Extra parameters to be passed to the function
  1591. extra_params = {
  1592. "__model__": model,
  1593. "__id__": filter_id,
  1594. "__event_emitter__": __event_emitter__,
  1595. "__event_call__": __event_call__,
  1596. }
  1597. # Add extra params in contained in function signature
  1598. for key, value in extra_params.items():
  1599. if key in sig.parameters:
  1600. params[key] = value
  1601. if "__user__" in sig.parameters:
  1602. __user__ = {
  1603. "id": user.id,
  1604. "email": user.email,
  1605. "name": user.name,
  1606. "role": user.role,
  1607. }
  1608. try:
  1609. if hasattr(function_module, "UserValves"):
  1610. __user__["valves"] = function_module.UserValves(
  1611. **Functions.get_user_valves_by_id_and_user_id(
  1612. filter_id, user.id
  1613. )
  1614. )
  1615. except Exception as e:
  1616. print(e)
  1617. params = {**params, "__user__": __user__}
  1618. if inspect.iscoroutinefunction(outlet):
  1619. data = await outlet(**params)
  1620. else:
  1621. data = outlet(**params)
  1622. except Exception as e:
  1623. print(f"Error: {e}")
  1624. return JSONResponse(
  1625. status_code=status.HTTP_400_BAD_REQUEST,
  1626. content={"detail": str(e)},
  1627. )
  1628. return data
  1629. @app.post("/api/chat/actions/{action_id}")
  1630. async def chat_action(action_id: str, form_data: dict, user=Depends(get_verified_user)):
  1631. if "." in action_id:
  1632. action_id, sub_action_id = action_id.split(".")
  1633. else:
  1634. sub_action_id = None
  1635. action = Functions.get_function_by_id(action_id)
  1636. if not action:
  1637. raise HTTPException(
  1638. status_code=status.HTTP_404_NOT_FOUND,
  1639. detail="Action not found",
  1640. )
  1641. model_list = await get_all_models()
  1642. models = {model["id"]: model for model in model_list}
  1643. data = form_data
  1644. model_id = data["model"]
  1645. if model_id not in models:
  1646. raise HTTPException(
  1647. status_code=status.HTTP_404_NOT_FOUND,
  1648. detail="Model not found",
  1649. )
  1650. model = models[model_id]
  1651. __event_emitter__ = get_event_emitter(
  1652. {
  1653. "chat_id": data["chat_id"],
  1654. "message_id": data["id"],
  1655. "session_id": data["session_id"],
  1656. }
  1657. )
  1658. __event_call__ = get_event_call(
  1659. {
  1660. "chat_id": data["chat_id"],
  1661. "message_id": data["id"],
  1662. "session_id": data["session_id"],
  1663. }
  1664. )
  1665. if action_id in webui_app.state.FUNCTIONS:
  1666. function_module = webui_app.state.FUNCTIONS[action_id]
  1667. else:
  1668. function_module, _, _ = load_function_module_by_id(action_id)
  1669. webui_app.state.FUNCTIONS[action_id] = function_module
  1670. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1671. valves = Functions.get_function_valves_by_id(action_id)
  1672. function_module.valves = function_module.Valves(**(valves if valves else {}))
  1673. if hasattr(function_module, "action"):
  1674. try:
  1675. action = function_module.action
  1676. # Get the signature of the function
  1677. sig = inspect.signature(action)
  1678. params = {"body": data}
  1679. # Extra parameters to be passed to the function
  1680. extra_params = {
  1681. "__model__": model,
  1682. "__id__": sub_action_id if sub_action_id is not None else action_id,
  1683. "__event_emitter__": __event_emitter__,
  1684. "__event_call__": __event_call__,
  1685. }
  1686. # Add extra params in contained in function signature
  1687. for key, value in extra_params.items():
  1688. if key in sig.parameters:
  1689. params[key] = value
  1690. if "__user__" in sig.parameters:
  1691. __user__ = {
  1692. "id": user.id,
  1693. "email": user.email,
  1694. "name": user.name,
  1695. "role": user.role,
  1696. }
  1697. try:
  1698. if hasattr(function_module, "UserValves"):
  1699. __user__["valves"] = function_module.UserValves(
  1700. **Functions.get_user_valves_by_id_and_user_id(
  1701. action_id, user.id
  1702. )
  1703. )
  1704. except Exception as e:
  1705. print(e)
  1706. params = {**params, "__user__": __user__}
  1707. if inspect.iscoroutinefunction(action):
  1708. data = await action(**params)
  1709. else:
  1710. data = action(**params)
  1711. except Exception as e:
  1712. print(f"Error: {e}")
  1713. return JSONResponse(
  1714. status_code=status.HTTP_400_BAD_REQUEST,
  1715. content={"detail": str(e)},
  1716. )
  1717. return data
  1718. ##################################
  1719. #
  1720. # Config Endpoints
  1721. #
  1722. ##################################
  1723. @app.get("/api/config")
  1724. async def get_app_config(request: Request):
  1725. user = None
  1726. if "token" in request.cookies:
  1727. token = request.cookies.get("token")
  1728. try:
  1729. data = decode_token(token)
  1730. except Exception as e:
  1731. log.debug(e)
  1732. raise HTTPException(
  1733. status_code=status.HTTP_401_UNAUTHORIZED,
  1734. detail="Invalid token",
  1735. )
  1736. if data is not None and "id" in data:
  1737. user = Users.get_user_by_id(data["id"])
  1738. onboarding = False
  1739. if user is None:
  1740. user_count = Users.get_num_users()
  1741. onboarding = user_count == 0
  1742. return {
  1743. **({"onboarding": True} if onboarding else {}),
  1744. "status": True,
  1745. "name": WEBUI_NAME,
  1746. "version": VERSION,
  1747. "default_locale": str(DEFAULT_LOCALE),
  1748. "oauth": {
  1749. "providers": {
  1750. name: config.get("name", name)
  1751. for name, config in OAUTH_PROVIDERS.items()
  1752. }
  1753. },
  1754. "features": {
  1755. "auth": WEBUI_AUTH,
  1756. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1757. "enable_ldap": webui_app.state.config.ENABLE_LDAP,
  1758. "enable_api_key": webui_app.state.config.ENABLE_API_KEY,
  1759. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1760. "enable_login_form": webui_app.state.config.ENABLE_LOGIN_FORM,
  1761. **(
  1762. {
  1763. "enable_web_search": retrieval_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1764. "enable_image_generation": images_app.state.config.ENABLED,
  1765. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1766. "enable_message_rating": webui_app.state.config.ENABLE_MESSAGE_RATING,
  1767. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1768. "enable_admin_chat_access": ENABLE_ADMIN_CHAT_ACCESS,
  1769. }
  1770. if user is not None
  1771. else {}
  1772. ),
  1773. },
  1774. **(
  1775. {
  1776. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1777. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1778. "audio": {
  1779. "tts": {
  1780. "engine": audio_app.state.config.TTS_ENGINE,
  1781. "voice": audio_app.state.config.TTS_VOICE,
  1782. "split_on": audio_app.state.config.TTS_SPLIT_ON,
  1783. },
  1784. "stt": {
  1785. "engine": audio_app.state.config.STT_ENGINE,
  1786. },
  1787. },
  1788. "file": {
  1789. "max_size": retrieval_app.state.config.FILE_MAX_SIZE,
  1790. "max_count": retrieval_app.state.config.FILE_MAX_COUNT,
  1791. },
  1792. "permissions": {**webui_app.state.config.USER_PERMISSIONS},
  1793. }
  1794. if user is not None
  1795. else {}
  1796. ),
  1797. }
  1798. class UrlForm(BaseModel):
  1799. url: str
  1800. @app.get("/api/webhook")
  1801. async def get_webhook_url(user=Depends(get_admin_user)):
  1802. return {
  1803. "url": app.state.config.WEBHOOK_URL,
  1804. }
  1805. @app.post("/api/webhook")
  1806. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1807. app.state.config.WEBHOOK_URL = form_data.url
  1808. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1809. return {"url": app.state.config.WEBHOOK_URL}
  1810. @app.get("/api/version")
  1811. async def get_app_version():
  1812. return {
  1813. "version": VERSION,
  1814. }
  1815. @app.get("/api/version/updates")
  1816. async def get_app_latest_release_version():
  1817. if OFFLINE_MODE:
  1818. log.debug(
  1819. f"Offline mode is enabled, returning current version as latest version"
  1820. )
  1821. return {"current": VERSION, "latest": VERSION}
  1822. try:
  1823. timeout = aiohttp.ClientTimeout(total=1)
  1824. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  1825. async with session.get(
  1826. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1827. ) as response:
  1828. response.raise_for_status()
  1829. data = await response.json()
  1830. latest_version = data["tag_name"]
  1831. return {"current": VERSION, "latest": latest_version[1:]}
  1832. except Exception as e:
  1833. log.debug(e)
  1834. return {"current": VERSION, "latest": VERSION}
  1835. @app.get("/api/changelog")
  1836. async def get_app_changelog():
  1837. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1838. ############################
  1839. # OAuth Login & Callback
  1840. ############################
  1841. # SessionMiddleware is used by authlib for oauth
  1842. if len(OAUTH_PROVIDERS) > 0:
  1843. app.add_middleware(
  1844. SessionMiddleware,
  1845. secret_key=WEBUI_SECRET_KEY,
  1846. session_cookie="oui-session",
  1847. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  1848. https_only=WEBUI_SESSION_COOKIE_SECURE,
  1849. )
  1850. @app.get("/oauth/{provider}/login")
  1851. async def oauth_login(provider: str, request: Request):
  1852. return await oauth_manager.handle_login(provider, request)
  1853. # OAuth login logic is as follows:
  1854. # 1. Attempt to find a user with matching subject ID, tied to the provider
  1855. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  1856. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  1857. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  1858. # - Email addresses are considered unique, so we fail registration if the email address is already taken
  1859. @app.get("/oauth/{provider}/callback")
  1860. async def oauth_callback(provider: str, request: Request, response: Response):
  1861. return await oauth_manager.handle_callback(provider, request, response)
  1862. @app.get("/manifest.json")
  1863. async def get_manifest_json():
  1864. return {
  1865. "name": WEBUI_NAME,
  1866. "short_name": WEBUI_NAME,
  1867. "description": "Open WebUI is an open, extensible, user-friendly interface for AI that adapts to your workflow.",
  1868. "start_url": "/",
  1869. "display": "standalone",
  1870. "background_color": "#343541",
  1871. "orientation": "natural",
  1872. "icons": [
  1873. {
  1874. "src": "/static/logo.png",
  1875. "type": "image/png",
  1876. "sizes": "500x500",
  1877. "purpose": "any",
  1878. },
  1879. {
  1880. "src": "/static/logo.png",
  1881. "type": "image/png",
  1882. "sizes": "500x500",
  1883. "purpose": "maskable",
  1884. },
  1885. ],
  1886. }
  1887. @app.get("/opensearch.xml")
  1888. async def get_opensearch_xml():
  1889. xml_content = rf"""
  1890. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1891. <ShortName>{WEBUI_NAME}</ShortName>
  1892. <Description>Search {WEBUI_NAME}</Description>
  1893. <InputEncoding>UTF-8</InputEncoding>
  1894. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/static/favicon.png</Image>
  1895. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1896. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1897. </OpenSearchDescription>
  1898. """
  1899. return Response(content=xml_content, media_type="application/xml")
  1900. @app.get("/health")
  1901. async def healthcheck():
  1902. return {"status": True}
  1903. @app.get("/health/db")
  1904. async def healthcheck_with_db():
  1905. Session.execute(text("SELECT 1;")).all()
  1906. return {"status": True}
  1907. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  1908. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  1909. if os.path.exists(FRONTEND_BUILD_DIR):
  1910. mimetypes.add_type("text/javascript", ".js")
  1911. app.mount(
  1912. "/",
  1913. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1914. name="spa-static-files",
  1915. )
  1916. else:
  1917. log.warning(
  1918. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1919. )