main.py 79 KB

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