main.py 89 KB

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