main.py 78 KB

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