main.py 71 KB

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