main.py 75 KB

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