main.py 82 KB

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