main.py 72 KB

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