main.py 77 KB

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