main.py 77 KB

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