main.py 76 KB

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