main.py 85 KB

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