main.py 74 KB

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