main.py 78 KB

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