main.py 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691
  1. import asyncio
  2. import inspect
  3. import json
  4. import logging
  5. import mimetypes
  6. import os
  7. import shutil
  8. import sys
  9. import time
  10. import random
  11. from contextlib import asynccontextmanager
  12. from typing import Optional
  13. from aiocache import cached
  14. import aiohttp
  15. import requests
  16. from fastapi import (
  17. Depends,
  18. FastAPI,
  19. File,
  20. Form,
  21. HTTPException,
  22. Request,
  23. UploadFile,
  24. status,
  25. )
  26. from fastapi.middleware.cors import CORSMiddleware
  27. from fastapi.responses import JSONResponse, RedirectResponse
  28. from fastapi.staticfiles import StaticFiles
  29. from pydantic import BaseModel
  30. from sqlalchemy import text
  31. from starlette.exceptions import HTTPException as StarletteHTTPException
  32. from starlette.middleware.base import BaseHTTPMiddleware
  33. from starlette.middleware.sessions import SessionMiddleware
  34. from starlette.responses import Response, StreamingResponse
  35. from open_webui.apps.audio.main import app as audio_app
  36. from open_webui.apps.images.main import app as images_app
  37. from open_webui.apps.ollama.main import (
  38. app as ollama_app,
  39. get_all_models as get_ollama_models,
  40. generate_chat_completion as generate_ollama_chat_completion,
  41. GenerateChatCompletionForm,
  42. )
  43. from open_webui.apps.openai.main import (
  44. app as openai_app,
  45. generate_chat_completion as generate_openai_chat_completion,
  46. get_all_models as get_openai_models,
  47. get_all_models_responses as get_openai_models_responses,
  48. )
  49. from open_webui.apps.retrieval.main import app as retrieval_app
  50. from open_webui.apps.retrieval.utils import get_sources_from_files
  51. from open_webui.apps.socket.main import (
  52. app as socket_app,
  53. periodic_usage_pool_cleanup,
  54. get_event_call,
  55. get_event_emitter,
  56. )
  57. from open_webui.apps.webui.internal.db import Session
  58. from open_webui.apps.webui.main import (
  59. app as webui_app,
  60. generate_function_chat_completion,
  61. get_all_models as get_open_webui_models,
  62. )
  63. from open_webui.apps.webui.models.functions import Functions
  64. from open_webui.apps.webui.models.models import Models
  65. from open_webui.apps.webui.models.users import UserModel, Users
  66. from open_webui.apps.webui.utils import load_function_module_by_id
  67. from open_webui.config import (
  68. CACHE_DIR,
  69. CORS_ALLOW_ORIGIN,
  70. DEFAULT_LOCALE,
  71. ENABLE_ADMIN_CHAT_ACCESS,
  72. ENABLE_ADMIN_EXPORT,
  73. ENABLE_OLLAMA_API,
  74. ENABLE_OPENAI_API,
  75. ENABLE_TAGS_GENERATION,
  76. ENV,
  77. FRONTEND_BUILD_DIR,
  78. OAUTH_PROVIDERS,
  79. STATIC_DIR,
  80. TASK_MODEL,
  81. TASK_MODEL_EXTERNAL,
  82. ENABLE_SEARCH_QUERY_GENERATION,
  83. ENABLE_RETRIEVAL_QUERY_GENERATION,
  84. QUERY_GENERATION_PROMPT_TEMPLATE,
  85. DEFAULT_QUERY_GENERATION_PROMPT_TEMPLATE,
  86. TITLE_GENERATION_PROMPT_TEMPLATE,
  87. TAGS_GENERATION_PROMPT_TEMPLATE,
  88. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  89. WEBHOOK_URL,
  90. WEBUI_AUTH,
  91. WEBUI_NAME,
  92. AppConfig,
  93. reset_config,
  94. )
  95. from open_webui.constants import TASKS
  96. from open_webui.env import (
  97. CHANGELOG,
  98. GLOBAL_LOG_LEVEL,
  99. SAFE_MODE,
  100. SRC_LOG_LEVELS,
  101. VERSION,
  102. WEBUI_BUILD_HASH,
  103. WEBUI_SECRET_KEY,
  104. WEBUI_SESSION_COOKIE_SAME_SITE,
  105. WEBUI_SESSION_COOKIE_SECURE,
  106. WEBUI_URL,
  107. RESET_CONFIG_ON_START,
  108. OFFLINE_MODE,
  109. )
  110. from open_webui.utils.misc import (
  111. add_or_update_system_message,
  112. get_last_user_message,
  113. prepend_to_first_user_message_content,
  114. )
  115. from open_webui.utils.oauth import oauth_manager
  116. from open_webui.utils.payload import convert_payload_openai_to_ollama
  117. from open_webui.utils.response import (
  118. convert_response_ollama_to_openai,
  119. convert_streaming_response_ollama_to_openai,
  120. )
  121. from open_webui.utils.security_headers import SecurityHeadersMiddleware
  122. from open_webui.utils.task import (
  123. rag_template,
  124. title_generation_template,
  125. query_generation_template,
  126. tags_generation_template,
  127. emoji_generation_template,
  128. moa_response_generation_template,
  129. tools_function_calling_generation_template,
  130. )
  131. from open_webui.utils.tools import get_tools
  132. from open_webui.utils.utils import (
  133. decode_token,
  134. get_admin_user,
  135. get_current_user,
  136. get_http_authorization_cred,
  137. get_verified_user,
  138. )
  139. from open_webui.utils.access_control import has_access
  140. if SAFE_MODE:
  141. print("SAFE MODE ENABLED")
  142. Functions.deactivate_all_functions()
  143. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  144. log = logging.getLogger(__name__)
  145. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  146. class SPAStaticFiles(StaticFiles):
  147. async def get_response(self, path: str, scope):
  148. try:
  149. return await super().get_response(path, scope)
  150. except (HTTPException, StarletteHTTPException) as ex:
  151. if ex.status_code == 404:
  152. return await super().get_response("index.html", scope)
  153. else:
  154. raise ex
  155. print(
  156. rf"""
  157. ___ __ __ _ _ _ ___
  158. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  159. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  160. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  161. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  162. |_|
  163. v{VERSION} - building the best open-source AI user interface.
  164. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  165. https://github.com/open-webui/open-webui
  166. """
  167. )
  168. @asynccontextmanager
  169. async def lifespan(app: FastAPI):
  170. if RESET_CONFIG_ON_START:
  171. reset_config()
  172. asyncio.create_task(periodic_usage_pool_cleanup())
  173. yield
  174. app = FastAPI(
  175. docs_url="/docs" if ENV == "dev" else None,
  176. openapi_url="/openapi.json" if ENV == "dev" else None,
  177. redoc_url=None,
  178. lifespan=lifespan,
  179. )
  180. app.state.config = AppConfig()
  181. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  182. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  183. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  184. app.state.config.TASK_MODEL = TASK_MODEL
  185. app.state.config.TASK_MODEL_EXTERNAL = TASK_MODEL_EXTERNAL
  186. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = TITLE_GENERATION_PROMPT_TEMPLATE
  187. app.state.config.ENABLE_TAGS_GENERATION = ENABLE_TAGS_GENERATION
  188. app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE = TAGS_GENERATION_PROMPT_TEMPLATE
  189. app.state.config.ENABLE_SEARCH_QUERY_GENERATION = ENABLE_SEARCH_QUERY_GENERATION
  190. app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION = ENABLE_RETRIEVAL_QUERY_GENERATION
  191. app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE = QUERY_GENERATION_PROMPT_TEMPLATE
  192. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  193. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  194. )
  195. ##################################
  196. #
  197. # ChatCompletion Middleware
  198. #
  199. ##################################
  200. def get_filter_function_ids(model):
  201. def get_priority(function_id):
  202. function = Functions.get_function_by_id(function_id)
  203. if function is not None and hasattr(function, "valves"):
  204. # TODO: Fix FunctionModel
  205. return (function.valves if function.valves else {}).get("priority", 0)
  206. return 0
  207. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  208. if "info" in model and "meta" in model["info"]:
  209. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  210. filter_ids = list(set(filter_ids))
  211. enabled_filter_ids = [
  212. function.id
  213. for function in Functions.get_functions_by_type("filter", active_only=True)
  214. ]
  215. filter_ids = [
  216. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  217. ]
  218. filter_ids.sort(key=get_priority)
  219. return filter_ids
  220. async def chat_completion_filter_functions_handler(body, model, extra_params):
  221. skip_files = None
  222. filter_ids = get_filter_function_ids(model)
  223. for filter_id in filter_ids:
  224. filter = Functions.get_function_by_id(filter_id)
  225. if not filter:
  226. continue
  227. if filter_id in webui_app.state.FUNCTIONS:
  228. function_module = webui_app.state.FUNCTIONS[filter_id]
  229. else:
  230. function_module, _, _ = load_function_module_by_id(filter_id)
  231. webui_app.state.FUNCTIONS[filter_id] = function_module
  232. # Check if the function has a file_handler variable
  233. if hasattr(function_module, "file_handler"):
  234. skip_files = function_module.file_handler
  235. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  236. valves = Functions.get_function_valves_by_id(filter_id)
  237. function_module.valves = function_module.Valves(
  238. **(valves if valves else {})
  239. )
  240. if not hasattr(function_module, "inlet"):
  241. continue
  242. try:
  243. inlet = function_module.inlet
  244. # Get the signature of the function
  245. sig = inspect.signature(inlet)
  246. params = {"body": body} | {
  247. k: v
  248. for k, v in {
  249. **extra_params,
  250. "__model__": model,
  251. "__id__": filter_id,
  252. }.items()
  253. if k in sig.parameters
  254. }
  255. if "__user__" in params and hasattr(function_module, "UserValves"):
  256. try:
  257. params["__user__"]["valves"] = function_module.UserValves(
  258. **Functions.get_user_valves_by_id_and_user_id(
  259. filter_id, params["__user__"]["id"]
  260. )
  261. )
  262. except Exception as e:
  263. print(e)
  264. if inspect.iscoroutinefunction(inlet):
  265. body = await inlet(**params)
  266. else:
  267. body = inlet(**params)
  268. except Exception as e:
  269. print(f"Error: {e}")
  270. raise e
  271. if skip_files and "files" in body.get("metadata", {}):
  272. del body["metadata"]["files"]
  273. return body, {}
  274. def get_tools_function_calling_payload(messages, task_model_id, content):
  275. user_message = get_last_user_message(messages)
  276. history = "\n".join(
  277. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  278. for message in messages[::-1][:4]
  279. )
  280. prompt = f"History:\n{history}\nQuery: {user_message}"
  281. return {
  282. "model": task_model_id,
  283. "messages": [
  284. {"role": "system", "content": content},
  285. {"role": "user", "content": f"Query: {prompt}"},
  286. ],
  287. "stream": False,
  288. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  289. }
  290. async def get_content_from_response(response) -> Optional[str]:
  291. content = None
  292. if hasattr(response, "body_iterator"):
  293. async for chunk in response.body_iterator:
  294. data = json.loads(chunk.decode("utf-8"))
  295. content = data["choices"][0]["message"]["content"]
  296. # Cleanup any remaining background tasks if necessary
  297. if response.background is not None:
  298. await response.background()
  299. else:
  300. content = response["choices"][0]["message"]["content"]
  301. return content
  302. def get_task_model_id(
  303. default_model_id: str, task_model: str, task_model_external: str, models
  304. ) -> str:
  305. # Set the task model
  306. task_model_id = default_model_id
  307. # Check if the user has a custom task model and use that model
  308. if models[task_model_id]["owned_by"] == "ollama":
  309. if task_model and task_model in models:
  310. task_model_id = task_model
  311. else:
  312. if task_model_external and task_model_external in models:
  313. task_model_id = task_model_external
  314. return task_model_id
  315. async def chat_completion_tools_handler(
  316. body: dict, user: UserModel, models, extra_params: dict
  317. ) -> tuple[dict, dict]:
  318. # If tool_ids field is present, call the functions
  319. metadata = body.get("metadata", {})
  320. tool_ids = metadata.get("tool_ids", None)
  321. log.debug(f"{tool_ids=}")
  322. if not tool_ids:
  323. return body, {}
  324. skip_files = False
  325. sources = []
  326. task_model_id = get_task_model_id(
  327. body["model"],
  328. app.state.config.TASK_MODEL,
  329. app.state.config.TASK_MODEL_EXTERNAL,
  330. models,
  331. )
  332. tools = get_tools(
  333. webui_app,
  334. tool_ids,
  335. user,
  336. {
  337. **extra_params,
  338. "__model__": models[task_model_id],
  339. "__messages__": body["messages"],
  340. "__files__": metadata.get("files", []),
  341. },
  342. )
  343. log.info(f"{tools=}")
  344. specs = [tool["spec"] for tool in tools.values()]
  345. tools_specs = json.dumps(specs)
  346. if app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE != "":
  347. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  348. else:
  349. template = """Available Tools: {{TOOLS}}\nReturn an empty string if no tools match the query. If a function tool matches, construct and return a JSON object in the format {\"name\": \"functionName\", \"parameters\": {\"requiredFunctionParamKey\": \"requiredFunctionParamValue\"}} using the appropriate tool and its parameters. Only return the object and limit the response to the JSON object without additional text."""
  350. tools_function_calling_prompt = tools_function_calling_generation_template(
  351. template, tools_specs
  352. )
  353. log.info(f"{tools_function_calling_prompt=}")
  354. payload = get_tools_function_calling_payload(
  355. body["messages"], task_model_id, tools_function_calling_prompt
  356. )
  357. try:
  358. payload = filter_pipeline(payload, user, models)
  359. except Exception as e:
  360. raise e
  361. try:
  362. response = await generate_chat_completions(form_data=payload, user=user)
  363. log.debug(f"{response=}")
  364. content = await get_content_from_response(response)
  365. log.debug(f"{content=}")
  366. if not content:
  367. return body, {}
  368. try:
  369. content = content[content.find("{") : content.rfind("}") + 1]
  370. if not content:
  371. raise Exception("No JSON object found in the response")
  372. result = json.loads(content)
  373. tool_function_name = result.get("name", None)
  374. if tool_function_name not in tools:
  375. return body, {}
  376. tool_function_params = result.get("parameters", {})
  377. try:
  378. required_params = (
  379. tools[tool_function_name]
  380. .get("spec", {})
  381. .get("parameters", {})
  382. .get("required", [])
  383. )
  384. tool_function = tools[tool_function_name]["callable"]
  385. tool_function_params = {
  386. k: v
  387. for k, v in tool_function_params.items()
  388. if k in required_params
  389. }
  390. tool_output = await tool_function(**tool_function_params)
  391. except Exception as e:
  392. tool_output = str(e)
  393. print(tools[tool_function_name]["citation"])
  394. if isinstance(tool_output, str):
  395. if tools[tool_function_name]["citation"]:
  396. sources.append(
  397. {
  398. "source": {
  399. "name": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  400. },
  401. "document": [tool_output],
  402. "metadata": [
  403. {
  404. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  405. }
  406. ],
  407. }
  408. )
  409. else:
  410. sources.append(
  411. {
  412. "source": {},
  413. "document": [tool_output],
  414. "metadata": [
  415. {
  416. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  417. }
  418. ],
  419. }
  420. )
  421. if tools[tool_function_name]["file_handler"]:
  422. skip_files = True
  423. except Exception as e:
  424. log.exception(f"Error: {e}")
  425. content = None
  426. except Exception as e:
  427. log.exception(f"Error: {e}")
  428. content = None
  429. log.debug(f"tool_contexts: {sources}")
  430. if skip_files and "files" in body.get("metadata", {}):
  431. del body["metadata"]["files"]
  432. return body, {"sources": sources}
  433. async def chat_completion_files_handler(
  434. body: dict, user: UserModel
  435. ) -> tuple[dict, dict[str, list]]:
  436. sources = []
  437. if files := body.get("metadata", {}).get("files", None):
  438. try:
  439. queries_response = await generate_queries(
  440. {
  441. "model": body["model"],
  442. "messages": body["messages"],
  443. "type": "retrieval",
  444. },
  445. user,
  446. )
  447. queries_response = queries_response["choices"][0]["message"]["content"]
  448. try:
  449. bracket_start = queries_response.find("{")
  450. bracket_end = queries_response.rfind("}") + 1
  451. if bracket_start == -1 or bracket_end == -1:
  452. raise Exception("No JSON object found in the response")
  453. queries_response = queries_response[bracket_start:bracket_end]
  454. queries_response = json.loads(queries_response)
  455. except Exception as e:
  456. queries_response = {"queries": [queries_response]}
  457. queries = queries_response.get("queries", [])
  458. except Exception as e:
  459. queries = []
  460. if len(queries) == 0:
  461. queries = [get_last_user_message(body["messages"])]
  462. sources = get_sources_from_files(
  463. files=files,
  464. queries=queries,
  465. embedding_function=retrieval_app.state.EMBEDDING_FUNCTION,
  466. k=retrieval_app.state.config.TOP_K,
  467. reranking_function=retrieval_app.state.sentence_transformer_rf,
  468. r=retrieval_app.state.config.RELEVANCE_THRESHOLD,
  469. hybrid_search=retrieval_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  470. )
  471. log.debug(f"rag_contexts:sources: {sources}")
  472. return body, {"sources": sources}
  473. def is_chat_completion_request(request):
  474. return request.method == "POST" and any(
  475. endpoint in request.url.path
  476. for endpoint in ["/ollama/api/chat", "/chat/completions"]
  477. )
  478. async def get_body_and_model_and_user(request, models):
  479. # Read the original request body
  480. body = await request.body()
  481. body_str = body.decode("utf-8")
  482. body = json.loads(body_str) if body_str else {}
  483. model_id = body["model"]
  484. if model_id not in models:
  485. raise Exception("Model not found")
  486. model = models[model_id]
  487. user = get_current_user(
  488. request,
  489. get_http_authorization_cred(request.headers.get("Authorization")),
  490. )
  491. return body, model, user
  492. class ChatCompletionMiddleware(BaseHTTPMiddleware):
  493. async def dispatch(self, request: Request, call_next):
  494. if not is_chat_completion_request(request):
  495. return await call_next(request)
  496. log.debug(f"request.url.path: {request.url.path}")
  497. model_list = await get_all_models()
  498. models = {model["id"]: model for model in model_list}
  499. try:
  500. body, model, user = await get_body_and_model_and_user(request, models)
  501. except Exception as e:
  502. return JSONResponse(
  503. status_code=status.HTTP_400_BAD_REQUEST,
  504. content={"detail": str(e)},
  505. )
  506. model_info = Models.get_model_by_id(model["id"])
  507. if user.role == "user":
  508. if model.get("arena"):
  509. if not has_access(
  510. user.id,
  511. type="read",
  512. access_control=model.get("info", {})
  513. .get("meta", {})
  514. .get("access_control", {}),
  515. ):
  516. raise HTTPException(
  517. status_code=403,
  518. detail="Model not found",
  519. )
  520. else:
  521. if not model_info:
  522. return JSONResponse(
  523. status_code=status.HTTP_404_NOT_FOUND,
  524. content={"detail": "Model not found"},
  525. )
  526. elif not (
  527. user.id == model_info.user_id
  528. or has_access(
  529. user.id, type="read", access_control=model_info.access_control
  530. )
  531. ):
  532. return JSONResponse(
  533. status_code=status.HTTP_403_FORBIDDEN,
  534. content={"detail": "User does not have access to the model"},
  535. )
  536. metadata = {
  537. "chat_id": body.pop("chat_id", None),
  538. "message_id": body.pop("id", None),
  539. "session_id": body.pop("session_id", None),
  540. "tool_ids": body.get("tool_ids", None),
  541. "files": body.get("files", None),
  542. }
  543. body["metadata"] = metadata
  544. extra_params = {
  545. "__event_emitter__": get_event_emitter(metadata),
  546. "__event_call__": get_event_call(metadata),
  547. "__user__": {
  548. "id": user.id,
  549. "email": user.email,
  550. "name": user.name,
  551. "role": user.role,
  552. },
  553. "__metadata__": metadata,
  554. }
  555. # Initialize data_items to store additional data to be sent to the client
  556. # Initialize contexts and citation
  557. data_items = []
  558. sources = []
  559. try:
  560. body, flags = await chat_completion_filter_functions_handler(
  561. body, model, extra_params
  562. )
  563. except Exception as e:
  564. return JSONResponse(
  565. status_code=status.HTTP_400_BAD_REQUEST,
  566. content={"detail": str(e)},
  567. )
  568. tool_ids = body.pop("tool_ids", None)
  569. files = body.pop("files", None)
  570. metadata = {
  571. **metadata,
  572. "tool_ids": tool_ids,
  573. "files": files,
  574. }
  575. body["metadata"] = metadata
  576. try:
  577. body, flags = await chat_completion_tools_handler(
  578. body, user, models, extra_params
  579. )
  580. sources.extend(flags.get("sources", []))
  581. except Exception as e:
  582. log.exception(e)
  583. try:
  584. body, flags = await chat_completion_files_handler(body, user)
  585. sources.extend(flags.get("sources", []))
  586. except Exception as e:
  587. log.exception(e)
  588. # If context is not empty, insert it into the messages
  589. if len(sources) > 0:
  590. context_string = ""
  591. for source_idx, source in enumerate(sources):
  592. source_id = source.get("source", {}).get("name", "")
  593. if "document" in source:
  594. for doc_idx, doc_context in enumerate(source["document"]):
  595. metadata = source.get("metadata")
  596. doc_source_id = None
  597. if metadata:
  598. doc_source_id = metadata[doc_idx].get("source", source_id)
  599. if source_id:
  600. context_string += f"<source><source_id>{doc_source_id if doc_source_id is not None else source_id}</source_id><source_context>{doc_context}</source_context></source>\n"
  601. else:
  602. # If there is no source_id, then do not include the source_id tag
  603. context_string += f"<source><source_context>{doc_context}</source_context></source>\n"
  604. context_string = context_string.strip()
  605. prompt = get_last_user_message(body["messages"])
  606. if prompt is None:
  607. raise Exception("No user message found")
  608. if (
  609. retrieval_app.state.config.RELEVANCE_THRESHOLD == 0
  610. and context_string.strip() == ""
  611. ):
  612. log.debug(
  613. f"With a 0 relevancy threshold for RAG, the context cannot be empty"
  614. )
  615. # Workaround for Ollama 2.0+ system prompt issue
  616. # TODO: replace with add_or_update_system_message
  617. if model["owned_by"] == "ollama":
  618. body["messages"] = prepend_to_first_user_message_content(
  619. rag_template(
  620. retrieval_app.state.config.RAG_TEMPLATE, context_string, prompt
  621. ),
  622. body["messages"],
  623. )
  624. else:
  625. body["messages"] = add_or_update_system_message(
  626. rag_template(
  627. retrieval_app.state.config.RAG_TEMPLATE, context_string, prompt
  628. ),
  629. body["messages"],
  630. )
  631. # If there are citations, add them to the data_items
  632. sources = [
  633. source for source in sources if source.get("source", {}).get("name", "")
  634. ]
  635. if len(sources) > 0:
  636. data_items.append({"sources": sources})
  637. modified_body_bytes = json.dumps(body).encode("utf-8")
  638. # Replace the request body with the modified one
  639. request._body = modified_body_bytes
  640. # Set custom header to ensure content-length matches new body length
  641. request.headers.__dict__["_list"] = [
  642. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  643. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  644. ]
  645. response = await call_next(request)
  646. if not isinstance(response, StreamingResponse):
  647. return response
  648. content_type = response.headers["Content-Type"]
  649. is_openai = "text/event-stream" in content_type
  650. is_ollama = "application/x-ndjson" in content_type
  651. if not is_openai and not is_ollama:
  652. return response
  653. def wrap_item(item):
  654. return f"data: {item}\n\n" if is_openai else f"{item}\n"
  655. async def stream_wrapper(original_generator, data_items):
  656. for item in data_items:
  657. yield wrap_item(json.dumps(item))
  658. async for data in original_generator:
  659. yield data
  660. return StreamingResponse(
  661. stream_wrapper(response.body_iterator, data_items),
  662. headers=dict(response.headers),
  663. )
  664. async def _receive(self, body: bytes):
  665. return {"type": "http.request", "body": body, "more_body": False}
  666. app.add_middleware(ChatCompletionMiddleware)
  667. ##################################
  668. #
  669. # Pipeline Middleware
  670. #
  671. ##################################
  672. def get_sorted_filters(model_id, models):
  673. filters = [
  674. model
  675. for model in models.values()
  676. if "pipeline" in model
  677. and "type" in model["pipeline"]
  678. and model["pipeline"]["type"] == "filter"
  679. and (
  680. model["pipeline"]["pipelines"] == ["*"]
  681. or any(
  682. model_id == target_model_id
  683. for target_model_id in model["pipeline"]["pipelines"]
  684. )
  685. )
  686. ]
  687. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  688. return sorted_filters
  689. def filter_pipeline(payload, user, models):
  690. user = {"id": user.id, "email": user.email, "name": user.name, "role": user.role}
  691. model_id = payload["model"]
  692. sorted_filters = get_sorted_filters(model_id, models)
  693. model = models[model_id]
  694. if "pipeline" in model:
  695. sorted_filters.append(model)
  696. for filter in sorted_filters:
  697. r = None
  698. try:
  699. urlIdx = filter["urlIdx"]
  700. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  701. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  702. if key == "":
  703. continue
  704. headers = {"Authorization": f"Bearer {key}"}
  705. r = requests.post(
  706. f"{url}/{filter['id']}/filter/inlet",
  707. headers=headers,
  708. json={
  709. "user": user,
  710. "body": payload,
  711. },
  712. )
  713. r.raise_for_status()
  714. payload = r.json()
  715. except Exception as e:
  716. # Handle connection error here
  717. print(f"Connection error: {e}")
  718. if r is not None:
  719. res = r.json()
  720. if "detail" in res:
  721. raise Exception(r.status_code, res["detail"])
  722. return payload
  723. class PipelineMiddleware(BaseHTTPMiddleware):
  724. async def dispatch(self, request: Request, call_next):
  725. if not is_chat_completion_request(request):
  726. return await call_next(request)
  727. log.debug(f"request.url.path: {request.url.path}")
  728. # Read the original request body
  729. body = await request.body()
  730. # Decode body to string
  731. body_str = body.decode("utf-8")
  732. # Parse string to JSON
  733. data = json.loads(body_str) if body_str else {}
  734. try:
  735. user = get_current_user(
  736. request,
  737. get_http_authorization_cred(request.headers["Authorization"]),
  738. )
  739. except KeyError as e:
  740. if len(e.args) > 1:
  741. return JSONResponse(
  742. status_code=e.args[0],
  743. content={"detail": e.args[1]},
  744. )
  745. else:
  746. return JSONResponse(
  747. status_code=status.HTTP_401_UNAUTHORIZED,
  748. content={"detail": "Not authenticated"},
  749. )
  750. except HTTPException as e:
  751. return JSONResponse(
  752. status_code=e.status_code,
  753. content={"detail": e.detail},
  754. )
  755. model_list = await get_all_models()
  756. models = {model["id"]: model for model in model_list}
  757. try:
  758. data = filter_pipeline(data, user, models)
  759. except Exception as e:
  760. if len(e.args) > 1:
  761. return JSONResponse(
  762. status_code=e.args[0],
  763. content={"detail": e.args[1]},
  764. )
  765. else:
  766. return JSONResponse(
  767. status_code=status.HTTP_400_BAD_REQUEST,
  768. content={"detail": str(e)},
  769. )
  770. modified_body_bytes = json.dumps(data).encode("utf-8")
  771. # Replace the request body with the modified one
  772. request._body = modified_body_bytes
  773. # Set custom header to ensure content-length matches new body length
  774. request.headers.__dict__["_list"] = [
  775. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  776. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  777. ]
  778. response = await call_next(request)
  779. return response
  780. async def _receive(self, body: bytes):
  781. return {"type": "http.request", "body": body, "more_body": False}
  782. app.add_middleware(PipelineMiddleware)
  783. from urllib.parse import urlencode, parse_qs, urlparse
  784. class RedirectMiddleware(BaseHTTPMiddleware):
  785. async def dispatch(self, request: Request, call_next):
  786. # Check if the request is a GET request
  787. if request.method == "GET":
  788. path = request.url.path
  789. query_params = dict(parse_qs(urlparse(str(request.url)).query))
  790. # Check for the specific watch path and the presence of 'v' parameter
  791. if path.endswith("/watch") and "v" in query_params:
  792. video_id = query_params["v"][0] # Extract the first 'v' parameter
  793. encoded_video_id = urlencode({"youtube": video_id})
  794. redirect_url = f"/?{encoded_video_id}"
  795. return RedirectResponse(url=redirect_url)
  796. # Proceed with the normal flow of other requests
  797. response = await call_next(request)
  798. return response
  799. # Add the middleware to the app
  800. app.add_middleware(RedirectMiddleware)
  801. app.add_middleware(
  802. CORSMiddleware,
  803. allow_origins=CORS_ALLOW_ORIGIN,
  804. allow_credentials=True,
  805. allow_methods=["*"],
  806. allow_headers=["*"],
  807. )
  808. app.add_middleware(SecurityHeadersMiddleware)
  809. @app.middleware("http")
  810. async def commit_session_after_request(request: Request, call_next):
  811. response = await call_next(request)
  812. # log.debug("Commit session after request")
  813. Session.commit()
  814. return response
  815. @app.middleware("http")
  816. async def check_url(request: Request, call_next):
  817. start_time = int(time.time())
  818. request.state.enable_api_key = webui_app.state.config.ENABLE_API_KEY
  819. response = await call_next(request)
  820. process_time = int(time.time()) - start_time
  821. response.headers["X-Process-Time"] = str(process_time)
  822. return response
  823. @app.middleware("http")
  824. async def update_embedding_function(request: Request, call_next):
  825. response = await call_next(request)
  826. if "/embedding/update" in request.url.path:
  827. webui_app.state.EMBEDDING_FUNCTION = retrieval_app.state.EMBEDDING_FUNCTION
  828. return response
  829. @app.middleware("http")
  830. async def inspect_websocket(request: Request, call_next):
  831. if (
  832. "/ws/socket.io" in request.url.path
  833. and request.query_params.get("transport") == "websocket"
  834. ):
  835. upgrade = (request.headers.get("Upgrade") or "").lower()
  836. connection = (request.headers.get("Connection") or "").lower().split(",")
  837. # Check that there's the correct headers for an upgrade, else reject the connection
  838. # This is to work around this upstream issue: https://github.com/miguelgrinberg/python-engineio/issues/367
  839. if upgrade != "websocket" or "upgrade" not in connection:
  840. return JSONResponse(
  841. status_code=status.HTTP_400_BAD_REQUEST,
  842. content={"detail": "Invalid WebSocket upgrade request"},
  843. )
  844. return await call_next(request)
  845. app.mount("/ws", socket_app)
  846. app.mount("/ollama", ollama_app)
  847. app.mount("/openai", openai_app)
  848. app.mount("/images/api/v1", images_app)
  849. app.mount("/audio/api/v1", audio_app)
  850. app.mount("/retrieval/api/v1", retrieval_app)
  851. app.mount("/api/v1", webui_app)
  852. webui_app.state.EMBEDDING_FUNCTION = retrieval_app.state.EMBEDDING_FUNCTION
  853. async def get_all_base_models():
  854. open_webui_models = []
  855. openai_models = []
  856. ollama_models = []
  857. if app.state.config.ENABLE_OPENAI_API:
  858. openai_models = await get_openai_models()
  859. openai_models = openai_models["data"]
  860. if app.state.config.ENABLE_OLLAMA_API:
  861. ollama_models = await get_ollama_models()
  862. ollama_models = [
  863. {
  864. "id": model["model"],
  865. "name": model["name"],
  866. "object": "model",
  867. "created": int(time.time()),
  868. "owned_by": "ollama",
  869. "ollama": model,
  870. }
  871. for model in ollama_models["models"]
  872. ]
  873. open_webui_models = await get_open_webui_models()
  874. models = open_webui_models + openai_models + ollama_models
  875. return models
  876. @cached(ttl=3)
  877. async def get_all_models():
  878. models = await get_all_base_models()
  879. # If there are no models, return an empty list
  880. if len([model for model in models if not model.get("arena", False)]) == 0:
  881. return []
  882. global_action_ids = [
  883. function.id for function in Functions.get_global_action_functions()
  884. ]
  885. enabled_action_ids = [
  886. function.id
  887. for function in Functions.get_functions_by_type("action", active_only=True)
  888. ]
  889. custom_models = Models.get_all_models()
  890. for custom_model in custom_models:
  891. if custom_model.base_model_id is None:
  892. for model in models:
  893. if (
  894. custom_model.id == model["id"]
  895. or custom_model.id == model["id"].split(":")[0]
  896. ):
  897. if custom_model.is_active:
  898. model["name"] = custom_model.name
  899. model["info"] = custom_model.model_dump()
  900. action_ids = []
  901. if "info" in model and "meta" in model["info"]:
  902. action_ids.extend(
  903. model["info"]["meta"].get("actionIds", [])
  904. )
  905. model["action_ids"] = action_ids
  906. else:
  907. models.remove(model)
  908. elif custom_model.is_active and (
  909. custom_model.id not in [model["id"] for model in models]
  910. ):
  911. owned_by = "openai"
  912. pipe = None
  913. action_ids = []
  914. for model in models:
  915. if (
  916. custom_model.base_model_id == model["id"]
  917. or custom_model.base_model_id == model["id"].split(":")[0]
  918. ):
  919. owned_by = model["owned_by"]
  920. if "pipe" in model:
  921. pipe = model["pipe"]
  922. break
  923. if custom_model.meta:
  924. meta = custom_model.meta.model_dump()
  925. if "actionIds" in meta:
  926. action_ids.extend(meta["actionIds"])
  927. models.append(
  928. {
  929. "id": f"{custom_model.id}",
  930. "name": custom_model.name,
  931. "object": "model",
  932. "created": custom_model.created_at,
  933. "owned_by": owned_by,
  934. "info": custom_model.model_dump(),
  935. "preset": True,
  936. **({"pipe": pipe} if pipe is not None else {}),
  937. "action_ids": action_ids,
  938. }
  939. )
  940. # Process action_ids to get the actions
  941. def get_action_items_from_module(function, module):
  942. actions = []
  943. if hasattr(module, "actions"):
  944. actions = module.actions
  945. return [
  946. {
  947. "id": f"{function.id}.{action['id']}",
  948. "name": action.get("name", f"{function.name} ({action['id']})"),
  949. "description": function.meta.description,
  950. "icon_url": action.get(
  951. "icon_url", function.meta.manifest.get("icon_url", None)
  952. ),
  953. }
  954. for action in actions
  955. ]
  956. else:
  957. return [
  958. {
  959. "id": function.id,
  960. "name": function.name,
  961. "description": function.meta.description,
  962. "icon_url": function.meta.manifest.get("icon_url", None),
  963. }
  964. ]
  965. def get_function_module_by_id(function_id):
  966. if function_id in webui_app.state.FUNCTIONS:
  967. function_module = webui_app.state.FUNCTIONS[function_id]
  968. else:
  969. function_module, _, _ = load_function_module_by_id(function_id)
  970. webui_app.state.FUNCTIONS[function_id] = function_module
  971. for model in models:
  972. action_ids = [
  973. action_id
  974. for action_id in list(set(model.pop("action_ids", []) + global_action_ids))
  975. if action_id in enabled_action_ids
  976. ]
  977. model["actions"] = []
  978. for action_id in action_ids:
  979. action_function = Functions.get_function_by_id(action_id)
  980. if action_function is None:
  981. raise Exception(f"Action not found: {action_id}")
  982. function_module = get_function_module_by_id(action_id)
  983. model["actions"].extend(
  984. get_action_items_from_module(action_function, function_module)
  985. )
  986. log.debug(f"get_all_models() returned {len(models)} models")
  987. return models
  988. @app.get("/api/models")
  989. async def get_models(user=Depends(get_verified_user)):
  990. models = await get_all_models()
  991. # Filter out filter pipelines
  992. models = [
  993. model
  994. for model in models
  995. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  996. ]
  997. model_order_list = webui_app.state.config.MODEL_ORDER_LIST
  998. if model_order_list:
  999. model_order_dict = {model_id: i for i, model_id in enumerate(model_order_list)}
  1000. # Sort models by order list priority, with fallback for those not in the list
  1001. models.sort(
  1002. key=lambda x: (model_order_dict.get(x["id"], float("inf")), x["name"])
  1003. )
  1004. # Filter out models that the user does not have access to
  1005. if user.role == "user":
  1006. filtered_models = []
  1007. for model in models:
  1008. if model.get("arena"):
  1009. if has_access(
  1010. user.id,
  1011. type="read",
  1012. access_control=model.get("info", {})
  1013. .get("meta", {})
  1014. .get("access_control", {}),
  1015. ):
  1016. filtered_models.append(model)
  1017. continue
  1018. model_info = Models.get_model_by_id(model["id"])
  1019. if model_info:
  1020. if user.id == model_info.user_id or has_access(
  1021. user.id, type="read", access_control=model_info.access_control
  1022. ):
  1023. filtered_models.append(model)
  1024. models = filtered_models
  1025. log.debug(
  1026. f"/api/models returned filtered models accessible to the user: {json.dumps([model['id'] for model in models])}"
  1027. )
  1028. return {"data": models}
  1029. @app.get("/api/models/base")
  1030. async def get_base_models(user=Depends(get_admin_user)):
  1031. models = await get_all_base_models()
  1032. # Filter out arena models
  1033. models = [model for model in models if not model.get("arena", False)]
  1034. return {"data": models}
  1035. @app.post("/api/chat/completions")
  1036. async def generate_chat_completions(
  1037. form_data: dict, user=Depends(get_verified_user), bypass_filter: bool = False
  1038. ):
  1039. model_list = await get_all_models()
  1040. models = {model["id"]: model for model in model_list}
  1041. model_id = form_data["model"]
  1042. if model_id not in models:
  1043. raise HTTPException(
  1044. status_code=status.HTTP_404_NOT_FOUND,
  1045. detail="Model not found",
  1046. )
  1047. model = models[model_id]
  1048. # Check if user has access to the model
  1049. if not bypass_filter and user.role == "user":
  1050. if model.get("arena"):
  1051. if not has_access(
  1052. user.id,
  1053. type="read",
  1054. access_control=model.get("info", {})
  1055. .get("meta", {})
  1056. .get("access_control", {}),
  1057. ):
  1058. raise HTTPException(
  1059. status_code=403,
  1060. detail="Model not found",
  1061. )
  1062. else:
  1063. model_info = Models.get_model_by_id(model_id)
  1064. if not model_info:
  1065. raise HTTPException(
  1066. status_code=404,
  1067. detail="Model not found",
  1068. )
  1069. elif not (
  1070. user.id == model_info.user_id
  1071. or has_access(
  1072. user.id, type="read", access_control=model_info.access_control
  1073. )
  1074. ):
  1075. raise HTTPException(
  1076. status_code=403,
  1077. detail="Model not found",
  1078. )
  1079. if model["owned_by"] == "arena":
  1080. model_ids = model.get("info", {}).get("meta", {}).get("model_ids")
  1081. filter_mode = model.get("info", {}).get("meta", {}).get("filter_mode")
  1082. if model_ids and filter_mode == "exclude":
  1083. model_ids = [
  1084. model["id"]
  1085. for model in await get_all_models()
  1086. if model.get("owned_by") != "arena" and model["id"] not in model_ids
  1087. ]
  1088. selected_model_id = None
  1089. if isinstance(model_ids, list) and model_ids:
  1090. selected_model_id = random.choice(model_ids)
  1091. else:
  1092. model_ids = [
  1093. model["id"]
  1094. for model in await get_all_models()
  1095. if model.get("owned_by") != "arena"
  1096. ]
  1097. selected_model_id = random.choice(model_ids)
  1098. form_data["model"] = selected_model_id
  1099. if form_data.get("stream") == True:
  1100. async def stream_wrapper(stream):
  1101. yield f"data: {json.dumps({'selected_model_id': selected_model_id})}\n\n"
  1102. async for chunk in stream:
  1103. yield chunk
  1104. response = await generate_chat_completions(
  1105. form_data, user, bypass_filter=True
  1106. )
  1107. return StreamingResponse(
  1108. stream_wrapper(response.body_iterator), media_type="text/event-stream"
  1109. )
  1110. else:
  1111. return {
  1112. **(
  1113. await generate_chat_completions(form_data, user, bypass_filter=True)
  1114. ),
  1115. "selected_model_id": selected_model_id,
  1116. }
  1117. if model.get("pipe"):
  1118. # Below does not require bypass_filter because this is the only route the uses this function and it is already bypassing the filter
  1119. return await generate_function_chat_completion(
  1120. form_data, user=user, models=models
  1121. )
  1122. if model["owned_by"] == "ollama":
  1123. # Using /ollama/api/chat endpoint
  1124. form_data = convert_payload_openai_to_ollama(form_data)
  1125. form_data = GenerateChatCompletionForm(**form_data)
  1126. response = await generate_ollama_chat_completion(
  1127. form_data=form_data, user=user, bypass_filter=bypass_filter
  1128. )
  1129. if form_data.stream:
  1130. response.headers["content-type"] = "text/event-stream"
  1131. return StreamingResponse(
  1132. convert_streaming_response_ollama_to_openai(response),
  1133. headers=dict(response.headers),
  1134. )
  1135. else:
  1136. return convert_response_ollama_to_openai(response)
  1137. else:
  1138. return await generate_openai_chat_completion(
  1139. form_data, user=user, bypass_filter=bypass_filter
  1140. )
  1141. @app.post("/api/chat/completed")
  1142. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  1143. model_list = await get_all_models()
  1144. models = {model["id"]: model for model in model_list}
  1145. data = form_data
  1146. model_id = data["model"]
  1147. if model_id not in models:
  1148. raise HTTPException(
  1149. status_code=status.HTTP_404_NOT_FOUND,
  1150. detail="Model not found",
  1151. )
  1152. model = models[model_id]
  1153. sorted_filters = get_sorted_filters(model_id, models)
  1154. if "pipeline" in model:
  1155. sorted_filters = [model] + sorted_filters
  1156. for filter in sorted_filters:
  1157. r = None
  1158. try:
  1159. urlIdx = filter["urlIdx"]
  1160. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1161. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1162. if key != "":
  1163. headers = {"Authorization": f"Bearer {key}"}
  1164. r = requests.post(
  1165. f"{url}/{filter['id']}/filter/outlet",
  1166. headers=headers,
  1167. json={
  1168. "user": {
  1169. "id": user.id,
  1170. "name": user.name,
  1171. "email": user.email,
  1172. "role": user.role,
  1173. },
  1174. "body": data,
  1175. },
  1176. )
  1177. r.raise_for_status()
  1178. data = r.json()
  1179. except Exception as e:
  1180. # Handle connection error here
  1181. print(f"Connection error: {e}")
  1182. if r is not None:
  1183. try:
  1184. res = r.json()
  1185. if "detail" in res:
  1186. return JSONResponse(
  1187. status_code=r.status_code,
  1188. content=res,
  1189. )
  1190. except Exception:
  1191. pass
  1192. else:
  1193. pass
  1194. __event_emitter__ = get_event_emitter(
  1195. {
  1196. "chat_id": data["chat_id"],
  1197. "message_id": data["id"],
  1198. "session_id": data["session_id"],
  1199. }
  1200. )
  1201. __event_call__ = get_event_call(
  1202. {
  1203. "chat_id": data["chat_id"],
  1204. "message_id": data["id"],
  1205. "session_id": data["session_id"],
  1206. }
  1207. )
  1208. def get_priority(function_id):
  1209. function = Functions.get_function_by_id(function_id)
  1210. if function is not None and hasattr(function, "valves"):
  1211. # TODO: Fix FunctionModel to include vavles
  1212. return (function.valves if function.valves else {}).get("priority", 0)
  1213. return 0
  1214. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  1215. if "info" in model and "meta" in model["info"]:
  1216. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  1217. filter_ids = list(set(filter_ids))
  1218. enabled_filter_ids = [
  1219. function.id
  1220. for function in Functions.get_functions_by_type("filter", active_only=True)
  1221. ]
  1222. filter_ids = [
  1223. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  1224. ]
  1225. # Sort filter_ids by priority, using the get_priority function
  1226. filter_ids.sort(key=get_priority)
  1227. for filter_id in filter_ids:
  1228. filter = Functions.get_function_by_id(filter_id)
  1229. if not filter:
  1230. continue
  1231. if filter_id in webui_app.state.FUNCTIONS:
  1232. function_module = webui_app.state.FUNCTIONS[filter_id]
  1233. else:
  1234. function_module, _, _ = load_function_module_by_id(filter_id)
  1235. webui_app.state.FUNCTIONS[filter_id] = function_module
  1236. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1237. valves = Functions.get_function_valves_by_id(filter_id)
  1238. function_module.valves = function_module.Valves(
  1239. **(valves if valves else {})
  1240. )
  1241. if not hasattr(function_module, "outlet"):
  1242. continue
  1243. try:
  1244. outlet = function_module.outlet
  1245. # Get the signature of the function
  1246. sig = inspect.signature(outlet)
  1247. params = {"body": data}
  1248. # Extra parameters to be passed to the function
  1249. extra_params = {
  1250. "__model__": model,
  1251. "__id__": filter_id,
  1252. "__event_emitter__": __event_emitter__,
  1253. "__event_call__": __event_call__,
  1254. }
  1255. # Add extra params in contained in function signature
  1256. for key, value in extra_params.items():
  1257. if key in sig.parameters:
  1258. params[key] = value
  1259. if "__user__" in sig.parameters:
  1260. __user__ = {
  1261. "id": user.id,
  1262. "email": user.email,
  1263. "name": user.name,
  1264. "role": user.role,
  1265. }
  1266. try:
  1267. if hasattr(function_module, "UserValves"):
  1268. __user__["valves"] = function_module.UserValves(
  1269. **Functions.get_user_valves_by_id_and_user_id(
  1270. filter_id, user.id
  1271. )
  1272. )
  1273. except Exception as e:
  1274. print(e)
  1275. params = {**params, "__user__": __user__}
  1276. if inspect.iscoroutinefunction(outlet):
  1277. data = await outlet(**params)
  1278. else:
  1279. data = outlet(**params)
  1280. except Exception as e:
  1281. print(f"Error: {e}")
  1282. return JSONResponse(
  1283. status_code=status.HTTP_400_BAD_REQUEST,
  1284. content={"detail": str(e)},
  1285. )
  1286. return data
  1287. @app.post("/api/chat/actions/{action_id}")
  1288. async def chat_action(action_id: str, form_data: dict, user=Depends(get_verified_user)):
  1289. if "." in action_id:
  1290. action_id, sub_action_id = action_id.split(".")
  1291. else:
  1292. sub_action_id = None
  1293. action = Functions.get_function_by_id(action_id)
  1294. if not action:
  1295. raise HTTPException(
  1296. status_code=status.HTTP_404_NOT_FOUND,
  1297. detail="Action not found",
  1298. )
  1299. model_list = await get_all_models()
  1300. models = {model["id"]: model for model in model_list}
  1301. data = form_data
  1302. model_id = data["model"]
  1303. if model_id not in models:
  1304. raise HTTPException(
  1305. status_code=status.HTTP_404_NOT_FOUND,
  1306. detail="Model not found",
  1307. )
  1308. model = models[model_id]
  1309. __event_emitter__ = get_event_emitter(
  1310. {
  1311. "chat_id": data["chat_id"],
  1312. "message_id": data["id"],
  1313. "session_id": data["session_id"],
  1314. }
  1315. )
  1316. __event_call__ = get_event_call(
  1317. {
  1318. "chat_id": data["chat_id"],
  1319. "message_id": data["id"],
  1320. "session_id": data["session_id"],
  1321. }
  1322. )
  1323. if action_id in webui_app.state.FUNCTIONS:
  1324. function_module = webui_app.state.FUNCTIONS[action_id]
  1325. else:
  1326. function_module, _, _ = load_function_module_by_id(action_id)
  1327. webui_app.state.FUNCTIONS[action_id] = function_module
  1328. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1329. valves = Functions.get_function_valves_by_id(action_id)
  1330. function_module.valves = function_module.Valves(**(valves if valves else {}))
  1331. if hasattr(function_module, "action"):
  1332. try:
  1333. action = function_module.action
  1334. # Get the signature of the function
  1335. sig = inspect.signature(action)
  1336. params = {"body": data}
  1337. # Extra parameters to be passed to the function
  1338. extra_params = {
  1339. "__model__": model,
  1340. "__id__": sub_action_id if sub_action_id is not None else action_id,
  1341. "__event_emitter__": __event_emitter__,
  1342. "__event_call__": __event_call__,
  1343. }
  1344. # Add extra params in contained in function signature
  1345. for key, value in extra_params.items():
  1346. if key in sig.parameters:
  1347. params[key] = value
  1348. if "__user__" in sig.parameters:
  1349. __user__ = {
  1350. "id": user.id,
  1351. "email": user.email,
  1352. "name": user.name,
  1353. "role": user.role,
  1354. }
  1355. try:
  1356. if hasattr(function_module, "UserValves"):
  1357. __user__["valves"] = function_module.UserValves(
  1358. **Functions.get_user_valves_by_id_and_user_id(
  1359. action_id, user.id
  1360. )
  1361. )
  1362. except Exception as e:
  1363. print(e)
  1364. params = {**params, "__user__": __user__}
  1365. if inspect.iscoroutinefunction(action):
  1366. data = await action(**params)
  1367. else:
  1368. data = action(**params)
  1369. except Exception as e:
  1370. print(f"Error: {e}")
  1371. return JSONResponse(
  1372. status_code=status.HTTP_400_BAD_REQUEST,
  1373. content={"detail": str(e)},
  1374. )
  1375. return data
  1376. ##################################
  1377. #
  1378. # Task Endpoints
  1379. #
  1380. ##################################
  1381. # TODO: Refactor task API endpoints below into a separate file
  1382. @app.get("/api/task/config")
  1383. async def get_task_config(user=Depends(get_verified_user)):
  1384. return {
  1385. "TASK_MODEL": app.state.config.TASK_MODEL,
  1386. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1387. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1388. "TAGS_GENERATION_PROMPT_TEMPLATE": app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE,
  1389. "ENABLE_TAGS_GENERATION": app.state.config.ENABLE_TAGS_GENERATION,
  1390. "ENABLE_SEARCH_QUERY_GENERATION": app.state.config.ENABLE_SEARCH_QUERY_GENERATION,
  1391. "ENABLE_RETRIEVAL_QUERY_GENERATION": app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION,
  1392. "QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE,
  1393. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1394. }
  1395. class TaskConfigForm(BaseModel):
  1396. TASK_MODEL: Optional[str]
  1397. TASK_MODEL_EXTERNAL: Optional[str]
  1398. TITLE_GENERATION_PROMPT_TEMPLATE: str
  1399. TAGS_GENERATION_PROMPT_TEMPLATE: str
  1400. ENABLE_TAGS_GENERATION: bool
  1401. ENABLE_SEARCH_QUERY_GENERATION: bool
  1402. ENABLE_RETRIEVAL_QUERY_GENERATION: bool
  1403. QUERY_GENERATION_PROMPT_TEMPLATE: str
  1404. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  1405. @app.post("/api/task/config/update")
  1406. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  1407. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  1408. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  1409. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  1410. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  1411. )
  1412. app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE = (
  1413. form_data.TAGS_GENERATION_PROMPT_TEMPLATE
  1414. )
  1415. app.state.config.ENABLE_TAGS_GENERATION = form_data.ENABLE_TAGS_GENERATION
  1416. app.state.config.ENABLE_SEARCH_QUERY_GENERATION = (
  1417. form_data.ENABLE_SEARCH_QUERY_GENERATION
  1418. )
  1419. app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION = (
  1420. form_data.ENABLE_RETRIEVAL_QUERY_GENERATION
  1421. )
  1422. app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE = (
  1423. form_data.QUERY_GENERATION_PROMPT_TEMPLATE
  1424. )
  1425. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  1426. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1427. )
  1428. return {
  1429. "TASK_MODEL": app.state.config.TASK_MODEL,
  1430. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1431. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1432. "TAGS_GENERATION_PROMPT_TEMPLATE": app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE,
  1433. "ENABLE_TAGS_GENERATION": app.state.config.ENABLE_TAGS_GENERATION,
  1434. "ENABLE_SEARCH_QUERY_GENERATION": app.state.config.ENABLE_SEARCH_QUERY_GENERATION,
  1435. "ENABLE_RETRIEVAL_QUERY_GENERATION": app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION,
  1436. "QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE,
  1437. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1438. }
  1439. @app.post("/api/task/title/completions")
  1440. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  1441. model_list = await get_all_models()
  1442. models = {model["id"]: model for model in model_list}
  1443. model_id = form_data["model"]
  1444. if model_id not in models:
  1445. raise HTTPException(
  1446. status_code=status.HTTP_404_NOT_FOUND,
  1447. detail="Model not found",
  1448. )
  1449. # Check if the user has a custom task model
  1450. # If the user has a custom task model, use that model
  1451. task_model_id = get_task_model_id(
  1452. model_id,
  1453. app.state.config.TASK_MODEL,
  1454. app.state.config.TASK_MODEL_EXTERNAL,
  1455. models,
  1456. )
  1457. log.debug(
  1458. f"generating chat title using model {task_model_id} for user {user.email} "
  1459. )
  1460. if app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE != "":
  1461. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  1462. else:
  1463. template = """Create a concise, 3-5 word title with an emoji as a title for the chat history, in the given language. Suitable Emojis for the summary can be used to enhance understanding but avoid quotation marks or special formatting. RESPOND ONLY WITH THE TITLE TEXT.
  1464. Examples of titles:
  1465. 📉 Stock Market Trends
  1466. 🍪 Perfect Chocolate Chip Recipe
  1467. Evolution of Music Streaming
  1468. Remote Work Productivity Tips
  1469. Artificial Intelligence in Healthcare
  1470. 🎮 Video Game Development Insights
  1471. <chat_history>
  1472. {{MESSAGES:END:2}}
  1473. </chat_history>"""
  1474. content = title_generation_template(
  1475. template,
  1476. form_data["messages"],
  1477. {
  1478. "name": user.name,
  1479. "location": user.info.get("location") if user.info else None,
  1480. },
  1481. )
  1482. payload = {
  1483. "model": task_model_id,
  1484. "messages": [{"role": "user", "content": content}],
  1485. "stream": False,
  1486. **(
  1487. {"max_tokens": 50}
  1488. if models[task_model_id]["owned_by"] == "ollama"
  1489. else {
  1490. "max_completion_tokens": 50,
  1491. }
  1492. ),
  1493. "metadata": {
  1494. "task": str(TASKS.TITLE_GENERATION),
  1495. "task_body": form_data,
  1496. "chat_id": form_data.get("chat_id", None),
  1497. },
  1498. }
  1499. # Handle pipeline filters
  1500. try:
  1501. payload = filter_pipeline(payload, user, models)
  1502. except Exception as e:
  1503. if len(e.args) > 1:
  1504. return JSONResponse(
  1505. status_code=e.args[0],
  1506. content={"detail": e.args[1]},
  1507. )
  1508. else:
  1509. return JSONResponse(
  1510. status_code=status.HTTP_400_BAD_REQUEST,
  1511. content={"detail": str(e)},
  1512. )
  1513. if "chat_id" in payload:
  1514. del payload["chat_id"]
  1515. return await generate_chat_completions(form_data=payload, user=user)
  1516. @app.post("/api/task/tags/completions")
  1517. async def generate_chat_tags(form_data: dict, user=Depends(get_verified_user)):
  1518. if not app.state.config.ENABLE_TAGS_GENERATION:
  1519. return JSONResponse(
  1520. status_code=status.HTTP_200_OK,
  1521. content={"detail": "Tags generation is disabled"},
  1522. )
  1523. model_list = await get_all_models()
  1524. models = {model["id"]: model for model in model_list}
  1525. model_id = form_data["model"]
  1526. if model_id not in models:
  1527. raise HTTPException(
  1528. status_code=status.HTTP_404_NOT_FOUND,
  1529. detail="Model not found",
  1530. )
  1531. # Check if the user has a custom task model
  1532. # If the user has a custom task model, use that model
  1533. task_model_id = get_task_model_id(
  1534. model_id,
  1535. app.state.config.TASK_MODEL,
  1536. app.state.config.TASK_MODEL_EXTERNAL,
  1537. models,
  1538. )
  1539. log.debug(
  1540. f"generating chat tags using model {task_model_id} for user {user.email} "
  1541. )
  1542. if app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE != "":
  1543. template = app.state.config.TAGS_GENERATION_PROMPT_TEMPLATE
  1544. else:
  1545. template = """### Task:
  1546. Generate 1-3 broad tags categorizing the main themes of the chat history, along with 1-3 more specific subtopic tags.
  1547. ### Guidelines:
  1548. - Start with high-level domains (e.g. Science, Technology, Philosophy, Arts, Politics, Business, Health, Sports, Entertainment, Education)
  1549. - Consider including relevant subfields/subdomains if they are strongly represented throughout the conversation
  1550. - If content is too short (less than 3 messages) or too diverse, use only ["General"]
  1551. - Use the chat's primary language; default to English if multilingual
  1552. - Prioritize accuracy over specificity
  1553. ### Output:
  1554. JSON format: { "tags": ["tag1", "tag2", "tag3"] }
  1555. ### Chat History:
  1556. <chat_history>
  1557. {{MESSAGES:END:6}}
  1558. </chat_history>"""
  1559. content = tags_generation_template(
  1560. template, form_data["messages"], {"name": user.name}
  1561. )
  1562. payload = {
  1563. "model": task_model_id,
  1564. "messages": [{"role": "user", "content": content}],
  1565. "stream": False,
  1566. "metadata": {
  1567. "task": str(TASKS.TAGS_GENERATION),
  1568. "task_body": form_data,
  1569. "chat_id": form_data.get("chat_id", None),
  1570. },
  1571. }
  1572. # Handle pipeline filters
  1573. try:
  1574. payload = filter_pipeline(payload, user, models)
  1575. except Exception as e:
  1576. if len(e.args) > 1:
  1577. return JSONResponse(
  1578. status_code=e.args[0],
  1579. content={"detail": e.args[1]},
  1580. )
  1581. else:
  1582. return JSONResponse(
  1583. status_code=status.HTTP_400_BAD_REQUEST,
  1584. content={"detail": str(e)},
  1585. )
  1586. if "chat_id" in payload:
  1587. del payload["chat_id"]
  1588. return await generate_chat_completions(form_data=payload, user=user)
  1589. @app.post("/api/task/queries/completions")
  1590. async def generate_queries(form_data: dict, user=Depends(get_verified_user)):
  1591. type = form_data.get("type")
  1592. if type == "web_search":
  1593. if not app.state.config.ENABLE_SEARCH_QUERY_GENERATION:
  1594. raise HTTPException(
  1595. status_code=status.HTTP_400_BAD_REQUEST,
  1596. detail=f"Search query generation is disabled",
  1597. )
  1598. elif type == "retrieval":
  1599. if not app.state.config.ENABLE_RETRIEVAL_QUERY_GENERATION:
  1600. raise HTTPException(
  1601. status_code=status.HTTP_400_BAD_REQUEST,
  1602. detail=f"Query generation is disabled",
  1603. )
  1604. model_list = await get_all_models()
  1605. models = {model["id"]: model for model in model_list}
  1606. model_id = form_data["model"]
  1607. if model_id not in models:
  1608. raise HTTPException(
  1609. status_code=status.HTTP_404_NOT_FOUND,
  1610. detail="Model not found",
  1611. )
  1612. # Check if the user has a custom task model
  1613. # If the user has a custom task model, use that model
  1614. task_model_id = get_task_model_id(
  1615. model_id,
  1616. app.state.config.TASK_MODEL,
  1617. app.state.config.TASK_MODEL_EXTERNAL,
  1618. models,
  1619. )
  1620. log.debug(
  1621. f"generating {type} queries using model {task_model_id} for user {user.email}"
  1622. )
  1623. if app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE != "":
  1624. template = app.state.config.QUERY_GENERATION_PROMPT_TEMPLATE
  1625. else:
  1626. template = DEFAULT_QUERY_GENERATION_PROMPT_TEMPLATE
  1627. content = query_generation_template(
  1628. template, form_data["messages"], {"name": user.name}
  1629. )
  1630. payload = {
  1631. "model": task_model_id,
  1632. "messages": [{"role": "user", "content": content}],
  1633. "stream": False,
  1634. "metadata": {
  1635. "task": str(TASKS.QUERY_GENERATION),
  1636. "task_body": form_data,
  1637. "chat_id": form_data.get("chat_id", None),
  1638. },
  1639. }
  1640. # Handle pipeline filters
  1641. try:
  1642. payload = filter_pipeline(payload, user, models)
  1643. except Exception as e:
  1644. if len(e.args) > 1:
  1645. return JSONResponse(
  1646. status_code=e.args[0],
  1647. content={"detail": e.args[1]},
  1648. )
  1649. else:
  1650. return JSONResponse(
  1651. status_code=status.HTTP_400_BAD_REQUEST,
  1652. content={"detail": str(e)},
  1653. )
  1654. if "chat_id" in payload:
  1655. del payload["chat_id"]
  1656. return await generate_chat_completions(form_data=payload, user=user)
  1657. @app.post("/api/task/emoji/completions")
  1658. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  1659. model_list = await get_all_models()
  1660. models = {model["id"]: model for model in model_list}
  1661. model_id = form_data["model"]
  1662. if model_id not in models:
  1663. raise HTTPException(
  1664. status_code=status.HTTP_404_NOT_FOUND,
  1665. detail="Model not found",
  1666. )
  1667. # Check if the user has a custom task model
  1668. # If the user has a custom task model, use that model
  1669. task_model_id = get_task_model_id(
  1670. model_id,
  1671. app.state.config.TASK_MODEL,
  1672. app.state.config.TASK_MODEL_EXTERNAL,
  1673. models,
  1674. )
  1675. log.debug(f"generating emoji using model {task_model_id} for user {user.email} ")
  1676. template = '''
  1677. 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., 😊, 😢, 😡, 😱).
  1678. Message: """{{prompt}}"""
  1679. '''
  1680. content = emoji_generation_template(
  1681. template,
  1682. form_data["prompt"],
  1683. {
  1684. "name": user.name,
  1685. "location": user.info.get("location") if user.info else None,
  1686. },
  1687. )
  1688. payload = {
  1689. "model": task_model_id,
  1690. "messages": [{"role": "user", "content": content}],
  1691. "stream": False,
  1692. **(
  1693. {"max_tokens": 4}
  1694. if models[task_model_id]["owned_by"] == "ollama"
  1695. else {
  1696. "max_completion_tokens": 4,
  1697. }
  1698. ),
  1699. "chat_id": form_data.get("chat_id", None),
  1700. "metadata": {"task": str(TASKS.EMOJI_GENERATION), "task_body": form_data},
  1701. }
  1702. # Handle pipeline filters
  1703. try:
  1704. payload = filter_pipeline(payload, user, models)
  1705. except Exception as e:
  1706. if len(e.args) > 1:
  1707. return JSONResponse(
  1708. status_code=e.args[0],
  1709. content={"detail": e.args[1]},
  1710. )
  1711. else:
  1712. return JSONResponse(
  1713. status_code=status.HTTP_400_BAD_REQUEST,
  1714. content={"detail": str(e)},
  1715. )
  1716. if "chat_id" in payload:
  1717. del payload["chat_id"]
  1718. return await generate_chat_completions(form_data=payload, user=user)
  1719. @app.post("/api/task/moa/completions")
  1720. async def generate_moa_response(form_data: dict, user=Depends(get_verified_user)):
  1721. model_list = await get_all_models()
  1722. models = {model["id"]: model for model in model_list}
  1723. model_id = form_data["model"]
  1724. if model_id not in models:
  1725. raise HTTPException(
  1726. status_code=status.HTTP_404_NOT_FOUND,
  1727. detail="Model not found",
  1728. )
  1729. # Check if the user has a custom task model
  1730. # If the user has a custom task model, use that model
  1731. task_model_id = get_task_model_id(
  1732. model_id,
  1733. app.state.config.TASK_MODEL,
  1734. app.state.config.TASK_MODEL_EXTERNAL,
  1735. models,
  1736. )
  1737. log.debug(f"generating MOA model {task_model_id} for user {user.email} ")
  1738. template = """You have been provided with a set of responses from various models to the latest user query: "{{prompt}}"
  1739. Your task is to synthesize these responses into a single, high-quality response. It is crucial to critically evaluate the information provided in these responses, recognizing that some of it may be biased or incorrect. Your response should not simply replicate the given answers but should offer a refined, accurate, and comprehensive reply to the instruction. Ensure your response is well-structured, coherent, and adheres to the highest standards of accuracy and reliability.
  1740. Responses from models: {{responses}}"""
  1741. content = moa_response_generation_template(
  1742. template,
  1743. form_data["prompt"],
  1744. form_data["responses"],
  1745. )
  1746. payload = {
  1747. "model": task_model_id,
  1748. "messages": [{"role": "user", "content": content}],
  1749. "stream": form_data.get("stream", False),
  1750. "chat_id": form_data.get("chat_id", None),
  1751. "metadata": {
  1752. "task": str(TASKS.MOA_RESPONSE_GENERATION),
  1753. "task_body": form_data,
  1754. },
  1755. }
  1756. try:
  1757. payload = filter_pipeline(payload, user, models)
  1758. except Exception as e:
  1759. if len(e.args) > 1:
  1760. return JSONResponse(
  1761. status_code=e.args[0],
  1762. content={"detail": e.args[1]},
  1763. )
  1764. else:
  1765. return JSONResponse(
  1766. status_code=status.HTTP_400_BAD_REQUEST,
  1767. content={"detail": str(e)},
  1768. )
  1769. if "chat_id" in payload:
  1770. del payload["chat_id"]
  1771. return await generate_chat_completions(form_data=payload, user=user)
  1772. ##################################
  1773. #
  1774. # Pipelines Endpoints
  1775. #
  1776. ##################################
  1777. # TODO: Refactor pipelines API endpoints below into a separate file
  1778. @app.get("/api/pipelines/list")
  1779. async def get_pipelines_list(user=Depends(get_admin_user)):
  1780. responses = await get_openai_models_responses()
  1781. log.debug(f"get_pipelines_list: get_openai_models_responses returned {responses}")
  1782. urlIdxs = [
  1783. idx
  1784. for idx, response in enumerate(responses)
  1785. if response is not None and "pipelines" in response
  1786. ]
  1787. return {
  1788. "data": [
  1789. {
  1790. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  1791. "idx": urlIdx,
  1792. }
  1793. for urlIdx in urlIdxs
  1794. ]
  1795. }
  1796. @app.post("/api/pipelines/upload")
  1797. async def upload_pipeline(
  1798. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  1799. ):
  1800. print("upload_pipeline", urlIdx, file.filename)
  1801. # Check if the uploaded file is a python file
  1802. if not (file.filename and file.filename.endswith(".py")):
  1803. raise HTTPException(
  1804. status_code=status.HTTP_400_BAD_REQUEST,
  1805. detail="Only Python (.py) files are allowed.",
  1806. )
  1807. upload_folder = f"{CACHE_DIR}/pipelines"
  1808. os.makedirs(upload_folder, exist_ok=True)
  1809. file_path = os.path.join(upload_folder, file.filename)
  1810. r = None
  1811. try:
  1812. # Save the uploaded file
  1813. with open(file_path, "wb") as buffer:
  1814. shutil.copyfileobj(file.file, buffer)
  1815. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1816. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1817. headers = {"Authorization": f"Bearer {key}"}
  1818. with open(file_path, "rb") as f:
  1819. files = {"file": f}
  1820. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1821. r.raise_for_status()
  1822. data = r.json()
  1823. return {**data}
  1824. except Exception as e:
  1825. # Handle connection error here
  1826. print(f"Connection error: {e}")
  1827. detail = "Pipeline not found"
  1828. status_code = status.HTTP_404_NOT_FOUND
  1829. if r is not None:
  1830. status_code = r.status_code
  1831. try:
  1832. res = r.json()
  1833. if "detail" in res:
  1834. detail = res["detail"]
  1835. except Exception:
  1836. pass
  1837. raise HTTPException(
  1838. status_code=status_code,
  1839. detail=detail,
  1840. )
  1841. finally:
  1842. # Ensure the file is deleted after the upload is completed or on failure
  1843. if os.path.exists(file_path):
  1844. os.remove(file_path)
  1845. class AddPipelineForm(BaseModel):
  1846. url: str
  1847. urlIdx: int
  1848. @app.post("/api/pipelines/add")
  1849. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1850. r = None
  1851. try:
  1852. urlIdx = form_data.urlIdx
  1853. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1854. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1855. headers = {"Authorization": f"Bearer {key}"}
  1856. r = requests.post(
  1857. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1858. )
  1859. r.raise_for_status()
  1860. data = r.json()
  1861. return {**data}
  1862. except Exception as e:
  1863. # Handle connection error here
  1864. print(f"Connection error: {e}")
  1865. detail = "Pipeline not found"
  1866. if r is not None:
  1867. try:
  1868. res = r.json()
  1869. if "detail" in res:
  1870. detail = res["detail"]
  1871. except Exception:
  1872. pass
  1873. raise HTTPException(
  1874. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1875. detail=detail,
  1876. )
  1877. class DeletePipelineForm(BaseModel):
  1878. id: str
  1879. urlIdx: int
  1880. @app.delete("/api/pipelines/delete")
  1881. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1882. r = None
  1883. try:
  1884. urlIdx = form_data.urlIdx
  1885. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1886. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1887. headers = {"Authorization": f"Bearer {key}"}
  1888. r = requests.delete(
  1889. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1890. )
  1891. r.raise_for_status()
  1892. data = r.json()
  1893. return {**data}
  1894. except Exception as e:
  1895. # Handle connection error here
  1896. print(f"Connection error: {e}")
  1897. detail = "Pipeline not found"
  1898. if r is not None:
  1899. try:
  1900. res = r.json()
  1901. if "detail" in res:
  1902. detail = res["detail"]
  1903. except Exception:
  1904. pass
  1905. raise HTTPException(
  1906. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1907. detail=detail,
  1908. )
  1909. @app.get("/api/pipelines")
  1910. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  1911. r = None
  1912. try:
  1913. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1914. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1915. headers = {"Authorization": f"Bearer {key}"}
  1916. r = requests.get(f"{url}/pipelines", headers=headers)
  1917. r.raise_for_status()
  1918. data = r.json()
  1919. return {**data}
  1920. except Exception as e:
  1921. # Handle connection error here
  1922. print(f"Connection error: {e}")
  1923. detail = "Pipeline not found"
  1924. if r is not None:
  1925. try:
  1926. res = r.json()
  1927. if "detail" in res:
  1928. detail = res["detail"]
  1929. except Exception:
  1930. pass
  1931. raise HTTPException(
  1932. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1933. detail=detail,
  1934. )
  1935. @app.get("/api/pipelines/{pipeline_id}/valves")
  1936. async def get_pipeline_valves(
  1937. urlIdx: Optional[int],
  1938. pipeline_id: str,
  1939. user=Depends(get_admin_user),
  1940. ):
  1941. r = None
  1942. try:
  1943. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1944. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1945. headers = {"Authorization": f"Bearer {key}"}
  1946. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  1947. r.raise_for_status()
  1948. data = r.json()
  1949. return {**data}
  1950. except Exception as e:
  1951. # Handle connection error here
  1952. print(f"Connection error: {e}")
  1953. detail = "Pipeline not found"
  1954. if r is not None:
  1955. try:
  1956. res = r.json()
  1957. if "detail" in res:
  1958. detail = res["detail"]
  1959. except Exception:
  1960. pass
  1961. raise HTTPException(
  1962. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1963. detail=detail,
  1964. )
  1965. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1966. async def get_pipeline_valves_spec(
  1967. urlIdx: Optional[int],
  1968. pipeline_id: str,
  1969. user=Depends(get_admin_user),
  1970. ):
  1971. r = None
  1972. try:
  1973. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1974. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1975. headers = {"Authorization": f"Bearer {key}"}
  1976. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  1977. r.raise_for_status()
  1978. data = r.json()
  1979. return {**data}
  1980. except Exception as e:
  1981. # Handle connection error here
  1982. print(f"Connection error: {e}")
  1983. detail = "Pipeline not found"
  1984. if r is not None:
  1985. try:
  1986. res = r.json()
  1987. if "detail" in res:
  1988. detail = res["detail"]
  1989. except Exception:
  1990. pass
  1991. raise HTTPException(
  1992. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1993. detail=detail,
  1994. )
  1995. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1996. async def update_pipeline_valves(
  1997. urlIdx: Optional[int],
  1998. pipeline_id: str,
  1999. form_data: dict,
  2000. user=Depends(get_admin_user),
  2001. ):
  2002. r = None
  2003. try:
  2004. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  2005. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  2006. headers = {"Authorization": f"Bearer {key}"}
  2007. r = requests.post(
  2008. f"{url}/{pipeline_id}/valves/update",
  2009. headers=headers,
  2010. json={**form_data},
  2011. )
  2012. r.raise_for_status()
  2013. data = r.json()
  2014. return {**data}
  2015. except Exception as e:
  2016. # Handle connection error here
  2017. print(f"Connection error: {e}")
  2018. detail = "Pipeline not found"
  2019. if r is not None:
  2020. try:
  2021. res = r.json()
  2022. if "detail" in res:
  2023. detail = res["detail"]
  2024. except Exception:
  2025. pass
  2026. raise HTTPException(
  2027. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  2028. detail=detail,
  2029. )
  2030. ##################################
  2031. #
  2032. # Config Endpoints
  2033. #
  2034. ##################################
  2035. @app.get("/api/config")
  2036. async def get_app_config(request: Request):
  2037. user = None
  2038. if "token" in request.cookies:
  2039. token = request.cookies.get("token")
  2040. try:
  2041. data = decode_token(token)
  2042. except Exception as e:
  2043. log.debug(e)
  2044. raise HTTPException(
  2045. status_code=status.HTTP_401_UNAUTHORIZED,
  2046. detail="Invalid token",
  2047. )
  2048. if data is not None and "id" in data:
  2049. user = Users.get_user_by_id(data["id"])
  2050. onboarding = False
  2051. if user is None:
  2052. user_count = Users.get_num_users()
  2053. onboarding = user_count == 0
  2054. return {
  2055. **({"onboarding": True} if onboarding else {}),
  2056. "status": True,
  2057. "name": WEBUI_NAME,
  2058. "version": VERSION,
  2059. "default_locale": str(DEFAULT_LOCALE),
  2060. "oauth": {
  2061. "providers": {
  2062. name: config.get("name", name)
  2063. for name, config in OAUTH_PROVIDERS.items()
  2064. }
  2065. },
  2066. "features": {
  2067. "auth": WEBUI_AUTH,
  2068. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  2069. "enable_ldap": webui_app.state.config.ENABLE_LDAP,
  2070. "enable_api_key": webui_app.state.config.ENABLE_API_KEY,
  2071. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  2072. "enable_login_form": webui_app.state.config.ENABLE_LOGIN_FORM,
  2073. **(
  2074. {
  2075. "enable_web_search": retrieval_app.state.config.ENABLE_RAG_WEB_SEARCH,
  2076. "enable_image_generation": images_app.state.config.ENABLED,
  2077. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  2078. "enable_message_rating": webui_app.state.config.ENABLE_MESSAGE_RATING,
  2079. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  2080. "enable_admin_chat_access": ENABLE_ADMIN_CHAT_ACCESS,
  2081. }
  2082. if user is not None
  2083. else {}
  2084. ),
  2085. },
  2086. **(
  2087. {
  2088. "default_models": webui_app.state.config.DEFAULT_MODELS,
  2089. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  2090. "audio": {
  2091. "tts": {
  2092. "engine": audio_app.state.config.TTS_ENGINE,
  2093. "voice": audio_app.state.config.TTS_VOICE,
  2094. "split_on": audio_app.state.config.TTS_SPLIT_ON,
  2095. },
  2096. "stt": {
  2097. "engine": audio_app.state.config.STT_ENGINE,
  2098. },
  2099. },
  2100. "file": {
  2101. "max_size": retrieval_app.state.config.FILE_MAX_SIZE,
  2102. "max_count": retrieval_app.state.config.FILE_MAX_COUNT,
  2103. },
  2104. "permissions": {**webui_app.state.config.USER_PERMISSIONS},
  2105. }
  2106. if user is not None
  2107. else {}
  2108. ),
  2109. }
  2110. # TODO: webhook endpoint should be under config endpoints
  2111. @app.get("/api/webhook")
  2112. async def get_webhook_url(user=Depends(get_admin_user)):
  2113. return {
  2114. "url": app.state.config.WEBHOOK_URL,
  2115. }
  2116. class UrlForm(BaseModel):
  2117. url: str
  2118. @app.post("/api/webhook")
  2119. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  2120. app.state.config.WEBHOOK_URL = form_data.url
  2121. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  2122. return {"url": app.state.config.WEBHOOK_URL}
  2123. @app.get("/api/version")
  2124. async def get_app_version():
  2125. return {
  2126. "version": VERSION,
  2127. }
  2128. @app.get("/api/changelog")
  2129. async def get_app_changelog():
  2130. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  2131. @app.get("/api/version/updates")
  2132. async def get_app_latest_release_version():
  2133. if OFFLINE_MODE:
  2134. log.debug(
  2135. f"Offline mode is enabled, returning current version as latest version"
  2136. )
  2137. return {"current": VERSION, "latest": VERSION}
  2138. try:
  2139. timeout = aiohttp.ClientTimeout(total=1)
  2140. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  2141. async with session.get(
  2142. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  2143. ) as response:
  2144. response.raise_for_status()
  2145. data = await response.json()
  2146. latest_version = data["tag_name"]
  2147. return {"current": VERSION, "latest": latest_version[1:]}
  2148. except Exception as e:
  2149. log.debug(e)
  2150. return {"current": VERSION, "latest": VERSION}
  2151. ############################
  2152. # OAuth Login & Callback
  2153. ############################
  2154. # SessionMiddleware is used by authlib for oauth
  2155. if len(OAUTH_PROVIDERS) > 0:
  2156. app.add_middleware(
  2157. SessionMiddleware,
  2158. secret_key=WEBUI_SECRET_KEY,
  2159. session_cookie="oui-session",
  2160. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  2161. https_only=WEBUI_SESSION_COOKIE_SECURE,
  2162. )
  2163. @app.get("/oauth/{provider}/login")
  2164. async def oauth_login(provider: str, request: Request):
  2165. return await oauth_manager.handle_login(provider, request)
  2166. # OAuth login logic is as follows:
  2167. # 1. Attempt to find a user with matching subject ID, tied to the provider
  2168. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  2169. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  2170. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  2171. # - Email addresses are considered unique, so we fail registration if the email address is already taken
  2172. @app.get("/oauth/{provider}/callback")
  2173. async def oauth_callback(provider: str, request: Request, response: Response):
  2174. return await oauth_manager.handle_callback(provider, request, response)
  2175. @app.get("/manifest.json")
  2176. async def get_manifest_json():
  2177. return {
  2178. "name": WEBUI_NAME,
  2179. "short_name": WEBUI_NAME,
  2180. "description": "Open WebUI is an open, extensible, user-friendly interface for AI that adapts to your workflow.",
  2181. "start_url": "/",
  2182. "display": "standalone",
  2183. "background_color": "#343541",
  2184. "orientation": "natural",
  2185. "icons": [
  2186. {
  2187. "src": "/static/logo.png",
  2188. "type": "image/png",
  2189. "sizes": "500x500",
  2190. "purpose": "any",
  2191. },
  2192. {
  2193. "src": "/static/logo.png",
  2194. "type": "image/png",
  2195. "sizes": "500x500",
  2196. "purpose": "maskable",
  2197. },
  2198. ],
  2199. }
  2200. @app.get("/opensearch.xml")
  2201. async def get_opensearch_xml():
  2202. xml_content = rf"""
  2203. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  2204. <ShortName>{WEBUI_NAME}</ShortName>
  2205. <Description>Search {WEBUI_NAME}</Description>
  2206. <InputEncoding>UTF-8</InputEncoding>
  2207. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/static/favicon.png</Image>
  2208. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  2209. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  2210. </OpenSearchDescription>
  2211. """
  2212. return Response(content=xml_content, media_type="application/xml")
  2213. @app.get("/health")
  2214. async def healthcheck():
  2215. return {"status": True}
  2216. @app.get("/health/db")
  2217. async def healthcheck_with_db():
  2218. Session.execute(text("SELECT 1;")).all()
  2219. return {"status": True}
  2220. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  2221. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  2222. if os.path.exists(FRONTEND_BUILD_DIR):
  2223. mimetypes.add_type("text/javascript", ".js")
  2224. app.mount(
  2225. "/",
  2226. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  2227. name="spa-static-files",
  2228. )
  2229. else:
  2230. log.warning(
  2231. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  2232. )