main.py 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187
  1. import base64
  2. import uuid
  3. from contextlib import asynccontextmanager
  4. from authlib.integrations.starlette_client import OAuth
  5. from authlib.oidc.core import UserInfo
  6. from bs4 import BeautifulSoup
  7. import json
  8. import markdown
  9. import time
  10. import os
  11. import sys
  12. import logging
  13. import aiohttp
  14. import requests
  15. import mimetypes
  16. import shutil
  17. import os
  18. import uuid
  19. import inspect
  20. import asyncio
  21. from fastapi.concurrency import run_in_threadpool
  22. from fastapi import FastAPI, Request, Depends, status, UploadFile, File, Form
  23. from fastapi.staticfiles import StaticFiles
  24. from fastapi.responses import JSONResponse
  25. from fastapi import HTTPException
  26. from fastapi.middleware.wsgi import WSGIMiddleware
  27. from fastapi.middleware.cors import CORSMiddleware
  28. from starlette.exceptions import HTTPException as StarletteHTTPException
  29. from starlette.middleware.base import BaseHTTPMiddleware
  30. from starlette.middleware.sessions import SessionMiddleware
  31. from starlette.responses import StreamingResponse, Response, RedirectResponse
  32. from apps.socket.main import 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. pipe = None
  802. for model in models:
  803. if (
  804. custom_model.base_model_id == model["id"]
  805. or custom_model.base_model_id == model["id"].split(":")[0]
  806. ):
  807. owned_by = model["owned_by"]
  808. if "pipe" in model:
  809. pipe = model["pipe"]
  810. break
  811. models.append(
  812. {
  813. "id": custom_model.id,
  814. "name": custom_model.name,
  815. "object": "model",
  816. "created": custom_model.created_at,
  817. "owned_by": owned_by,
  818. "info": custom_model.model_dump(),
  819. "preset": True,
  820. **({"pipe": pipe} if pipe is not None else {}),
  821. }
  822. )
  823. app.state.MODELS = {model["id"]: model for model in models}
  824. webui_app.state.MODELS = app.state.MODELS
  825. return models
  826. @app.get("/api/models")
  827. async def get_models(user=Depends(get_verified_user)):
  828. models = await get_all_models()
  829. # Filter out filter pipelines
  830. models = [
  831. model
  832. for model in models
  833. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  834. ]
  835. if app.state.config.ENABLE_MODEL_FILTER:
  836. if user.role == "user":
  837. models = list(
  838. filter(
  839. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  840. models,
  841. )
  842. )
  843. return {"data": models}
  844. return {"data": models}
  845. @app.post("/api/chat/completions")
  846. async def generate_chat_completions(form_data: dict, user=Depends(get_verified_user)):
  847. model_id = form_data["model"]
  848. if model_id not in app.state.MODELS:
  849. raise HTTPException(
  850. status_code=status.HTTP_404_NOT_FOUND,
  851. detail="Model not found",
  852. )
  853. model = app.state.MODELS[model_id]
  854. pipe = model.get("pipe")
  855. if pipe:
  856. return await generate_function_chat_completion(form_data, user=user)
  857. if model["owned_by"] == "ollama":
  858. return await generate_ollama_chat_completion(form_data, user=user)
  859. else:
  860. return await generate_openai_chat_completion(form_data, user=user)
  861. @app.post("/api/chat/completed")
  862. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  863. data = form_data
  864. model_id = data["model"]
  865. if model_id not in app.state.MODELS:
  866. raise HTTPException(
  867. status_code=status.HTTP_404_NOT_FOUND,
  868. detail="Model not found",
  869. )
  870. model = app.state.MODELS[model_id]
  871. filters = [
  872. model
  873. for model in app.state.MODELS.values()
  874. if "pipeline" in model
  875. and "type" in model["pipeline"]
  876. and model["pipeline"]["type"] == "filter"
  877. and (
  878. model["pipeline"]["pipelines"] == ["*"]
  879. or any(
  880. model_id == target_model_id
  881. for target_model_id in model["pipeline"]["pipelines"]
  882. )
  883. )
  884. ]
  885. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  886. if "pipeline" in model:
  887. sorted_filters = [model] + sorted_filters
  888. for filter in sorted_filters:
  889. r = None
  890. try:
  891. urlIdx = filter["urlIdx"]
  892. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  893. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  894. if key != "":
  895. headers = {"Authorization": f"Bearer {key}"}
  896. r = requests.post(
  897. f"{url}/{filter['id']}/filter/outlet",
  898. headers=headers,
  899. json={
  900. "user": {
  901. "id": user.id,
  902. "name": user.name,
  903. "email": user.email,
  904. "role": user.role,
  905. },
  906. "body": data,
  907. },
  908. )
  909. r.raise_for_status()
  910. data = r.json()
  911. except Exception as e:
  912. # Handle connection error here
  913. print(f"Connection error: {e}")
  914. if r is not None:
  915. try:
  916. res = r.json()
  917. if "detail" in res:
  918. return JSONResponse(
  919. status_code=r.status_code,
  920. content=res,
  921. )
  922. except:
  923. pass
  924. else:
  925. pass
  926. async def __event_emitter__(data):
  927. await sio.emit(
  928. "chat-events",
  929. {
  930. "chat_id": data["chat_id"],
  931. "message_id": data["id"],
  932. "data": data,
  933. },
  934. to=data["session_id"],
  935. )
  936. def get_priority(function_id):
  937. function = Functions.get_function_by_id(function_id)
  938. if function is not None and hasattr(function, "valves"):
  939. return (function.valves if function.valves else {}).get("priority", 0)
  940. return 0
  941. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  942. if "info" in model and "meta" in model["info"]:
  943. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  944. filter_ids = list(set(filter_ids))
  945. enabled_filter_ids = [
  946. function.id
  947. for function in Functions.get_functions_by_type("filter", active_only=True)
  948. ]
  949. filter_ids = [
  950. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  951. ]
  952. # Sort filter_ids by priority, using the get_priority function
  953. filter_ids.sort(key=get_priority)
  954. for filter_id in filter_ids:
  955. filter = Functions.get_function_by_id(filter_id)
  956. if filter:
  957. if filter_id in webui_app.state.FUNCTIONS:
  958. function_module = webui_app.state.FUNCTIONS[filter_id]
  959. else:
  960. function_module, function_type, frontmatter = (
  961. load_function_module_by_id(filter_id)
  962. )
  963. webui_app.state.FUNCTIONS[filter_id] = function_module
  964. if hasattr(function_module, "valves") and hasattr(
  965. function_module, "Valves"
  966. ):
  967. valves = Functions.get_function_valves_by_id(filter_id)
  968. function_module.valves = function_module.Valves(
  969. **(valves if valves else {})
  970. )
  971. try:
  972. if hasattr(function_module, "outlet"):
  973. outlet = function_module.outlet
  974. # Get the signature of the function
  975. sig = inspect.signature(outlet)
  976. params = {"body": data}
  977. if "__user__" in sig.parameters:
  978. __user__ = {
  979. "id": user.id,
  980. "email": user.email,
  981. "name": user.name,
  982. "role": user.role,
  983. }
  984. try:
  985. if hasattr(function_module, "UserValves"):
  986. __user__["valves"] = function_module.UserValves(
  987. **Functions.get_user_valves_by_id_and_user_id(
  988. filter_id, user.id
  989. )
  990. )
  991. except Exception as e:
  992. print(e)
  993. params = {**params, "__user__": __user__}
  994. if "__id__" in sig.parameters:
  995. params = {
  996. **params,
  997. "__id__": filter_id,
  998. }
  999. if "__model__" in sig.parameters:
  1000. params = {
  1001. **params,
  1002. "__model__": model,
  1003. }
  1004. if "__event_emitter__" in sig.parameters:
  1005. params = {
  1006. **params,
  1007. "__event_emitter__": __event_emitter__,
  1008. }
  1009. if inspect.iscoroutinefunction(outlet):
  1010. data = await outlet(**params)
  1011. else:
  1012. data = outlet(**params)
  1013. except Exception as e:
  1014. print(f"Error: {e}")
  1015. return JSONResponse(
  1016. status_code=status.HTTP_400_BAD_REQUEST,
  1017. content={"detail": str(e)},
  1018. )
  1019. return data
  1020. ##################################
  1021. #
  1022. # Task Endpoints
  1023. #
  1024. ##################################
  1025. # TODO: Refactor task API endpoints below into a separate file
  1026. @app.get("/api/task/config")
  1027. async def get_task_config(user=Depends(get_verified_user)):
  1028. return {
  1029. "TASK_MODEL": app.state.config.TASK_MODEL,
  1030. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1031. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1032. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1033. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  1034. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1035. }
  1036. class TaskConfigForm(BaseModel):
  1037. TASK_MODEL: Optional[str]
  1038. TASK_MODEL_EXTERNAL: Optional[str]
  1039. TITLE_GENERATION_PROMPT_TEMPLATE: str
  1040. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE: str
  1041. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD: int
  1042. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  1043. @app.post("/api/task/config/update")
  1044. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  1045. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  1046. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  1047. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  1048. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  1049. )
  1050. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  1051. form_data.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1052. )
  1053. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  1054. form_data.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  1055. )
  1056. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  1057. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1058. )
  1059. return {
  1060. "TASK_MODEL": app.state.config.TASK_MODEL,
  1061. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1062. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1063. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1064. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  1065. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1066. }
  1067. @app.post("/api/task/title/completions")
  1068. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  1069. print("generate_title")
  1070. model_id = form_data["model"]
  1071. if model_id not in app.state.MODELS:
  1072. raise HTTPException(
  1073. status_code=status.HTTP_404_NOT_FOUND,
  1074. detail="Model not found",
  1075. )
  1076. # Check if the user has a custom task model
  1077. # If the user has a custom task model, use that model
  1078. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  1079. if app.state.config.TASK_MODEL:
  1080. task_model_id = app.state.config.TASK_MODEL
  1081. if task_model_id in app.state.MODELS:
  1082. model_id = task_model_id
  1083. else:
  1084. if app.state.config.TASK_MODEL_EXTERNAL:
  1085. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  1086. if task_model_id in app.state.MODELS:
  1087. model_id = task_model_id
  1088. print(model_id)
  1089. model = app.state.MODELS[model_id]
  1090. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  1091. content = title_generation_template(
  1092. template,
  1093. form_data["prompt"],
  1094. {
  1095. "name": user.name,
  1096. "location": user.info.get("location") if user.info else None,
  1097. },
  1098. )
  1099. payload = {
  1100. "model": model_id,
  1101. "messages": [{"role": "user", "content": content}],
  1102. "stream": False,
  1103. "max_tokens": 50,
  1104. "chat_id": form_data.get("chat_id", None),
  1105. "task": TASKS.TITLE_GENERATION,
  1106. }
  1107. log.debug(payload)
  1108. try:
  1109. payload = filter_pipeline(payload, user)
  1110. except Exception as e:
  1111. return JSONResponse(
  1112. status_code=e.args[0],
  1113. content={"detail": e.args[1]},
  1114. )
  1115. if "chat_id" in payload:
  1116. del payload["chat_id"]
  1117. return await generate_chat_completions(form_data=payload, user=user)
  1118. @app.post("/api/task/query/completions")
  1119. async def generate_search_query(form_data: dict, user=Depends(get_verified_user)):
  1120. print("generate_search_query")
  1121. if len(form_data["prompt"]) < app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD:
  1122. raise HTTPException(
  1123. status_code=status.HTTP_400_BAD_REQUEST,
  1124. detail=f"Skip search query generation for short prompts (< {app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD} characters)",
  1125. )
  1126. model_id = form_data["model"]
  1127. if model_id not in app.state.MODELS:
  1128. raise HTTPException(
  1129. status_code=status.HTTP_404_NOT_FOUND,
  1130. detail="Model not found",
  1131. )
  1132. # Check if the user has a custom task model
  1133. # If the user has a custom task model, use that model
  1134. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  1135. if app.state.config.TASK_MODEL:
  1136. task_model_id = app.state.config.TASK_MODEL
  1137. if task_model_id in app.state.MODELS:
  1138. model_id = task_model_id
  1139. else:
  1140. if app.state.config.TASK_MODEL_EXTERNAL:
  1141. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  1142. if task_model_id in app.state.MODELS:
  1143. model_id = task_model_id
  1144. print(model_id)
  1145. model = app.state.MODELS[model_id]
  1146. template = app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1147. content = search_query_generation_template(
  1148. template, form_data["prompt"], {"name": user.name}
  1149. )
  1150. payload = {
  1151. "model": model_id,
  1152. "messages": [{"role": "user", "content": content}],
  1153. "stream": False,
  1154. "max_tokens": 30,
  1155. "task": TASKS.QUERY_GENERATION,
  1156. }
  1157. print(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/emoji/completions")
  1169. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  1170. print("generate_emoji")
  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. model = app.state.MODELS[model_id]
  1191. template = '''
  1192. 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., 😊, 😢, 😡, 😱).
  1193. Message: """{{prompt}}"""
  1194. '''
  1195. content = title_generation_template(
  1196. template,
  1197. form_data["prompt"],
  1198. {
  1199. "name": user.name,
  1200. "location": user.info.get("location") if user.info else None,
  1201. },
  1202. )
  1203. payload = {
  1204. "model": model_id,
  1205. "messages": [{"role": "user", "content": content}],
  1206. "stream": False,
  1207. "max_tokens": 4,
  1208. "chat_id": form_data.get("chat_id", None),
  1209. "task": TASKS.EMOJI_GENERATION,
  1210. }
  1211. log.debug(payload)
  1212. try:
  1213. payload = filter_pipeline(payload, user)
  1214. except Exception as e:
  1215. return JSONResponse(
  1216. status_code=e.args[0],
  1217. content={"detail": e.args[1]},
  1218. )
  1219. if "chat_id" in payload:
  1220. del payload["chat_id"]
  1221. return await generate_chat_completions(form_data=payload, user=user)
  1222. @app.post("/api/task/tools/completions")
  1223. async def get_tools_function_calling(form_data: dict, user=Depends(get_verified_user)):
  1224. print("get_tools_function_calling")
  1225. model_id = form_data["model"]
  1226. if model_id not in app.state.MODELS:
  1227. raise HTTPException(
  1228. status_code=status.HTTP_404_NOT_FOUND,
  1229. detail="Model not found",
  1230. )
  1231. # Check if the user has a custom task model
  1232. # If the user has a custom task model, use that model
  1233. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  1234. if app.state.config.TASK_MODEL:
  1235. task_model_id = app.state.config.TASK_MODEL
  1236. if task_model_id in app.state.MODELS:
  1237. model_id = task_model_id
  1238. else:
  1239. if app.state.config.TASK_MODEL_EXTERNAL:
  1240. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  1241. if task_model_id in app.state.MODELS:
  1242. model_id = task_model_id
  1243. print(model_id)
  1244. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1245. try:
  1246. context, citation, file_handler = await get_function_call_response(
  1247. form_data["messages"],
  1248. form_data.get("files", []),
  1249. form_data["tool_id"],
  1250. template,
  1251. model_id,
  1252. user,
  1253. )
  1254. return context
  1255. except Exception as e:
  1256. return JSONResponse(
  1257. status_code=e.args[0],
  1258. content={"detail": e.args[1]},
  1259. )
  1260. ##################################
  1261. #
  1262. # Pipelines Endpoints
  1263. #
  1264. ##################################
  1265. # TODO: Refactor pipelines API endpoints below into a separate file
  1266. @app.get("/api/pipelines/list")
  1267. async def get_pipelines_list(user=Depends(get_admin_user)):
  1268. responses = await get_openai_models(raw=True)
  1269. print(responses)
  1270. urlIdxs = [
  1271. idx
  1272. for idx, response in enumerate(responses)
  1273. if response != None and "pipelines" in response
  1274. ]
  1275. return {
  1276. "data": [
  1277. {
  1278. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  1279. "idx": urlIdx,
  1280. }
  1281. for urlIdx in urlIdxs
  1282. ]
  1283. }
  1284. @app.post("/api/pipelines/upload")
  1285. async def upload_pipeline(
  1286. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  1287. ):
  1288. print("upload_pipeline", urlIdx, file.filename)
  1289. # Check if the uploaded file is a python file
  1290. if not file.filename.endswith(".py"):
  1291. raise HTTPException(
  1292. status_code=status.HTTP_400_BAD_REQUEST,
  1293. detail="Only Python (.py) files are allowed.",
  1294. )
  1295. upload_folder = f"{CACHE_DIR}/pipelines"
  1296. os.makedirs(upload_folder, exist_ok=True)
  1297. file_path = os.path.join(upload_folder, file.filename)
  1298. try:
  1299. # Save the uploaded file
  1300. with open(file_path, "wb") as buffer:
  1301. shutil.copyfileobj(file.file, buffer)
  1302. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1303. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1304. headers = {"Authorization": f"Bearer {key}"}
  1305. with open(file_path, "rb") as f:
  1306. files = {"file": f}
  1307. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1308. r.raise_for_status()
  1309. data = r.json()
  1310. return {**data}
  1311. except Exception as e:
  1312. # Handle connection error here
  1313. print(f"Connection error: {e}")
  1314. detail = "Pipeline not found"
  1315. if r is not None:
  1316. try:
  1317. res = r.json()
  1318. if "detail" in res:
  1319. detail = res["detail"]
  1320. except:
  1321. pass
  1322. raise HTTPException(
  1323. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1324. detail=detail,
  1325. )
  1326. finally:
  1327. # Ensure the file is deleted after the upload is completed or on failure
  1328. if os.path.exists(file_path):
  1329. os.remove(file_path)
  1330. class AddPipelineForm(BaseModel):
  1331. url: str
  1332. urlIdx: int
  1333. @app.post("/api/pipelines/add")
  1334. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1335. r = None
  1336. try:
  1337. urlIdx = form_data.urlIdx
  1338. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1339. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1340. headers = {"Authorization": f"Bearer {key}"}
  1341. r = requests.post(
  1342. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1343. )
  1344. r.raise_for_status()
  1345. data = r.json()
  1346. return {**data}
  1347. except Exception as e:
  1348. # Handle connection error here
  1349. print(f"Connection error: {e}")
  1350. detail = "Pipeline not found"
  1351. if r is not None:
  1352. try:
  1353. res = r.json()
  1354. if "detail" in res:
  1355. detail = res["detail"]
  1356. except:
  1357. pass
  1358. raise HTTPException(
  1359. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1360. detail=detail,
  1361. )
  1362. class DeletePipelineForm(BaseModel):
  1363. id: str
  1364. urlIdx: int
  1365. @app.delete("/api/pipelines/delete")
  1366. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1367. r = None
  1368. try:
  1369. urlIdx = form_data.urlIdx
  1370. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1371. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1372. headers = {"Authorization": f"Bearer {key}"}
  1373. r = requests.delete(
  1374. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1375. )
  1376. r.raise_for_status()
  1377. data = r.json()
  1378. return {**data}
  1379. except Exception as e:
  1380. # Handle connection error here
  1381. print(f"Connection error: {e}")
  1382. detail = "Pipeline not found"
  1383. if r is not None:
  1384. try:
  1385. res = r.json()
  1386. if "detail" in res:
  1387. detail = res["detail"]
  1388. except:
  1389. pass
  1390. raise HTTPException(
  1391. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1392. detail=detail,
  1393. )
  1394. @app.get("/api/pipelines")
  1395. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  1396. r = None
  1397. try:
  1398. urlIdx
  1399. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1400. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1401. headers = {"Authorization": f"Bearer {key}"}
  1402. r = requests.get(f"{url}/pipelines", headers=headers)
  1403. r.raise_for_status()
  1404. data = r.json()
  1405. return {**data}
  1406. except Exception as e:
  1407. # Handle connection error here
  1408. print(f"Connection error: {e}")
  1409. detail = "Pipeline not found"
  1410. if r is not None:
  1411. try:
  1412. res = r.json()
  1413. if "detail" in res:
  1414. detail = res["detail"]
  1415. except:
  1416. pass
  1417. raise HTTPException(
  1418. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1419. detail=detail,
  1420. )
  1421. @app.get("/api/pipelines/{pipeline_id}/valves")
  1422. async def get_pipeline_valves(
  1423. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  1424. ):
  1425. models = await get_all_models()
  1426. r = None
  1427. try:
  1428. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1429. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1430. headers = {"Authorization": f"Bearer {key}"}
  1431. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  1432. r.raise_for_status()
  1433. data = r.json()
  1434. return {**data}
  1435. except Exception as e:
  1436. # Handle connection error here
  1437. print(f"Connection error: {e}")
  1438. detail = "Pipeline not found"
  1439. if r is not None:
  1440. try:
  1441. res = r.json()
  1442. if "detail" in res:
  1443. detail = res["detail"]
  1444. except:
  1445. pass
  1446. raise HTTPException(
  1447. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1448. detail=detail,
  1449. )
  1450. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1451. async def get_pipeline_valves_spec(
  1452. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  1453. ):
  1454. models = await get_all_models()
  1455. r = None
  1456. try:
  1457. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1458. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1459. headers = {"Authorization": f"Bearer {key}"}
  1460. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  1461. r.raise_for_status()
  1462. data = r.json()
  1463. return {**data}
  1464. except Exception as e:
  1465. # Handle connection error here
  1466. print(f"Connection error: {e}")
  1467. detail = "Pipeline not found"
  1468. if r is not None:
  1469. try:
  1470. res = r.json()
  1471. if "detail" in res:
  1472. detail = res["detail"]
  1473. except:
  1474. pass
  1475. raise HTTPException(
  1476. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1477. detail=detail,
  1478. )
  1479. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1480. async def update_pipeline_valves(
  1481. urlIdx: Optional[int],
  1482. pipeline_id: str,
  1483. form_data: dict,
  1484. user=Depends(get_admin_user),
  1485. ):
  1486. models = await get_all_models()
  1487. r = None
  1488. try:
  1489. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1490. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1491. headers = {"Authorization": f"Bearer {key}"}
  1492. r = requests.post(
  1493. f"{url}/{pipeline_id}/valves/update",
  1494. headers=headers,
  1495. json={**form_data},
  1496. )
  1497. r.raise_for_status()
  1498. data = r.json()
  1499. return {**data}
  1500. except Exception as e:
  1501. # Handle connection error here
  1502. print(f"Connection error: {e}")
  1503. detail = "Pipeline not found"
  1504. if r is not None:
  1505. try:
  1506. res = r.json()
  1507. if "detail" in res:
  1508. detail = res["detail"]
  1509. except:
  1510. pass
  1511. raise HTTPException(
  1512. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1513. detail=detail,
  1514. )
  1515. ##################################
  1516. #
  1517. # Config Endpoints
  1518. #
  1519. ##################################
  1520. @app.get("/api/config")
  1521. async def get_app_config():
  1522. return {
  1523. "status": True,
  1524. "name": WEBUI_NAME,
  1525. "version": VERSION,
  1526. "default_locale": str(DEFAULT_LOCALE),
  1527. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1528. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1529. "features": {
  1530. "auth": WEBUI_AUTH,
  1531. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1532. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1533. "enable_web_search": rag_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1534. "enable_image_generation": images_app.state.config.ENABLED,
  1535. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1536. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1537. },
  1538. "audio": {
  1539. "tts": {
  1540. "engine": audio_app.state.config.TTS_ENGINE,
  1541. "voice": audio_app.state.config.TTS_VOICE,
  1542. },
  1543. "stt": {
  1544. "engine": audio_app.state.config.STT_ENGINE,
  1545. },
  1546. },
  1547. "oauth": {
  1548. "providers": {
  1549. name: config.get("name", name)
  1550. for name, config in OAUTH_PROVIDERS.items()
  1551. }
  1552. },
  1553. }
  1554. @app.get("/api/config/model/filter")
  1555. async def get_model_filter_config(user=Depends(get_admin_user)):
  1556. return {
  1557. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1558. "models": app.state.config.MODEL_FILTER_LIST,
  1559. }
  1560. class ModelFilterConfigForm(BaseModel):
  1561. enabled: bool
  1562. models: List[str]
  1563. @app.post("/api/config/model/filter")
  1564. async def update_model_filter_config(
  1565. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  1566. ):
  1567. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  1568. app.state.config.MODEL_FILTER_LIST = form_data.models
  1569. return {
  1570. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1571. "models": app.state.config.MODEL_FILTER_LIST,
  1572. }
  1573. # TODO: webhook endpoint should be under config endpoints
  1574. @app.get("/api/webhook")
  1575. async def get_webhook_url(user=Depends(get_admin_user)):
  1576. return {
  1577. "url": app.state.config.WEBHOOK_URL,
  1578. }
  1579. class UrlForm(BaseModel):
  1580. url: str
  1581. @app.post("/api/webhook")
  1582. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1583. app.state.config.WEBHOOK_URL = form_data.url
  1584. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1585. return {"url": app.state.config.WEBHOOK_URL}
  1586. @app.get("/api/version")
  1587. async def get_app_config():
  1588. return {
  1589. "version": VERSION,
  1590. }
  1591. @app.get("/api/changelog")
  1592. async def get_app_changelog():
  1593. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1594. @app.get("/api/version/updates")
  1595. async def get_app_latest_release_version():
  1596. try:
  1597. async with aiohttp.ClientSession(trust_env=True) as session:
  1598. async with session.get(
  1599. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1600. ) as response:
  1601. response.raise_for_status()
  1602. data = await response.json()
  1603. latest_version = data["tag_name"]
  1604. return {"current": VERSION, "latest": latest_version[1:]}
  1605. except aiohttp.ClientError as e:
  1606. raise HTTPException(
  1607. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  1608. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  1609. )
  1610. ############################
  1611. # OAuth Login & Callback
  1612. ############################
  1613. oauth = OAuth()
  1614. for provider_name, provider_config in OAUTH_PROVIDERS.items():
  1615. oauth.register(
  1616. name=provider_name,
  1617. client_id=provider_config["client_id"],
  1618. client_secret=provider_config["client_secret"],
  1619. server_metadata_url=provider_config["server_metadata_url"],
  1620. client_kwargs={
  1621. "scope": provider_config["scope"],
  1622. },
  1623. )
  1624. # SessionMiddleware is used by authlib for oauth
  1625. if len(OAUTH_PROVIDERS) > 0:
  1626. app.add_middleware(
  1627. SessionMiddleware,
  1628. secret_key=WEBUI_SECRET_KEY,
  1629. session_cookie="oui-session",
  1630. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  1631. https_only=WEBUI_SESSION_COOKIE_SECURE,
  1632. )
  1633. @app.get("/oauth/{provider}/login")
  1634. async def oauth_login(provider: str, request: Request):
  1635. if provider not in OAUTH_PROVIDERS:
  1636. raise HTTPException(404)
  1637. redirect_uri = request.url_for("oauth_callback", provider=provider)
  1638. return await oauth.create_client(provider).authorize_redirect(request, redirect_uri)
  1639. # OAuth login logic is as follows:
  1640. # 1. Attempt to find a user with matching subject ID, tied to the provider
  1641. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  1642. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  1643. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  1644. # - Email addresses are considered unique, so we fail registration if the email address is alreayd taken
  1645. @app.get("/oauth/{provider}/callback")
  1646. async def oauth_callback(provider: str, request: Request, response: Response):
  1647. if provider not in OAUTH_PROVIDERS:
  1648. raise HTTPException(404)
  1649. client = oauth.create_client(provider)
  1650. try:
  1651. token = await client.authorize_access_token(request)
  1652. except Exception as e:
  1653. log.warning(f"OAuth callback error: {e}")
  1654. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1655. user_data: UserInfo = token["userinfo"]
  1656. sub = user_data.get("sub")
  1657. if not sub:
  1658. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  1659. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1660. provider_sub = f"{provider}@{sub}"
  1661. email = user_data.get("email", "").lower()
  1662. # We currently mandate that email addresses are provided
  1663. if not email:
  1664. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  1665. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1666. # Check if the user exists
  1667. user = Users.get_user_by_oauth_sub(provider_sub)
  1668. if not user:
  1669. # If the user does not exist, check if merging is enabled
  1670. if OAUTH_MERGE_ACCOUNTS_BY_EMAIL.value:
  1671. # Check if the user exists by email
  1672. user = Users.get_user_by_email(email)
  1673. if user:
  1674. # Update the user with the new oauth sub
  1675. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  1676. if not user:
  1677. # If the user does not exist, check if signups are enabled
  1678. if ENABLE_OAUTH_SIGNUP.value:
  1679. # Check if an existing user with the same email already exists
  1680. existing_user = Users.get_user_by_email(user_data.get("email", "").lower())
  1681. if existing_user:
  1682. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  1683. picture_claim = webui_app.state.config.OAUTH_PICTURE_CLAIM
  1684. picture_url = user_data.get(picture_claim, "")
  1685. if picture_url:
  1686. # Download the profile image into a base64 string
  1687. try:
  1688. async with aiohttp.ClientSession() as session:
  1689. async with session.get(picture_url) as resp:
  1690. picture = await resp.read()
  1691. base64_encoded_picture = base64.b64encode(picture).decode(
  1692. "utf-8"
  1693. )
  1694. guessed_mime_type = mimetypes.guess_type(picture_url)[0]
  1695. if guessed_mime_type is None:
  1696. # assume JPG, browsers are tolerant enough of image formats
  1697. guessed_mime_type = "image/jpeg"
  1698. picture_url = f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  1699. except Exception as e:
  1700. log.error(f"Error downloading profile image '{picture_url}': {e}")
  1701. picture_url = ""
  1702. if not picture_url:
  1703. picture_url = "/user.png"
  1704. username_claim = webui_app.state.config.OAUTH_USERNAME_CLAIM
  1705. role = (
  1706. "admin"
  1707. if Users.get_num_users() == 0
  1708. else webui_app.state.config.DEFAULT_USER_ROLE
  1709. )
  1710. user = Auths.insert_new_auth(
  1711. email=email,
  1712. password=get_password_hash(
  1713. str(uuid.uuid4())
  1714. ), # Random password, not used
  1715. name=user_data.get(username_claim, "User"),
  1716. profile_image_url=picture_url,
  1717. role=role,
  1718. oauth_sub=provider_sub,
  1719. )
  1720. if webui_app.state.config.WEBHOOK_URL:
  1721. post_webhook(
  1722. webui_app.state.config.WEBHOOK_URL,
  1723. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1724. {
  1725. "action": "signup",
  1726. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1727. "user": user.model_dump_json(exclude_none=True),
  1728. },
  1729. )
  1730. else:
  1731. raise HTTPException(
  1732. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  1733. )
  1734. jwt_token = create_token(
  1735. data={"id": user.id},
  1736. expires_delta=parse_duration(webui_app.state.config.JWT_EXPIRES_IN),
  1737. )
  1738. # Set the cookie token
  1739. response.set_cookie(
  1740. key="token",
  1741. value=jwt_token,
  1742. httponly=True, # Ensures the cookie is not accessible via JavaScript
  1743. )
  1744. # Redirect back to the frontend with the JWT token
  1745. redirect_url = f"{request.base_url}auth#token={jwt_token}"
  1746. return RedirectResponse(url=redirect_url)
  1747. @app.get("/manifest.json")
  1748. async def get_manifest_json():
  1749. return {
  1750. "name": WEBUI_NAME,
  1751. "short_name": WEBUI_NAME,
  1752. "start_url": "/",
  1753. "display": "standalone",
  1754. "background_color": "#343541",
  1755. "orientation": "portrait-primary",
  1756. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  1757. }
  1758. @app.get("/opensearch.xml")
  1759. async def get_opensearch_xml():
  1760. xml_content = rf"""
  1761. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1762. <ShortName>{WEBUI_NAME}</ShortName>
  1763. <Description>Search {WEBUI_NAME}</Description>
  1764. <InputEncoding>UTF-8</InputEncoding>
  1765. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/favicon.png</Image>
  1766. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1767. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1768. </OpenSearchDescription>
  1769. """
  1770. return Response(content=xml_content, media_type="application/xml")
  1771. @app.get("/health")
  1772. async def healthcheck():
  1773. return {"status": True}
  1774. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  1775. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  1776. if os.path.exists(FRONTEND_BUILD_DIR):
  1777. mimetypes.add_type("text/javascript", ".js")
  1778. app.mount(
  1779. "/",
  1780. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1781. name="spa-static-files",
  1782. )
  1783. else:
  1784. log.warning(
  1785. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1786. )