main.py 78 KB

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