main.py 79 KB

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