main.py 68 KB

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