main.py 81 KB

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