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