main.py 71 KB

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