main.py 56 KB

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