main.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  1. from contextlib import asynccontextmanager
  2. from bs4 import BeautifulSoup
  3. import json
  4. import markdown
  5. import time
  6. import os
  7. import sys
  8. import logging
  9. import aiohttp
  10. import requests
  11. import mimetypes
  12. import shutil
  13. import os
  14. import inspect
  15. import asyncio
  16. from fastapi import FastAPI, Request, Depends, status, UploadFile, File, Form
  17. from fastapi.staticfiles import StaticFiles
  18. from fastapi.responses import JSONResponse
  19. from fastapi import HTTPException
  20. from fastapi.middleware.wsgi import WSGIMiddleware
  21. from fastapi.middleware.cors import CORSMiddleware
  22. from starlette.exceptions import HTTPException as StarletteHTTPException
  23. from starlette.middleware.base import BaseHTTPMiddleware
  24. from starlette.responses import StreamingResponse, Response
  25. from apps.socket.main import app as socket_app
  26. from apps.ollama.main import (
  27. app as ollama_app,
  28. OpenAIChatCompletionForm,
  29. get_all_models as get_ollama_models,
  30. generate_openai_chat_completion as generate_ollama_chat_completion,
  31. )
  32. from apps.openai.main import (
  33. app as openai_app,
  34. get_all_models as get_openai_models,
  35. generate_chat_completion as generate_openai_chat_completion,
  36. )
  37. from apps.audio.main import app as audio_app
  38. from apps.images.main import app as images_app
  39. from apps.rag.main import app as rag_app
  40. from apps.webui.main import app as webui_app
  41. from pydantic import BaseModel
  42. from typing import List, Optional
  43. from apps.webui.models.models import Models, ModelModel
  44. from apps.webui.models.tools import Tools
  45. from apps.webui.utils import load_toolkit_module_by_id
  46. from utils.utils import (
  47. get_admin_user,
  48. get_verified_user,
  49. get_current_user,
  50. get_http_authorization_cred,
  51. )
  52. from utils.task import (
  53. title_generation_template,
  54. search_query_generation_template,
  55. tools_function_calling_generation_template,
  56. )
  57. from utils.misc import get_last_user_message, add_or_update_system_message
  58. from apps.rag.utils import get_rag_context, rag_template
  59. from config import (
  60. CONFIG_DATA,
  61. WEBUI_NAME,
  62. WEBUI_URL,
  63. WEBUI_AUTH,
  64. ENV,
  65. VERSION,
  66. CHANGELOG,
  67. FRONTEND_BUILD_DIR,
  68. CACHE_DIR,
  69. STATIC_DIR,
  70. ENABLE_OPENAI_API,
  71. ENABLE_OLLAMA_API,
  72. ENABLE_MODEL_FILTER,
  73. MODEL_FILTER_LIST,
  74. GLOBAL_LOG_LEVEL,
  75. SRC_LOG_LEVELS,
  76. WEBHOOK_URL,
  77. ENABLE_ADMIN_EXPORT,
  78. WEBUI_BUILD_HASH,
  79. TASK_MODEL,
  80. TASK_MODEL_EXTERNAL,
  81. TITLE_GENERATION_PROMPT_TEMPLATE,
  82. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  83. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  84. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  85. AppConfig,
  86. )
  87. from constants import ERROR_MESSAGES
  88. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  89. log = logging.getLogger(__name__)
  90. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  91. class SPAStaticFiles(StaticFiles):
  92. async def get_response(self, path: str, scope):
  93. try:
  94. return await super().get_response(path, scope)
  95. except (HTTPException, StarletteHTTPException) as ex:
  96. if ex.status_code == 404:
  97. return await super().get_response("index.html", scope)
  98. else:
  99. raise ex
  100. print(
  101. rf"""
  102. ___ __ __ _ _ _ ___
  103. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  104. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  105. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  106. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  107. |_|
  108. v{VERSION} - building the best open-source AI user interface.
  109. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  110. https://github.com/open-webui/open-webui
  111. """
  112. )
  113. @asynccontextmanager
  114. async def lifespan(app: FastAPI):
  115. yield
  116. app = FastAPI(
  117. docs_url="/docs" if ENV == "dev" else None, redoc_url=None, lifespan=lifespan
  118. )
  119. app.state.config = AppConfig()
  120. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  121. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  122. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  123. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  124. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  125. app.state.config.TASK_MODEL = TASK_MODEL
  126. app.state.config.TASK_MODEL_EXTERNAL = TASK_MODEL_EXTERNAL
  127. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = TITLE_GENERATION_PROMPT_TEMPLATE
  128. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  129. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  130. )
  131. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  132. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  133. )
  134. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  135. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  136. )
  137. app.state.MODELS = {}
  138. origins = ["*"]
  139. async def get_function_call_response(messages, tool_id, template, task_model_id, user):
  140. tool = Tools.get_tool_by_id(tool_id)
  141. tools_specs = json.dumps(tool.specs, indent=2)
  142. content = tools_function_calling_generation_template(template, tools_specs)
  143. user_message = get_last_user_message(messages)
  144. prompt = (
  145. "History:\n"
  146. + "\n".join(
  147. [
  148. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  149. for message in messages[::-1][:4]
  150. ]
  151. )
  152. + f"\nQuery: {user_message}"
  153. )
  154. print(prompt)
  155. payload = {
  156. "model": task_model_id,
  157. "messages": [
  158. {"role": "system", "content": content},
  159. {"role": "user", "content": f"Query: {prompt}"},
  160. ],
  161. "stream": False,
  162. }
  163. try:
  164. payload = filter_pipeline(payload, user)
  165. except Exception as e:
  166. raise e
  167. model = app.state.MODELS[task_model_id]
  168. response = None
  169. try:
  170. if model["owned_by"] == "ollama":
  171. response = await generate_ollama_chat_completion(
  172. OpenAIChatCompletionForm(**payload), user=user
  173. )
  174. else:
  175. response = await generate_openai_chat_completion(payload, user=user)
  176. content = None
  177. if hasattr(response, "body_iterator"):
  178. async for chunk in response.body_iterator:
  179. data = json.loads(chunk.decode("utf-8"))
  180. content = data["choices"][0]["message"]["content"]
  181. # Cleanup any remaining background tasks if necessary
  182. if response.background is not None:
  183. await response.background()
  184. else:
  185. content = response["choices"][0]["message"]["content"]
  186. # Parse the function response
  187. if content is not None:
  188. print(f"content: {content}")
  189. result = json.loads(content)
  190. print(result)
  191. # Call the function
  192. if "name" in result:
  193. if tool_id in webui_app.state.TOOLS:
  194. toolkit_module = webui_app.state.TOOLS[tool_id]
  195. else:
  196. toolkit_module = load_toolkit_module_by_id(tool_id)
  197. webui_app.state.TOOLS[tool_id] = toolkit_module
  198. function = getattr(toolkit_module, result["name"])
  199. function_result = None
  200. try:
  201. # Get the signature of the function
  202. sig = inspect.signature(function)
  203. # Check if '__user__' is a parameter of the function
  204. if "__user__" in sig.parameters:
  205. # Call the function with the '__user__' parameter included
  206. function_result = function(
  207. **{
  208. **result["parameters"],
  209. "__user__": {
  210. "id": user.id,
  211. "email": user.email,
  212. "name": user.name,
  213. "role": user.role,
  214. },
  215. }
  216. )
  217. else:
  218. # Call the function without modifying the parameters
  219. function_result = function(**result["parameters"])
  220. except Exception as e:
  221. print(e)
  222. # Add the function result to the system prompt
  223. if function_result:
  224. return function_result
  225. except Exception as e:
  226. print(f"Error: {e}")
  227. return None
  228. class ChatCompletionMiddleware(BaseHTTPMiddleware):
  229. async def dispatch(self, request: Request, call_next):
  230. return_citations = False
  231. if request.method == "POST" and (
  232. "/ollama/api/chat" in request.url.path
  233. or "/chat/completions" in request.url.path
  234. ):
  235. log.debug(f"request.url.path: {request.url.path}")
  236. # Read the original request body
  237. body = await request.body()
  238. # Decode body to string
  239. body_str = body.decode("utf-8")
  240. # Parse string to JSON
  241. data = json.loads(body_str) if body_str else {}
  242. user = get_current_user(
  243. get_http_authorization_cred(request.headers.get("Authorization"))
  244. )
  245. # Remove the citations from the body
  246. return_citations = data.get("citations", False)
  247. if "citations" in data:
  248. del data["citations"]
  249. # Set the task model
  250. task_model_id = data["model"]
  251. if task_model_id not in app.state.MODELS:
  252. raise HTTPException(
  253. status_code=status.HTTP_404_NOT_FOUND,
  254. detail="Model not found",
  255. )
  256. # Check if the user has a custom task model
  257. # If the user has a custom task model, use that model
  258. if app.state.MODELS[task_model_id]["owned_by"] == "ollama":
  259. if (
  260. app.state.config.TASK_MODEL
  261. and app.state.config.TASK_MODEL in app.state.MODELS
  262. ):
  263. task_model_id = app.state.config.TASK_MODEL
  264. else:
  265. if (
  266. app.state.config.TASK_MODEL_EXTERNAL
  267. and app.state.config.TASK_MODEL_EXTERNAL in app.state.MODELS
  268. ):
  269. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  270. prompt = get_last_user_message(data["messages"])
  271. context = ""
  272. # If tool_ids field is present, call the functions
  273. if "tool_ids" in data:
  274. print(data["tool_ids"])
  275. for tool_id in data["tool_ids"]:
  276. print(tool_id)
  277. try:
  278. response = await get_function_call_response(
  279. messages=data["messages"],
  280. tool_id=tool_id,
  281. template=app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  282. task_model_id=task_model_id,
  283. user=user,
  284. )
  285. if response:
  286. context += ("\n" if context != "" else "") + response
  287. except Exception as e:
  288. print(f"Error: {e}")
  289. del data["tool_ids"]
  290. print(f"tool_context: {context}")
  291. # If docs field is present, generate RAG completions
  292. if "docs" in data:
  293. data = {**data}
  294. rag_context, citations = get_rag_context(
  295. docs=data["docs"],
  296. messages=data["messages"],
  297. embedding_function=rag_app.state.EMBEDDING_FUNCTION,
  298. k=rag_app.state.config.TOP_K,
  299. reranking_function=rag_app.state.sentence_transformer_rf,
  300. r=rag_app.state.config.RELEVANCE_THRESHOLD,
  301. hybrid_search=rag_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  302. )
  303. if rag_context:
  304. context += ("\n" if context != "" else "") + rag_context
  305. del data["docs"]
  306. log.debug(f"rag_context: {rag_context}, citations: {citations}")
  307. if context != "":
  308. system_prompt = rag_template(
  309. rag_app.state.config.RAG_TEMPLATE, context, prompt
  310. )
  311. print(system_prompt)
  312. data["messages"] = add_or_update_system_message(
  313. f"\n{system_prompt}", data["messages"]
  314. )
  315. modified_body_bytes = json.dumps(data).encode("utf-8")
  316. # Replace the request body with the modified one
  317. request._body = modified_body_bytes
  318. # Set custom header to ensure content-length matches new body length
  319. request.headers.__dict__["_list"] = [
  320. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  321. *[
  322. (k, v)
  323. for k, v in request.headers.raw
  324. if k.lower() != b"content-length"
  325. ],
  326. ]
  327. response = await call_next(request)
  328. if return_citations:
  329. # Inject the citations into the response
  330. if isinstance(response, StreamingResponse):
  331. # If it's a streaming response, inject it as SSE event or NDJSON line
  332. content_type = response.headers.get("Content-Type")
  333. if "text/event-stream" in content_type:
  334. return StreamingResponse(
  335. self.openai_stream_wrapper(response.body_iterator, citations),
  336. )
  337. if "application/x-ndjson" in content_type:
  338. return StreamingResponse(
  339. self.ollama_stream_wrapper(response.body_iterator, citations),
  340. )
  341. return response
  342. async def _receive(self, body: bytes):
  343. return {"type": "http.request", "body": body, "more_body": False}
  344. async def openai_stream_wrapper(self, original_generator, citations):
  345. yield f"data: {json.dumps({'citations': citations})}\n\n"
  346. async for data in original_generator:
  347. yield data
  348. async def ollama_stream_wrapper(self, original_generator, citations):
  349. yield f"{json.dumps({'citations': citations})}\n"
  350. async for data in original_generator:
  351. yield data
  352. app.add_middleware(ChatCompletionMiddleware)
  353. def filter_pipeline(payload, user):
  354. user = {"id": user.id, "name": user.name, "role": user.role}
  355. model_id = payload["model"]
  356. filters = [
  357. model
  358. for model in app.state.MODELS.values()
  359. if "pipeline" in model
  360. and "type" in model["pipeline"]
  361. and model["pipeline"]["type"] == "filter"
  362. and (
  363. model["pipeline"]["pipelines"] == ["*"]
  364. or any(
  365. model_id == target_model_id
  366. for target_model_id in model["pipeline"]["pipelines"]
  367. )
  368. )
  369. ]
  370. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  371. model = app.state.MODELS[model_id]
  372. if "pipeline" in model:
  373. sorted_filters.append(model)
  374. for filter in sorted_filters:
  375. r = None
  376. try:
  377. urlIdx = filter["urlIdx"]
  378. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  379. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  380. if key != "":
  381. headers = {"Authorization": f"Bearer {key}"}
  382. r = requests.post(
  383. f"{url}/{filter['id']}/filter/inlet",
  384. headers=headers,
  385. json={
  386. "user": user,
  387. "body": payload,
  388. },
  389. )
  390. r.raise_for_status()
  391. payload = r.json()
  392. except Exception as e:
  393. # Handle connection error here
  394. print(f"Connection error: {e}")
  395. if r is not None:
  396. try:
  397. res = r.json()
  398. except:
  399. pass
  400. if "detail" in res:
  401. raise Exception(r.status_code, res["detail"])
  402. else:
  403. pass
  404. if "pipeline" not in app.state.MODELS[model_id]:
  405. if "chat_id" in payload:
  406. del payload["chat_id"]
  407. if "title" in payload:
  408. del payload["title"]
  409. return payload
  410. class PipelineMiddleware(BaseHTTPMiddleware):
  411. async def dispatch(self, request: Request, call_next):
  412. if request.method == "POST" and (
  413. "/ollama/api/chat" in request.url.path
  414. or "/chat/completions" in request.url.path
  415. ):
  416. log.debug(f"request.url.path: {request.url.path}")
  417. # Read the original request body
  418. body = await request.body()
  419. # Decode body to string
  420. body_str = body.decode("utf-8")
  421. # Parse string to JSON
  422. data = json.loads(body_str) if body_str else {}
  423. user = get_current_user(
  424. get_http_authorization_cred(request.headers.get("Authorization"))
  425. )
  426. try:
  427. data = filter_pipeline(data, user)
  428. except Exception as e:
  429. return JSONResponse(
  430. status_code=e.args[0],
  431. content={"detail": e.args[1]},
  432. )
  433. modified_body_bytes = json.dumps(data).encode("utf-8")
  434. # Replace the request body with the modified one
  435. request._body = modified_body_bytes
  436. # Set custom header to ensure content-length matches new body length
  437. request.headers.__dict__["_list"] = [
  438. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  439. *[
  440. (k, v)
  441. for k, v in request.headers.raw
  442. if k.lower() != b"content-length"
  443. ],
  444. ]
  445. response = await call_next(request)
  446. return response
  447. async def _receive(self, body: bytes):
  448. return {"type": "http.request", "body": body, "more_body": False}
  449. app.add_middleware(PipelineMiddleware)
  450. app.add_middleware(
  451. CORSMiddleware,
  452. allow_origins=origins,
  453. allow_credentials=True,
  454. allow_methods=["*"],
  455. allow_headers=["*"],
  456. )
  457. @app.middleware("http")
  458. async def check_url(request: Request, call_next):
  459. if len(app.state.MODELS) == 0:
  460. await get_all_models()
  461. else:
  462. pass
  463. start_time = int(time.time())
  464. response = await call_next(request)
  465. process_time = int(time.time()) - start_time
  466. response.headers["X-Process-Time"] = str(process_time)
  467. return response
  468. @app.middleware("http")
  469. async def update_embedding_function(request: Request, call_next):
  470. response = await call_next(request)
  471. if "/embedding/update" in request.url.path:
  472. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  473. return response
  474. app.mount("/ws", socket_app)
  475. app.mount("/ollama", ollama_app)
  476. app.mount("/openai", openai_app)
  477. app.mount("/images/api/v1", images_app)
  478. app.mount("/audio/api/v1", audio_app)
  479. app.mount("/rag/api/v1", rag_app)
  480. app.mount("/api/v1", webui_app)
  481. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  482. async def get_all_models():
  483. openai_models = []
  484. ollama_models = []
  485. if app.state.config.ENABLE_OPENAI_API:
  486. openai_models = await get_openai_models()
  487. openai_models = openai_models["data"]
  488. if app.state.config.ENABLE_OLLAMA_API:
  489. ollama_models = await get_ollama_models()
  490. ollama_models = [
  491. {
  492. "id": model["model"],
  493. "name": model["name"],
  494. "object": "model",
  495. "created": int(time.time()),
  496. "owned_by": "ollama",
  497. "ollama": model,
  498. }
  499. for model in ollama_models["models"]
  500. ]
  501. models = openai_models + ollama_models
  502. custom_models = Models.get_all_models()
  503. for custom_model in custom_models:
  504. if custom_model.base_model_id == None:
  505. for model in models:
  506. if (
  507. custom_model.id == model["id"]
  508. or custom_model.id == model["id"].split(":")[0]
  509. ):
  510. model["name"] = custom_model.name
  511. model["info"] = custom_model.model_dump()
  512. else:
  513. owned_by = "openai"
  514. for model in models:
  515. if (
  516. custom_model.base_model_id == model["id"]
  517. or custom_model.base_model_id == model["id"].split(":")[0]
  518. ):
  519. owned_by = model["owned_by"]
  520. break
  521. models.append(
  522. {
  523. "id": custom_model.id,
  524. "name": custom_model.name,
  525. "object": "model",
  526. "created": custom_model.created_at,
  527. "owned_by": owned_by,
  528. "info": custom_model.model_dump(),
  529. "preset": True,
  530. }
  531. )
  532. app.state.MODELS = {model["id"]: model for model in models}
  533. webui_app.state.MODELS = app.state.MODELS
  534. return models
  535. @app.get("/api/models")
  536. async def get_models(user=Depends(get_verified_user)):
  537. models = await get_all_models()
  538. # Filter out filter pipelines
  539. models = [
  540. model
  541. for model in models
  542. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  543. ]
  544. if app.state.config.ENABLE_MODEL_FILTER:
  545. if user.role == "user":
  546. models = list(
  547. filter(
  548. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  549. models,
  550. )
  551. )
  552. return {"data": models}
  553. return {"data": models}
  554. @app.get("/api/task/config")
  555. async def get_task_config(user=Depends(get_verified_user)):
  556. return {
  557. "TASK_MODEL": app.state.config.TASK_MODEL,
  558. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  559. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  560. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  561. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  562. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  563. }
  564. class TaskConfigForm(BaseModel):
  565. TASK_MODEL: Optional[str]
  566. TASK_MODEL_EXTERNAL: Optional[str]
  567. TITLE_GENERATION_PROMPT_TEMPLATE: str
  568. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE: str
  569. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD: int
  570. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  571. @app.post("/api/task/config/update")
  572. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  573. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  574. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  575. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  576. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  577. )
  578. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  579. form_data.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  580. )
  581. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  582. form_data.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  583. )
  584. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  585. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  586. )
  587. return {
  588. "TASK_MODEL": app.state.config.TASK_MODEL,
  589. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  590. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  591. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  592. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  593. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  594. }
  595. @app.post("/api/task/title/completions")
  596. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  597. print("generate_title")
  598. model_id = form_data["model"]
  599. if model_id not in app.state.MODELS:
  600. raise HTTPException(
  601. status_code=status.HTTP_404_NOT_FOUND,
  602. detail="Model not found",
  603. )
  604. # Check if the user has a custom task model
  605. # If the user has a custom task model, use that model
  606. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  607. if app.state.config.TASK_MODEL:
  608. task_model_id = app.state.config.TASK_MODEL
  609. if task_model_id in app.state.MODELS:
  610. model_id = task_model_id
  611. else:
  612. if app.state.config.TASK_MODEL_EXTERNAL:
  613. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  614. if task_model_id in app.state.MODELS:
  615. model_id = task_model_id
  616. print(model_id)
  617. model = app.state.MODELS[model_id]
  618. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  619. content = title_generation_template(
  620. template, form_data["prompt"], user.model_dump()
  621. )
  622. payload = {
  623. "model": model_id,
  624. "messages": [{"role": "user", "content": content}],
  625. "stream": False,
  626. "max_tokens": 50,
  627. "chat_id": form_data.get("chat_id", None),
  628. "title": True,
  629. }
  630. print(payload)
  631. try:
  632. payload = filter_pipeline(payload, user)
  633. except Exception as e:
  634. return JSONResponse(
  635. status_code=e.args[0],
  636. content={"detail": e.args[1]},
  637. )
  638. if model["owned_by"] == "ollama":
  639. return await generate_ollama_chat_completion(
  640. OpenAIChatCompletionForm(**payload), user=user
  641. )
  642. else:
  643. return await generate_openai_chat_completion(payload, user=user)
  644. @app.post("/api/task/query/completions")
  645. async def generate_search_query(form_data: dict, user=Depends(get_verified_user)):
  646. print("generate_search_query")
  647. if len(form_data["prompt"]) < app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD:
  648. raise HTTPException(
  649. status_code=status.HTTP_400_BAD_REQUEST,
  650. detail=f"Skip search query generation for short prompts (< {app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD} characters)",
  651. )
  652. model_id = form_data["model"]
  653. if model_id not in app.state.MODELS:
  654. raise HTTPException(
  655. status_code=status.HTTP_404_NOT_FOUND,
  656. detail="Model not found",
  657. )
  658. # Check if the user has a custom task model
  659. # If the user has a custom task model, use that model
  660. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  661. if app.state.config.TASK_MODEL:
  662. task_model_id = app.state.config.TASK_MODEL
  663. if task_model_id in app.state.MODELS:
  664. model_id = task_model_id
  665. else:
  666. if app.state.config.TASK_MODEL_EXTERNAL:
  667. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  668. if task_model_id in app.state.MODELS:
  669. model_id = task_model_id
  670. print(model_id)
  671. model = app.state.MODELS[model_id]
  672. template = app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  673. content = search_query_generation_template(
  674. template, form_data["prompt"], user.model_dump()
  675. )
  676. payload = {
  677. "model": model_id,
  678. "messages": [{"role": "user", "content": content}],
  679. "stream": False,
  680. "max_tokens": 30,
  681. }
  682. print(payload)
  683. try:
  684. payload = filter_pipeline(payload, user)
  685. except Exception as e:
  686. return JSONResponse(
  687. status_code=e.args[0],
  688. content={"detail": e.args[1]},
  689. )
  690. if model["owned_by"] == "ollama":
  691. return await generate_ollama_chat_completion(
  692. OpenAIChatCompletionForm(**payload), user=user
  693. )
  694. else:
  695. return await generate_openai_chat_completion(payload, user=user)
  696. @app.post("/api/task/tools/completions")
  697. async def get_tools_function_calling(form_data: dict, user=Depends(get_verified_user)):
  698. print("get_tools_function_calling")
  699. model_id = form_data["model"]
  700. if model_id not in app.state.MODELS:
  701. raise HTTPException(
  702. status_code=status.HTTP_404_NOT_FOUND,
  703. detail="Model not found",
  704. )
  705. # Check if the user has a custom task model
  706. # If the user has a custom task model, use that model
  707. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  708. if app.state.config.TASK_MODEL:
  709. task_model_id = app.state.config.TASK_MODEL
  710. if task_model_id in app.state.MODELS:
  711. model_id = task_model_id
  712. else:
  713. if app.state.config.TASK_MODEL_EXTERNAL:
  714. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  715. if task_model_id in app.state.MODELS:
  716. model_id = task_model_id
  717. print(model_id)
  718. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  719. try:
  720. context = await get_function_call_response(
  721. form_data["messages"], form_data["tool_id"], template, model_id, user
  722. )
  723. return context
  724. except Exception as e:
  725. return JSONResponse(
  726. status_code=e.args[0],
  727. content={"detail": e.args[1]},
  728. )
  729. @app.post("/api/chat/completions")
  730. async def generate_chat_completions(form_data: dict, user=Depends(get_verified_user)):
  731. model_id = form_data["model"]
  732. if model_id not in app.state.MODELS:
  733. raise HTTPException(
  734. status_code=status.HTTP_404_NOT_FOUND,
  735. detail="Model not found",
  736. )
  737. model = app.state.MODELS[model_id]
  738. print(model)
  739. if model["owned_by"] == "ollama":
  740. return await generate_ollama_chat_completion(
  741. OpenAIChatCompletionForm(**form_data), user=user
  742. )
  743. else:
  744. return await generate_openai_chat_completion(form_data, user=user)
  745. @app.post("/api/chat/completed")
  746. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  747. data = form_data
  748. model_id = data["model"]
  749. filters = [
  750. model
  751. for model in app.state.MODELS.values()
  752. if "pipeline" in model
  753. and "type" in model["pipeline"]
  754. and model["pipeline"]["type"] == "filter"
  755. and (
  756. model["pipeline"]["pipelines"] == ["*"]
  757. or any(
  758. model_id == target_model_id
  759. for target_model_id in model["pipeline"]["pipelines"]
  760. )
  761. )
  762. ]
  763. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  764. print(model_id)
  765. if model_id in app.state.MODELS:
  766. model = app.state.MODELS[model_id]
  767. if "pipeline" in model:
  768. sorted_filters = [model] + sorted_filters
  769. for filter in sorted_filters:
  770. r = None
  771. try:
  772. urlIdx = filter["urlIdx"]
  773. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  774. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  775. if key != "":
  776. headers = {"Authorization": f"Bearer {key}"}
  777. r = requests.post(
  778. f"{url}/{filter['id']}/filter/outlet",
  779. headers=headers,
  780. json={
  781. "user": {"id": user.id, "name": user.name, "role": user.role},
  782. "body": data,
  783. },
  784. )
  785. r.raise_for_status()
  786. data = r.json()
  787. except Exception as e:
  788. # Handle connection error here
  789. print(f"Connection error: {e}")
  790. if r is not None:
  791. try:
  792. res = r.json()
  793. if "detail" in res:
  794. return JSONResponse(
  795. status_code=r.status_code,
  796. content=res,
  797. )
  798. except:
  799. pass
  800. else:
  801. pass
  802. return data
  803. @app.get("/api/pipelines/list")
  804. async def get_pipelines_list(user=Depends(get_admin_user)):
  805. responses = await get_openai_models(raw=True)
  806. print(responses)
  807. urlIdxs = [
  808. idx
  809. for idx, response in enumerate(responses)
  810. if response != None and "pipelines" in response
  811. ]
  812. return {
  813. "data": [
  814. {
  815. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  816. "idx": urlIdx,
  817. }
  818. for urlIdx in urlIdxs
  819. ]
  820. }
  821. @app.post("/api/pipelines/upload")
  822. async def upload_pipeline(
  823. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  824. ):
  825. print("upload_pipeline", urlIdx, file.filename)
  826. # Check if the uploaded file is a python file
  827. if not file.filename.endswith(".py"):
  828. raise HTTPException(
  829. status_code=status.HTTP_400_BAD_REQUEST,
  830. detail="Only Python (.py) files are allowed.",
  831. )
  832. upload_folder = f"{CACHE_DIR}/pipelines"
  833. os.makedirs(upload_folder, exist_ok=True)
  834. file_path = os.path.join(upload_folder, file.filename)
  835. try:
  836. # Save the uploaded file
  837. with open(file_path, "wb") as buffer:
  838. shutil.copyfileobj(file.file, buffer)
  839. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  840. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  841. headers = {"Authorization": f"Bearer {key}"}
  842. with open(file_path, "rb") as f:
  843. files = {"file": f}
  844. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  845. r.raise_for_status()
  846. data = r.json()
  847. return {**data}
  848. except Exception as e:
  849. # Handle connection error here
  850. print(f"Connection error: {e}")
  851. detail = "Pipeline not found"
  852. if r is not None:
  853. try:
  854. res = r.json()
  855. if "detail" in res:
  856. detail = res["detail"]
  857. except:
  858. pass
  859. raise HTTPException(
  860. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  861. detail=detail,
  862. )
  863. finally:
  864. # Ensure the file is deleted after the upload is completed or on failure
  865. if os.path.exists(file_path):
  866. os.remove(file_path)
  867. class AddPipelineForm(BaseModel):
  868. url: str
  869. urlIdx: int
  870. @app.post("/api/pipelines/add")
  871. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  872. r = None
  873. try:
  874. urlIdx = form_data.urlIdx
  875. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  876. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  877. headers = {"Authorization": f"Bearer {key}"}
  878. r = requests.post(
  879. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  880. )
  881. r.raise_for_status()
  882. data = r.json()
  883. return {**data}
  884. except Exception as e:
  885. # Handle connection error here
  886. print(f"Connection error: {e}")
  887. detail = "Pipeline not found"
  888. if r is not None:
  889. try:
  890. res = r.json()
  891. if "detail" in res:
  892. detail = res["detail"]
  893. except:
  894. pass
  895. raise HTTPException(
  896. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  897. detail=detail,
  898. )
  899. class DeletePipelineForm(BaseModel):
  900. id: str
  901. urlIdx: int
  902. @app.delete("/api/pipelines/delete")
  903. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  904. r = None
  905. try:
  906. urlIdx = form_data.urlIdx
  907. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  908. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  909. headers = {"Authorization": f"Bearer {key}"}
  910. r = requests.delete(
  911. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  912. )
  913. r.raise_for_status()
  914. data = r.json()
  915. return {**data}
  916. except Exception as e:
  917. # Handle connection error here
  918. print(f"Connection error: {e}")
  919. detail = "Pipeline not found"
  920. if r is not None:
  921. try:
  922. res = r.json()
  923. if "detail" in res:
  924. detail = res["detail"]
  925. except:
  926. pass
  927. raise HTTPException(
  928. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  929. detail=detail,
  930. )
  931. @app.get("/api/pipelines")
  932. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  933. r = None
  934. try:
  935. urlIdx
  936. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  937. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  938. headers = {"Authorization": f"Bearer {key}"}
  939. r = requests.get(f"{url}/pipelines", headers=headers)
  940. r.raise_for_status()
  941. data = r.json()
  942. return {**data}
  943. except Exception as e:
  944. # Handle connection error here
  945. print(f"Connection error: {e}")
  946. detail = "Pipeline not found"
  947. if r is not None:
  948. try:
  949. res = r.json()
  950. if "detail" in res:
  951. detail = res["detail"]
  952. except:
  953. pass
  954. raise HTTPException(
  955. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  956. detail=detail,
  957. )
  958. @app.get("/api/pipelines/{pipeline_id}/valves")
  959. async def get_pipeline_valves(
  960. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  961. ):
  962. models = await get_all_models()
  963. r = None
  964. try:
  965. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  966. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  967. headers = {"Authorization": f"Bearer {key}"}
  968. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  969. r.raise_for_status()
  970. data = r.json()
  971. return {**data}
  972. except Exception as e:
  973. # Handle connection error here
  974. print(f"Connection error: {e}")
  975. detail = "Pipeline not found"
  976. if r is not None:
  977. try:
  978. res = r.json()
  979. if "detail" in res:
  980. detail = res["detail"]
  981. except:
  982. pass
  983. raise HTTPException(
  984. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  985. detail=detail,
  986. )
  987. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  988. async def get_pipeline_valves_spec(
  989. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  990. ):
  991. models = await get_all_models()
  992. r = None
  993. try:
  994. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  995. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  996. headers = {"Authorization": f"Bearer {key}"}
  997. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  998. r.raise_for_status()
  999. data = r.json()
  1000. return {**data}
  1001. except Exception as e:
  1002. # Handle connection error here
  1003. print(f"Connection error: {e}")
  1004. detail = "Pipeline not found"
  1005. if r is not None:
  1006. try:
  1007. res = r.json()
  1008. if "detail" in res:
  1009. detail = res["detail"]
  1010. except:
  1011. pass
  1012. raise HTTPException(
  1013. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1014. detail=detail,
  1015. )
  1016. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1017. async def update_pipeline_valves(
  1018. urlIdx: Optional[int],
  1019. pipeline_id: str,
  1020. form_data: dict,
  1021. user=Depends(get_admin_user),
  1022. ):
  1023. models = await get_all_models()
  1024. r = None
  1025. try:
  1026. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1027. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1028. headers = {"Authorization": f"Bearer {key}"}
  1029. r = requests.post(
  1030. f"{url}/{pipeline_id}/valves/update",
  1031. headers=headers,
  1032. json={**form_data},
  1033. )
  1034. r.raise_for_status()
  1035. data = r.json()
  1036. return {**data}
  1037. except Exception as e:
  1038. # Handle connection error here
  1039. print(f"Connection error: {e}")
  1040. detail = "Pipeline not found"
  1041. if r is not None:
  1042. try:
  1043. res = r.json()
  1044. if "detail" in res:
  1045. detail = res["detail"]
  1046. except:
  1047. pass
  1048. raise HTTPException(
  1049. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1050. detail=detail,
  1051. )
  1052. @app.get("/api/config")
  1053. async def get_app_config():
  1054. # Checking and Handling the Absence of 'ui' in CONFIG_DATA
  1055. default_locale = "en-US"
  1056. if "ui" in CONFIG_DATA:
  1057. default_locale = CONFIG_DATA["ui"].get("default_locale", "en-US")
  1058. # The Rest of the Function Now Uses the Variables Defined Above
  1059. return {
  1060. "status": True,
  1061. "name": WEBUI_NAME,
  1062. "version": VERSION,
  1063. "default_locale": default_locale,
  1064. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1065. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1066. "features": {
  1067. "auth": WEBUI_AUTH,
  1068. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1069. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1070. "enable_web_search": rag_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1071. "enable_image_generation": images_app.state.config.ENABLED,
  1072. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1073. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1074. },
  1075. "audio": {
  1076. "tts": {
  1077. "engine": audio_app.state.config.TTS_ENGINE,
  1078. "voice": audio_app.state.config.TTS_VOICE,
  1079. },
  1080. "stt": {
  1081. "engine": audio_app.state.config.STT_ENGINE,
  1082. },
  1083. },
  1084. }
  1085. @app.get("/api/config/model/filter")
  1086. async def get_model_filter_config(user=Depends(get_admin_user)):
  1087. return {
  1088. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1089. "models": app.state.config.MODEL_FILTER_LIST,
  1090. }
  1091. class ModelFilterConfigForm(BaseModel):
  1092. enabled: bool
  1093. models: List[str]
  1094. @app.post("/api/config/model/filter")
  1095. async def update_model_filter_config(
  1096. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  1097. ):
  1098. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  1099. app.state.config.MODEL_FILTER_LIST = form_data.models
  1100. return {
  1101. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1102. "models": app.state.config.MODEL_FILTER_LIST,
  1103. }
  1104. @app.get("/api/webhook")
  1105. async def get_webhook_url(user=Depends(get_admin_user)):
  1106. return {
  1107. "url": app.state.config.WEBHOOK_URL,
  1108. }
  1109. class UrlForm(BaseModel):
  1110. url: str
  1111. @app.post("/api/webhook")
  1112. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1113. app.state.config.WEBHOOK_URL = form_data.url
  1114. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1115. return {"url": app.state.config.WEBHOOK_URL}
  1116. @app.get("/api/version")
  1117. async def get_app_config():
  1118. return {
  1119. "version": VERSION,
  1120. }
  1121. @app.get("/api/changelog")
  1122. async def get_app_changelog():
  1123. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1124. @app.get("/api/version/updates")
  1125. async def get_app_latest_release_version():
  1126. try:
  1127. async with aiohttp.ClientSession(trust_env=True) as session:
  1128. async with session.get(
  1129. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1130. ) as response:
  1131. response.raise_for_status()
  1132. data = await response.json()
  1133. latest_version = data["tag_name"]
  1134. return {"current": VERSION, "latest": latest_version[1:]}
  1135. except aiohttp.ClientError as e:
  1136. raise HTTPException(
  1137. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  1138. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  1139. )
  1140. @app.get("/manifest.json")
  1141. async def get_manifest_json():
  1142. return {
  1143. "name": WEBUI_NAME,
  1144. "short_name": WEBUI_NAME,
  1145. "start_url": "/",
  1146. "display": "standalone",
  1147. "background_color": "#343541",
  1148. "theme_color": "#343541",
  1149. "orientation": "portrait-primary",
  1150. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  1151. }
  1152. @app.get("/opensearch.xml")
  1153. async def get_opensearch_xml():
  1154. xml_content = rf"""
  1155. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1156. <ShortName>{WEBUI_NAME}</ShortName>
  1157. <Description>Search {WEBUI_NAME}</Description>
  1158. <InputEncoding>UTF-8</InputEncoding>
  1159. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/favicon.png</Image>
  1160. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1161. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1162. </OpenSearchDescription>
  1163. """
  1164. return Response(content=xml_content, media_type="application/xml")
  1165. @app.get("/health")
  1166. async def healthcheck():
  1167. return {"status": True}
  1168. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  1169. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  1170. if os.path.exists(FRONTEND_BUILD_DIR):
  1171. mimetypes.add_type("text/javascript", ".js")
  1172. app.mount(
  1173. "/",
  1174. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1175. name="spa-static-files",
  1176. )
  1177. else:
  1178. log.warning(
  1179. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1180. )