main.py 86 KB

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