main.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  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 "pipeline" not in app.state.MODELS[model_id]:
  259. if "chat_id" in data:
  260. del data["chat_id"]
  261. if "title" in data:
  262. del data["title"]
  263. modified_body_bytes = json.dumps(data).encode("utf-8")
  264. # Replace the request body with the modified one
  265. request._body = modified_body_bytes
  266. # Set custom header to ensure content-length matches new body length
  267. request.headers.__dict__["_list"] = [
  268. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  269. *[
  270. (k, v)
  271. for k, v in request.headers.raw
  272. if k.lower() != b"content-length"
  273. ],
  274. ]
  275. response = await call_next(request)
  276. return response
  277. async def _receive(self, body: bytes):
  278. return {"type": "http.request", "body": body, "more_body": False}
  279. app.add_middleware(PipelineMiddleware)
  280. app.add_middleware(
  281. CORSMiddleware,
  282. allow_origins=origins,
  283. allow_credentials=True,
  284. allow_methods=["*"],
  285. allow_headers=["*"],
  286. )
  287. @app.middleware("http")
  288. async def check_url(request: Request, call_next):
  289. if len(app.state.MODELS) == 0:
  290. await get_all_models()
  291. else:
  292. pass
  293. start_time = int(time.time())
  294. response = await call_next(request)
  295. process_time = int(time.time()) - start_time
  296. response.headers["X-Process-Time"] = str(process_time)
  297. return response
  298. @app.middleware("http")
  299. async def update_embedding_function(request: Request, call_next):
  300. response = await call_next(request)
  301. if "/embedding/update" in request.url.path:
  302. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  303. return response
  304. app.mount("/ollama", ollama_app)
  305. app.mount("/openai", openai_app)
  306. app.mount("/images/api/v1", images_app)
  307. app.mount("/audio/api/v1", audio_app)
  308. app.mount("/rag/api/v1", rag_app)
  309. app.mount("/api/v1", webui_app)
  310. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  311. async def get_all_models():
  312. openai_models = []
  313. ollama_models = []
  314. if app.state.config.ENABLE_OPENAI_API:
  315. openai_models = await get_openai_models()
  316. openai_models = openai_models["data"]
  317. if app.state.config.ENABLE_OLLAMA_API:
  318. ollama_models = await get_ollama_models()
  319. ollama_models = [
  320. {
  321. "id": model["model"],
  322. "name": model["name"],
  323. "object": "model",
  324. "created": int(time.time()),
  325. "owned_by": "ollama",
  326. "ollama": model,
  327. }
  328. for model in ollama_models["models"]
  329. ]
  330. models = openai_models + ollama_models
  331. custom_models = Models.get_all_models()
  332. for custom_model in custom_models:
  333. if custom_model.base_model_id == None:
  334. for model in models:
  335. if (
  336. custom_model.id == model["id"]
  337. or custom_model.id == model["id"].split(":")[0]
  338. ):
  339. model["name"] = custom_model.name
  340. model["info"] = custom_model.model_dump()
  341. else:
  342. owned_by = "openai"
  343. for model in models:
  344. if (
  345. custom_model.base_model_id == model["id"]
  346. or custom_model.base_model_id == model["id"].split(":")[0]
  347. ):
  348. owned_by = model["owned_by"]
  349. break
  350. models.append(
  351. {
  352. "id": custom_model.id,
  353. "name": custom_model.name,
  354. "object": "model",
  355. "created": custom_model.created_at,
  356. "owned_by": owned_by,
  357. "info": custom_model.model_dump(),
  358. "preset": True,
  359. }
  360. )
  361. app.state.MODELS = {model["id"]: model for model in models}
  362. webui_app.state.MODELS = app.state.MODELS
  363. return models
  364. @app.get("/api/models")
  365. async def get_models(user=Depends(get_verified_user)):
  366. models = await get_all_models()
  367. # Filter out filter pipelines
  368. models = [
  369. model
  370. for model in models
  371. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  372. ]
  373. if app.state.config.ENABLE_MODEL_FILTER:
  374. if user.role == "user":
  375. models = list(
  376. filter(
  377. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  378. models,
  379. )
  380. )
  381. return {"data": models}
  382. return {"data": models}
  383. @app.post("/api/chat/completed")
  384. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  385. data = form_data
  386. model_id = data["model"]
  387. filters = [
  388. model
  389. for model in app.state.MODELS.values()
  390. if "pipeline" in model
  391. and "type" in model["pipeline"]
  392. and model["pipeline"]["type"] == "filter"
  393. and (
  394. model["pipeline"]["pipelines"] == ["*"]
  395. or any(
  396. model_id == target_model_id
  397. for target_model_id in model["pipeline"]["pipelines"]
  398. )
  399. )
  400. ]
  401. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  402. model = app.state.MODELS[model_id]
  403. if "pipeline" in model:
  404. sorted_filters = [model] + sorted_filters
  405. for filter in sorted_filters:
  406. r = None
  407. try:
  408. urlIdx = filter["urlIdx"]
  409. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  410. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  411. if key != "":
  412. headers = {"Authorization": f"Bearer {key}"}
  413. r = requests.post(
  414. f"{url}/{filter['id']}/filter/outlet",
  415. headers=headers,
  416. json={
  417. "user": {"id": user.id, "name": user.name, "role": user.role},
  418. "body": data,
  419. },
  420. )
  421. r.raise_for_status()
  422. data = r.json()
  423. except Exception as e:
  424. # Handle connection error here
  425. print(f"Connection error: {e}")
  426. if r is not None:
  427. try:
  428. res = r.json()
  429. if "detail" in res:
  430. return JSONResponse(
  431. status_code=r.status_code,
  432. content=res,
  433. )
  434. except:
  435. pass
  436. else:
  437. pass
  438. return data
  439. @app.get("/api/pipelines/list")
  440. async def get_pipelines_list(user=Depends(get_admin_user)):
  441. responses = await get_openai_models(raw=True)
  442. print(responses)
  443. urlIdxs = [idx for idx, response in enumerate(responses) if "pipelines" in response]
  444. return {
  445. "data": [
  446. {
  447. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  448. "idx": urlIdx,
  449. }
  450. for urlIdx in urlIdxs
  451. ]
  452. }
  453. class AddPipelineForm(BaseModel):
  454. url: str
  455. urlIdx: int
  456. @app.post("/api/pipelines/add")
  457. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  458. r = None
  459. try:
  460. urlIdx = form_data.urlIdx
  461. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  462. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  463. headers = {"Authorization": f"Bearer {key}"}
  464. r = requests.post(
  465. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  466. )
  467. r.raise_for_status()
  468. data = r.json()
  469. return {**data}
  470. except Exception as e:
  471. # Handle connection error here
  472. print(f"Connection error: {e}")
  473. detail = "Pipeline not found"
  474. if r is not None:
  475. try:
  476. res = r.json()
  477. if "detail" in res:
  478. detail = res["detail"]
  479. except:
  480. pass
  481. raise HTTPException(
  482. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  483. detail=detail,
  484. )
  485. class DeletePipelineForm(BaseModel):
  486. id: str
  487. urlIdx: int
  488. @app.delete("/api/pipelines/delete")
  489. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  490. r = None
  491. try:
  492. urlIdx = form_data.urlIdx
  493. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  494. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  495. headers = {"Authorization": f"Bearer {key}"}
  496. r = requests.delete(
  497. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  498. )
  499. r.raise_for_status()
  500. data = r.json()
  501. return {**data}
  502. except Exception as e:
  503. # Handle connection error here
  504. print(f"Connection error: {e}")
  505. detail = "Pipeline not found"
  506. if r is not None:
  507. try:
  508. res = r.json()
  509. if "detail" in res:
  510. detail = res["detail"]
  511. except:
  512. pass
  513. raise HTTPException(
  514. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  515. detail=detail,
  516. )
  517. @app.get("/api/pipelines")
  518. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  519. r = None
  520. try:
  521. urlIdx
  522. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  523. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  524. headers = {"Authorization": f"Bearer {key}"}
  525. r = requests.get(f"{url}/pipelines", headers=headers)
  526. r.raise_for_status()
  527. data = r.json()
  528. return {**data}
  529. except Exception as e:
  530. # Handle connection error here
  531. print(f"Connection error: {e}")
  532. detail = "Pipeline not found"
  533. if r is not None:
  534. try:
  535. res = r.json()
  536. if "detail" in res:
  537. detail = res["detail"]
  538. except:
  539. pass
  540. raise HTTPException(
  541. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  542. detail=detail,
  543. )
  544. @app.get("/api/pipelines/{pipeline_id}/valves")
  545. async def get_pipeline_valves(
  546. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  547. ):
  548. models = await get_all_models()
  549. r = None
  550. try:
  551. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  552. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  553. headers = {"Authorization": f"Bearer {key}"}
  554. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  555. r.raise_for_status()
  556. data = r.json()
  557. return {**data}
  558. except Exception as e:
  559. # Handle connection error here
  560. print(f"Connection error: {e}")
  561. detail = "Pipeline not found"
  562. if r is not None:
  563. try:
  564. res = r.json()
  565. if "detail" in res:
  566. detail = res["detail"]
  567. except:
  568. pass
  569. raise HTTPException(
  570. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  571. detail=detail,
  572. )
  573. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  574. async def get_pipeline_valves_spec(
  575. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  576. ):
  577. models = await get_all_models()
  578. r = None
  579. try:
  580. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  581. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  582. headers = {"Authorization": f"Bearer {key}"}
  583. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  584. r.raise_for_status()
  585. data = r.json()
  586. return {**data}
  587. except Exception as e:
  588. # Handle connection error here
  589. print(f"Connection error: {e}")
  590. detail = "Pipeline not found"
  591. if r is not None:
  592. try:
  593. res = r.json()
  594. if "detail" in res:
  595. detail = res["detail"]
  596. except:
  597. pass
  598. raise HTTPException(
  599. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  600. detail=detail,
  601. )
  602. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  603. async def update_pipeline_valves(
  604. urlIdx: Optional[int],
  605. pipeline_id: str,
  606. form_data: dict,
  607. user=Depends(get_admin_user),
  608. ):
  609. models = await get_all_models()
  610. r = None
  611. try:
  612. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  613. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  614. headers = {"Authorization": f"Bearer {key}"}
  615. r = requests.post(
  616. f"{url}/{pipeline_id}/valves/update",
  617. headers=headers,
  618. json={**form_data},
  619. )
  620. r.raise_for_status()
  621. data = r.json()
  622. return {**data}
  623. except Exception as e:
  624. # Handle connection error here
  625. print(f"Connection error: {e}")
  626. detail = "Pipeline not found"
  627. if r is not None:
  628. try:
  629. res = r.json()
  630. if "detail" in res:
  631. detail = res["detail"]
  632. except:
  633. pass
  634. raise HTTPException(
  635. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  636. detail=detail,
  637. )
  638. @app.get("/api/config")
  639. async def get_app_config():
  640. # Checking and Handling the Absence of 'ui' in CONFIG_DATA
  641. default_locale = "en-US"
  642. if "ui" in CONFIG_DATA:
  643. default_locale = CONFIG_DATA["ui"].get("default_locale", "en-US")
  644. # The Rest of the Function Now Uses the Variables Defined Above
  645. return {
  646. "status": True,
  647. "name": WEBUI_NAME,
  648. "version": VERSION,
  649. "default_locale": default_locale,
  650. "default_models": webui_app.state.config.DEFAULT_MODELS,
  651. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  652. "features": {
  653. "auth": WEBUI_AUTH,
  654. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  655. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  656. "enable_web_search": RAG_WEB_SEARCH_ENABLED,
  657. "enable_image_generation": images_app.state.config.ENABLED,
  658. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  659. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  660. },
  661. }
  662. @app.get("/api/config/model/filter")
  663. async def get_model_filter_config(user=Depends(get_admin_user)):
  664. return {
  665. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  666. "models": app.state.config.MODEL_FILTER_LIST,
  667. }
  668. class ModelFilterConfigForm(BaseModel):
  669. enabled: bool
  670. models: List[str]
  671. @app.post("/api/config/model/filter")
  672. async def update_model_filter_config(
  673. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  674. ):
  675. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  676. app.state.config.MODEL_FILTER_LIST = form_data.models
  677. return {
  678. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  679. "models": app.state.config.MODEL_FILTER_LIST,
  680. }
  681. @app.get("/api/webhook")
  682. async def get_webhook_url(user=Depends(get_admin_user)):
  683. return {
  684. "url": app.state.config.WEBHOOK_URL,
  685. }
  686. class UrlForm(BaseModel):
  687. url: str
  688. @app.post("/api/webhook")
  689. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  690. app.state.config.WEBHOOK_URL = form_data.url
  691. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  692. return {
  693. "url": app.state.config.WEBHOOK_URL,
  694. }
  695. @app.get("/api/community_sharing", response_model=bool)
  696. async def get_community_sharing_status(request: Request, user=Depends(get_admin_user)):
  697. return webui_app.state.config.ENABLE_COMMUNITY_SHARING
  698. @app.get("/api/community_sharing/toggle", response_model=bool)
  699. async def toggle_community_sharing(request: Request, user=Depends(get_admin_user)):
  700. webui_app.state.config.ENABLE_COMMUNITY_SHARING = (
  701. not webui_app.state.config.ENABLE_COMMUNITY_SHARING
  702. )
  703. return webui_app.state.config.ENABLE_COMMUNITY_SHARING
  704. @app.get("/api/version")
  705. async def get_app_config():
  706. return {
  707. "version": VERSION,
  708. }
  709. @app.get("/api/changelog")
  710. async def get_app_changelog():
  711. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  712. @app.get("/api/version/updates")
  713. async def get_app_latest_release_version():
  714. try:
  715. async with aiohttp.ClientSession() as session:
  716. async with session.get(
  717. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  718. ) as response:
  719. response.raise_for_status()
  720. data = await response.json()
  721. latest_version = data["tag_name"]
  722. return {"current": VERSION, "latest": latest_version[1:]}
  723. except aiohttp.ClientError as e:
  724. raise HTTPException(
  725. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  726. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  727. )
  728. @app.get("/manifest.json")
  729. async def get_manifest_json():
  730. return {
  731. "name": WEBUI_NAME,
  732. "short_name": WEBUI_NAME,
  733. "start_url": "/",
  734. "display": "standalone",
  735. "background_color": "#343541",
  736. "theme_color": "#343541",
  737. "orientation": "portrait-primary",
  738. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  739. }
  740. @app.get("/opensearch.xml")
  741. async def get_opensearch_xml():
  742. xml_content = rf"""
  743. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  744. <ShortName>{WEBUI_NAME}</ShortName>
  745. <Description>Search {WEBUI_NAME}</Description>
  746. <InputEncoding>UTF-8</InputEncoding>
  747. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/favicon.png</Image>
  748. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  749. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  750. </OpenSearchDescription>
  751. """
  752. return Response(content=xml_content, media_type="application/xml")
  753. @app.get("/health")
  754. async def healthcheck():
  755. return {"status": True}
  756. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  757. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  758. if os.path.exists(FRONTEND_BUILD_DIR):
  759. mimetypes.add_type("text/javascript", ".js")
  760. app.mount(
  761. "/",
  762. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  763. name="spa-static-files",
  764. )
  765. else:
  766. log.warning(
  767. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  768. )