main.py 86 KB

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