main.py 72 KB

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