main.py 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027
  1. import base64
  2. import uuid
  3. from contextlib import asynccontextmanager
  4. from authlib.integrations.starlette_client import OAuth
  5. from authlib.oidc.core import UserInfo
  6. from bs4 import BeautifulSoup
  7. import json
  8. import markdown
  9. import time
  10. import os
  11. import sys
  12. import logging
  13. import aiohttp
  14. import requests
  15. import mimetypes
  16. import shutil
  17. import os
  18. import uuid
  19. import inspect
  20. import asyncio
  21. from fastapi.concurrency import run_in_threadpool
  22. from fastapi import FastAPI, Request, Depends, status, UploadFile, File, Form
  23. from fastapi.staticfiles import StaticFiles
  24. from fastapi.responses import JSONResponse
  25. from fastapi import HTTPException
  26. from fastapi.middleware.wsgi import WSGIMiddleware
  27. from fastapi.middleware.cors import CORSMiddleware
  28. from starlette.exceptions import HTTPException as StarletteHTTPException
  29. from starlette.middleware.base import BaseHTTPMiddleware
  30. from starlette.middleware.sessions import SessionMiddleware
  31. from starlette.responses import StreamingResponse, Response, RedirectResponse
  32. from apps.socket.main import app as socket_app
  33. from apps.ollama.main import (
  34. app as ollama_app,
  35. OpenAIChatCompletionForm,
  36. get_all_models as get_ollama_models,
  37. generate_openai_chat_completion as generate_ollama_chat_completion,
  38. )
  39. from apps.openai.main import (
  40. app as openai_app,
  41. get_all_models as get_openai_models,
  42. generate_chat_completion as generate_openai_chat_completion,
  43. )
  44. from apps.audio.main import app as audio_app
  45. from apps.images.main import app as images_app
  46. from apps.rag.main import app as rag_app
  47. from apps.webui.main import (
  48. app as webui_app,
  49. get_pipe_models,
  50. generate_function_chat_completion,
  51. )
  52. from pydantic import BaseModel
  53. from typing import List, Optional, Iterator, Generator, Union
  54. from apps.webui.models.auths import Auths
  55. from apps.webui.models.models import Models, ModelModel
  56. from apps.webui.models.tools import Tools
  57. from apps.webui.models.functions import Functions
  58. from apps.webui.models.users import Users
  59. from apps.webui.utils import load_toolkit_module_by_id, load_function_module_by_id
  60. from utils.utils import (
  61. get_admin_user,
  62. get_verified_user,
  63. get_current_user,
  64. get_http_authorization_cred,
  65. get_password_hash,
  66. create_token,
  67. )
  68. from utils.task import (
  69. title_generation_template,
  70. search_query_generation_template,
  71. tools_function_calling_generation_template,
  72. )
  73. from utils.misc import (
  74. get_last_user_message,
  75. add_or_update_system_message,
  76. stream_message_template,
  77. parse_duration,
  78. )
  79. from apps.rag.utils import get_rag_context, rag_template
  80. from config import (
  81. CONFIG_DATA,
  82. WEBUI_NAME,
  83. WEBUI_URL,
  84. WEBUI_AUTH,
  85. ENV,
  86. VERSION,
  87. CHANGELOG,
  88. FRONTEND_BUILD_DIR,
  89. UPLOAD_DIR,
  90. CACHE_DIR,
  91. STATIC_DIR,
  92. ENABLE_OPENAI_API,
  93. ENABLE_OLLAMA_API,
  94. ENABLE_MODEL_FILTER,
  95. MODEL_FILTER_LIST,
  96. GLOBAL_LOG_LEVEL,
  97. SRC_LOG_LEVELS,
  98. WEBHOOK_URL,
  99. ENABLE_ADMIN_EXPORT,
  100. WEBUI_BUILD_HASH,
  101. TASK_MODEL,
  102. TASK_MODEL_EXTERNAL,
  103. TITLE_GENERATION_PROMPT_TEMPLATE,
  104. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  105. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  106. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  107. SAFE_MODE,
  108. OAUTH_PROVIDERS,
  109. ENABLE_OAUTH_SIGNUP,
  110. OAUTH_MERGE_ACCOUNTS_BY_EMAIL,
  111. WEBUI_SECRET_KEY,
  112. WEBUI_SESSION_COOKIE_SAME_SITE,
  113. WEBUI_SESSION_COOKIE_SECURE,
  114. AppConfig,
  115. )
  116. from constants import ERROR_MESSAGES, WEBHOOK_MESSAGES
  117. from utils.webhook import post_webhook
  118. if SAFE_MODE:
  119. print("SAFE MODE ENABLED")
  120. Functions.deactivate_all_functions()
  121. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  122. log = logging.getLogger(__name__)
  123. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  124. class SPAStaticFiles(StaticFiles):
  125. async def get_response(self, path: str, scope):
  126. try:
  127. return await super().get_response(path, scope)
  128. except (HTTPException, StarletteHTTPException) as ex:
  129. if ex.status_code == 404:
  130. return await super().get_response("index.html", scope)
  131. else:
  132. raise ex
  133. print(
  134. rf"""
  135. ___ __ __ _ _ _ ___
  136. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  137. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  138. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  139. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  140. |_|
  141. v{VERSION} - building the best open-source AI user interface.
  142. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  143. https://github.com/open-webui/open-webui
  144. """
  145. )
  146. @asynccontextmanager
  147. async def lifespan(app: FastAPI):
  148. yield
  149. app = FastAPI(
  150. docs_url="/docs" if ENV == "dev" else None, redoc_url=None, lifespan=lifespan
  151. )
  152. app.state.config = AppConfig()
  153. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  154. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  155. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  156. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  157. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  158. app.state.config.TASK_MODEL = TASK_MODEL
  159. app.state.config.TASK_MODEL_EXTERNAL = TASK_MODEL_EXTERNAL
  160. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = TITLE_GENERATION_PROMPT_TEMPLATE
  161. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  162. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  163. )
  164. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  165. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  166. )
  167. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  168. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  169. )
  170. app.state.MODELS = {}
  171. origins = ["*"]
  172. ##################################
  173. #
  174. # ChatCompletion Middleware
  175. #
  176. ##################################
  177. async def get_function_call_response(
  178. messages, files, tool_id, template, task_model_id, user
  179. ):
  180. tool = Tools.get_tool_by_id(tool_id)
  181. tools_specs = json.dumps(tool.specs, indent=2)
  182. content = tools_function_calling_generation_template(template, tools_specs)
  183. user_message = get_last_user_message(messages)
  184. prompt = (
  185. "History:\n"
  186. + "\n".join(
  187. [
  188. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  189. for message in messages[::-1][:4]
  190. ]
  191. )
  192. + f"\nQuery: {user_message}"
  193. )
  194. print(prompt)
  195. payload = {
  196. "model": task_model_id,
  197. "messages": [
  198. {"role": "system", "content": content},
  199. {"role": "user", "content": f"Query: {prompt}"},
  200. ],
  201. "stream": False,
  202. }
  203. try:
  204. payload = filter_pipeline(payload, user)
  205. except Exception as e:
  206. raise e
  207. model = app.state.MODELS[task_model_id]
  208. response = None
  209. try:
  210. response = await generate_chat_completions(form_data=payload, user=user)
  211. content = None
  212. if hasattr(response, "body_iterator"):
  213. async for chunk in response.body_iterator:
  214. data = json.loads(chunk.decode("utf-8"))
  215. content = data["choices"][0]["message"]["content"]
  216. # Cleanup any remaining background tasks if necessary
  217. if response.background is not None:
  218. await response.background()
  219. else:
  220. content = response["choices"][0]["message"]["content"]
  221. # Parse the function response
  222. if content is not None:
  223. print(f"content: {content}")
  224. result = json.loads(content)
  225. print(result)
  226. citation = None
  227. # Call the function
  228. if "name" in result:
  229. if tool_id in webui_app.state.TOOLS:
  230. toolkit_module = webui_app.state.TOOLS[tool_id]
  231. else:
  232. toolkit_module, frontmatter = load_toolkit_module_by_id(tool_id)
  233. webui_app.state.TOOLS[tool_id] = toolkit_module
  234. file_handler = False
  235. # check if toolkit_module has file_handler self variable
  236. if hasattr(toolkit_module, "file_handler"):
  237. file_handler = True
  238. print("file_handler: ", file_handler)
  239. if hasattr(toolkit_module, "valves") and hasattr(
  240. toolkit_module, "Valves"
  241. ):
  242. valves = Tools.get_tool_valves_by_id(tool_id)
  243. toolkit_module.valves = toolkit_module.Valves(
  244. **(valves if valves else {})
  245. )
  246. function = getattr(toolkit_module, result["name"])
  247. function_result = None
  248. try:
  249. # Get the signature of the function
  250. sig = inspect.signature(function)
  251. params = result["parameters"]
  252. if "__user__" in sig.parameters:
  253. # Call the function with the '__user__' parameter included
  254. __user__ = {
  255. "id": user.id,
  256. "email": user.email,
  257. "name": user.name,
  258. "role": user.role,
  259. }
  260. try:
  261. if hasattr(toolkit_module, "UserValves"):
  262. __user__["valves"] = toolkit_module.UserValves(
  263. **Tools.get_user_valves_by_id_and_user_id(
  264. tool_id, user.id
  265. )
  266. )
  267. except Exception as e:
  268. print(e)
  269. params = {**params, "__user__": __user__}
  270. if "__messages__" in sig.parameters:
  271. # Call the function with the '__messages__' parameter included
  272. params = {
  273. **params,
  274. "__messages__": messages,
  275. }
  276. if "__files__" in sig.parameters:
  277. # Call the function with the '__files__' parameter included
  278. params = {
  279. **params,
  280. "__files__": files,
  281. }
  282. if "__model__" in sig.parameters:
  283. # Call the function with the '__model__' parameter included
  284. params = {
  285. **params,
  286. "__model__": model,
  287. }
  288. if "__id__" in sig.parameters:
  289. # Call the function with the '__id__' parameter included
  290. params = {
  291. **params,
  292. "__id__": tool_id,
  293. }
  294. if inspect.iscoroutinefunction(function):
  295. function_result = await function(**params)
  296. else:
  297. function_result = function(**params)
  298. if hasattr(toolkit_module, "citation") and toolkit_module.citation:
  299. citation = {
  300. "source": {"name": f"TOOL:{tool.name}/{result['name']}"},
  301. "document": [function_result],
  302. "metadata": [{"source": result["name"]}],
  303. }
  304. except Exception as e:
  305. print(e)
  306. # Add the function result to the system prompt
  307. if function_result is not None:
  308. return function_result, citation, file_handler
  309. except Exception as e:
  310. print(f"Error: {e}")
  311. return None, None, False
  312. class ChatCompletionMiddleware(BaseHTTPMiddleware):
  313. async def dispatch(self, request: Request, call_next):
  314. data_items = []
  315. show_citations = False
  316. citations = []
  317. if request.method == "POST" and any(
  318. endpoint in request.url.path
  319. for endpoint in ["/ollama/api/chat", "/chat/completions"]
  320. ):
  321. log.debug(f"request.url.path: {request.url.path}")
  322. # Read the original request body
  323. body = await request.body()
  324. body_str = body.decode("utf-8")
  325. data = json.loads(body_str) if body_str else {}
  326. user = get_current_user(
  327. request,
  328. get_http_authorization_cred(request.headers.get("Authorization")),
  329. )
  330. # Flag to skip RAG completions if file_handler is present in tools/functions
  331. skip_files = False
  332. if data.get("citations"):
  333. show_citations = True
  334. del data["citations"]
  335. model_id = data["model"]
  336. if model_id not in app.state.MODELS:
  337. raise HTTPException(
  338. status_code=status.HTTP_404_NOT_FOUND,
  339. detail="Model not found",
  340. )
  341. model = app.state.MODELS[model_id]
  342. def get_priority(function_id):
  343. function = Functions.get_function_by_id(function_id)
  344. if function is not None and hasattr(function, "valves"):
  345. return (function.valves if function.valves else {}).get(
  346. "priority", 0
  347. )
  348. return 0
  349. filter_ids = [
  350. function.id
  351. for function in Functions.get_functions_by_type(
  352. "filter", active_only=True
  353. )
  354. ]
  355. # Check if the model has any filters
  356. if "info" in model and "meta" in model["info"]:
  357. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  358. filter_ids = list(set(filter_ids))
  359. filter_ids.sort(key=get_priority)
  360. for filter_id in filter_ids:
  361. filter = Functions.get_function_by_id(filter_id)
  362. if filter:
  363. if filter_id in webui_app.state.FUNCTIONS:
  364. function_module = webui_app.state.FUNCTIONS[filter_id]
  365. else:
  366. function_module, function_type, frontmatter = (
  367. load_function_module_by_id(filter_id)
  368. )
  369. webui_app.state.FUNCTIONS[filter_id] = function_module
  370. # Check if the function has a file_handler variable
  371. if hasattr(function_module, "file_handler"):
  372. skip_files = function_module.file_handler
  373. if hasattr(function_module, "valves") and hasattr(
  374. function_module, "Valves"
  375. ):
  376. valves = Functions.get_function_valves_by_id(filter_id)
  377. function_module.valves = function_module.Valves(
  378. **(valves if valves else {})
  379. )
  380. try:
  381. if hasattr(function_module, "inlet"):
  382. inlet = function_module.inlet
  383. # Get the signature of the function
  384. sig = inspect.signature(inlet)
  385. params = {"body": data}
  386. if "__user__" in sig.parameters:
  387. __user__ = {
  388. "id": user.id,
  389. "email": user.email,
  390. "name": user.name,
  391. "role": user.role,
  392. }
  393. try:
  394. if hasattr(function_module, "UserValves"):
  395. __user__["valves"] = function_module.UserValves(
  396. **Functions.get_user_valves_by_id_and_user_id(
  397. filter_id, user.id
  398. )
  399. )
  400. except Exception as e:
  401. print(e)
  402. params = {**params, "__user__": __user__}
  403. if "__id__" in sig.parameters:
  404. params = {
  405. **params,
  406. "__id__": filter_id,
  407. }
  408. if inspect.iscoroutinefunction(inlet):
  409. data = await inlet(**params)
  410. else:
  411. data = inlet(**params)
  412. except Exception as e:
  413. print(f"Error: {e}")
  414. return JSONResponse(
  415. status_code=status.HTTP_400_BAD_REQUEST,
  416. content={"detail": str(e)},
  417. )
  418. # Set the task model
  419. task_model_id = data["model"]
  420. # Check if the user has a custom task model and use that model
  421. if app.state.MODELS[task_model_id]["owned_by"] == "ollama":
  422. if (
  423. app.state.config.TASK_MODEL
  424. and app.state.config.TASK_MODEL in app.state.MODELS
  425. ):
  426. task_model_id = app.state.config.TASK_MODEL
  427. else:
  428. if (
  429. app.state.config.TASK_MODEL_EXTERNAL
  430. and app.state.config.TASK_MODEL_EXTERNAL in app.state.MODELS
  431. ):
  432. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  433. prompt = get_last_user_message(data["messages"])
  434. context = ""
  435. # If tool_ids field is present, call the functions
  436. if "tool_ids" in data:
  437. print(data["tool_ids"])
  438. for tool_id in data["tool_ids"]:
  439. print(tool_id)
  440. try:
  441. response, citation, file_handler = (
  442. await get_function_call_response(
  443. messages=data["messages"],
  444. files=data.get("files", []),
  445. tool_id=tool_id,
  446. template=app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  447. task_model_id=task_model_id,
  448. user=user,
  449. )
  450. )
  451. print(file_handler)
  452. if isinstance(response, str):
  453. context += ("\n" if context != "" else "") + response
  454. if citation:
  455. citations.append(citation)
  456. show_citations = True
  457. if file_handler:
  458. skip_files = True
  459. except Exception as e:
  460. print(f"Error: {e}")
  461. del data["tool_ids"]
  462. print(f"tool_context: {context}")
  463. # If files field is present, generate RAG completions
  464. # If skip_files is True, skip the RAG completions
  465. if "files" in data:
  466. if not skip_files:
  467. data = {**data}
  468. rag_context, rag_citations = get_rag_context(
  469. files=data["files"],
  470. messages=data["messages"],
  471. embedding_function=rag_app.state.EMBEDDING_FUNCTION,
  472. k=rag_app.state.config.TOP_K,
  473. reranking_function=rag_app.state.sentence_transformer_rf,
  474. r=rag_app.state.config.RELEVANCE_THRESHOLD,
  475. hybrid_search=rag_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  476. )
  477. if rag_context:
  478. context += ("\n" if context != "" else "") + rag_context
  479. log.debug(f"rag_context: {rag_context}, citations: {citations}")
  480. if rag_citations:
  481. citations.extend(rag_citations)
  482. del data["files"]
  483. if show_citations and len(citations) > 0:
  484. data_items.append({"citations": citations})
  485. if context != "":
  486. system_prompt = rag_template(
  487. rag_app.state.config.RAG_TEMPLATE, context, prompt
  488. )
  489. print(system_prompt)
  490. data["messages"] = add_or_update_system_message(
  491. system_prompt, data["messages"]
  492. )
  493. modified_body_bytes = json.dumps(data).encode("utf-8")
  494. # Replace the request body with the modified one
  495. request._body = modified_body_bytes
  496. # Set custom header to ensure content-length matches new body length
  497. request.headers.__dict__["_list"] = [
  498. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  499. *[
  500. (k, v)
  501. for k, v in request.headers.raw
  502. if k.lower() != b"content-length"
  503. ],
  504. ]
  505. response = await call_next(request)
  506. if isinstance(response, StreamingResponse):
  507. # If it's a streaming response, inject it as SSE event or NDJSON line
  508. content_type = response.headers.get("Content-Type")
  509. if "text/event-stream" in content_type:
  510. return StreamingResponse(
  511. self.openai_stream_wrapper(response.body_iterator, data_items),
  512. )
  513. if "application/x-ndjson" in content_type:
  514. return StreamingResponse(
  515. self.ollama_stream_wrapper(response.body_iterator, data_items),
  516. )
  517. else:
  518. return response
  519. # If it's not a chat completion request, just pass it through
  520. response = await call_next(request)
  521. return response
  522. async def _receive(self, body: bytes):
  523. return {"type": "http.request", "body": body, "more_body": False}
  524. async def openai_stream_wrapper(self, original_generator, data_items):
  525. for item in data_items:
  526. yield f"data: {json.dumps(item)}\n\n"
  527. async for data in original_generator:
  528. yield data
  529. async def ollama_stream_wrapper(self, original_generator, data_items):
  530. for item in data_items:
  531. yield f"{json.dumps(item)}\n"
  532. async for data in original_generator:
  533. yield data
  534. app.add_middleware(ChatCompletionMiddleware)
  535. ##################################
  536. #
  537. # Pipeline Middleware
  538. #
  539. ##################################
  540. def filter_pipeline(payload, user):
  541. user = {"id": user.id, "email": user.email, "name": user.name, "role": user.role}
  542. model_id = payload["model"]
  543. filters = [
  544. model
  545. for model in app.state.MODELS.values()
  546. if "pipeline" in model
  547. and "type" in model["pipeline"]
  548. and model["pipeline"]["type"] == "filter"
  549. and (
  550. model["pipeline"]["pipelines"] == ["*"]
  551. or any(
  552. model_id == target_model_id
  553. for target_model_id in model["pipeline"]["pipelines"]
  554. )
  555. )
  556. ]
  557. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  558. model = app.state.MODELS[model_id]
  559. if "pipeline" in model:
  560. sorted_filters.append(model)
  561. for filter in sorted_filters:
  562. r = None
  563. try:
  564. urlIdx = filter["urlIdx"]
  565. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  566. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  567. if key != "":
  568. headers = {"Authorization": f"Bearer {key}"}
  569. r = requests.post(
  570. f"{url}/{filter['id']}/filter/inlet",
  571. headers=headers,
  572. json={
  573. "user": user,
  574. "body": payload,
  575. },
  576. )
  577. r.raise_for_status()
  578. payload = r.json()
  579. except Exception as e:
  580. # Handle connection error here
  581. print(f"Connection error: {e}")
  582. if r is not None:
  583. try:
  584. res = r.json()
  585. except:
  586. pass
  587. if "detail" in res:
  588. raise Exception(r.status_code, res["detail"])
  589. else:
  590. pass
  591. if "pipeline" not in app.state.MODELS[model_id]:
  592. if "chat_id" in payload:
  593. del payload["chat_id"]
  594. if "title" in payload:
  595. del payload["title"]
  596. if "task" in payload:
  597. del payload["task"]
  598. return payload
  599. class PipelineMiddleware(BaseHTTPMiddleware):
  600. async def dispatch(self, request: Request, call_next):
  601. if request.method == "POST" and (
  602. "/ollama/api/chat" in request.url.path
  603. or "/chat/completions" in request.url.path
  604. ):
  605. log.debug(f"request.url.path: {request.url.path}")
  606. # Read the original request body
  607. body = await request.body()
  608. # Decode body to string
  609. body_str = body.decode("utf-8")
  610. # Parse string to JSON
  611. data = json.loads(body_str) if body_str else {}
  612. user = get_current_user(
  613. request,
  614. get_http_authorization_cred(request.headers.get("Authorization")),
  615. )
  616. try:
  617. data = filter_pipeline(data, user)
  618. except Exception as e:
  619. return JSONResponse(
  620. status_code=e.args[0],
  621. content={"detail": e.args[1]},
  622. )
  623. modified_body_bytes = json.dumps(data).encode("utf-8")
  624. # Replace the request body with the modified one
  625. request._body = modified_body_bytes
  626. # Set custom header to ensure content-length matches new body length
  627. request.headers.__dict__["_list"] = [
  628. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  629. *[
  630. (k, v)
  631. for k, v in request.headers.raw
  632. if k.lower() != b"content-length"
  633. ],
  634. ]
  635. response = await call_next(request)
  636. return response
  637. async def _receive(self, body: bytes):
  638. return {"type": "http.request", "body": body, "more_body": False}
  639. app.add_middleware(PipelineMiddleware)
  640. app.add_middleware(
  641. CORSMiddleware,
  642. allow_origins=origins,
  643. allow_credentials=True,
  644. allow_methods=["*"],
  645. allow_headers=["*"],
  646. )
  647. @app.middleware("http")
  648. async def check_url(request: Request, call_next):
  649. if len(app.state.MODELS) == 0:
  650. await get_all_models()
  651. else:
  652. pass
  653. start_time = int(time.time())
  654. response = await call_next(request)
  655. process_time = int(time.time()) - start_time
  656. response.headers["X-Process-Time"] = str(process_time)
  657. return response
  658. @app.middleware("http")
  659. async def update_embedding_function(request: Request, call_next):
  660. response = await call_next(request)
  661. if "/embedding/update" in request.url.path:
  662. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  663. return response
  664. app.mount("/ws", socket_app)
  665. app.mount("/ollama", ollama_app)
  666. app.mount("/openai", openai_app)
  667. app.mount("/images/api/v1", images_app)
  668. app.mount("/audio/api/v1", audio_app)
  669. app.mount("/rag/api/v1", rag_app)
  670. app.mount("/api/v1", webui_app)
  671. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  672. async def get_all_models():
  673. pipe_models = []
  674. openai_models = []
  675. ollama_models = []
  676. pipe_models = await get_pipe_models()
  677. if app.state.config.ENABLE_OPENAI_API:
  678. openai_models = await get_openai_models()
  679. openai_models = openai_models["data"]
  680. if app.state.config.ENABLE_OLLAMA_API:
  681. ollama_models = await get_ollama_models()
  682. ollama_models = [
  683. {
  684. "id": model["model"],
  685. "name": model["name"],
  686. "object": "model",
  687. "created": int(time.time()),
  688. "owned_by": "ollama",
  689. "ollama": model,
  690. }
  691. for model in ollama_models["models"]
  692. ]
  693. models = pipe_models + openai_models + ollama_models
  694. custom_models = Models.get_all_models()
  695. for custom_model in custom_models:
  696. if custom_model.base_model_id == None:
  697. for model in models:
  698. if (
  699. custom_model.id == model["id"]
  700. or custom_model.id == model["id"].split(":")[0]
  701. ):
  702. model["name"] = custom_model.name
  703. model["info"] = custom_model.model_dump()
  704. else:
  705. owned_by = "openai"
  706. for model in models:
  707. if (
  708. custom_model.base_model_id == model["id"]
  709. or custom_model.base_model_id == model["id"].split(":")[0]
  710. ):
  711. owned_by = model["owned_by"]
  712. break
  713. models.append(
  714. {
  715. "id": custom_model.id,
  716. "name": custom_model.name,
  717. "object": "model",
  718. "created": custom_model.created_at,
  719. "owned_by": owned_by,
  720. "info": custom_model.model_dump(),
  721. "preset": True,
  722. }
  723. )
  724. app.state.MODELS = {model["id"]: model for model in models}
  725. webui_app.state.MODELS = app.state.MODELS
  726. return models
  727. @app.get("/api/models")
  728. async def get_models(user=Depends(get_verified_user)):
  729. models = await get_all_models()
  730. # Filter out filter pipelines
  731. models = [
  732. model
  733. for model in models
  734. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  735. ]
  736. if app.state.config.ENABLE_MODEL_FILTER:
  737. if user.role == "user":
  738. models = list(
  739. filter(
  740. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  741. models,
  742. )
  743. )
  744. return {"data": models}
  745. return {"data": models}
  746. @app.post("/api/chat/completions")
  747. async def generate_chat_completions(form_data: dict, user=Depends(get_verified_user)):
  748. model_id = form_data["model"]
  749. if model_id not in app.state.MODELS:
  750. raise HTTPException(
  751. status_code=status.HTTP_404_NOT_FOUND,
  752. detail="Model not found",
  753. )
  754. model = app.state.MODELS[model_id]
  755. print(model)
  756. pipe = model.get("pipe")
  757. if pipe:
  758. return await generate_function_chat_completion(form_data, user=user)
  759. if model["owned_by"] == "ollama":
  760. return await generate_ollama_chat_completion(form_data, user=user)
  761. else:
  762. return await generate_openai_chat_completion(form_data, user=user)
  763. @app.post("/api/chat/completed")
  764. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  765. data = form_data
  766. model_id = data["model"]
  767. if model_id not in app.state.MODELS:
  768. raise HTTPException(
  769. status_code=status.HTTP_404_NOT_FOUND,
  770. detail="Model not found",
  771. )
  772. model = app.state.MODELS[model_id]
  773. filters = [
  774. model
  775. for model in app.state.MODELS.values()
  776. if "pipeline" in model
  777. and "type" in model["pipeline"]
  778. and model["pipeline"]["type"] == "filter"
  779. and (
  780. model["pipeline"]["pipelines"] == ["*"]
  781. or any(
  782. model_id == target_model_id
  783. for target_model_id in model["pipeline"]["pipelines"]
  784. )
  785. )
  786. ]
  787. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  788. if "pipeline" in model:
  789. sorted_filters = [model] + sorted_filters
  790. for filter in sorted_filters:
  791. r = None
  792. try:
  793. urlIdx = filter["urlIdx"]
  794. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  795. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  796. if key != "":
  797. headers = {"Authorization": f"Bearer {key}"}
  798. r = requests.post(
  799. f"{url}/{filter['id']}/filter/outlet",
  800. headers=headers,
  801. json={
  802. "user": {
  803. "id": user.id,
  804. "name": user.name,
  805. "email": user.email,
  806. "role": user.role,
  807. },
  808. "body": data,
  809. },
  810. )
  811. r.raise_for_status()
  812. data = r.json()
  813. except Exception as e:
  814. # Handle connection error here
  815. print(f"Connection error: {e}")
  816. if r is not None:
  817. try:
  818. res = r.json()
  819. if "detail" in res:
  820. return JSONResponse(
  821. status_code=r.status_code,
  822. content=res,
  823. )
  824. except:
  825. pass
  826. else:
  827. pass
  828. def get_priority(function_id):
  829. function = Functions.get_function_by_id(function_id)
  830. if function is not None and hasattr(function, "valves"):
  831. return (function.valves if function.valves else {}).get("priority", 0)
  832. return 0
  833. filter_ids = [
  834. function.id
  835. for function in Functions.get_functions_by_type("filter", active_only=True)
  836. ]
  837. # Check if the model has any filters
  838. if "info" in model and "meta" in model["info"]:
  839. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  840. filter_ids = list(set(filter_ids))
  841. # Sort filter_ids by priority, using the get_priority function
  842. filter_ids.sort(key=get_priority)
  843. for filter_id in filter_ids:
  844. filter = Functions.get_function_by_id(filter_id)
  845. if filter:
  846. if filter_id in webui_app.state.FUNCTIONS:
  847. function_module = webui_app.state.FUNCTIONS[filter_id]
  848. else:
  849. function_module, function_type, frontmatter = (
  850. load_function_module_by_id(filter_id)
  851. )
  852. webui_app.state.FUNCTIONS[filter_id] = function_module
  853. if hasattr(function_module, "valves") and hasattr(
  854. function_module, "Valves"
  855. ):
  856. valves = Functions.get_function_valves_by_id(filter_id)
  857. function_module.valves = function_module.Valves(
  858. **(valves if valves else {})
  859. )
  860. try:
  861. if hasattr(function_module, "outlet"):
  862. outlet = function_module.outlet
  863. # Get the signature of the function
  864. sig = inspect.signature(outlet)
  865. params = {"body": data}
  866. if "__user__" in sig.parameters:
  867. __user__ = {
  868. "id": user.id,
  869. "email": user.email,
  870. "name": user.name,
  871. "role": user.role,
  872. }
  873. try:
  874. if hasattr(function_module, "UserValves"):
  875. __user__["valves"] = function_module.UserValves(
  876. **Functions.get_user_valves_by_id_and_user_id(
  877. filter_id, user.id
  878. )
  879. )
  880. except Exception as e:
  881. print(e)
  882. params = {**params, "__user__": __user__}
  883. if "__id__" in sig.parameters:
  884. params = {
  885. **params,
  886. "__id__": filter_id,
  887. }
  888. if inspect.iscoroutinefunction(outlet):
  889. data = await outlet(**params)
  890. else:
  891. data = outlet(**params)
  892. except Exception as e:
  893. print(f"Error: {e}")
  894. return JSONResponse(
  895. status_code=status.HTTP_400_BAD_REQUEST,
  896. content={"detail": str(e)},
  897. )
  898. return data
  899. ##################################
  900. #
  901. # Task Endpoints
  902. #
  903. ##################################
  904. # TODO: Refactor task API endpoints below into a separate file
  905. @app.get("/api/task/config")
  906. async def get_task_config(user=Depends(get_verified_user)):
  907. return {
  908. "TASK_MODEL": app.state.config.TASK_MODEL,
  909. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  910. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  911. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  912. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  913. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  914. }
  915. class TaskConfigForm(BaseModel):
  916. TASK_MODEL: Optional[str]
  917. TASK_MODEL_EXTERNAL: Optional[str]
  918. TITLE_GENERATION_PROMPT_TEMPLATE: str
  919. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE: str
  920. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD: int
  921. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  922. @app.post("/api/task/config/update")
  923. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  924. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  925. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  926. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  927. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  928. )
  929. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  930. form_data.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  931. )
  932. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  933. form_data.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  934. )
  935. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  936. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  937. )
  938. return {
  939. "TASK_MODEL": app.state.config.TASK_MODEL,
  940. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  941. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  942. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  943. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  944. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  945. }
  946. @app.post("/api/task/title/completions")
  947. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  948. print("generate_title")
  949. model_id = form_data["model"]
  950. if model_id not in app.state.MODELS:
  951. raise HTTPException(
  952. status_code=status.HTTP_404_NOT_FOUND,
  953. detail="Model not found",
  954. )
  955. # Check if the user has a custom task model
  956. # If the user has a custom task model, use that model
  957. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  958. if app.state.config.TASK_MODEL:
  959. task_model_id = app.state.config.TASK_MODEL
  960. if task_model_id in app.state.MODELS:
  961. model_id = task_model_id
  962. else:
  963. if app.state.config.TASK_MODEL_EXTERNAL:
  964. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  965. if task_model_id in app.state.MODELS:
  966. model_id = task_model_id
  967. print(model_id)
  968. model = app.state.MODELS[model_id]
  969. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  970. content = title_generation_template(
  971. template,
  972. form_data["prompt"],
  973. {
  974. "name": user.name,
  975. "location": user.info.get("location") if user.info else None,
  976. },
  977. )
  978. payload = {
  979. "model": model_id,
  980. "messages": [{"role": "user", "content": content}],
  981. "stream": False,
  982. "max_tokens": 50,
  983. "chat_id": form_data.get("chat_id", None),
  984. "title": True,
  985. }
  986. log.debug(payload)
  987. try:
  988. payload = filter_pipeline(payload, user)
  989. except Exception as e:
  990. return JSONResponse(
  991. status_code=e.args[0],
  992. content={"detail": e.args[1]},
  993. )
  994. return await generate_chat_completions(form_data=payload, user=user)
  995. @app.post("/api/task/query/completions")
  996. async def generate_search_query(form_data: dict, user=Depends(get_verified_user)):
  997. print("generate_search_query")
  998. if len(form_data["prompt"]) < app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD:
  999. raise HTTPException(
  1000. status_code=status.HTTP_400_BAD_REQUEST,
  1001. detail=f"Skip search query generation for short prompts (< {app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD} characters)",
  1002. )
  1003. model_id = form_data["model"]
  1004. if model_id not in app.state.MODELS:
  1005. raise HTTPException(
  1006. status_code=status.HTTP_404_NOT_FOUND,
  1007. detail="Model not found",
  1008. )
  1009. # Check if the user has a custom task model
  1010. # If the user has a custom task model, use that model
  1011. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  1012. if app.state.config.TASK_MODEL:
  1013. task_model_id = app.state.config.TASK_MODEL
  1014. if task_model_id in app.state.MODELS:
  1015. model_id = task_model_id
  1016. else:
  1017. if app.state.config.TASK_MODEL_EXTERNAL:
  1018. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  1019. if task_model_id in app.state.MODELS:
  1020. model_id = task_model_id
  1021. print(model_id)
  1022. model = app.state.MODELS[model_id]
  1023. template = app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1024. content = search_query_generation_template(
  1025. template, form_data["prompt"], {"name": user.name}
  1026. )
  1027. payload = {
  1028. "model": model_id,
  1029. "messages": [{"role": "user", "content": content}],
  1030. "stream": False,
  1031. "max_tokens": 30,
  1032. "task": True,
  1033. }
  1034. print(payload)
  1035. try:
  1036. payload = filter_pipeline(payload, user)
  1037. except Exception as e:
  1038. return JSONResponse(
  1039. status_code=e.args[0],
  1040. content={"detail": e.args[1]},
  1041. )
  1042. return await generate_chat_completions(form_data=payload, user=user)
  1043. @app.post("/api/task/emoji/completions")
  1044. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  1045. print("generate_emoji")
  1046. model_id = form_data["model"]
  1047. if model_id not in app.state.MODELS:
  1048. raise HTTPException(
  1049. status_code=status.HTTP_404_NOT_FOUND,
  1050. detail="Model not found",
  1051. )
  1052. # Check if the user has a custom task model
  1053. # If the user has a custom task model, use that model
  1054. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  1055. if app.state.config.TASK_MODEL:
  1056. task_model_id = app.state.config.TASK_MODEL
  1057. if task_model_id in app.state.MODELS:
  1058. model_id = task_model_id
  1059. else:
  1060. if app.state.config.TASK_MODEL_EXTERNAL:
  1061. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  1062. if task_model_id in app.state.MODELS:
  1063. model_id = task_model_id
  1064. print(model_id)
  1065. model = app.state.MODELS[model_id]
  1066. template = '''
  1067. 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., 😊, 😢, 😡, 😱).
  1068. Message: """{{prompt}}"""
  1069. '''
  1070. content = title_generation_template(
  1071. template,
  1072. form_data["prompt"],
  1073. {
  1074. "name": user.name,
  1075. "location": user.info.get("location") if user.info else None,
  1076. },
  1077. )
  1078. payload = {
  1079. "model": model_id,
  1080. "messages": [{"role": "user", "content": content}],
  1081. "stream": False,
  1082. "max_tokens": 4,
  1083. "chat_id": form_data.get("chat_id", None),
  1084. "task": True,
  1085. }
  1086. log.debug(payload)
  1087. try:
  1088. payload = filter_pipeline(payload, user)
  1089. except Exception as e:
  1090. return JSONResponse(
  1091. status_code=e.args[0],
  1092. content={"detail": e.args[1]},
  1093. )
  1094. return await generate_chat_completions(form_data=payload, user=user)
  1095. @app.post("/api/task/tools/completions")
  1096. async def get_tools_function_calling(form_data: dict, user=Depends(get_verified_user)):
  1097. print("get_tools_function_calling")
  1098. model_id = form_data["model"]
  1099. if model_id not in app.state.MODELS:
  1100. raise HTTPException(
  1101. status_code=status.HTTP_404_NOT_FOUND,
  1102. detail="Model not found",
  1103. )
  1104. # Check if the user has a custom task model
  1105. # If the user has a custom task model, use that model
  1106. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  1107. if app.state.config.TASK_MODEL:
  1108. task_model_id = app.state.config.TASK_MODEL
  1109. if task_model_id in app.state.MODELS:
  1110. model_id = task_model_id
  1111. else:
  1112. if app.state.config.TASK_MODEL_EXTERNAL:
  1113. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  1114. if task_model_id in app.state.MODELS:
  1115. model_id = task_model_id
  1116. print(model_id)
  1117. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1118. try:
  1119. context, citation, file_handler = await get_function_call_response(
  1120. form_data["messages"],
  1121. form_data.get("files", []),
  1122. form_data["tool_id"],
  1123. template,
  1124. model_id,
  1125. user,
  1126. )
  1127. return context
  1128. except Exception as e:
  1129. return JSONResponse(
  1130. status_code=e.args[0],
  1131. content={"detail": e.args[1]},
  1132. )
  1133. ##################################
  1134. #
  1135. # Pipelines Endpoints
  1136. #
  1137. ##################################
  1138. # TODO: Refactor pipelines API endpoints below into a separate file
  1139. @app.get("/api/pipelines/list")
  1140. async def get_pipelines_list(user=Depends(get_admin_user)):
  1141. responses = await get_openai_models(raw=True)
  1142. print(responses)
  1143. urlIdxs = [
  1144. idx
  1145. for idx, response in enumerate(responses)
  1146. if response != None and "pipelines" in response
  1147. ]
  1148. return {
  1149. "data": [
  1150. {
  1151. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  1152. "idx": urlIdx,
  1153. }
  1154. for urlIdx in urlIdxs
  1155. ]
  1156. }
  1157. @app.post("/api/pipelines/upload")
  1158. async def upload_pipeline(
  1159. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  1160. ):
  1161. print("upload_pipeline", urlIdx, file.filename)
  1162. # Check if the uploaded file is a python file
  1163. if not file.filename.endswith(".py"):
  1164. raise HTTPException(
  1165. status_code=status.HTTP_400_BAD_REQUEST,
  1166. detail="Only Python (.py) files are allowed.",
  1167. )
  1168. upload_folder = f"{CACHE_DIR}/pipelines"
  1169. os.makedirs(upload_folder, exist_ok=True)
  1170. file_path = os.path.join(upload_folder, file.filename)
  1171. try:
  1172. # Save the uploaded file
  1173. with open(file_path, "wb") as buffer:
  1174. shutil.copyfileobj(file.file, buffer)
  1175. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1176. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1177. headers = {"Authorization": f"Bearer {key}"}
  1178. with open(file_path, "rb") as f:
  1179. files = {"file": f}
  1180. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1181. r.raise_for_status()
  1182. data = r.json()
  1183. return {**data}
  1184. except Exception as e:
  1185. # Handle connection error here
  1186. print(f"Connection error: {e}")
  1187. detail = "Pipeline not found"
  1188. if r is not None:
  1189. try:
  1190. res = r.json()
  1191. if "detail" in res:
  1192. detail = res["detail"]
  1193. except:
  1194. pass
  1195. raise HTTPException(
  1196. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1197. detail=detail,
  1198. )
  1199. finally:
  1200. # Ensure the file is deleted after the upload is completed or on failure
  1201. if os.path.exists(file_path):
  1202. os.remove(file_path)
  1203. class AddPipelineForm(BaseModel):
  1204. url: str
  1205. urlIdx: int
  1206. @app.post("/api/pipelines/add")
  1207. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1208. r = None
  1209. try:
  1210. urlIdx = form_data.urlIdx
  1211. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1212. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1213. headers = {"Authorization": f"Bearer {key}"}
  1214. r = requests.post(
  1215. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1216. )
  1217. r.raise_for_status()
  1218. data = r.json()
  1219. return {**data}
  1220. except Exception as e:
  1221. # Handle connection error here
  1222. print(f"Connection error: {e}")
  1223. detail = "Pipeline not found"
  1224. if r is not None:
  1225. try:
  1226. res = r.json()
  1227. if "detail" in res:
  1228. detail = res["detail"]
  1229. except:
  1230. pass
  1231. raise HTTPException(
  1232. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1233. detail=detail,
  1234. )
  1235. class DeletePipelineForm(BaseModel):
  1236. id: str
  1237. urlIdx: int
  1238. @app.delete("/api/pipelines/delete")
  1239. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1240. r = None
  1241. try:
  1242. urlIdx = form_data.urlIdx
  1243. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1244. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1245. headers = {"Authorization": f"Bearer {key}"}
  1246. r = requests.delete(
  1247. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1248. )
  1249. r.raise_for_status()
  1250. data = r.json()
  1251. return {**data}
  1252. except Exception as e:
  1253. # Handle connection error here
  1254. print(f"Connection error: {e}")
  1255. detail = "Pipeline not found"
  1256. if r is not None:
  1257. try:
  1258. res = r.json()
  1259. if "detail" in res:
  1260. detail = res["detail"]
  1261. except:
  1262. pass
  1263. raise HTTPException(
  1264. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1265. detail=detail,
  1266. )
  1267. @app.get("/api/pipelines")
  1268. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  1269. r = None
  1270. try:
  1271. urlIdx
  1272. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1273. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1274. headers = {"Authorization": f"Bearer {key}"}
  1275. r = requests.get(f"{url}/pipelines", headers=headers)
  1276. r.raise_for_status()
  1277. data = r.json()
  1278. return {**data}
  1279. except Exception as e:
  1280. # Handle connection error here
  1281. print(f"Connection error: {e}")
  1282. detail = "Pipeline not found"
  1283. if r is not None:
  1284. try:
  1285. res = r.json()
  1286. if "detail" in res:
  1287. detail = res["detail"]
  1288. except:
  1289. pass
  1290. raise HTTPException(
  1291. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1292. detail=detail,
  1293. )
  1294. @app.get("/api/pipelines/{pipeline_id}/valves")
  1295. async def get_pipeline_valves(
  1296. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  1297. ):
  1298. models = await get_all_models()
  1299. r = None
  1300. try:
  1301. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1302. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1303. headers = {"Authorization": f"Bearer {key}"}
  1304. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  1305. r.raise_for_status()
  1306. data = r.json()
  1307. return {**data}
  1308. except Exception as e:
  1309. # Handle connection error here
  1310. print(f"Connection error: {e}")
  1311. detail = "Pipeline not found"
  1312. if r is not None:
  1313. try:
  1314. res = r.json()
  1315. if "detail" in res:
  1316. detail = res["detail"]
  1317. except:
  1318. pass
  1319. raise HTTPException(
  1320. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1321. detail=detail,
  1322. )
  1323. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1324. async def get_pipeline_valves_spec(
  1325. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  1326. ):
  1327. models = await get_all_models()
  1328. r = None
  1329. try:
  1330. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1331. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1332. headers = {"Authorization": f"Bearer {key}"}
  1333. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  1334. r.raise_for_status()
  1335. data = r.json()
  1336. return {**data}
  1337. except Exception as e:
  1338. # Handle connection error here
  1339. print(f"Connection error: {e}")
  1340. detail = "Pipeline not found"
  1341. if r is not None:
  1342. try:
  1343. res = r.json()
  1344. if "detail" in res:
  1345. detail = res["detail"]
  1346. except:
  1347. pass
  1348. raise HTTPException(
  1349. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1350. detail=detail,
  1351. )
  1352. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1353. async def update_pipeline_valves(
  1354. urlIdx: Optional[int],
  1355. pipeline_id: str,
  1356. form_data: dict,
  1357. user=Depends(get_admin_user),
  1358. ):
  1359. models = await get_all_models()
  1360. r = None
  1361. try:
  1362. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1363. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1364. headers = {"Authorization": f"Bearer {key}"}
  1365. r = requests.post(
  1366. f"{url}/{pipeline_id}/valves/update",
  1367. headers=headers,
  1368. json={**form_data},
  1369. )
  1370. r.raise_for_status()
  1371. data = r.json()
  1372. return {**data}
  1373. except Exception as e:
  1374. # Handle connection error here
  1375. print(f"Connection error: {e}")
  1376. detail = "Pipeline not found"
  1377. if r is not None:
  1378. try:
  1379. res = r.json()
  1380. if "detail" in res:
  1381. detail = res["detail"]
  1382. except:
  1383. pass
  1384. raise HTTPException(
  1385. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1386. detail=detail,
  1387. )
  1388. ##################################
  1389. #
  1390. # Config Endpoints
  1391. #
  1392. ##################################
  1393. @app.get("/api/config")
  1394. async def get_app_config():
  1395. # Checking and Handling the Absence of 'ui' in CONFIG_DATA
  1396. default_locale = "en-US"
  1397. if "ui" in CONFIG_DATA:
  1398. default_locale = CONFIG_DATA["ui"].get("default_locale", "en-US")
  1399. # The Rest of the Function Now Uses the Variables Defined Above
  1400. return {
  1401. "status": True,
  1402. "name": WEBUI_NAME,
  1403. "version": VERSION,
  1404. "default_locale": default_locale,
  1405. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1406. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1407. "features": {
  1408. "auth": WEBUI_AUTH,
  1409. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1410. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1411. "enable_web_search": rag_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1412. "enable_image_generation": images_app.state.config.ENABLED,
  1413. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1414. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1415. },
  1416. "audio": {
  1417. "tts": {
  1418. "engine": audio_app.state.config.TTS_ENGINE,
  1419. "voice": audio_app.state.config.TTS_VOICE,
  1420. },
  1421. "stt": {
  1422. "engine": audio_app.state.config.STT_ENGINE,
  1423. },
  1424. },
  1425. "oauth": {
  1426. "providers": {
  1427. name: config.get("name", name)
  1428. for name, config in OAUTH_PROVIDERS.items()
  1429. }
  1430. },
  1431. }
  1432. @app.get("/api/config/model/filter")
  1433. async def get_model_filter_config(user=Depends(get_admin_user)):
  1434. return {
  1435. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1436. "models": app.state.config.MODEL_FILTER_LIST,
  1437. }
  1438. class ModelFilterConfigForm(BaseModel):
  1439. enabled: bool
  1440. models: List[str]
  1441. @app.post("/api/config/model/filter")
  1442. async def update_model_filter_config(
  1443. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  1444. ):
  1445. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  1446. app.state.config.MODEL_FILTER_LIST = form_data.models
  1447. return {
  1448. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1449. "models": app.state.config.MODEL_FILTER_LIST,
  1450. }
  1451. # TODO: webhook endpoint should be under config endpoints
  1452. @app.get("/api/webhook")
  1453. async def get_webhook_url(user=Depends(get_admin_user)):
  1454. return {
  1455. "url": app.state.config.WEBHOOK_URL,
  1456. }
  1457. class UrlForm(BaseModel):
  1458. url: str
  1459. @app.post("/api/webhook")
  1460. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1461. app.state.config.WEBHOOK_URL = form_data.url
  1462. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1463. return {"url": app.state.config.WEBHOOK_URL}
  1464. @app.get("/api/version")
  1465. async def get_app_config():
  1466. return {
  1467. "version": VERSION,
  1468. }
  1469. @app.get("/api/changelog")
  1470. async def get_app_changelog():
  1471. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1472. @app.get("/api/version/updates")
  1473. async def get_app_latest_release_version():
  1474. try:
  1475. async with aiohttp.ClientSession(trust_env=True) as session:
  1476. async with session.get(
  1477. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1478. ) as response:
  1479. response.raise_for_status()
  1480. data = await response.json()
  1481. latest_version = data["tag_name"]
  1482. return {"current": VERSION, "latest": latest_version[1:]}
  1483. except aiohttp.ClientError as e:
  1484. raise HTTPException(
  1485. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  1486. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  1487. )
  1488. ############################
  1489. # OAuth Login & Callback
  1490. ############################
  1491. oauth = OAuth()
  1492. for provider_name, provider_config in OAUTH_PROVIDERS.items():
  1493. oauth.register(
  1494. name=provider_name,
  1495. client_id=provider_config["client_id"],
  1496. client_secret=provider_config["client_secret"],
  1497. server_metadata_url=provider_config["server_metadata_url"],
  1498. client_kwargs={
  1499. "scope": provider_config["scope"],
  1500. },
  1501. )
  1502. # SessionMiddleware is used by authlib for oauth
  1503. if len(OAUTH_PROVIDERS) > 0:
  1504. app.add_middleware(
  1505. SessionMiddleware,
  1506. secret_key=WEBUI_SECRET_KEY,
  1507. session_cookie="oui-session",
  1508. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  1509. https_only=WEBUI_SESSION_COOKIE_SECURE,
  1510. )
  1511. @app.get("/oauth/{provider}/login")
  1512. async def oauth_login(provider: str, request: Request):
  1513. if provider not in OAUTH_PROVIDERS:
  1514. raise HTTPException(404)
  1515. redirect_uri = request.url_for("oauth_callback", provider=provider)
  1516. return await oauth.create_client(provider).authorize_redirect(request, redirect_uri)
  1517. # OAuth login logic is as follows:
  1518. # 1. Attempt to find a user with matching subject ID, tied to the provider
  1519. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  1520. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  1521. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  1522. # - Email addresses are considered unique, so we fail registration if the email address is alreayd taken
  1523. @app.get("/oauth/{provider}/callback")
  1524. async def oauth_callback(provider: str, request: Request, response: Response):
  1525. if provider not in OAUTH_PROVIDERS:
  1526. raise HTTPException(404)
  1527. client = oauth.create_client(provider)
  1528. try:
  1529. token = await client.authorize_access_token(request)
  1530. except Exception as e:
  1531. log.warning(f"OAuth callback error: {e}")
  1532. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1533. user_data: UserInfo = token["userinfo"]
  1534. sub = user_data.get("sub")
  1535. if not sub:
  1536. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  1537. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1538. provider_sub = f"{provider}@{sub}"
  1539. email = user_data.get("email", "").lower()
  1540. # We currently mandate that email addresses are provided
  1541. if not email:
  1542. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  1543. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1544. # Check if the user exists
  1545. user = Users.get_user_by_oauth_sub(provider_sub)
  1546. if not user:
  1547. # If the user does not exist, check if merging is enabled
  1548. if OAUTH_MERGE_ACCOUNTS_BY_EMAIL.value:
  1549. # Check if the user exists by email
  1550. user = Users.get_user_by_email(email)
  1551. if user:
  1552. # Update the user with the new oauth sub
  1553. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  1554. if not user:
  1555. # If the user does not exist, check if signups are enabled
  1556. if ENABLE_OAUTH_SIGNUP.value:
  1557. # Check if an existing user with the same email already exists
  1558. existing_user = Users.get_user_by_email(user_data.get("email", "").lower())
  1559. if existing_user:
  1560. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  1561. picture_url = user_data.get("picture", "")
  1562. if picture_url:
  1563. # Download the profile image into a base64 string
  1564. try:
  1565. async with aiohttp.ClientSession() as session:
  1566. async with session.get(picture_url) as resp:
  1567. picture = await resp.read()
  1568. base64_encoded_picture = base64.b64encode(picture).decode(
  1569. "utf-8"
  1570. )
  1571. guessed_mime_type = mimetypes.guess_type(picture_url)[0]
  1572. if guessed_mime_type is None:
  1573. # assume JPG, browsers are tolerant enough of image formats
  1574. guessed_mime_type = "image/jpeg"
  1575. picture_url = f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  1576. except Exception as e:
  1577. log.error(f"Error downloading profile image '{picture_url}': {e}")
  1578. picture_url = ""
  1579. if not picture_url:
  1580. picture_url = "/user.png"
  1581. user = Auths.insert_new_auth(
  1582. email=email,
  1583. password=get_password_hash(
  1584. str(uuid.uuid4())
  1585. ), # Random password, not used
  1586. name=user_data.get("name", "User"),
  1587. profile_image_url=picture_url,
  1588. role=webui_app.state.config.DEFAULT_USER_ROLE,
  1589. oauth_sub=provider_sub,
  1590. )
  1591. if webui_app.state.config.WEBHOOK_URL:
  1592. post_webhook(
  1593. webui_app.state.config.WEBHOOK_URL,
  1594. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1595. {
  1596. "action": "signup",
  1597. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1598. "user": user.model_dump_json(exclude_none=True),
  1599. },
  1600. )
  1601. else:
  1602. raise HTTPException(
  1603. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  1604. )
  1605. jwt_token = create_token(
  1606. data={"id": user.id},
  1607. expires_delta=parse_duration(webui_app.state.config.JWT_EXPIRES_IN),
  1608. )
  1609. # Set the cookie token
  1610. response.set_cookie(
  1611. key="token",
  1612. value=token,
  1613. httponly=True, # Ensures the cookie is not accessible via JavaScript
  1614. )
  1615. # Redirect back to the frontend with the JWT token
  1616. redirect_url = f"{request.base_url}auth#token={jwt_token}"
  1617. return RedirectResponse(url=redirect_url)
  1618. @app.get("/manifest.json")
  1619. async def get_manifest_json():
  1620. return {
  1621. "name": WEBUI_NAME,
  1622. "short_name": WEBUI_NAME,
  1623. "start_url": "/",
  1624. "display": "standalone",
  1625. "background_color": "#343541",
  1626. "orientation": "portrait-primary",
  1627. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  1628. }
  1629. @app.get("/opensearch.xml")
  1630. async def get_opensearch_xml():
  1631. xml_content = rf"""
  1632. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1633. <ShortName>{WEBUI_NAME}</ShortName>
  1634. <Description>Search {WEBUI_NAME}</Description>
  1635. <InputEncoding>UTF-8</InputEncoding>
  1636. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/favicon.png</Image>
  1637. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1638. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1639. </OpenSearchDescription>
  1640. """
  1641. return Response(content=xml_content, media_type="application/xml")
  1642. @app.get("/health")
  1643. async def healthcheck():
  1644. return {"status": True}
  1645. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  1646. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  1647. if os.path.exists(FRONTEND_BUILD_DIR):
  1648. mimetypes.add_type("text/javascript", ".js")
  1649. app.mount(
  1650. "/",
  1651. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1652. name="spa-static-files",
  1653. )
  1654. else:
  1655. log.warning(
  1656. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1657. )