main.py 77 KB

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