main.py 71 KB

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