main.py 74 KB

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