main.py 84 KB

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