main.py 70 KB

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