main.py 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456
  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. from urllib.parse import urlencode, parse_qs, urlparse
  676. class RedirectMiddleware(BaseHTTPMiddleware):
  677. async def dispatch(self, request: Request, call_next):
  678. # Check if the request is a GET request
  679. if request.method == "GET":
  680. path = request.url.path
  681. query_params = dict(parse_qs(urlparse(str(request.url)).query))
  682. # Check for the specific watch path and the presence of 'v' parameter
  683. if path.endswith("/watch") and "v" in query_params:
  684. video_id = query_params["v"][0] # Extract the first 'v' parameter
  685. encoded_video_id = urlencode({"youtube": video_id})
  686. redirect_url = f"/?{encoded_video_id}"
  687. return RedirectResponse(url=redirect_url)
  688. # Proceed with the normal flow of other requests
  689. response = await call_next(request)
  690. return response
  691. # Add the middleware to the app
  692. app.add_middleware(RedirectMiddleware)
  693. app.add_middleware(
  694. CORSMiddleware,
  695. allow_origins=CORS_ALLOW_ORIGIN,
  696. allow_credentials=True,
  697. allow_methods=["*"],
  698. allow_headers=["*"],
  699. )
  700. app.add_middleware(SecurityHeadersMiddleware)
  701. @app.middleware("http")
  702. async def commit_session_after_request(request: Request, call_next):
  703. response = await call_next(request)
  704. log.debug("Commit session after request")
  705. Session.commit()
  706. return response
  707. @app.middleware("http")
  708. async def check_url(request: Request, call_next):
  709. if len(app.state.MODELS) == 0:
  710. await get_all_models()
  711. else:
  712. pass
  713. start_time = int(time.time())
  714. response = await call_next(request)
  715. process_time = int(time.time()) - start_time
  716. response.headers["X-Process-Time"] = str(process_time)
  717. return response
  718. @app.middleware("http")
  719. async def update_embedding_function(request: Request, call_next):
  720. response = await call_next(request)
  721. if "/embedding/update" in request.url.path:
  722. webui_app.state.EMBEDDING_FUNCTION = retrieval_app.state.EMBEDDING_FUNCTION
  723. return response
  724. @app.middleware("http")
  725. async def inspect_websocket(request: Request, call_next):
  726. if (
  727. "/ws/socket.io" in request.url.path
  728. and request.query_params.get("transport") == "websocket"
  729. ):
  730. upgrade = (request.headers.get("Upgrade") or "").lower()
  731. connection = (request.headers.get("Connection") or "").lower().split(",")
  732. # Check that there's the correct headers for an upgrade, else reject the connection
  733. # This is to work around this upstream issue: https://github.com/miguelgrinberg/python-engineio/issues/367
  734. if upgrade != "websocket" or "upgrade" not in connection:
  735. return JSONResponse(
  736. status_code=status.HTTP_400_BAD_REQUEST,
  737. content={"detail": "Invalid WebSocket upgrade request"},
  738. )
  739. return await call_next(request)
  740. app.mount("/ws", socket_app)
  741. app.mount("/ollama", ollama_app)
  742. app.mount("/openai", openai_app)
  743. app.mount("/images/api/v1", images_app)
  744. app.mount("/audio/api/v1", audio_app)
  745. app.mount("/retrieval/api/v1", retrieval_app)
  746. app.mount("/api/v1", webui_app)
  747. webui_app.state.EMBEDDING_FUNCTION = retrieval_app.state.EMBEDDING_FUNCTION
  748. async def get_all_models():
  749. # TODO: Optimize this function
  750. pipe_models = []
  751. openai_models = []
  752. ollama_models = []
  753. pipe_models = await get_pipe_models()
  754. if app.state.config.ENABLE_OPENAI_API:
  755. openai_models = await get_openai_models()
  756. openai_models = openai_models["data"]
  757. if app.state.config.ENABLE_OLLAMA_API:
  758. ollama_models = await get_ollama_models()
  759. ollama_models = [
  760. {
  761. "id": model["model"],
  762. "name": model["name"],
  763. "object": "model",
  764. "created": int(time.time()),
  765. "owned_by": "ollama",
  766. "ollama": model,
  767. }
  768. for model in ollama_models["models"]
  769. ]
  770. models = pipe_models + openai_models + ollama_models
  771. global_action_ids = [
  772. function.id for function in Functions.get_global_action_functions()
  773. ]
  774. enabled_action_ids = [
  775. function.id
  776. for function in Functions.get_functions_by_type("action", active_only=True)
  777. ]
  778. custom_models = Models.get_all_models()
  779. for custom_model in custom_models:
  780. if custom_model.base_model_id is None:
  781. for model in models:
  782. if (
  783. custom_model.id == model["id"]
  784. or custom_model.id == model["id"].split(":")[0]
  785. ):
  786. model["name"] = custom_model.name
  787. model["info"] = custom_model.model_dump()
  788. action_ids = []
  789. if "info" in model and "meta" in model["info"]:
  790. action_ids.extend(model["info"]["meta"].get("actionIds", []))
  791. model["action_ids"] = action_ids
  792. else:
  793. owned_by = "openai"
  794. pipe = None
  795. action_ids = []
  796. for model in models:
  797. if (
  798. custom_model.base_model_id == model["id"]
  799. or custom_model.base_model_id == model["id"].split(":")[0]
  800. ):
  801. owned_by = model["owned_by"]
  802. if "pipe" in model:
  803. pipe = model["pipe"]
  804. if "info" in model and "meta" in model["info"]:
  805. action_ids.extend(model["info"]["meta"].get("actionIds", []))
  806. break
  807. models.append(
  808. {
  809. "id": custom_model.id,
  810. "name": custom_model.name,
  811. "object": "model",
  812. "created": custom_model.created_at,
  813. "owned_by": owned_by,
  814. "info": custom_model.model_dump(),
  815. "preset": True,
  816. **({"pipe": pipe} if pipe is not None else {}),
  817. "action_ids": action_ids,
  818. }
  819. )
  820. for model in models:
  821. action_ids = []
  822. if "action_ids" in model:
  823. action_ids = model["action_ids"]
  824. del model["action_ids"]
  825. action_ids = action_ids + global_action_ids
  826. action_ids = list(set(action_ids))
  827. action_ids = [
  828. action_id for action_id in action_ids if action_id in enabled_action_ids
  829. ]
  830. model["actions"] = []
  831. for action_id in action_ids:
  832. action = Functions.get_function_by_id(action_id)
  833. if action is None:
  834. raise Exception(f"Action not found: {action_id}")
  835. if action_id in webui_app.state.FUNCTIONS:
  836. function_module = webui_app.state.FUNCTIONS[action_id]
  837. else:
  838. function_module, _, _ = load_function_module_by_id(action_id)
  839. webui_app.state.FUNCTIONS[action_id] = function_module
  840. __webui__ = False
  841. if hasattr(function_module, "__webui__"):
  842. __webui__ = function_module.__webui__
  843. if hasattr(function_module, "actions"):
  844. actions = function_module.actions
  845. model["actions"].extend(
  846. [
  847. {
  848. "id": f"{action_id}.{_action['id']}",
  849. "name": _action.get(
  850. "name", f"{action.name} ({_action['id']})"
  851. ),
  852. "description": action.meta.description,
  853. "icon_url": _action.get(
  854. "icon_url", action.meta.manifest.get("icon_url", None)
  855. ),
  856. **({"__webui__": __webui__} if __webui__ else {}),
  857. }
  858. for _action in actions
  859. ]
  860. )
  861. else:
  862. model["actions"].append(
  863. {
  864. "id": action_id,
  865. "name": action.name,
  866. "description": action.meta.description,
  867. "icon_url": action.meta.manifest.get("icon_url", None),
  868. **({"__webui__": __webui__} if __webui__ else {}),
  869. }
  870. )
  871. app.state.MODELS = {model["id"]: model for model in models}
  872. webui_app.state.MODELS = app.state.MODELS
  873. return models
  874. @app.get("/api/models")
  875. async def get_models(user=Depends(get_verified_user)):
  876. models = await get_all_models()
  877. # Filter out filter pipelines
  878. models = [
  879. model
  880. for model in models
  881. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  882. ]
  883. if app.state.config.ENABLE_MODEL_FILTER:
  884. if user.role == "user":
  885. models = list(
  886. filter(
  887. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  888. models,
  889. )
  890. )
  891. return {"data": models}
  892. return {"data": models}
  893. @app.post("/api/chat/completions")
  894. async def generate_chat_completions(form_data: dict, user=Depends(get_verified_user)):
  895. model_id = form_data["model"]
  896. if model_id not in app.state.MODELS:
  897. raise HTTPException(
  898. status_code=status.HTTP_404_NOT_FOUND,
  899. detail="Model not found",
  900. )
  901. if app.state.config.ENABLE_MODEL_FILTER:
  902. if user.role == "user" and model_id not in app.state.config.MODEL_FILTER_LIST:
  903. raise HTTPException(
  904. status_code=status.HTTP_403_FORBIDDEN,
  905. detail="Model not found",
  906. )
  907. model = app.state.MODELS[model_id]
  908. if model.get("pipe"):
  909. return await generate_function_chat_completion(form_data, user=user)
  910. if model["owned_by"] == "ollama":
  911. # Using /ollama/api/chat endpoint
  912. form_data = convert_payload_openai_to_ollama(form_data)
  913. form_data = GenerateChatCompletionForm(**form_data)
  914. response = await generate_ollama_chat_completion(form_data=form_data, user=user)
  915. if form_data.stream:
  916. response.headers["content-type"] = "text/event-stream"
  917. return StreamingResponse(
  918. convert_streaming_response_ollama_to_openai(response),
  919. headers=dict(response.headers),
  920. )
  921. else:
  922. return convert_response_ollama_to_openai(response)
  923. else:
  924. return await generate_openai_chat_completion(form_data, user=user)
  925. @app.post("/api/chat/completed")
  926. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  927. data = form_data
  928. model_id = data["model"]
  929. if model_id not in app.state.MODELS:
  930. raise HTTPException(
  931. status_code=status.HTTP_404_NOT_FOUND,
  932. detail="Model not found",
  933. )
  934. model = app.state.MODELS[model_id]
  935. sorted_filters = get_sorted_filters(model_id)
  936. if "pipeline" in model:
  937. sorted_filters = [model] + sorted_filters
  938. for filter in sorted_filters:
  939. r = None
  940. try:
  941. urlIdx = filter["urlIdx"]
  942. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  943. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  944. if key != "":
  945. headers = {"Authorization": f"Bearer {key}"}
  946. r = requests.post(
  947. f"{url}/{filter['id']}/filter/outlet",
  948. headers=headers,
  949. json={
  950. "user": {
  951. "id": user.id,
  952. "name": user.name,
  953. "email": user.email,
  954. "role": user.role,
  955. },
  956. "body": data,
  957. },
  958. )
  959. r.raise_for_status()
  960. data = r.json()
  961. except Exception as e:
  962. # Handle connection error here
  963. print(f"Connection error: {e}")
  964. if r is not None:
  965. try:
  966. res = r.json()
  967. if "detail" in res:
  968. return JSONResponse(
  969. status_code=r.status_code,
  970. content=res,
  971. )
  972. except Exception:
  973. pass
  974. else:
  975. pass
  976. __event_emitter__ = get_event_emitter(
  977. {
  978. "chat_id": data["chat_id"],
  979. "message_id": data["id"],
  980. "session_id": data["session_id"],
  981. }
  982. )
  983. __event_call__ = get_event_call(
  984. {
  985. "chat_id": data["chat_id"],
  986. "message_id": data["id"],
  987. "session_id": data["session_id"],
  988. }
  989. )
  990. def get_priority(function_id):
  991. function = Functions.get_function_by_id(function_id)
  992. if function is not None and hasattr(function, "valves"):
  993. # TODO: Fix FunctionModel to include vavles
  994. return (function.valves if function.valves else {}).get("priority", 0)
  995. return 0
  996. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  997. if "info" in model and "meta" in model["info"]:
  998. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  999. filter_ids = list(set(filter_ids))
  1000. enabled_filter_ids = [
  1001. function.id
  1002. for function in Functions.get_functions_by_type("filter", active_only=True)
  1003. ]
  1004. filter_ids = [
  1005. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  1006. ]
  1007. # Sort filter_ids by priority, using the get_priority function
  1008. filter_ids.sort(key=get_priority)
  1009. for filter_id in filter_ids:
  1010. filter = Functions.get_function_by_id(filter_id)
  1011. if not filter:
  1012. continue
  1013. if filter_id in webui_app.state.FUNCTIONS:
  1014. function_module = webui_app.state.FUNCTIONS[filter_id]
  1015. else:
  1016. function_module, _, _ = load_function_module_by_id(filter_id)
  1017. webui_app.state.FUNCTIONS[filter_id] = function_module
  1018. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1019. valves = Functions.get_function_valves_by_id(filter_id)
  1020. function_module.valves = function_module.Valves(
  1021. **(valves if valves else {})
  1022. )
  1023. if not hasattr(function_module, "outlet"):
  1024. continue
  1025. try:
  1026. outlet = function_module.outlet
  1027. # Get the signature of the function
  1028. sig = inspect.signature(outlet)
  1029. params = {"body": data}
  1030. # Extra parameters to be passed to the function
  1031. extra_params = {
  1032. "__model__": model,
  1033. "__id__": filter_id,
  1034. "__event_emitter__": __event_emitter__,
  1035. "__event_call__": __event_call__,
  1036. }
  1037. # Add extra params in contained in function signature
  1038. for key, value in extra_params.items():
  1039. if key in sig.parameters:
  1040. params[key] = value
  1041. if "__user__" in sig.parameters:
  1042. __user__ = {
  1043. "id": user.id,
  1044. "email": user.email,
  1045. "name": user.name,
  1046. "role": user.role,
  1047. }
  1048. try:
  1049. if hasattr(function_module, "UserValves"):
  1050. __user__["valves"] = function_module.UserValves(
  1051. **Functions.get_user_valves_by_id_and_user_id(
  1052. filter_id, user.id
  1053. )
  1054. )
  1055. except Exception as e:
  1056. print(e)
  1057. params = {**params, "__user__": __user__}
  1058. if inspect.iscoroutinefunction(outlet):
  1059. data = await outlet(**params)
  1060. else:
  1061. data = outlet(**params)
  1062. except Exception as e:
  1063. print(f"Error: {e}")
  1064. return JSONResponse(
  1065. status_code=status.HTTP_400_BAD_REQUEST,
  1066. content={"detail": str(e)},
  1067. )
  1068. return data
  1069. @app.post("/api/chat/actions/{action_id}")
  1070. async def chat_action(action_id: str, form_data: dict, user=Depends(get_verified_user)):
  1071. if "." in action_id:
  1072. action_id, sub_action_id = action_id.split(".")
  1073. else:
  1074. sub_action_id = None
  1075. action = Functions.get_function_by_id(action_id)
  1076. if not action:
  1077. raise HTTPException(
  1078. status_code=status.HTTP_404_NOT_FOUND,
  1079. detail="Action not found",
  1080. )
  1081. data = form_data
  1082. model_id = data["model"]
  1083. if model_id not in app.state.MODELS:
  1084. raise HTTPException(
  1085. status_code=status.HTTP_404_NOT_FOUND,
  1086. detail="Model not found",
  1087. )
  1088. model = app.state.MODELS[model_id]
  1089. __event_emitter__ = get_event_emitter(
  1090. {
  1091. "chat_id": data["chat_id"],
  1092. "message_id": data["id"],
  1093. "session_id": data["session_id"],
  1094. }
  1095. )
  1096. __event_call__ = get_event_call(
  1097. {
  1098. "chat_id": data["chat_id"],
  1099. "message_id": data["id"],
  1100. "session_id": data["session_id"],
  1101. }
  1102. )
  1103. if action_id in webui_app.state.FUNCTIONS:
  1104. function_module = webui_app.state.FUNCTIONS[action_id]
  1105. else:
  1106. function_module, _, _ = load_function_module_by_id(action_id)
  1107. webui_app.state.FUNCTIONS[action_id] = function_module
  1108. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1109. valves = Functions.get_function_valves_by_id(action_id)
  1110. function_module.valves = function_module.Valves(**(valves if valves else {}))
  1111. if hasattr(function_module, "action"):
  1112. try:
  1113. action = function_module.action
  1114. # Get the signature of the function
  1115. sig = inspect.signature(action)
  1116. params = {"body": data}
  1117. # Extra parameters to be passed to the function
  1118. extra_params = {
  1119. "__model__": model,
  1120. "__id__": sub_action_id if sub_action_id is not None else action_id,
  1121. "__event_emitter__": __event_emitter__,
  1122. "__event_call__": __event_call__,
  1123. }
  1124. # Add extra params in contained in function signature
  1125. for key, value in extra_params.items():
  1126. if key in sig.parameters:
  1127. params[key] = value
  1128. if "__user__" in sig.parameters:
  1129. __user__ = {
  1130. "id": user.id,
  1131. "email": user.email,
  1132. "name": user.name,
  1133. "role": user.role,
  1134. }
  1135. try:
  1136. if hasattr(function_module, "UserValves"):
  1137. __user__["valves"] = function_module.UserValves(
  1138. **Functions.get_user_valves_by_id_and_user_id(
  1139. action_id, user.id
  1140. )
  1141. )
  1142. except Exception as e:
  1143. print(e)
  1144. params = {**params, "__user__": __user__}
  1145. if inspect.iscoroutinefunction(action):
  1146. data = await action(**params)
  1147. else:
  1148. data = action(**params)
  1149. except Exception as e:
  1150. print(f"Error: {e}")
  1151. return JSONResponse(
  1152. status_code=status.HTTP_400_BAD_REQUEST,
  1153. content={"detail": str(e)},
  1154. )
  1155. return data
  1156. ##################################
  1157. #
  1158. # Task Endpoints
  1159. #
  1160. ##################################
  1161. # TODO: Refactor task API endpoints below into a separate file
  1162. @app.get("/api/task/config")
  1163. async def get_task_config(user=Depends(get_verified_user)):
  1164. return {
  1165. "TASK_MODEL": app.state.config.TASK_MODEL,
  1166. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1167. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1168. "ENABLE_SEARCH_QUERY": app.state.config.ENABLE_SEARCH_QUERY,
  1169. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1170. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1171. }
  1172. class TaskConfigForm(BaseModel):
  1173. TASK_MODEL: Optional[str]
  1174. TASK_MODEL_EXTERNAL: Optional[str]
  1175. TITLE_GENERATION_PROMPT_TEMPLATE: str
  1176. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE: str
  1177. ENABLE_SEARCH_QUERY: bool
  1178. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  1179. @app.post("/api/task/config/update")
  1180. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  1181. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  1182. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  1183. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  1184. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  1185. )
  1186. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  1187. form_data.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1188. )
  1189. app.state.config.ENABLE_SEARCH_QUERY = form_data.ENABLE_SEARCH_QUERY
  1190. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  1191. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1192. )
  1193. return {
  1194. "TASK_MODEL": app.state.config.TASK_MODEL,
  1195. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1196. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1197. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1198. "ENABLE_SEARCH_QUERY": app.state.config.ENABLE_SEARCH_QUERY,
  1199. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1200. }
  1201. @app.post("/api/task/title/completions")
  1202. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  1203. print("generate_title")
  1204. model_id = form_data["model"]
  1205. if model_id not in app.state.MODELS:
  1206. raise HTTPException(
  1207. status_code=status.HTTP_404_NOT_FOUND,
  1208. detail="Model not found",
  1209. )
  1210. # Check if the user has a custom task model
  1211. # If the user has a custom task model, use that model
  1212. task_model_id = get_task_model_id(model_id)
  1213. print(task_model_id)
  1214. model = app.state.MODELS[task_model_id]
  1215. if app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE != "":
  1216. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  1217. else:
  1218. template = """Create a concise, 3-5 word title with an emoji as a title for the 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.
  1219. Examples of titles:
  1220. 📉 Stock Market Trends
  1221. 🍪 Perfect Chocolate Chip Recipe
  1222. Evolution of Music Streaming
  1223. Remote Work Productivity Tips
  1224. Artificial Intelligence in Healthcare
  1225. 🎮 Video Game Development Insights
  1226. Prompt: {{prompt:middletruncate:8000}}"""
  1227. content = title_generation_template(
  1228. template,
  1229. form_data["prompt"],
  1230. {
  1231. "name": user.name,
  1232. "location": user.info.get("location") if user.info else None,
  1233. },
  1234. )
  1235. payload = {
  1236. "model": task_model_id,
  1237. "messages": [{"role": "user", "content": content}],
  1238. "stream": False,
  1239. **(
  1240. {"max_tokens": 50}
  1241. if app.state.MODELS[task_model_id]["owned_by"] == "ollama"
  1242. else {
  1243. "max_completion_tokens": 50,
  1244. }
  1245. ),
  1246. "chat_id": form_data.get("chat_id", None),
  1247. "metadata": {"task": str(TASKS.TITLE_GENERATION), "task_body": form_data},
  1248. }
  1249. log.debug(payload)
  1250. # Handle pipeline filters
  1251. try:
  1252. payload = filter_pipeline(payload, user)
  1253. except Exception as e:
  1254. if len(e.args) > 1:
  1255. return JSONResponse(
  1256. status_code=e.args[0],
  1257. content={"detail": e.args[1]},
  1258. )
  1259. else:
  1260. return JSONResponse(
  1261. status_code=status.HTTP_400_BAD_REQUEST,
  1262. content={"detail": str(e)},
  1263. )
  1264. if "chat_id" in payload:
  1265. del payload["chat_id"]
  1266. return await generate_chat_completions(form_data=payload, user=user)
  1267. @app.post("/api/task/query/completions")
  1268. async def generate_search_query(form_data: dict, user=Depends(get_verified_user)):
  1269. print("generate_search_query")
  1270. if not app.state.config.ENABLE_SEARCH_QUERY:
  1271. raise HTTPException(
  1272. status_code=status.HTTP_400_BAD_REQUEST,
  1273. detail=f"Search query generation is disabled",
  1274. )
  1275. model_id = form_data["model"]
  1276. if model_id not in app.state.MODELS:
  1277. raise HTTPException(
  1278. status_code=status.HTTP_404_NOT_FOUND,
  1279. detail="Model not found",
  1280. )
  1281. # Check if the user has a custom task model
  1282. # If the user has a custom task model, use that model
  1283. task_model_id = get_task_model_id(model_id)
  1284. print(task_model_id)
  1285. model = app.state.MODELS[task_model_id]
  1286. if app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE != "":
  1287. template = app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1288. else:
  1289. 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}}.
  1290. User Message:
  1291. {{prompt:end:4000}}
  1292. Interaction History:
  1293. {{MESSAGES:END:6}}
  1294. Search Query:"""
  1295. content = search_query_generation_template(
  1296. template, form_data["messages"], {"name": user.name}
  1297. )
  1298. print("content", content)
  1299. payload = {
  1300. "model": task_model_id,
  1301. "messages": [{"role": "user", "content": content}],
  1302. "stream": False,
  1303. **(
  1304. {"max_tokens": 30}
  1305. if app.state.MODELS[task_model_id]["owned_by"] == "ollama"
  1306. else {
  1307. "max_completion_tokens": 30,
  1308. }
  1309. ),
  1310. "metadata": {"task": str(TASKS.QUERY_GENERATION), "task_body": form_data},
  1311. }
  1312. log.debug(payload)
  1313. # Handle pipeline filters
  1314. try:
  1315. payload = filter_pipeline(payload, user)
  1316. except Exception as e:
  1317. if len(e.args) > 1:
  1318. return JSONResponse(
  1319. status_code=e.args[0],
  1320. content={"detail": e.args[1]},
  1321. )
  1322. else:
  1323. return JSONResponse(
  1324. status_code=status.HTTP_400_BAD_REQUEST,
  1325. content={"detail": str(e)},
  1326. )
  1327. if "chat_id" in payload:
  1328. del payload["chat_id"]
  1329. return await generate_chat_completions(form_data=payload, user=user)
  1330. @app.post("/api/task/emoji/completions")
  1331. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  1332. print("generate_emoji")
  1333. model_id = form_data["model"]
  1334. if model_id not in app.state.MODELS:
  1335. raise HTTPException(
  1336. status_code=status.HTTP_404_NOT_FOUND,
  1337. detail="Model not found",
  1338. )
  1339. # Check if the user has a custom task model
  1340. # If the user has a custom task model, use that model
  1341. task_model_id = get_task_model_id(model_id)
  1342. print(task_model_id)
  1343. model = app.state.MODELS[task_model_id]
  1344. template = '''
  1345. 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., 😊, 😢, 😡, 😱).
  1346. Message: """{{prompt}}"""
  1347. '''
  1348. content = title_generation_template(
  1349. template,
  1350. form_data["prompt"],
  1351. {
  1352. "name": user.name,
  1353. "location": user.info.get("location") if user.info else None,
  1354. },
  1355. )
  1356. payload = {
  1357. "model": task_model_id,
  1358. "messages": [{"role": "user", "content": content}],
  1359. "stream": False,
  1360. **(
  1361. {"max_tokens": 4}
  1362. if app.state.MODELS[task_model_id]["owned_by"] == "ollama"
  1363. else {
  1364. "max_completion_tokens": 4,
  1365. }
  1366. ),
  1367. "chat_id": form_data.get("chat_id", None),
  1368. "metadata": {"task": str(TASKS.EMOJI_GENERATION), "task_body": form_data},
  1369. }
  1370. log.debug(payload)
  1371. # Handle pipeline filters
  1372. try:
  1373. payload = filter_pipeline(payload, user)
  1374. except Exception as e:
  1375. if len(e.args) > 1:
  1376. return JSONResponse(
  1377. status_code=e.args[0],
  1378. content={"detail": e.args[1]},
  1379. )
  1380. else:
  1381. return JSONResponse(
  1382. status_code=status.HTTP_400_BAD_REQUEST,
  1383. content={"detail": str(e)},
  1384. )
  1385. if "chat_id" in payload:
  1386. del payload["chat_id"]
  1387. return await generate_chat_completions(form_data=payload, user=user)
  1388. @app.post("/api/task/moa/completions")
  1389. async def generate_moa_response(form_data: dict, user=Depends(get_verified_user)):
  1390. print("generate_moa_response")
  1391. model_id = form_data["model"]
  1392. if model_id not in app.state.MODELS:
  1393. raise HTTPException(
  1394. status_code=status.HTTP_404_NOT_FOUND,
  1395. detail="Model not found",
  1396. )
  1397. # Check if the user has a custom task model
  1398. # If the user has a custom task model, use that model
  1399. task_model_id = get_task_model_id(model_id)
  1400. print(task_model_id)
  1401. model = app.state.MODELS[task_model_id]
  1402. template = """You have been provided with a set of responses from various models to the latest user query: "{{prompt}}"
  1403. 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.
  1404. Responses from models: {{responses}}"""
  1405. content = moa_response_generation_template(
  1406. template,
  1407. form_data["prompt"],
  1408. form_data["responses"],
  1409. )
  1410. payload = {
  1411. "model": task_model_id,
  1412. "messages": [{"role": "user", "content": content}],
  1413. "stream": form_data.get("stream", False),
  1414. "chat_id": form_data.get("chat_id", None),
  1415. "metadata": {
  1416. "task": str(TASKS.MOA_RESPONSE_GENERATION),
  1417. "task_body": form_data,
  1418. },
  1419. }
  1420. log.debug(payload)
  1421. try:
  1422. payload = filter_pipeline(payload, user)
  1423. except Exception as e:
  1424. if len(e.args) > 1:
  1425. return JSONResponse(
  1426. status_code=e.args[0],
  1427. content={"detail": e.args[1]},
  1428. )
  1429. else:
  1430. return JSONResponse(
  1431. status_code=status.HTTP_400_BAD_REQUEST,
  1432. content={"detail": str(e)},
  1433. )
  1434. if "chat_id" in payload:
  1435. del payload["chat_id"]
  1436. return await generate_chat_completions(form_data=payload, user=user)
  1437. ##################################
  1438. #
  1439. # Pipelines Endpoints
  1440. #
  1441. ##################################
  1442. # TODO: Refactor pipelines API endpoints below into a separate file
  1443. @app.get("/api/pipelines/list")
  1444. async def get_pipelines_list(user=Depends(get_admin_user)):
  1445. responses = await get_openai_models(raw=True)
  1446. print(responses)
  1447. urlIdxs = [
  1448. idx
  1449. for idx, response in enumerate(responses)
  1450. if response is not None and "pipelines" in response
  1451. ]
  1452. return {
  1453. "data": [
  1454. {
  1455. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  1456. "idx": urlIdx,
  1457. }
  1458. for urlIdx in urlIdxs
  1459. ]
  1460. }
  1461. @app.post("/api/pipelines/upload")
  1462. async def upload_pipeline(
  1463. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  1464. ):
  1465. print("upload_pipeline", urlIdx, file.filename)
  1466. # Check if the uploaded file is a python file
  1467. if not (file.filename and file.filename.endswith(".py")):
  1468. raise HTTPException(
  1469. status_code=status.HTTP_400_BAD_REQUEST,
  1470. detail="Only Python (.py) files are allowed.",
  1471. )
  1472. upload_folder = f"{CACHE_DIR}/pipelines"
  1473. os.makedirs(upload_folder, exist_ok=True)
  1474. file_path = os.path.join(upload_folder, file.filename)
  1475. r = None
  1476. try:
  1477. # Save the uploaded file
  1478. with open(file_path, "wb") as buffer:
  1479. shutil.copyfileobj(file.file, buffer)
  1480. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1481. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1482. headers = {"Authorization": f"Bearer {key}"}
  1483. with open(file_path, "rb") as f:
  1484. files = {"file": f}
  1485. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1486. r.raise_for_status()
  1487. data = r.json()
  1488. return {**data}
  1489. except Exception as e:
  1490. # Handle connection error here
  1491. print(f"Connection error: {e}")
  1492. detail = "Pipeline not found"
  1493. status_code = status.HTTP_404_NOT_FOUND
  1494. if r is not None:
  1495. status_code = r.status_code
  1496. try:
  1497. res = r.json()
  1498. if "detail" in res:
  1499. detail = res["detail"]
  1500. except Exception:
  1501. pass
  1502. raise HTTPException(
  1503. status_code=status_code,
  1504. detail=detail,
  1505. )
  1506. finally:
  1507. # Ensure the file is deleted after the upload is completed or on failure
  1508. if os.path.exists(file_path):
  1509. os.remove(file_path)
  1510. class AddPipelineForm(BaseModel):
  1511. url: str
  1512. urlIdx: int
  1513. @app.post("/api/pipelines/add")
  1514. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1515. r = None
  1516. try:
  1517. urlIdx = form_data.urlIdx
  1518. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1519. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1520. headers = {"Authorization": f"Bearer {key}"}
  1521. r = requests.post(
  1522. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1523. )
  1524. r.raise_for_status()
  1525. data = r.json()
  1526. return {**data}
  1527. except Exception as e:
  1528. # Handle connection error here
  1529. print(f"Connection error: {e}")
  1530. detail = "Pipeline not found"
  1531. if r is not None:
  1532. try:
  1533. res = r.json()
  1534. if "detail" in res:
  1535. detail = res["detail"]
  1536. except Exception:
  1537. pass
  1538. raise HTTPException(
  1539. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1540. detail=detail,
  1541. )
  1542. class DeletePipelineForm(BaseModel):
  1543. id: str
  1544. urlIdx: int
  1545. @app.delete("/api/pipelines/delete")
  1546. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1547. r = None
  1548. try:
  1549. urlIdx = form_data.urlIdx
  1550. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1551. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1552. headers = {"Authorization": f"Bearer {key}"}
  1553. r = requests.delete(
  1554. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1555. )
  1556. r.raise_for_status()
  1557. data = r.json()
  1558. return {**data}
  1559. except Exception as e:
  1560. # Handle connection error here
  1561. print(f"Connection error: {e}")
  1562. detail = "Pipeline not found"
  1563. if r is not None:
  1564. try:
  1565. res = r.json()
  1566. if "detail" in res:
  1567. detail = res["detail"]
  1568. except Exception:
  1569. pass
  1570. raise HTTPException(
  1571. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1572. detail=detail,
  1573. )
  1574. @app.get("/api/pipelines")
  1575. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  1576. r = None
  1577. try:
  1578. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1579. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1580. headers = {"Authorization": f"Bearer {key}"}
  1581. r = requests.get(f"{url}/pipelines", headers=headers)
  1582. r.raise_for_status()
  1583. data = r.json()
  1584. return {**data}
  1585. except Exception as e:
  1586. # Handle connection error here
  1587. print(f"Connection error: {e}")
  1588. detail = "Pipeline not found"
  1589. if r is not None:
  1590. try:
  1591. res = r.json()
  1592. if "detail" in res:
  1593. detail = res["detail"]
  1594. except Exception:
  1595. pass
  1596. raise HTTPException(
  1597. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1598. detail=detail,
  1599. )
  1600. @app.get("/api/pipelines/{pipeline_id}/valves")
  1601. async def get_pipeline_valves(
  1602. urlIdx: Optional[int],
  1603. pipeline_id: str,
  1604. user=Depends(get_admin_user),
  1605. ):
  1606. r = None
  1607. try:
  1608. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1609. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1610. headers = {"Authorization": f"Bearer {key}"}
  1611. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  1612. r.raise_for_status()
  1613. data = r.json()
  1614. return {**data}
  1615. except Exception as e:
  1616. # Handle connection error here
  1617. print(f"Connection error: {e}")
  1618. detail = "Pipeline not found"
  1619. if r is not None:
  1620. try:
  1621. res = r.json()
  1622. if "detail" in res:
  1623. detail = res["detail"]
  1624. except Exception:
  1625. pass
  1626. raise HTTPException(
  1627. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1628. detail=detail,
  1629. )
  1630. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1631. async def get_pipeline_valves_spec(
  1632. urlIdx: Optional[int],
  1633. pipeline_id: str,
  1634. user=Depends(get_admin_user),
  1635. ):
  1636. r = None
  1637. try:
  1638. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1639. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1640. headers = {"Authorization": f"Bearer {key}"}
  1641. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  1642. r.raise_for_status()
  1643. data = r.json()
  1644. return {**data}
  1645. except Exception as e:
  1646. # Handle connection error here
  1647. print(f"Connection error: {e}")
  1648. detail = "Pipeline not found"
  1649. if r is not None:
  1650. try:
  1651. res = r.json()
  1652. if "detail" in res:
  1653. detail = res["detail"]
  1654. except Exception:
  1655. pass
  1656. raise HTTPException(
  1657. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1658. detail=detail,
  1659. )
  1660. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1661. async def update_pipeline_valves(
  1662. urlIdx: Optional[int],
  1663. pipeline_id: str,
  1664. form_data: dict,
  1665. user=Depends(get_admin_user),
  1666. ):
  1667. r = None
  1668. try:
  1669. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1670. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1671. headers = {"Authorization": f"Bearer {key}"}
  1672. r = requests.post(
  1673. f"{url}/{pipeline_id}/valves/update",
  1674. headers=headers,
  1675. json={**form_data},
  1676. )
  1677. r.raise_for_status()
  1678. data = r.json()
  1679. return {**data}
  1680. except Exception as e:
  1681. # Handle connection error here
  1682. print(f"Connection error: {e}")
  1683. detail = "Pipeline not found"
  1684. if r is not None:
  1685. try:
  1686. res = r.json()
  1687. if "detail" in res:
  1688. detail = res["detail"]
  1689. except Exception:
  1690. pass
  1691. raise HTTPException(
  1692. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1693. detail=detail,
  1694. )
  1695. ##################################
  1696. #
  1697. # Config Endpoints
  1698. #
  1699. ##################################
  1700. @app.get("/api/config")
  1701. async def get_app_config(request: Request):
  1702. user = None
  1703. if "token" in request.cookies:
  1704. token = request.cookies.get("token")
  1705. data = decode_token(token)
  1706. if data is not None and "id" in data:
  1707. user = Users.get_user_by_id(data["id"])
  1708. return {
  1709. "status": True,
  1710. "name": WEBUI_NAME,
  1711. "version": VERSION,
  1712. "default_locale": str(DEFAULT_LOCALE),
  1713. "oauth": {
  1714. "providers": {
  1715. name: config.get("name", name)
  1716. for name, config in OAUTH_PROVIDERS.items()
  1717. }
  1718. },
  1719. "features": {
  1720. "auth": WEBUI_AUTH,
  1721. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1722. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1723. "enable_login_form": webui_app.state.config.ENABLE_LOGIN_FORM,
  1724. **(
  1725. {
  1726. "enable_web_search": retrieval_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1727. "enable_image_generation": images_app.state.config.ENABLED,
  1728. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1729. "enable_message_rating": webui_app.state.config.ENABLE_MESSAGE_RATING,
  1730. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1731. "enable_admin_chat_access": ENABLE_ADMIN_CHAT_ACCESS,
  1732. }
  1733. if user is not None
  1734. else {}
  1735. ),
  1736. },
  1737. **(
  1738. {
  1739. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1740. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1741. "audio": {
  1742. "tts": {
  1743. "engine": audio_app.state.config.TTS_ENGINE,
  1744. "voice": audio_app.state.config.TTS_VOICE,
  1745. "split_on": audio_app.state.config.TTS_SPLIT_ON,
  1746. },
  1747. "stt": {
  1748. "engine": audio_app.state.config.STT_ENGINE,
  1749. },
  1750. },
  1751. "file": {
  1752. "max_size": retrieval_app.state.config.FILE_MAX_SIZE,
  1753. "max_count": retrieval_app.state.config.FILE_MAX_COUNT,
  1754. },
  1755. "permissions": {**webui_app.state.config.USER_PERMISSIONS},
  1756. }
  1757. if user is not None
  1758. else {}
  1759. ),
  1760. }
  1761. @app.get("/api/config/model/filter")
  1762. async def get_model_filter_config(user=Depends(get_admin_user)):
  1763. return {
  1764. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1765. "models": app.state.config.MODEL_FILTER_LIST,
  1766. }
  1767. class ModelFilterConfigForm(BaseModel):
  1768. enabled: bool
  1769. models: list[str]
  1770. @app.post("/api/config/model/filter")
  1771. async def update_model_filter_config(
  1772. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  1773. ):
  1774. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  1775. app.state.config.MODEL_FILTER_LIST = form_data.models
  1776. return {
  1777. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1778. "models": app.state.config.MODEL_FILTER_LIST,
  1779. }
  1780. # TODO: webhook endpoint should be under config endpoints
  1781. @app.get("/api/webhook")
  1782. async def get_webhook_url(user=Depends(get_admin_user)):
  1783. return {
  1784. "url": app.state.config.WEBHOOK_URL,
  1785. }
  1786. class UrlForm(BaseModel):
  1787. url: str
  1788. @app.post("/api/webhook")
  1789. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1790. app.state.config.WEBHOOK_URL = form_data.url
  1791. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1792. return {"url": app.state.config.WEBHOOK_URL}
  1793. @app.get("/api/version")
  1794. async def get_app_version():
  1795. return {
  1796. "version": VERSION,
  1797. }
  1798. @app.get("/api/changelog")
  1799. async def get_app_changelog():
  1800. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1801. @app.get("/api/version/updates")
  1802. async def get_app_latest_release_version():
  1803. try:
  1804. timeout = aiohttp.ClientTimeout(total=1)
  1805. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  1806. async with session.get(
  1807. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1808. ) as response:
  1809. response.raise_for_status()
  1810. data = await response.json()
  1811. latest_version = data["tag_name"]
  1812. return {"current": VERSION, "latest": latest_version[1:]}
  1813. except Exception as e:
  1814. log.debug(e)
  1815. return {"current": VERSION, "latest": VERSION}
  1816. ############################
  1817. # OAuth Login & Callback
  1818. ############################
  1819. oauth = OAuth()
  1820. for provider_name, provider_config in OAUTH_PROVIDERS.items():
  1821. oauth.register(
  1822. name=provider_name,
  1823. client_id=provider_config["client_id"],
  1824. client_secret=provider_config["client_secret"],
  1825. server_metadata_url=provider_config["server_metadata_url"],
  1826. client_kwargs={
  1827. "scope": provider_config["scope"],
  1828. },
  1829. redirect_uri=provider_config["redirect_uri"],
  1830. )
  1831. # SessionMiddleware is used by authlib for oauth
  1832. if len(OAUTH_PROVIDERS) > 0:
  1833. app.add_middleware(
  1834. SessionMiddleware,
  1835. secret_key=WEBUI_SECRET_KEY,
  1836. session_cookie="oui-session",
  1837. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  1838. https_only=WEBUI_SESSION_COOKIE_SECURE,
  1839. )
  1840. @app.get("/oauth/{provider}/login")
  1841. async def oauth_login(provider: str, request: Request):
  1842. if provider not in OAUTH_PROVIDERS:
  1843. raise HTTPException(404)
  1844. # If the provider has a custom redirect URL, use that, otherwise automatically generate one
  1845. redirect_uri = OAUTH_PROVIDERS[provider].get("redirect_uri") or request.url_for(
  1846. "oauth_callback", provider=provider
  1847. )
  1848. client = oauth.create_client(provider)
  1849. if client is None:
  1850. raise HTTPException(404)
  1851. return await client.authorize_redirect(request, redirect_uri)
  1852. # OAuth login logic is as follows:
  1853. # 1. Attempt to find a user with matching subject ID, tied to the provider
  1854. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  1855. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  1856. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  1857. # - Email addresses are considered unique, so we fail registration if the email address is alreayd taken
  1858. @app.get("/oauth/{provider}/callback")
  1859. async def oauth_callback(provider: str, request: Request, response: Response):
  1860. if provider not in OAUTH_PROVIDERS:
  1861. raise HTTPException(404)
  1862. client = oauth.create_client(provider)
  1863. try:
  1864. token = await client.authorize_access_token(request)
  1865. except Exception as e:
  1866. log.warning(f"OAuth callback error: {e}")
  1867. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1868. user_data: UserInfo = token["userinfo"]
  1869. sub = user_data.get("sub")
  1870. if not sub:
  1871. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  1872. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1873. provider_sub = f"{provider}@{sub}"
  1874. email_claim = webui_app.state.config.OAUTH_EMAIL_CLAIM
  1875. email = user_data.get(email_claim, "").lower()
  1876. # We currently mandate that email addresses are provided
  1877. if not email:
  1878. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  1879. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1880. # Check if the user exists
  1881. user = Users.get_user_by_oauth_sub(provider_sub)
  1882. if not user:
  1883. # If the user does not exist, check if merging is enabled
  1884. if OAUTH_MERGE_ACCOUNTS_BY_EMAIL.value:
  1885. # Check if the user exists by email
  1886. user = Users.get_user_by_email(email)
  1887. if user:
  1888. # Update the user with the new oauth sub
  1889. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  1890. if not user:
  1891. # If the user does not exist, check if signups are enabled
  1892. if ENABLE_OAUTH_SIGNUP.value:
  1893. # Check if an existing user with the same email already exists
  1894. existing_user = Users.get_user_by_email(user_data.get("email", "").lower())
  1895. if existing_user:
  1896. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  1897. picture_claim = webui_app.state.config.OAUTH_PICTURE_CLAIM
  1898. picture_url = user_data.get(picture_claim, "")
  1899. if picture_url:
  1900. # Download the profile image into a base64 string
  1901. try:
  1902. async with aiohttp.ClientSession() as session:
  1903. async with session.get(picture_url) as resp:
  1904. picture = await resp.read()
  1905. base64_encoded_picture = base64.b64encode(picture).decode(
  1906. "utf-8"
  1907. )
  1908. guessed_mime_type = mimetypes.guess_type(picture_url)[0]
  1909. if guessed_mime_type is None:
  1910. # assume JPG, browsers are tolerant enough of image formats
  1911. guessed_mime_type = "image/jpeg"
  1912. picture_url = f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  1913. except Exception as e:
  1914. log.error(f"Error downloading profile image '{picture_url}': {e}")
  1915. picture_url = ""
  1916. if not picture_url:
  1917. picture_url = "/user.png"
  1918. username_claim = webui_app.state.config.OAUTH_USERNAME_CLAIM
  1919. role = (
  1920. "admin"
  1921. if Users.get_num_users() == 0
  1922. else webui_app.state.config.DEFAULT_USER_ROLE
  1923. )
  1924. user = Auths.insert_new_auth(
  1925. email=email,
  1926. password=get_password_hash(
  1927. str(uuid.uuid4())
  1928. ), # Random password, not used
  1929. name=user_data.get(username_claim, "User"),
  1930. profile_image_url=picture_url,
  1931. role=role,
  1932. oauth_sub=provider_sub,
  1933. )
  1934. if webui_app.state.config.WEBHOOK_URL:
  1935. post_webhook(
  1936. webui_app.state.config.WEBHOOK_URL,
  1937. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1938. {
  1939. "action": "signup",
  1940. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1941. "user": user.model_dump_json(exclude_none=True),
  1942. },
  1943. )
  1944. else:
  1945. raise HTTPException(
  1946. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  1947. )
  1948. jwt_token = create_token(
  1949. data={"id": user.id},
  1950. expires_delta=parse_duration(webui_app.state.config.JWT_EXPIRES_IN),
  1951. )
  1952. # Set the cookie token
  1953. response.set_cookie(
  1954. key="token",
  1955. value=jwt_token,
  1956. httponly=True, # Ensures the cookie is not accessible via JavaScript
  1957. )
  1958. # Redirect back to the frontend with the JWT token
  1959. redirect_url = f"{request.base_url}auth#token={jwt_token}"
  1960. return RedirectResponse(url=redirect_url)
  1961. @app.get("/manifest.json")
  1962. async def get_manifest_json():
  1963. return {
  1964. "name": WEBUI_NAME,
  1965. "short_name": WEBUI_NAME,
  1966. "description": "Open WebUI is an open, extensible, user-friendly interface for AI that adapts to your workflow.",
  1967. "start_url": "/",
  1968. "display": "standalone",
  1969. "background_color": "#343541",
  1970. "orientation": "any",
  1971. "icons": [
  1972. {
  1973. "src": "/static/logo.png",
  1974. "type": "image/png",
  1975. "sizes": "500x500",
  1976. "purpose": "any",
  1977. },
  1978. {
  1979. "src": "/static/logo.png",
  1980. "type": "image/png",
  1981. "sizes": "500x500",
  1982. "purpose": "maskable",
  1983. },
  1984. ],
  1985. }
  1986. @app.get("/opensearch.xml")
  1987. async def get_opensearch_xml():
  1988. xml_content = rf"""
  1989. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1990. <ShortName>{WEBUI_NAME}</ShortName>
  1991. <Description>Search {WEBUI_NAME}</Description>
  1992. <InputEncoding>UTF-8</InputEncoding>
  1993. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/static/favicon.png</Image>
  1994. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1995. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1996. </OpenSearchDescription>
  1997. """
  1998. return Response(content=xml_content, media_type="application/xml")
  1999. @app.get("/health")
  2000. async def healthcheck():
  2001. return {"status": True}
  2002. @app.get("/health/db")
  2003. async def healthcheck_with_db():
  2004. Session.execute(text("SELECT 1;")).all()
  2005. return {"status": True}
  2006. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  2007. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  2008. if os.path.exists(FRONTEND_BUILD_DIR):
  2009. mimetypes.add_type("text/javascript", ".js")
  2010. app.mount(
  2011. "/",
  2012. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  2013. name="spa-static-files",
  2014. )
  2015. else:
  2016. log.warning(
  2017. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  2018. )