main.py 71 KB

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