main.py 84 KB

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