main.py 69 KB

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