main.py 91 KB

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