main.py 67 KB

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