main.py 44 KB

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