main.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  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. from fastapi import FastAPI, Request, Depends, status
  13. from fastapi.staticfiles import StaticFiles
  14. from fastapi.responses import JSONResponse
  15. from fastapi import HTTPException
  16. from fastapi.middleware.wsgi import WSGIMiddleware
  17. from fastapi.middleware.cors import CORSMiddleware
  18. from starlette.exceptions import HTTPException as StarletteHTTPException
  19. from starlette.middleware.base import BaseHTTPMiddleware
  20. from starlette.responses import StreamingResponse, Response
  21. from apps.ollama.main import app as ollama_app, get_all_models as get_ollama_models
  22. from apps.openai.main import app as openai_app, get_all_models as get_openai_models
  23. from apps.audio.main import app as audio_app
  24. from apps.images.main import app as images_app
  25. from apps.rag.main import app as rag_app
  26. from apps.webui.main import app as webui_app
  27. import asyncio
  28. from pydantic import BaseModel
  29. from typing import List, Optional
  30. from apps.webui.models.models import Models, ModelModel
  31. from utils.utils import (
  32. get_admin_user,
  33. get_verified_user,
  34. get_current_user,
  35. get_http_authorization_cred,
  36. )
  37. from apps.rag.utils import rag_messages
  38. from config import (
  39. CONFIG_DATA,
  40. WEBUI_NAME,
  41. WEBUI_URL,
  42. WEBUI_AUTH,
  43. ENV,
  44. VERSION,
  45. CHANGELOG,
  46. FRONTEND_BUILD_DIR,
  47. CACHE_DIR,
  48. STATIC_DIR,
  49. ENABLE_OPENAI_API,
  50. ENABLE_OLLAMA_API,
  51. ENABLE_MODEL_FILTER,
  52. MODEL_FILTER_LIST,
  53. GLOBAL_LOG_LEVEL,
  54. SRC_LOG_LEVELS,
  55. WEBHOOK_URL,
  56. ENABLE_ADMIN_EXPORT,
  57. RAG_WEB_SEARCH_ENABLED,
  58. AppConfig,
  59. WEBUI_BUILD_HASH,
  60. )
  61. from constants import ERROR_MESSAGES
  62. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  63. log = logging.getLogger(__name__)
  64. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  65. class SPAStaticFiles(StaticFiles):
  66. async def get_response(self, path: str, scope):
  67. try:
  68. return await super().get_response(path, scope)
  69. except (HTTPException, StarletteHTTPException) as ex:
  70. if ex.status_code == 404:
  71. return await super().get_response("index.html", scope)
  72. else:
  73. raise ex
  74. print(
  75. rf"""
  76. ___ __ __ _ _ _ ___
  77. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  78. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  79. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  80. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  81. |_|
  82. v{VERSION} - building the best open-source AI user interface.
  83. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  84. https://github.com/open-webui/open-webui
  85. """
  86. )
  87. @asynccontextmanager
  88. async def lifespan(app: FastAPI):
  89. yield
  90. app = FastAPI(
  91. docs_url="/docs" if ENV == "dev" else None, redoc_url=None, lifespan=lifespan
  92. )
  93. app.state.config = AppConfig()
  94. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  95. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  96. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  97. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  98. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  99. app.state.MODELS = {}
  100. origins = ["*"]
  101. # Custom middleware to add security headers
  102. # class SecurityHeadersMiddleware(BaseHTTPMiddleware):
  103. # async def dispatch(self, request: Request, call_next):
  104. # response: Response = await call_next(request)
  105. # response.headers["Cross-Origin-Opener-Policy"] = "same-origin"
  106. # response.headers["Cross-Origin-Embedder-Policy"] = "require-corp"
  107. # return response
  108. # app.add_middleware(SecurityHeadersMiddleware)
  109. class RAGMiddleware(BaseHTTPMiddleware):
  110. async def dispatch(self, request: Request, call_next):
  111. return_citations = False
  112. if request.method == "POST" and (
  113. "/ollama/api/chat" in request.url.path
  114. or "/chat/completions" in request.url.path
  115. ):
  116. log.debug(f"request.url.path: {request.url.path}")
  117. # Read the original request body
  118. body = await request.body()
  119. # Decode body to string
  120. body_str = body.decode("utf-8")
  121. # Parse string to JSON
  122. data = json.loads(body_str) if body_str else {}
  123. return_citations = data.get("citations", False)
  124. if "citations" in data:
  125. del data["citations"]
  126. # Example: Add a new key-value pair or modify existing ones
  127. # data["modified"] = True # Example modification
  128. if "docs" in data:
  129. data = {**data}
  130. data["messages"], citations = rag_messages(
  131. docs=data["docs"],
  132. messages=data["messages"],
  133. template=rag_app.state.config.RAG_TEMPLATE,
  134. embedding_function=rag_app.state.EMBEDDING_FUNCTION,
  135. k=rag_app.state.config.TOP_K,
  136. reranking_function=rag_app.state.sentence_transformer_rf,
  137. r=rag_app.state.config.RELEVANCE_THRESHOLD,
  138. hybrid_search=rag_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  139. )
  140. del data["docs"]
  141. log.debug(
  142. f"data['messages']: {data['messages']}, citations: {citations}"
  143. )
  144. modified_body_bytes = json.dumps(data).encode("utf-8")
  145. # Replace the request body with the modified one
  146. request._body = modified_body_bytes
  147. # Set custom header to ensure content-length matches new body length
  148. request.headers.__dict__["_list"] = [
  149. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  150. *[
  151. (k, v)
  152. for k, v in request.headers.raw
  153. if k.lower() != b"content-length"
  154. ],
  155. ]
  156. response = await call_next(request)
  157. if return_citations:
  158. # Inject the citations into the response
  159. if isinstance(response, StreamingResponse):
  160. # If it's a streaming response, inject it as SSE event or NDJSON line
  161. content_type = response.headers.get("Content-Type")
  162. if "text/event-stream" in content_type:
  163. return StreamingResponse(
  164. self.openai_stream_wrapper(response.body_iterator, citations),
  165. )
  166. if "application/x-ndjson" in content_type:
  167. return StreamingResponse(
  168. self.ollama_stream_wrapper(response.body_iterator, citations),
  169. )
  170. return response
  171. async def _receive(self, body: bytes):
  172. return {"type": "http.request", "body": body, "more_body": False}
  173. async def openai_stream_wrapper(self, original_generator, citations):
  174. yield f"data: {json.dumps({'citations': citations})}\n\n"
  175. async for data in original_generator:
  176. yield data
  177. async def ollama_stream_wrapper(self, original_generator, citations):
  178. yield f"{json.dumps({'citations': citations})}\n"
  179. async for data in original_generator:
  180. yield data
  181. app.add_middleware(RAGMiddleware)
  182. class PipelineMiddleware(BaseHTTPMiddleware):
  183. async def dispatch(self, request: Request, call_next):
  184. if request.method == "POST" and (
  185. "/ollama/api/chat" in request.url.path
  186. or "/chat/completions" in request.url.path
  187. ):
  188. log.debug(f"request.url.path: {request.url.path}")
  189. # Read the original request body
  190. body = await request.body()
  191. # Decode body to string
  192. body_str = body.decode("utf-8")
  193. # Parse string to JSON
  194. data = json.loads(body_str) if body_str else {}
  195. model_id = data["model"]
  196. filters = [
  197. model
  198. for model in app.state.MODELS.values()
  199. if "pipeline" in model
  200. and "type" in model["pipeline"]
  201. and model["pipeline"]["type"] == "filter"
  202. and (
  203. model["pipeline"]["pipelines"] == ["*"]
  204. or any(
  205. model_id == target_model_id
  206. for target_model_id in model["pipeline"]["pipelines"]
  207. )
  208. )
  209. ]
  210. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  211. user = None
  212. if len(sorted_filters) > 0:
  213. try:
  214. user = get_current_user(
  215. get_http_authorization_cred(
  216. request.headers.get("Authorization")
  217. )
  218. )
  219. user = {"id": user.id, "name": user.name, "role": user.role}
  220. except:
  221. pass
  222. model = app.state.MODELS[model_id]
  223. if "pipeline" in model:
  224. sorted_filters.append(model)
  225. for filter in sorted_filters:
  226. r = None
  227. try:
  228. urlIdx = filter["urlIdx"]
  229. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  230. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  231. if key != "":
  232. headers = {"Authorization": f"Bearer {key}"}
  233. r = requests.post(
  234. f"{url}/{filter['id']}/filter/inlet",
  235. headers=headers,
  236. json={
  237. "user": user,
  238. "body": data,
  239. },
  240. )
  241. r.raise_for_status()
  242. data = r.json()
  243. except Exception as e:
  244. # Handle connection error here
  245. print(f"Connection error: {e}")
  246. if r is not None:
  247. try:
  248. res = r.json()
  249. if "detail" in res:
  250. return JSONResponse(
  251. status_code=r.status_code,
  252. content=res,
  253. )
  254. except:
  255. pass
  256. else:
  257. pass
  258. if "chat_id" in data:
  259. del data["chat_id"]
  260. modified_body_bytes = json.dumps(data).encode("utf-8")
  261. # Replace the request body with the modified one
  262. request._body = modified_body_bytes
  263. # Set custom header to ensure content-length matches new body length
  264. request.headers.__dict__["_list"] = [
  265. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  266. *[
  267. (k, v)
  268. for k, v in request.headers.raw
  269. if k.lower() != b"content-length"
  270. ],
  271. ]
  272. response = await call_next(request)
  273. return response
  274. async def _receive(self, body: bytes):
  275. return {"type": "http.request", "body": body, "more_body": False}
  276. app.add_middleware(PipelineMiddleware)
  277. app.add_middleware(
  278. CORSMiddleware,
  279. allow_origins=origins,
  280. allow_credentials=True,
  281. allow_methods=["*"],
  282. allow_headers=["*"],
  283. )
  284. @app.middleware("http")
  285. async def check_url(request: Request, call_next):
  286. if len(app.state.MODELS) == 0:
  287. await get_all_models()
  288. else:
  289. pass
  290. start_time = int(time.time())
  291. response = await call_next(request)
  292. process_time = int(time.time()) - start_time
  293. response.headers["X-Process-Time"] = str(process_time)
  294. return response
  295. @app.middleware("http")
  296. async def update_embedding_function(request: Request, call_next):
  297. response = await call_next(request)
  298. if "/embedding/update" in request.url.path:
  299. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  300. return response
  301. app.mount("/ollama", ollama_app)
  302. app.mount("/openai", openai_app)
  303. app.mount("/images/api/v1", images_app)
  304. app.mount("/audio/api/v1", audio_app)
  305. app.mount("/rag/api/v1", rag_app)
  306. app.mount("/api/v1", webui_app)
  307. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  308. async def get_all_models():
  309. openai_models = []
  310. ollama_models = []
  311. if app.state.config.ENABLE_OPENAI_API:
  312. openai_models = await get_openai_models()
  313. openai_models = openai_models["data"]
  314. if app.state.config.ENABLE_OLLAMA_API:
  315. ollama_models = await get_ollama_models()
  316. ollama_models = [
  317. {
  318. "id": model["model"],
  319. "name": model["name"],
  320. "object": "model",
  321. "created": int(time.time()),
  322. "owned_by": "ollama",
  323. "ollama": model,
  324. }
  325. for model in ollama_models["models"]
  326. ]
  327. models = openai_models + ollama_models
  328. custom_models = Models.get_all_models()
  329. for custom_model in custom_models:
  330. if custom_model.base_model_id == None:
  331. for model in models:
  332. if (
  333. custom_model.id == model["id"]
  334. or custom_model.id == model["id"].split(":")[0]
  335. ):
  336. model["name"] = custom_model.name
  337. model["info"] = custom_model.model_dump()
  338. else:
  339. owned_by = "openai"
  340. for model in models:
  341. if (
  342. custom_model.base_model_id == model["id"]
  343. or custom_model.base_model_id == model["id"].split(":")[0]
  344. ):
  345. owned_by = model["owned_by"]
  346. break
  347. models.append(
  348. {
  349. "id": custom_model.id,
  350. "name": custom_model.name,
  351. "object": "model",
  352. "created": custom_model.created_at,
  353. "owned_by": owned_by,
  354. "info": custom_model.model_dump(),
  355. "preset": True,
  356. }
  357. )
  358. app.state.MODELS = {model["id"]: model for model in models}
  359. webui_app.state.MODELS = app.state.MODELS
  360. return models
  361. @app.get("/api/models")
  362. async def get_models(user=Depends(get_verified_user)):
  363. models = await get_all_models()
  364. # Filter out filter pipelines
  365. models = [
  366. model
  367. for model in models
  368. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  369. ]
  370. if app.state.config.ENABLE_MODEL_FILTER:
  371. if user.role == "user":
  372. models = list(
  373. filter(
  374. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  375. models,
  376. )
  377. )
  378. return {"data": models}
  379. return {"data": models}
  380. @app.post("/api/chat/completed")
  381. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  382. data = form_data
  383. model_id = data["model"]
  384. filters = [
  385. model
  386. for model in app.state.MODELS.values()
  387. if "pipeline" in model
  388. and "type" in model["pipeline"]
  389. and model["pipeline"]["type"] == "filter"
  390. and (
  391. model["pipeline"]["pipelines"] == ["*"]
  392. or any(
  393. model_id == target_model_id
  394. for target_model_id in model["pipeline"]["pipelines"]
  395. )
  396. )
  397. ]
  398. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  399. model = app.state.MODELS[model_id]
  400. if "pipeline" in model:
  401. sorted_filters = [model] + sorted_filters
  402. for filter in sorted_filters:
  403. r = None
  404. try:
  405. urlIdx = filter["urlIdx"]
  406. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  407. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  408. if key != "":
  409. headers = {"Authorization": f"Bearer {key}"}
  410. r = requests.post(
  411. f"{url}/{filter['id']}/filter/outlet",
  412. headers=headers,
  413. json={
  414. "user": {"id": user.id, "name": user.name, "role": user.role},
  415. "body": data,
  416. },
  417. )
  418. r.raise_for_status()
  419. data = r.json()
  420. except Exception as e:
  421. # Handle connection error here
  422. print(f"Connection error: {e}")
  423. if r is not None:
  424. try:
  425. res = r.json()
  426. if "detail" in res:
  427. return JSONResponse(
  428. status_code=r.status_code,
  429. content=res,
  430. )
  431. except:
  432. pass
  433. else:
  434. pass
  435. return data
  436. @app.get("/api/pipelines/list")
  437. async def get_pipelines_list(user=Depends(get_admin_user)):
  438. responses = await get_openai_models(raw=True)
  439. print(responses)
  440. urlIdxs = [idx for idx, response in enumerate(responses) if "pipelines" in response]
  441. return {
  442. "data": [
  443. {
  444. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  445. "idx": urlIdx,
  446. }
  447. for urlIdx in urlIdxs
  448. ]
  449. }
  450. class AddPipelineForm(BaseModel):
  451. url: str
  452. urlIdx: int
  453. @app.post("/api/pipelines/add")
  454. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  455. r = None
  456. try:
  457. urlIdx = form_data.urlIdx
  458. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  459. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  460. headers = {"Authorization": f"Bearer {key}"}
  461. r = requests.post(
  462. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  463. )
  464. r.raise_for_status()
  465. data = r.json()
  466. return {**data}
  467. except Exception as e:
  468. # Handle connection error here
  469. print(f"Connection error: {e}")
  470. detail = "Pipeline not found"
  471. if r is not None:
  472. try:
  473. res = r.json()
  474. if "detail" in res:
  475. detail = res["detail"]
  476. except:
  477. pass
  478. raise HTTPException(
  479. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  480. detail=detail,
  481. )
  482. class DeletePipelineForm(BaseModel):
  483. id: str
  484. urlIdx: int
  485. @app.delete("/api/pipelines/delete")
  486. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  487. r = None
  488. try:
  489. urlIdx = form_data.urlIdx
  490. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  491. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  492. headers = {"Authorization": f"Bearer {key}"}
  493. r = requests.delete(
  494. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  495. )
  496. r.raise_for_status()
  497. data = r.json()
  498. return {**data}
  499. except Exception as e:
  500. # Handle connection error here
  501. print(f"Connection error: {e}")
  502. detail = "Pipeline not found"
  503. if r is not None:
  504. try:
  505. res = r.json()
  506. if "detail" in res:
  507. detail = res["detail"]
  508. except:
  509. pass
  510. raise HTTPException(
  511. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  512. detail=detail,
  513. )
  514. @app.get("/api/pipelines")
  515. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  516. r = None
  517. try:
  518. urlIdx
  519. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  520. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  521. headers = {"Authorization": f"Bearer {key}"}
  522. r = requests.get(f"{url}/pipelines", headers=headers)
  523. r.raise_for_status()
  524. data = r.json()
  525. return {**data}
  526. except Exception as e:
  527. # Handle connection error here
  528. print(f"Connection error: {e}")
  529. detail = "Pipeline not found"
  530. if r is not None:
  531. try:
  532. res = r.json()
  533. if "detail" in res:
  534. detail = res["detail"]
  535. except:
  536. pass
  537. raise HTTPException(
  538. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  539. detail=detail,
  540. )
  541. @app.get("/api/pipelines/{pipeline_id}/valves")
  542. async def get_pipeline_valves(
  543. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  544. ):
  545. models = await get_all_models()
  546. r = None
  547. try:
  548. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  549. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  550. headers = {"Authorization": f"Bearer {key}"}
  551. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  552. r.raise_for_status()
  553. data = r.json()
  554. return {**data}
  555. except Exception as e:
  556. # Handle connection error here
  557. print(f"Connection error: {e}")
  558. detail = "Pipeline not found"
  559. if r is not None:
  560. try:
  561. res = r.json()
  562. if "detail" in res:
  563. detail = res["detail"]
  564. except:
  565. pass
  566. raise HTTPException(
  567. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  568. detail=detail,
  569. )
  570. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  571. async def get_pipeline_valves_spec(
  572. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  573. ):
  574. models = await get_all_models()
  575. r = None
  576. try:
  577. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  578. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  579. headers = {"Authorization": f"Bearer {key}"}
  580. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  581. r.raise_for_status()
  582. data = r.json()
  583. return {**data}
  584. except Exception as e:
  585. # Handle connection error here
  586. print(f"Connection error: {e}")
  587. detail = "Pipeline not found"
  588. if r is not None:
  589. try:
  590. res = r.json()
  591. if "detail" in res:
  592. detail = res["detail"]
  593. except:
  594. pass
  595. raise HTTPException(
  596. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  597. detail=detail,
  598. )
  599. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  600. async def update_pipeline_valves(
  601. urlIdx: Optional[int],
  602. pipeline_id: str,
  603. form_data: dict,
  604. user=Depends(get_admin_user),
  605. ):
  606. models = await get_all_models()
  607. r = None
  608. try:
  609. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  610. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  611. headers = {"Authorization": f"Bearer {key}"}
  612. r = requests.post(
  613. f"{url}/{pipeline_id}/valves/update",
  614. headers=headers,
  615. json={**form_data},
  616. )
  617. r.raise_for_status()
  618. data = r.json()
  619. return {**data}
  620. except Exception as e:
  621. # Handle connection error here
  622. print(f"Connection error: {e}")
  623. detail = "Pipeline not found"
  624. if r is not None:
  625. try:
  626. res = r.json()
  627. if "detail" in res:
  628. detail = res["detail"]
  629. except:
  630. pass
  631. raise HTTPException(
  632. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  633. detail=detail,
  634. )
  635. @app.get("/api/config")
  636. async def get_app_config():
  637. # Checking and Handling the Absence of 'ui' in CONFIG_DATA
  638. default_locale = "en-US"
  639. if "ui" in CONFIG_DATA:
  640. default_locale = CONFIG_DATA["ui"].get("default_locale", "en-US")
  641. # The Rest of the Function Now Uses the Variables Defined Above
  642. return {
  643. "status": True,
  644. "name": WEBUI_NAME,
  645. "version": VERSION,
  646. "default_locale": default_locale,
  647. "default_models": webui_app.state.config.DEFAULT_MODELS,
  648. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  649. "features": {
  650. "auth": WEBUI_AUTH,
  651. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  652. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  653. "enable_web_search": RAG_WEB_SEARCH_ENABLED,
  654. "enable_image_generation": images_app.state.config.ENABLED,
  655. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  656. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  657. },
  658. }
  659. @app.get("/api/config/model/filter")
  660. async def get_model_filter_config(user=Depends(get_admin_user)):
  661. return {
  662. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  663. "models": app.state.config.MODEL_FILTER_LIST,
  664. }
  665. class ModelFilterConfigForm(BaseModel):
  666. enabled: bool
  667. models: List[str]
  668. @app.post("/api/config/model/filter")
  669. async def update_model_filter_config(
  670. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  671. ):
  672. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  673. app.state.config.MODEL_FILTER_LIST = form_data.models
  674. return {
  675. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  676. "models": app.state.config.MODEL_FILTER_LIST,
  677. }
  678. @app.get("/api/webhook")
  679. async def get_webhook_url(user=Depends(get_admin_user)):
  680. return {
  681. "url": app.state.config.WEBHOOK_URL,
  682. }
  683. class UrlForm(BaseModel):
  684. url: str
  685. @app.post("/api/webhook")
  686. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  687. app.state.config.WEBHOOK_URL = form_data.url
  688. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  689. return {
  690. "url": app.state.config.WEBHOOK_URL,
  691. }
  692. @app.get("/api/community_sharing", response_model=bool)
  693. async def get_community_sharing_status(request: Request, user=Depends(get_admin_user)):
  694. return webui_app.state.config.ENABLE_COMMUNITY_SHARING
  695. @app.get("/api/community_sharing/toggle", response_model=bool)
  696. async def toggle_community_sharing(request: Request, user=Depends(get_admin_user)):
  697. webui_app.state.config.ENABLE_COMMUNITY_SHARING = (
  698. not webui_app.state.config.ENABLE_COMMUNITY_SHARING
  699. )
  700. return webui_app.state.config.ENABLE_COMMUNITY_SHARING
  701. @app.get("/api/version")
  702. async def get_app_config():
  703. return {
  704. "version": VERSION,
  705. }
  706. @app.get("/api/changelog")
  707. async def get_app_changelog():
  708. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  709. @app.get("/api/version/updates")
  710. async def get_app_latest_release_version():
  711. try:
  712. async with aiohttp.ClientSession() as session:
  713. async with session.get(
  714. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  715. ) as response:
  716. response.raise_for_status()
  717. data = await response.json()
  718. latest_version = data["tag_name"]
  719. return {"current": VERSION, "latest": latest_version[1:]}
  720. except aiohttp.ClientError as e:
  721. raise HTTPException(
  722. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  723. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  724. )
  725. @app.get("/manifest.json")
  726. async def get_manifest_json():
  727. return {
  728. "name": WEBUI_NAME,
  729. "short_name": WEBUI_NAME,
  730. "start_url": "/",
  731. "display": "standalone",
  732. "background_color": "#343541",
  733. "theme_color": "#343541",
  734. "orientation": "portrait-primary",
  735. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  736. }
  737. @app.get("/opensearch.xml")
  738. async def get_opensearch_xml():
  739. xml_content = rf"""
  740. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  741. <ShortName>{WEBUI_NAME}</ShortName>
  742. <Description>Search {WEBUI_NAME}</Description>
  743. <InputEncoding>UTF-8</InputEncoding>
  744. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/favicon.png</Image>
  745. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  746. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  747. </OpenSearchDescription>
  748. """
  749. return Response(content=xml_content, media_type="application/xml")
  750. @app.get("/health")
  751. async def healthcheck():
  752. return {"status": True}
  753. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  754. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  755. if os.path.exists(FRONTEND_BUILD_DIR):
  756. mimetypes.add_type("text/javascript", ".js")
  757. app.mount(
  758. "/",
  759. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  760. name="spa-static-files",
  761. )
  762. else:
  763. log.warning(
  764. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  765. )