main.py 82 KB

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