main.py 82 KB

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