main.py 29 KB

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