main.py 69 KB

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