main.py 79 KB

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