main.py 82 KB

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