main.py 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307
  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 valves from the request body
  503. valves = None
  504. if "valves" in body:
  505. valves = body["valves"]
  506. del body["valves"]
  507. # Extract session_id, chat_id and message_id from the request body
  508. session_id = None
  509. if "session_id" in body:
  510. session_id = body["session_id"]
  511. del body["session_id"]
  512. chat_id = None
  513. if "chat_id" in body:
  514. chat_id = body["chat_id"]
  515. del body["chat_id"]
  516. message_id = None
  517. if "id" in body:
  518. message_id = body["id"]
  519. del body["id"]
  520. __event_emitter__ = await get_event_emitter(
  521. {"chat_id": chat_id, "message_id": message_id, "session_id": session_id}
  522. )
  523. __event_call__ = await get_event_call(
  524. {"chat_id": chat_id, "message_id": message_id, "session_id": session_id}
  525. )
  526. # Initialize data_items to store additional data to be sent to the client
  527. data_items = []
  528. # Initialize context, and citations
  529. contexts = []
  530. citations = []
  531. try:
  532. body, flags = await chat_completion_functions_handler(
  533. body, model, user, __event_emitter__, __event_call__
  534. )
  535. except Exception as e:
  536. return JSONResponse(
  537. status_code=status.HTTP_400_BAD_REQUEST,
  538. content={"detail": str(e)},
  539. )
  540. try:
  541. body, flags = await chat_completion_tools_handler(
  542. body, user, __event_emitter__, __event_call__
  543. )
  544. contexts.extend(flags.get("contexts", []))
  545. citations.extend(flags.get("citations", []))
  546. except Exception as e:
  547. print(e)
  548. pass
  549. try:
  550. body, flags = await chat_completion_files_handler(body)
  551. contexts.extend(flags.get("contexts", []))
  552. citations.extend(flags.get("citations", []))
  553. except Exception as e:
  554. print(e)
  555. pass
  556. # If context is not empty, insert it into the messages
  557. if len(contexts) > 0:
  558. context_string = "/n".join(contexts).strip()
  559. prompt = get_last_user_message(body["messages"])
  560. body["messages"] = add_or_update_system_message(
  561. rag_template(
  562. rag_app.state.config.RAG_TEMPLATE, context_string, prompt
  563. ),
  564. body["messages"],
  565. )
  566. # If there are citations, add them to the data_items
  567. if len(citations) > 0:
  568. data_items.append({"citations": citations})
  569. body["metadata"] = {
  570. "session_id": session_id,
  571. "chat_id": chat_id,
  572. "message_id": message_id,
  573. "valves": valves,
  574. }
  575. modified_body_bytes = json.dumps(body).encode("utf-8")
  576. # Replace the request body with the modified one
  577. request._body = modified_body_bytes
  578. # Set custom header to ensure content-length matches new body length
  579. request.headers.__dict__["_list"] = [
  580. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  581. *[
  582. (k, v)
  583. for k, v in request.headers.raw
  584. if k.lower() != b"content-length"
  585. ],
  586. ]
  587. response = await call_next(request)
  588. if isinstance(response, StreamingResponse):
  589. # If it's a streaming response, inject it as SSE event or NDJSON line
  590. content_type = response.headers.get("Content-Type")
  591. if "text/event-stream" in content_type:
  592. return StreamingResponse(
  593. self.openai_stream_wrapper(response.body_iterator, data_items),
  594. )
  595. if "application/x-ndjson" in content_type:
  596. return StreamingResponse(
  597. self.ollama_stream_wrapper(response.body_iterator, data_items),
  598. )
  599. return response
  600. else:
  601. return response
  602. # If it's not a chat completion request, just pass it through
  603. response = await call_next(request)
  604. return response
  605. async def _receive(self, body: bytes):
  606. return {"type": "http.request", "body": body, "more_body": False}
  607. async def openai_stream_wrapper(self, original_generator, data_items):
  608. for item in data_items:
  609. yield f"data: {json.dumps(item)}\n\n"
  610. async for data in original_generator:
  611. yield data
  612. async def ollama_stream_wrapper(self, original_generator, data_items):
  613. for item in data_items:
  614. yield f"{json.dumps(item)}\n"
  615. async for data in original_generator:
  616. yield data
  617. app.add_middleware(ChatCompletionMiddleware)
  618. ##################################
  619. #
  620. # Pipeline Middleware
  621. #
  622. ##################################
  623. def get_sorted_filters(model_id):
  624. filters = [
  625. model
  626. for model in app.state.MODELS.values()
  627. if "pipeline" in model
  628. and "type" in model["pipeline"]
  629. and model["pipeline"]["type"] == "filter"
  630. and (
  631. model["pipeline"]["pipelines"] == ["*"]
  632. or any(
  633. model_id == target_model_id
  634. for target_model_id in model["pipeline"]["pipelines"]
  635. )
  636. )
  637. ]
  638. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  639. return sorted_filters
  640. def filter_pipeline(payload, user):
  641. user = {"id": user.id, "email": user.email, "name": user.name, "role": user.role}
  642. model_id = payload["model"]
  643. sorted_filters = get_sorted_filters(model_id)
  644. model = app.state.MODELS[model_id]
  645. if "pipeline" in model:
  646. sorted_filters.append(model)
  647. for filter in sorted_filters:
  648. r = None
  649. try:
  650. urlIdx = filter["urlIdx"]
  651. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  652. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  653. if key != "":
  654. headers = {"Authorization": f"Bearer {key}"}
  655. r = requests.post(
  656. f"{url}/{filter['id']}/filter/inlet",
  657. headers=headers,
  658. json={
  659. "user": user,
  660. "body": payload,
  661. },
  662. )
  663. r.raise_for_status()
  664. payload = r.json()
  665. except Exception as e:
  666. # Handle connection error here
  667. print(f"Connection error: {e}")
  668. if r is not None:
  669. res = r.json()
  670. if "detail" in res:
  671. raise Exception(r.status_code, res["detail"])
  672. return payload
  673. class PipelineMiddleware(BaseHTTPMiddleware):
  674. async def dispatch(self, request: Request, call_next):
  675. if request.method == "POST" and (
  676. "/ollama/api/chat" in request.url.path
  677. or "/chat/completions" in request.url.path
  678. ):
  679. log.debug(f"request.url.path: {request.url.path}")
  680. # Read the original request body
  681. body = await request.body()
  682. # Decode body to string
  683. body_str = body.decode("utf-8")
  684. # Parse string to JSON
  685. data = json.loads(body_str) if body_str else {}
  686. user = get_current_user(
  687. request,
  688. get_http_authorization_cred(request.headers.get("Authorization")),
  689. )
  690. try:
  691. data = filter_pipeline(data, user)
  692. except Exception as e:
  693. return JSONResponse(
  694. status_code=e.args[0],
  695. content={"detail": e.args[1]},
  696. )
  697. modified_body_bytes = json.dumps(data).encode("utf-8")
  698. # Replace the request body with the modified one
  699. request._body = modified_body_bytes
  700. # Set custom header to ensure content-length matches new body length
  701. request.headers.__dict__["_list"] = [
  702. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  703. *[
  704. (k, v)
  705. for k, v in request.headers.raw
  706. if k.lower() != b"content-length"
  707. ],
  708. ]
  709. response = await call_next(request)
  710. return response
  711. async def _receive(self, body: bytes):
  712. return {"type": "http.request", "body": body, "more_body": False}
  713. app.add_middleware(PipelineMiddleware)
  714. app.add_middleware(
  715. CORSMiddleware,
  716. allow_origins=origins,
  717. allow_credentials=True,
  718. allow_methods=["*"],
  719. allow_headers=["*"],
  720. )
  721. @app.middleware("http")
  722. async def commit_session_after_request(request: Request, call_next):
  723. response = await call_next(request)
  724. log.debug("Commit session after request")
  725. Session.commit()
  726. return response
  727. @app.middleware("http")
  728. async def check_url(request: Request, call_next):
  729. if len(app.state.MODELS) == 0:
  730. await get_all_models()
  731. else:
  732. pass
  733. start_time = int(time.time())
  734. response = await call_next(request)
  735. process_time = int(time.time()) - start_time
  736. response.headers["X-Process-Time"] = str(process_time)
  737. return response
  738. @app.middleware("http")
  739. async def update_embedding_function(request: Request, call_next):
  740. response = await call_next(request)
  741. if "/embedding/update" in request.url.path:
  742. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  743. return response
  744. app.mount("/ws", socket_app)
  745. app.mount("/ollama", ollama_app)
  746. app.mount("/openai", openai_app)
  747. app.mount("/images/api/v1", images_app)
  748. app.mount("/audio/api/v1", audio_app)
  749. app.mount("/rag/api/v1", rag_app)
  750. app.mount("/api/v1", webui_app)
  751. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  752. async def get_all_models():
  753. # TODO: Optimize this function
  754. pipe_models = []
  755. openai_models = []
  756. ollama_models = []
  757. pipe_models = await get_pipe_models()
  758. if app.state.config.ENABLE_OPENAI_API:
  759. openai_models = await get_openai_models()
  760. openai_models = openai_models["data"]
  761. if app.state.config.ENABLE_OLLAMA_API:
  762. ollama_models = await get_ollama_models()
  763. ollama_models = [
  764. {
  765. "id": model["model"],
  766. "name": model["name"],
  767. "object": "model",
  768. "created": int(time.time()),
  769. "owned_by": "ollama",
  770. "ollama": model,
  771. }
  772. for model in ollama_models["models"]
  773. ]
  774. models = pipe_models + openai_models + ollama_models
  775. global_action_ids = [
  776. function.id for function in Functions.get_global_action_functions()
  777. ]
  778. enabled_action_ids = [
  779. function.id
  780. for function in Functions.get_functions_by_type("action", active_only=True)
  781. ]
  782. custom_models = Models.get_all_models()
  783. for custom_model in custom_models:
  784. if custom_model.base_model_id == None:
  785. for model in models:
  786. if (
  787. custom_model.id == model["id"]
  788. or custom_model.id == model["id"].split(":")[0]
  789. ):
  790. model["name"] = custom_model.name
  791. model["info"] = custom_model.model_dump()
  792. action_ids = [] + global_action_ids
  793. if "info" in model and "meta" in model["info"]:
  794. action_ids.extend(model["info"]["meta"].get("actionIds", []))
  795. action_ids = list(set(action_ids))
  796. action_ids = [
  797. action_id
  798. for action_id in action_ids
  799. if action_id in enabled_action_ids
  800. ]
  801. model["actions"] = []
  802. for action_id in action_ids:
  803. action = Functions.get_function_by_id(action_id)
  804. model["actions"].append(
  805. {
  806. "id": action_id,
  807. "name": action.name,
  808. "description": action.meta.description,
  809. "icon_url": action.meta.manifest.get("icon_url", None),
  810. }
  811. )
  812. else:
  813. owned_by = "openai"
  814. pipe = None
  815. actions = []
  816. for model in models:
  817. if (
  818. custom_model.base_model_id == model["id"]
  819. or custom_model.base_model_id == model["id"].split(":")[0]
  820. ):
  821. owned_by = model["owned_by"]
  822. if "pipe" in model:
  823. pipe = model["pipe"]
  824. action_ids = [] + global_action_ids
  825. if "info" in model and "meta" in model["info"]:
  826. action_ids.extend(model["info"]["meta"].get("actionIds", []))
  827. action_ids = list(set(action_ids))
  828. action_ids = [
  829. action_id
  830. for action_id in action_ids
  831. if action_id in enabled_action_ids
  832. ]
  833. actions = [
  834. {
  835. "id": action_id,
  836. "name": Functions.get_function_by_id(action_id).name,
  837. "description": Functions.get_function_by_id(
  838. action_id
  839. ).meta.description,
  840. }
  841. for action_id in action_ids
  842. ]
  843. break
  844. models.append(
  845. {
  846. "id": custom_model.id,
  847. "name": custom_model.name,
  848. "object": "model",
  849. "created": custom_model.created_at,
  850. "owned_by": owned_by,
  851. "info": custom_model.model_dump(),
  852. "preset": True,
  853. **({"pipe": pipe} if pipe is not None else {}),
  854. "actions": actions,
  855. }
  856. )
  857. app.state.MODELS = {model["id"]: model for model in models}
  858. webui_app.state.MODELS = app.state.MODELS
  859. return models
  860. @app.get("/api/models")
  861. async def get_models(user=Depends(get_verified_user)):
  862. models = await get_all_models()
  863. # Filter out filter pipelines
  864. models = [
  865. model
  866. for model in models
  867. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  868. ]
  869. if app.state.config.ENABLE_MODEL_FILTER:
  870. if user.role == "user":
  871. models = list(
  872. filter(
  873. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  874. models,
  875. )
  876. )
  877. return {"data": models}
  878. return {"data": models}
  879. @app.post("/api/chat/completions")
  880. async def generate_chat_completions(form_data: dict, user=Depends(get_verified_user)):
  881. model_id = form_data["model"]
  882. if model_id not in app.state.MODELS:
  883. raise HTTPException(
  884. status_code=status.HTTP_404_NOT_FOUND,
  885. detail="Model not found",
  886. )
  887. model = app.state.MODELS[model_id]
  888. # `task` field is used to determine the type of the request, e.g. `title_generation`, `query_generation`, etc.
  889. task = None
  890. if "task" in form_data:
  891. task = form_data["task"]
  892. del form_data["task"]
  893. if task:
  894. if "metadata" in form_data:
  895. form_data["metadata"]["task"] = task
  896. else:
  897. form_data["metadata"] = {"task": task}
  898. if model.get("pipe"):
  899. return await generate_function_chat_completion(form_data, user=user)
  900. if model["owned_by"] == "ollama":
  901. print("generate_ollama_chat_completion")
  902. return await generate_ollama_chat_completion(form_data, user=user)
  903. else:
  904. return await generate_openai_chat_completion(form_data, user=user)
  905. @app.post("/api/chat/completed")
  906. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  907. data = form_data
  908. model_id = data["model"]
  909. if model_id not in app.state.MODELS:
  910. raise HTTPException(
  911. status_code=status.HTTP_404_NOT_FOUND,
  912. detail="Model not found",
  913. )
  914. model = app.state.MODELS[model_id]
  915. sorted_filters = get_sorted_filters(model_id)
  916. if "pipeline" in model:
  917. sorted_filters = [model] + sorted_filters
  918. for filter in sorted_filters:
  919. r = None
  920. try:
  921. urlIdx = filter["urlIdx"]
  922. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  923. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  924. if key != "":
  925. headers = {"Authorization": f"Bearer {key}"}
  926. r = requests.post(
  927. f"{url}/{filter['id']}/filter/outlet",
  928. headers=headers,
  929. json={
  930. "user": {
  931. "id": user.id,
  932. "name": user.name,
  933. "email": user.email,
  934. "role": user.role,
  935. },
  936. "body": data,
  937. },
  938. )
  939. r.raise_for_status()
  940. data = r.json()
  941. except Exception as e:
  942. # Handle connection error here
  943. print(f"Connection error: {e}")
  944. if r is not None:
  945. try:
  946. res = r.json()
  947. if "detail" in res:
  948. return JSONResponse(
  949. status_code=r.status_code,
  950. content=res,
  951. )
  952. except:
  953. pass
  954. else:
  955. pass
  956. __event_emitter__ = await get_event_emitter(
  957. {
  958. "chat_id": data["chat_id"],
  959. "message_id": data["id"],
  960. "session_id": data["session_id"],
  961. }
  962. )
  963. __event_call__ = await get_event_call(
  964. {
  965. "chat_id": data["chat_id"],
  966. "message_id": data["id"],
  967. "session_id": data["session_id"],
  968. }
  969. )
  970. def get_priority(function_id):
  971. function = Functions.get_function_by_id(function_id)
  972. if function is not None and hasattr(function, "valves"):
  973. return (function.valves if function.valves else {}).get("priority", 0)
  974. return 0
  975. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  976. if "info" in model and "meta" in model["info"]:
  977. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  978. filter_ids = list(set(filter_ids))
  979. enabled_filter_ids = [
  980. function.id
  981. for function in Functions.get_functions_by_type("filter", active_only=True)
  982. ]
  983. filter_ids = [
  984. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  985. ]
  986. # Sort filter_ids by priority, using the get_priority function
  987. filter_ids.sort(key=get_priority)
  988. for filter_id in filter_ids:
  989. filter = Functions.get_function_by_id(filter_id)
  990. if not filter:
  991. continue
  992. if filter_id in webui_app.state.FUNCTIONS:
  993. function_module = webui_app.state.FUNCTIONS[filter_id]
  994. else:
  995. function_module, _, _ = load_function_module_by_id(filter_id)
  996. webui_app.state.FUNCTIONS[filter_id] = function_module
  997. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  998. valves = Functions.get_function_valves_by_id(filter_id)
  999. function_module.valves = function_module.Valves(
  1000. **(valves if valves else {})
  1001. )
  1002. if not hasattr(function_module, "outlet"):
  1003. continue
  1004. try:
  1005. outlet = function_module.outlet
  1006. # Get the signature of the function
  1007. sig = inspect.signature(outlet)
  1008. params = {"body": data}
  1009. # Extra parameters to be passed to the function
  1010. extra_params = {
  1011. "__model__": model,
  1012. "__id__": filter_id,
  1013. "__event_emitter__": __event_emitter__,
  1014. "__event_call__": __event_call__,
  1015. }
  1016. # Add extra params in contained in function signature
  1017. for key, value in extra_params.items():
  1018. if key in sig.parameters:
  1019. params[key] = value
  1020. if "__user__" in sig.parameters:
  1021. __user__ = {
  1022. "id": user.id,
  1023. "email": user.email,
  1024. "name": user.name,
  1025. "role": user.role,
  1026. }
  1027. try:
  1028. if hasattr(function_module, "UserValves"):
  1029. __user__["valves"] = function_module.UserValves(
  1030. **Functions.get_user_valves_by_id_and_user_id(
  1031. filter_id, user.id
  1032. )
  1033. )
  1034. except Exception as e:
  1035. print(e)
  1036. params = {**params, "__user__": __user__}
  1037. if inspect.iscoroutinefunction(outlet):
  1038. data = await outlet(**params)
  1039. else:
  1040. data = outlet(**params)
  1041. except Exception as e:
  1042. print(f"Error: {e}")
  1043. return JSONResponse(
  1044. status_code=status.HTTP_400_BAD_REQUEST,
  1045. content={"detail": str(e)},
  1046. )
  1047. return data
  1048. @app.post("/api/chat/actions/{action_id}")
  1049. async def chat_completed(
  1050. action_id: str, form_data: dict, user=Depends(get_verified_user)
  1051. ):
  1052. action = Functions.get_function_by_id(action_id)
  1053. if not action:
  1054. raise HTTPException(
  1055. status_code=status.HTTP_404_NOT_FOUND,
  1056. detail="Action not found",
  1057. )
  1058. data = form_data
  1059. model_id = data["model"]
  1060. if model_id not in app.state.MODELS:
  1061. raise HTTPException(
  1062. status_code=status.HTTP_404_NOT_FOUND,
  1063. detail="Model not found",
  1064. )
  1065. model = app.state.MODELS[model_id]
  1066. __event_emitter__ = await get_event_emitter(
  1067. {
  1068. "chat_id": data["chat_id"],
  1069. "message_id": data["id"],
  1070. "session_id": data["session_id"],
  1071. }
  1072. )
  1073. __event_call__ = await get_event_call(
  1074. {
  1075. "chat_id": data["chat_id"],
  1076. "message_id": data["id"],
  1077. "session_id": data["session_id"],
  1078. }
  1079. )
  1080. if action_id in webui_app.state.FUNCTIONS:
  1081. function_module = webui_app.state.FUNCTIONS[action_id]
  1082. else:
  1083. function_module, _, _ = load_function_module_by_id(action_id)
  1084. webui_app.state.FUNCTIONS[action_id] = function_module
  1085. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1086. valves = Functions.get_function_valves_by_id(action_id)
  1087. function_module.valves = function_module.Valves(**(valves if valves else {}))
  1088. if hasattr(function_module, "action"):
  1089. try:
  1090. action = function_module.action
  1091. # Get the signature of the function
  1092. sig = inspect.signature(action)
  1093. params = {"body": data}
  1094. # Extra parameters to be passed to the function
  1095. extra_params = {
  1096. "__model__": model,
  1097. "__id__": action_id,
  1098. "__event_emitter__": __event_emitter__,
  1099. "__event_call__": __event_call__,
  1100. }
  1101. # Add extra params in contained in function signature
  1102. for key, value in extra_params.items():
  1103. if key in sig.parameters:
  1104. params[key] = value
  1105. if "__user__" in sig.parameters:
  1106. __user__ = {
  1107. "id": user.id,
  1108. "email": user.email,
  1109. "name": user.name,
  1110. "role": user.role,
  1111. }
  1112. try:
  1113. if hasattr(function_module, "UserValves"):
  1114. __user__["valves"] = function_module.UserValves(
  1115. **Functions.get_user_valves_by_id_and_user_id(
  1116. action_id, user.id
  1117. )
  1118. )
  1119. except Exception as e:
  1120. print(e)
  1121. params = {**params, "__user__": __user__}
  1122. if inspect.iscoroutinefunction(action):
  1123. data = await action(**params)
  1124. else:
  1125. data = action(**params)
  1126. except Exception as e:
  1127. print(f"Error: {e}")
  1128. return JSONResponse(
  1129. status_code=status.HTTP_400_BAD_REQUEST,
  1130. content={"detail": str(e)},
  1131. )
  1132. return data
  1133. ##################################
  1134. #
  1135. # Task Endpoints
  1136. #
  1137. ##################################
  1138. # TODO: Refactor task API endpoints below into a separate file
  1139. @app.get("/api/task/config")
  1140. async def get_task_config(user=Depends(get_verified_user)):
  1141. return {
  1142. "TASK_MODEL": app.state.config.TASK_MODEL,
  1143. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1144. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1145. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1146. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  1147. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1148. }
  1149. class TaskConfigForm(BaseModel):
  1150. TASK_MODEL: Optional[str]
  1151. TASK_MODEL_EXTERNAL: Optional[str]
  1152. TITLE_GENERATION_PROMPT_TEMPLATE: str
  1153. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE: str
  1154. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD: int
  1155. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  1156. @app.post("/api/task/config/update")
  1157. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  1158. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  1159. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  1160. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  1161. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  1162. )
  1163. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  1164. form_data.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1165. )
  1166. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  1167. form_data.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  1168. )
  1169. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  1170. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1171. )
  1172. return {
  1173. "TASK_MODEL": app.state.config.TASK_MODEL,
  1174. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1175. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1176. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1177. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  1178. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1179. }
  1180. @app.post("/api/task/title/completions")
  1181. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  1182. print("generate_title")
  1183. model_id = form_data["model"]
  1184. if model_id not in app.state.MODELS:
  1185. raise HTTPException(
  1186. status_code=status.HTTP_404_NOT_FOUND,
  1187. detail="Model not found",
  1188. )
  1189. # Check if the user has a custom task model
  1190. # If the user has a custom task model, use that model
  1191. model_id = get_task_model_id(model_id)
  1192. print(model_id)
  1193. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  1194. content = title_generation_template(
  1195. template,
  1196. form_data["prompt"],
  1197. {
  1198. "name": user.name,
  1199. "location": user.info.get("location") if user.info else None,
  1200. },
  1201. )
  1202. payload = {
  1203. "model": model_id,
  1204. "messages": [{"role": "user", "content": content}],
  1205. "stream": False,
  1206. "max_tokens": 50,
  1207. "chat_id": form_data.get("chat_id", None),
  1208. "task": str(TASKS.TITLE_GENERATION),
  1209. }
  1210. log.debug(payload)
  1211. try:
  1212. payload = filter_pipeline(payload, user)
  1213. except Exception as e:
  1214. return JSONResponse(
  1215. status_code=e.args[0],
  1216. content={"detail": e.args[1]},
  1217. )
  1218. if "chat_id" in payload:
  1219. del payload["chat_id"]
  1220. return await generate_chat_completions(form_data=payload, user=user)
  1221. @app.post("/api/task/query/completions")
  1222. async def generate_search_query(form_data: dict, user=Depends(get_verified_user)):
  1223. print("generate_search_query")
  1224. if len(form_data["prompt"]) < app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD:
  1225. raise HTTPException(
  1226. status_code=status.HTTP_400_BAD_REQUEST,
  1227. detail=f"Skip search query generation for short prompts (< {app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD} characters)",
  1228. )
  1229. model_id = form_data["model"]
  1230. if model_id not in app.state.MODELS:
  1231. raise HTTPException(
  1232. status_code=status.HTTP_404_NOT_FOUND,
  1233. detail="Model not found",
  1234. )
  1235. # Check if the user has a custom task model
  1236. # If the user has a custom task model, use that model
  1237. model_id = get_task_model_id(model_id)
  1238. print(model_id)
  1239. template = app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1240. content = search_query_generation_template(
  1241. template, form_data["prompt"], {"name": user.name}
  1242. )
  1243. payload = {
  1244. "model": model_id,
  1245. "messages": [{"role": "user", "content": content}],
  1246. "stream": False,
  1247. "max_tokens": 30,
  1248. "task": str(TASKS.QUERY_GENERATION),
  1249. }
  1250. print(payload)
  1251. try:
  1252. payload = filter_pipeline(payload, user)
  1253. except Exception as e:
  1254. return JSONResponse(
  1255. status_code=e.args[0],
  1256. content={"detail": e.args[1]},
  1257. )
  1258. if "chat_id" in payload:
  1259. del payload["chat_id"]
  1260. return await generate_chat_completions(form_data=payload, user=user)
  1261. @app.post("/api/task/emoji/completions")
  1262. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  1263. print("generate_emoji")
  1264. model_id = form_data["model"]
  1265. if model_id not in app.state.MODELS:
  1266. raise HTTPException(
  1267. status_code=status.HTTP_404_NOT_FOUND,
  1268. detail="Model not found",
  1269. )
  1270. # Check if the user has a custom task model
  1271. # If the user has a custom task model, use that model
  1272. model_id = get_task_model_id(model_id)
  1273. print(model_id)
  1274. template = '''
  1275. 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., 😊, 😢, 😡, 😱).
  1276. Message: """{{prompt}}"""
  1277. '''
  1278. content = title_generation_template(
  1279. template,
  1280. form_data["prompt"],
  1281. {
  1282. "name": user.name,
  1283. "location": user.info.get("location") if user.info else None,
  1284. },
  1285. )
  1286. payload = {
  1287. "model": model_id,
  1288. "messages": [{"role": "user", "content": content}],
  1289. "stream": False,
  1290. "max_tokens": 4,
  1291. "chat_id": form_data.get("chat_id", None),
  1292. "task": str(TASKS.EMOJI_GENERATION),
  1293. }
  1294. log.debug(payload)
  1295. try:
  1296. payload = filter_pipeline(payload, user)
  1297. except Exception as e:
  1298. return JSONResponse(
  1299. status_code=e.args[0],
  1300. content={"detail": e.args[1]},
  1301. )
  1302. if "chat_id" in payload:
  1303. del payload["chat_id"]
  1304. return await generate_chat_completions(form_data=payload, user=user)
  1305. @app.post("/api/task/tools/completions")
  1306. async def get_tools_function_calling(form_data: dict, user=Depends(get_verified_user)):
  1307. print("get_tools_function_calling")
  1308. model_id = form_data["model"]
  1309. if model_id not in app.state.MODELS:
  1310. raise HTTPException(
  1311. status_code=status.HTTP_404_NOT_FOUND,
  1312. detail="Model not found",
  1313. )
  1314. # Check if the user has a custom task model
  1315. # If the user has a custom task model, use that model
  1316. model_id = get_task_model_id(model_id)
  1317. print(model_id)
  1318. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1319. try:
  1320. context, _, _ = await get_function_call_response(
  1321. form_data["messages"],
  1322. form_data.get("files", []),
  1323. form_data["tool_id"],
  1324. template,
  1325. model_id,
  1326. user,
  1327. )
  1328. return context
  1329. except Exception as e:
  1330. return JSONResponse(
  1331. status_code=e.args[0],
  1332. content={"detail": e.args[1]},
  1333. )
  1334. ##################################
  1335. #
  1336. # Pipelines Endpoints
  1337. #
  1338. ##################################
  1339. # TODO: Refactor pipelines API endpoints below into a separate file
  1340. @app.get("/api/pipelines/list")
  1341. async def get_pipelines_list(user=Depends(get_admin_user)):
  1342. responses = await get_openai_models(raw=True)
  1343. print(responses)
  1344. urlIdxs = [
  1345. idx
  1346. for idx, response in enumerate(responses)
  1347. if response != None and "pipelines" in response
  1348. ]
  1349. return {
  1350. "data": [
  1351. {
  1352. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  1353. "idx": urlIdx,
  1354. }
  1355. for urlIdx in urlIdxs
  1356. ]
  1357. }
  1358. @app.post("/api/pipelines/upload")
  1359. async def upload_pipeline(
  1360. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  1361. ):
  1362. print("upload_pipeline", urlIdx, file.filename)
  1363. # Check if the uploaded file is a python file
  1364. if not file.filename.endswith(".py"):
  1365. raise HTTPException(
  1366. status_code=status.HTTP_400_BAD_REQUEST,
  1367. detail="Only Python (.py) files are allowed.",
  1368. )
  1369. upload_folder = f"{CACHE_DIR}/pipelines"
  1370. os.makedirs(upload_folder, exist_ok=True)
  1371. file_path = os.path.join(upload_folder, file.filename)
  1372. r = None
  1373. try:
  1374. # Save the uploaded file
  1375. with open(file_path, "wb") as buffer:
  1376. shutil.copyfileobj(file.file, buffer)
  1377. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1378. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1379. headers = {"Authorization": f"Bearer {key}"}
  1380. with open(file_path, "rb") as f:
  1381. files = {"file": f}
  1382. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1383. r.raise_for_status()
  1384. data = r.json()
  1385. return {**data}
  1386. except Exception as e:
  1387. # Handle connection error here
  1388. print(f"Connection error: {e}")
  1389. detail = "Pipeline not found"
  1390. status_code = status.HTTP_404_NOT_FOUND
  1391. if r is not None:
  1392. status_code = r.status_code
  1393. try:
  1394. res = r.json()
  1395. if "detail" in res:
  1396. detail = res["detail"]
  1397. except:
  1398. pass
  1399. raise HTTPException(
  1400. status_code=status_code,
  1401. detail=detail,
  1402. )
  1403. finally:
  1404. # Ensure the file is deleted after the upload is completed or on failure
  1405. if os.path.exists(file_path):
  1406. os.remove(file_path)
  1407. class AddPipelineForm(BaseModel):
  1408. url: str
  1409. urlIdx: int
  1410. @app.post("/api/pipelines/add")
  1411. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1412. r = None
  1413. try:
  1414. urlIdx = form_data.urlIdx
  1415. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1416. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1417. headers = {"Authorization": f"Bearer {key}"}
  1418. r = requests.post(
  1419. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1420. )
  1421. r.raise_for_status()
  1422. data = r.json()
  1423. return {**data}
  1424. except Exception as e:
  1425. # Handle connection error here
  1426. print(f"Connection error: {e}")
  1427. detail = "Pipeline not found"
  1428. if r is not None:
  1429. try:
  1430. res = r.json()
  1431. if "detail" in res:
  1432. detail = res["detail"]
  1433. except:
  1434. pass
  1435. raise HTTPException(
  1436. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1437. detail=detail,
  1438. )
  1439. class DeletePipelineForm(BaseModel):
  1440. id: str
  1441. urlIdx: int
  1442. @app.delete("/api/pipelines/delete")
  1443. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1444. r = None
  1445. try:
  1446. urlIdx = form_data.urlIdx
  1447. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1448. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1449. headers = {"Authorization": f"Bearer {key}"}
  1450. r = requests.delete(
  1451. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1452. )
  1453. r.raise_for_status()
  1454. data = r.json()
  1455. return {**data}
  1456. except Exception as e:
  1457. # Handle connection error here
  1458. print(f"Connection error: {e}")
  1459. detail = "Pipeline not found"
  1460. if r is not None:
  1461. try:
  1462. res = r.json()
  1463. if "detail" in res:
  1464. detail = res["detail"]
  1465. except:
  1466. pass
  1467. raise HTTPException(
  1468. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1469. detail=detail,
  1470. )
  1471. @app.get("/api/pipelines")
  1472. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  1473. r = None
  1474. try:
  1475. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1476. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1477. headers = {"Authorization": f"Bearer {key}"}
  1478. r = requests.get(f"{url}/pipelines", headers=headers)
  1479. r.raise_for_status()
  1480. data = r.json()
  1481. return {**data}
  1482. except Exception as e:
  1483. # Handle connection error here
  1484. print(f"Connection error: {e}")
  1485. detail = "Pipeline not found"
  1486. if r is not None:
  1487. try:
  1488. res = r.json()
  1489. if "detail" in res:
  1490. detail = res["detail"]
  1491. except:
  1492. pass
  1493. raise HTTPException(
  1494. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1495. detail=detail,
  1496. )
  1497. @app.get("/api/pipelines/{pipeline_id}/valves")
  1498. async def get_pipeline_valves(
  1499. urlIdx: Optional[int],
  1500. pipeline_id: str,
  1501. user=Depends(get_admin_user),
  1502. ):
  1503. models = await get_all_models()
  1504. r = None
  1505. try:
  1506. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1507. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1508. headers = {"Authorization": f"Bearer {key}"}
  1509. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  1510. r.raise_for_status()
  1511. data = r.json()
  1512. return {**data}
  1513. except Exception as e:
  1514. # Handle connection error here
  1515. print(f"Connection error: {e}")
  1516. detail = "Pipeline not found"
  1517. if r is not None:
  1518. try:
  1519. res = r.json()
  1520. if "detail" in res:
  1521. detail = res["detail"]
  1522. except:
  1523. pass
  1524. raise HTTPException(
  1525. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1526. detail=detail,
  1527. )
  1528. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1529. async def get_pipeline_valves_spec(
  1530. urlIdx: Optional[int],
  1531. pipeline_id: str,
  1532. user=Depends(get_admin_user),
  1533. ):
  1534. models = await get_all_models()
  1535. r = None
  1536. try:
  1537. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1538. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1539. headers = {"Authorization": f"Bearer {key}"}
  1540. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  1541. r.raise_for_status()
  1542. data = r.json()
  1543. return {**data}
  1544. except Exception as e:
  1545. # Handle connection error here
  1546. print(f"Connection error: {e}")
  1547. detail = "Pipeline not found"
  1548. if r is not None:
  1549. try:
  1550. res = r.json()
  1551. if "detail" in res:
  1552. detail = res["detail"]
  1553. except:
  1554. pass
  1555. raise HTTPException(
  1556. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1557. detail=detail,
  1558. )
  1559. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1560. async def update_pipeline_valves(
  1561. urlIdx: Optional[int],
  1562. pipeline_id: str,
  1563. form_data: dict,
  1564. user=Depends(get_admin_user),
  1565. ):
  1566. models = await get_all_models()
  1567. r = None
  1568. try:
  1569. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1570. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1571. headers = {"Authorization": f"Bearer {key}"}
  1572. r = requests.post(
  1573. f"{url}/{pipeline_id}/valves/update",
  1574. headers=headers,
  1575. json={**form_data},
  1576. )
  1577. r.raise_for_status()
  1578. data = r.json()
  1579. return {**data}
  1580. except Exception as e:
  1581. # Handle connection error here
  1582. print(f"Connection error: {e}")
  1583. detail = "Pipeline not found"
  1584. if r is not None:
  1585. try:
  1586. res = r.json()
  1587. if "detail" in res:
  1588. detail = res["detail"]
  1589. except:
  1590. pass
  1591. raise HTTPException(
  1592. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1593. detail=detail,
  1594. )
  1595. ##################################
  1596. #
  1597. # Config Endpoints
  1598. #
  1599. ##################################
  1600. @app.get("/api/config")
  1601. async def get_app_config():
  1602. return {
  1603. "status": True,
  1604. "name": WEBUI_NAME,
  1605. "version": VERSION,
  1606. "default_locale": str(DEFAULT_LOCALE),
  1607. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1608. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1609. "features": {
  1610. "auth": WEBUI_AUTH,
  1611. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1612. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1613. "enable_login_form": webui_app.state.config.ENABLE_LOGIN_FORM,
  1614. "enable_web_search": rag_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1615. "enable_image_generation": images_app.state.config.ENABLED,
  1616. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1617. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1618. },
  1619. "audio": {
  1620. "tts": {
  1621. "engine": audio_app.state.config.TTS_ENGINE,
  1622. "voice": audio_app.state.config.TTS_VOICE,
  1623. },
  1624. "stt": {
  1625. "engine": audio_app.state.config.STT_ENGINE,
  1626. },
  1627. },
  1628. "oauth": {
  1629. "providers": {
  1630. name: config.get("name", name)
  1631. for name, config in OAUTH_PROVIDERS.items()
  1632. }
  1633. },
  1634. }
  1635. @app.get("/api/config/model/filter")
  1636. async def get_model_filter_config(user=Depends(get_admin_user)):
  1637. return {
  1638. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1639. "models": app.state.config.MODEL_FILTER_LIST,
  1640. }
  1641. class ModelFilterConfigForm(BaseModel):
  1642. enabled: bool
  1643. models: List[str]
  1644. @app.post("/api/config/model/filter")
  1645. async def update_model_filter_config(
  1646. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  1647. ):
  1648. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  1649. app.state.config.MODEL_FILTER_LIST = form_data.models
  1650. return {
  1651. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1652. "models": app.state.config.MODEL_FILTER_LIST,
  1653. }
  1654. # TODO: webhook endpoint should be under config endpoints
  1655. @app.get("/api/webhook")
  1656. async def get_webhook_url(user=Depends(get_admin_user)):
  1657. return {
  1658. "url": app.state.config.WEBHOOK_URL,
  1659. }
  1660. class UrlForm(BaseModel):
  1661. url: str
  1662. @app.post("/api/webhook")
  1663. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1664. app.state.config.WEBHOOK_URL = form_data.url
  1665. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1666. return {"url": app.state.config.WEBHOOK_URL}
  1667. @app.get("/api/version")
  1668. async def get_app_config():
  1669. return {
  1670. "version": VERSION,
  1671. }
  1672. @app.get("/api/changelog")
  1673. async def get_app_changelog():
  1674. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1675. @app.get("/api/version/updates")
  1676. async def get_app_latest_release_version():
  1677. try:
  1678. async with aiohttp.ClientSession(trust_env=True) as session:
  1679. async with session.get(
  1680. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1681. ) as response:
  1682. response.raise_for_status()
  1683. data = await response.json()
  1684. latest_version = data["tag_name"]
  1685. return {"current": VERSION, "latest": latest_version[1:]}
  1686. except aiohttp.ClientError as e:
  1687. raise HTTPException(
  1688. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  1689. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  1690. )
  1691. ############################
  1692. # OAuth Login & Callback
  1693. ############################
  1694. oauth = OAuth()
  1695. for provider_name, provider_config in OAUTH_PROVIDERS.items():
  1696. oauth.register(
  1697. name=provider_name,
  1698. client_id=provider_config["client_id"],
  1699. client_secret=provider_config["client_secret"],
  1700. server_metadata_url=provider_config["server_metadata_url"],
  1701. client_kwargs={
  1702. "scope": provider_config["scope"],
  1703. },
  1704. )
  1705. # SessionMiddleware is used by authlib for oauth
  1706. if len(OAUTH_PROVIDERS) > 0:
  1707. app.add_middleware(
  1708. SessionMiddleware,
  1709. secret_key=WEBUI_SECRET_KEY,
  1710. session_cookie="oui-session",
  1711. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  1712. https_only=WEBUI_SESSION_COOKIE_SECURE,
  1713. )
  1714. @app.get("/oauth/{provider}/login")
  1715. async def oauth_login(provider: str, request: Request):
  1716. if provider not in OAUTH_PROVIDERS:
  1717. raise HTTPException(404)
  1718. redirect_uri = request.url_for("oauth_callback", provider=provider)
  1719. return await oauth.create_client(provider).authorize_redirect(request, redirect_uri)
  1720. # OAuth login logic is as follows:
  1721. # 1. Attempt to find a user with matching subject ID, tied to the provider
  1722. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  1723. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  1724. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  1725. # - Email addresses are considered unique, so we fail registration if the email address is alreayd taken
  1726. @app.get("/oauth/{provider}/callback")
  1727. async def oauth_callback(provider: str, request: Request, response: Response):
  1728. if provider not in OAUTH_PROVIDERS:
  1729. raise HTTPException(404)
  1730. client = oauth.create_client(provider)
  1731. try:
  1732. token = await client.authorize_access_token(request)
  1733. except Exception as e:
  1734. log.warning(f"OAuth callback error: {e}")
  1735. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1736. user_data: UserInfo = token["userinfo"]
  1737. sub = user_data.get("sub")
  1738. if not sub:
  1739. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  1740. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1741. provider_sub = f"{provider}@{sub}"
  1742. email = user_data.get("email", "").lower()
  1743. # We currently mandate that email addresses are provided
  1744. if not email:
  1745. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  1746. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1747. # Check if the user exists
  1748. user = Users.get_user_by_oauth_sub(provider_sub)
  1749. if not user:
  1750. # If the user does not exist, check if merging is enabled
  1751. if OAUTH_MERGE_ACCOUNTS_BY_EMAIL.value:
  1752. # Check if the user exists by email
  1753. user = Users.get_user_by_email(email)
  1754. if user:
  1755. # Update the user with the new oauth sub
  1756. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  1757. if not user:
  1758. # If the user does not exist, check if signups are enabled
  1759. if ENABLE_OAUTH_SIGNUP.value:
  1760. # Check if an existing user with the same email already exists
  1761. existing_user = Users.get_user_by_email(user_data.get("email", "").lower())
  1762. if existing_user:
  1763. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  1764. picture_claim = webui_app.state.config.OAUTH_PICTURE_CLAIM
  1765. picture_url = user_data.get(picture_claim, "")
  1766. if picture_url:
  1767. # Download the profile image into a base64 string
  1768. try:
  1769. async with aiohttp.ClientSession() as session:
  1770. async with session.get(picture_url) as resp:
  1771. picture = await resp.read()
  1772. base64_encoded_picture = base64.b64encode(picture).decode(
  1773. "utf-8"
  1774. )
  1775. guessed_mime_type = mimetypes.guess_type(picture_url)[0]
  1776. if guessed_mime_type is None:
  1777. # assume JPG, browsers are tolerant enough of image formats
  1778. guessed_mime_type = "image/jpeg"
  1779. picture_url = f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  1780. except Exception as e:
  1781. log.error(f"Error downloading profile image '{picture_url}': {e}")
  1782. picture_url = ""
  1783. if not picture_url:
  1784. picture_url = "/user.png"
  1785. username_claim = webui_app.state.config.OAUTH_USERNAME_CLAIM
  1786. role = (
  1787. "admin"
  1788. if Users.get_num_users() == 0
  1789. else webui_app.state.config.DEFAULT_USER_ROLE
  1790. )
  1791. user = Auths.insert_new_auth(
  1792. email=email,
  1793. password=get_password_hash(
  1794. str(uuid.uuid4())
  1795. ), # Random password, not used
  1796. name=user_data.get(username_claim, "User"),
  1797. profile_image_url=picture_url,
  1798. role=role,
  1799. oauth_sub=provider_sub,
  1800. )
  1801. if webui_app.state.config.WEBHOOK_URL:
  1802. post_webhook(
  1803. webui_app.state.config.WEBHOOK_URL,
  1804. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1805. {
  1806. "action": "signup",
  1807. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1808. "user": user.model_dump_json(exclude_none=True),
  1809. },
  1810. )
  1811. else:
  1812. raise HTTPException(
  1813. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  1814. )
  1815. jwt_token = create_token(
  1816. data={"id": user.id},
  1817. expires_delta=parse_duration(webui_app.state.config.JWT_EXPIRES_IN),
  1818. )
  1819. # Set the cookie token
  1820. response.set_cookie(
  1821. key="token",
  1822. value=jwt_token,
  1823. httponly=True, # Ensures the cookie is not accessible via JavaScript
  1824. )
  1825. # Redirect back to the frontend with the JWT token
  1826. redirect_url = f"{request.base_url}auth#token={jwt_token}"
  1827. return RedirectResponse(url=redirect_url)
  1828. @app.get("/manifest.json")
  1829. async def get_manifest_json():
  1830. return {
  1831. "name": WEBUI_NAME,
  1832. "short_name": WEBUI_NAME,
  1833. "start_url": "/",
  1834. "display": "standalone",
  1835. "background_color": "#343541",
  1836. "orientation": "portrait-primary",
  1837. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  1838. }
  1839. @app.get("/opensearch.xml")
  1840. async def get_opensearch_xml():
  1841. xml_content = rf"""
  1842. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1843. <ShortName>{WEBUI_NAME}</ShortName>
  1844. <Description>Search {WEBUI_NAME}</Description>
  1845. <InputEncoding>UTF-8</InputEncoding>
  1846. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/static/favicon.png</Image>
  1847. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1848. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1849. </OpenSearchDescription>
  1850. """
  1851. return Response(content=xml_content, media_type="application/xml")
  1852. @app.get("/health")
  1853. async def healthcheck():
  1854. return {"status": True}
  1855. @app.get("/health/db")
  1856. async def healthcheck_with_db():
  1857. Session.execute(text("SELECT 1;")).all()
  1858. return {"status": True}
  1859. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  1860. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  1861. if os.path.exists(FRONTEND_BUILD_DIR):
  1862. mimetypes.add_type("text/javascript", ".js")
  1863. app.mount(
  1864. "/",
  1865. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1866. name="spa-static-files",
  1867. )
  1868. else:
  1869. log.warning(
  1870. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1871. )