main.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694
  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 uuid
  15. import inspect
  16. import asyncio
  17. from fastapi import FastAPI, Request, Depends, status, UploadFile, File, Form
  18. from fastapi.staticfiles import StaticFiles
  19. from fastapi.responses import JSONResponse
  20. from fastapi import HTTPException
  21. from fastapi.middleware.wsgi import WSGIMiddleware
  22. from fastapi.middleware.cors import CORSMiddleware
  23. from starlette.exceptions import HTTPException as StarletteHTTPException
  24. from starlette.middleware.base import BaseHTTPMiddleware
  25. from starlette.responses import StreamingResponse, Response
  26. from apps.socket.main import app as socket_app
  27. from apps.ollama.main import (
  28. app as ollama_app,
  29. OpenAIChatCompletionForm,
  30. get_all_models as get_ollama_models,
  31. generate_openai_chat_completion as generate_ollama_chat_completion,
  32. )
  33. from apps.openai.main import (
  34. app as openai_app,
  35. get_all_models as get_openai_models,
  36. generate_chat_completion as generate_openai_chat_completion,
  37. )
  38. from apps.audio.main import app as audio_app
  39. from apps.images.main import app as images_app
  40. from apps.rag.main import app as rag_app
  41. from apps.webui.main import app as webui_app
  42. from pydantic import BaseModel
  43. from typing import List, Optional
  44. from apps.webui.models.models import Models, ModelModel
  45. from apps.webui.models.tools import Tools
  46. from apps.webui.models.functions import Functions
  47. from apps.webui.utils import load_toolkit_module_by_id, load_function_module_by_id
  48. from utils.utils import (
  49. get_admin_user,
  50. get_verified_user,
  51. get_current_user,
  52. get_http_authorization_cred,
  53. )
  54. from utils.task import (
  55. title_generation_template,
  56. search_query_generation_template,
  57. tools_function_calling_generation_template,
  58. )
  59. from utils.misc import get_last_user_message, add_or_update_system_message
  60. from apps.rag.utils import get_rag_context, rag_template
  61. from config import (
  62. CONFIG_DATA,
  63. WEBUI_NAME,
  64. WEBUI_URL,
  65. WEBUI_AUTH,
  66. ENV,
  67. VERSION,
  68. CHANGELOG,
  69. FRONTEND_BUILD_DIR,
  70. UPLOAD_DIR,
  71. CACHE_DIR,
  72. STATIC_DIR,
  73. ENABLE_OPENAI_API,
  74. ENABLE_OLLAMA_API,
  75. ENABLE_MODEL_FILTER,
  76. MODEL_FILTER_LIST,
  77. GLOBAL_LOG_LEVEL,
  78. SRC_LOG_LEVELS,
  79. WEBHOOK_URL,
  80. ENABLE_ADMIN_EXPORT,
  81. WEBUI_BUILD_HASH,
  82. TASK_MODEL,
  83. TASK_MODEL_EXTERNAL,
  84. TITLE_GENERATION_PROMPT_TEMPLATE,
  85. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  86. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  87. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  88. AppConfig,
  89. )
  90. from constants import ERROR_MESSAGES
  91. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  92. log = logging.getLogger(__name__)
  93. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  94. class SPAStaticFiles(StaticFiles):
  95. async def get_response(self, path: str, scope):
  96. try:
  97. return await super().get_response(path, scope)
  98. except (HTTPException, StarletteHTTPException) as ex:
  99. if ex.status_code == 404:
  100. return await super().get_response("index.html", scope)
  101. else:
  102. raise ex
  103. print(
  104. rf"""
  105. ___ __ __ _ _ _ ___
  106. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  107. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  108. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  109. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  110. |_|
  111. v{VERSION} - building the best open-source AI user interface.
  112. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  113. https://github.com/open-webui/open-webui
  114. """
  115. )
  116. @asynccontextmanager
  117. async def lifespan(app: FastAPI):
  118. yield
  119. app = FastAPI(
  120. docs_url="/docs" if ENV == "dev" else None, redoc_url=None, lifespan=lifespan
  121. )
  122. app.state.config = AppConfig()
  123. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  124. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  125. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  126. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  127. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  128. app.state.config.TASK_MODEL = TASK_MODEL
  129. app.state.config.TASK_MODEL_EXTERNAL = TASK_MODEL_EXTERNAL
  130. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = TITLE_GENERATION_PROMPT_TEMPLATE
  131. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  132. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  133. )
  134. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  135. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  136. )
  137. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  138. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  139. )
  140. app.state.MODELS = {}
  141. origins = ["*"]
  142. ##################################
  143. #
  144. # ChatCompletion Middleware
  145. #
  146. ##################################
  147. async def get_function_call_response(
  148. messages, files, tool_id, template, task_model_id, user
  149. ):
  150. tool = Tools.get_tool_by_id(tool_id)
  151. tools_specs = json.dumps(tool.specs, indent=2)
  152. content = tools_function_calling_generation_template(template, tools_specs)
  153. user_message = get_last_user_message(messages)
  154. prompt = (
  155. "History:\n"
  156. + "\n".join(
  157. [
  158. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  159. for message in messages[::-1][:4]
  160. ]
  161. )
  162. + f"\nQuery: {user_message}"
  163. )
  164. print(prompt)
  165. payload = {
  166. "model": task_model_id,
  167. "messages": [
  168. {"role": "system", "content": content},
  169. {"role": "user", "content": f"Query: {prompt}"},
  170. ],
  171. "stream": False,
  172. }
  173. try:
  174. payload = filter_pipeline(payload, user)
  175. except Exception as e:
  176. raise e
  177. model = app.state.MODELS[task_model_id]
  178. response = None
  179. try:
  180. if model["owned_by"] == "ollama":
  181. response = await generate_ollama_chat_completion(payload, user=user)
  182. else:
  183. response = await generate_openai_chat_completion(payload, user=user)
  184. content = None
  185. if hasattr(response, "body_iterator"):
  186. async for chunk in response.body_iterator:
  187. data = json.loads(chunk.decode("utf-8"))
  188. content = data["choices"][0]["message"]["content"]
  189. # Cleanup any remaining background tasks if necessary
  190. if response.background is not None:
  191. await response.background()
  192. else:
  193. content = response["choices"][0]["message"]["content"]
  194. # Parse the function response
  195. if content is not None:
  196. print(f"content: {content}")
  197. result = json.loads(content)
  198. print(result)
  199. # Call the function
  200. if "name" in result:
  201. if tool_id in webui_app.state.TOOLS:
  202. toolkit_module = webui_app.state.TOOLS[tool_id]
  203. else:
  204. toolkit_module = load_toolkit_module_by_id(tool_id)
  205. webui_app.state.TOOLS[tool_id] = toolkit_module
  206. file_handler = False
  207. # check if toolkit_module has file_handler self variable
  208. if hasattr(toolkit_module, "file_handler"):
  209. file_handler = True
  210. print("file_handler: ", file_handler)
  211. function = getattr(toolkit_module, result["name"])
  212. function_result = None
  213. try:
  214. # Get the signature of the function
  215. sig = inspect.signature(function)
  216. params = result["parameters"]
  217. if "__user__" in sig.parameters:
  218. # Call the function with the '__user__' parameter included
  219. params = {
  220. **params,
  221. "__user__": {
  222. "id": user.id,
  223. "email": user.email,
  224. "name": user.name,
  225. "role": user.role,
  226. },
  227. }
  228. if "__messages__" in sig.parameters:
  229. # Call the function with the '__messages__' parameter included
  230. params = {
  231. **params,
  232. "__messages__": messages,
  233. }
  234. if "__files__" in sig.parameters:
  235. # Call the function with the '__files__' parameter included
  236. params = {
  237. **params,
  238. "__files__": files,
  239. }
  240. if "__model__" in sig.parameters:
  241. # Call the function with the '__model__' parameter included
  242. params = {
  243. **params,
  244. "__model__": model,
  245. }
  246. if "__id__" in sig.parameters:
  247. # Call the function with the '__id__' parameter included
  248. params = {
  249. **params,
  250. "__id__": tool_id,
  251. }
  252. function_result = function(**params)
  253. except Exception as e:
  254. print(e)
  255. # Add the function result to the system prompt
  256. if function_result is not None:
  257. return function_result, file_handler
  258. except Exception as e:
  259. print(f"Error: {e}")
  260. return None, False
  261. class ChatCompletionMiddleware(BaseHTTPMiddleware):
  262. async def dispatch(self, request: Request, call_next):
  263. data_items = []
  264. if request.method == "POST" and any(
  265. endpoint in request.url.path
  266. for endpoint in ["/ollama/api/chat", "/chat/completions"]
  267. ):
  268. log.debug(f"request.url.path: {request.url.path}")
  269. # Read the original request body
  270. body = await request.body()
  271. body_str = body.decode("utf-8")
  272. data = json.loads(body_str) if body_str else {}
  273. user = get_current_user(
  274. request,
  275. get_http_authorization_cred(request.headers.get("Authorization")),
  276. )
  277. # Flag to skip RAG completions if file_handler is present in tools/functions
  278. skip_files = False
  279. model_id = data["model"]
  280. if model_id not in app.state.MODELS:
  281. raise HTTPException(
  282. status_code=status.HTTP_404_NOT_FOUND,
  283. detail="Model not found",
  284. )
  285. model = app.state.MODELS[model_id]
  286. # Check if the model has any filters
  287. for filter_id in model["info"]["meta"].get("filterIds", []):
  288. filter = Functions.get_function_by_id(filter_id)
  289. if filter:
  290. if filter_id in webui_app.state.FUNCTIONS:
  291. function_module = webui_app.state.FUNCTIONS[filter_id]
  292. else:
  293. function_module, function_type = load_function_module_by_id(
  294. filter_id
  295. )
  296. webui_app.state.FUNCTIONS[filter_id] = function_module
  297. # Check if the function has a file_handler variable
  298. if getattr(function_module, "file_handler"):
  299. skip_files = True
  300. try:
  301. if hasattr(function_module, "inlet"):
  302. data = function_module.inlet(
  303. data,
  304. {
  305. "id": user.id,
  306. "email": user.email,
  307. "name": user.name,
  308. "role": user.role,
  309. },
  310. )
  311. except Exception as e:
  312. print(f"Error: {e}")
  313. return JSONResponse(
  314. status_code=status.HTTP_400_BAD_REQUEST,
  315. content={"detail": str(e)},
  316. )
  317. # Set the task model
  318. task_model_id = data["model"]
  319. # Check if the user has a custom task model and use that model
  320. if app.state.MODELS[task_model_id]["owned_by"] == "ollama":
  321. if (
  322. app.state.config.TASK_MODEL
  323. and app.state.config.TASK_MODEL in app.state.MODELS
  324. ):
  325. task_model_id = app.state.config.TASK_MODEL
  326. else:
  327. if (
  328. app.state.config.TASK_MODEL_EXTERNAL
  329. and app.state.config.TASK_MODEL_EXTERNAL in app.state.MODELS
  330. ):
  331. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  332. prompt = get_last_user_message(data["messages"])
  333. context = ""
  334. # If tool_ids field is present, call the functions
  335. if "tool_ids" in data:
  336. print(data["tool_ids"])
  337. for tool_id in data["tool_ids"]:
  338. print(tool_id)
  339. try:
  340. response, file_handler = await get_function_call_response(
  341. messages=data["messages"],
  342. files=data.get("files", []),
  343. tool_id=tool_id,
  344. template=app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  345. task_model_id=task_model_id,
  346. user=user,
  347. )
  348. print(file_handler)
  349. if isinstance(response, str):
  350. context += ("\n" if context != "" else "") + response
  351. if file_handler:
  352. skip_files = True
  353. except Exception as e:
  354. print(f"Error: {e}")
  355. del data["tool_ids"]
  356. print(f"tool_context: {context}")
  357. # If files field is present, generate RAG completions
  358. # If skip_files is True, skip the RAG completions
  359. if "files" in data:
  360. if not skip_files:
  361. data = {**data}
  362. rag_context, citations = get_rag_context(
  363. files=data["files"],
  364. messages=data["messages"],
  365. embedding_function=rag_app.state.EMBEDDING_FUNCTION,
  366. k=rag_app.state.config.TOP_K,
  367. reranking_function=rag_app.state.sentence_transformer_rf,
  368. r=rag_app.state.config.RELEVANCE_THRESHOLD,
  369. hybrid_search=rag_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  370. )
  371. if rag_context:
  372. context += ("\n" if context != "" else "") + rag_context
  373. log.debug(f"rag_context: {rag_context}, citations: {citations}")
  374. if citations and data.get("citations"):
  375. data_items.append({"citations": citations})
  376. del data["citations"]
  377. del data["files"]
  378. if context != "":
  379. system_prompt = rag_template(
  380. rag_app.state.config.RAG_TEMPLATE, context, prompt
  381. )
  382. print(system_prompt)
  383. data["messages"] = add_or_update_system_message(
  384. system_prompt, data["messages"]
  385. )
  386. modified_body_bytes = json.dumps(data).encode("utf-8")
  387. # Replace the request body with the modified one
  388. request._body = modified_body_bytes
  389. # Set custom header to ensure content-length matches new body length
  390. request.headers.__dict__["_list"] = [
  391. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  392. *[
  393. (k, v)
  394. for k, v in request.headers.raw
  395. if k.lower() != b"content-length"
  396. ],
  397. ]
  398. response = await call_next(request)
  399. if isinstance(response, StreamingResponse):
  400. # If it's a streaming response, inject it as SSE event or NDJSON line
  401. content_type = response.headers.get("Content-Type")
  402. if "text/event-stream" in content_type:
  403. return StreamingResponse(
  404. self.openai_stream_wrapper(response.body_iterator, data_items),
  405. )
  406. if "application/x-ndjson" in content_type:
  407. return StreamingResponse(
  408. self.ollama_stream_wrapper(response.body_iterator, data_items),
  409. )
  410. else:
  411. return response
  412. # If it's not a chat completion request, just pass it through
  413. response = await call_next(request)
  414. return response
  415. async def _receive(self, body: bytes):
  416. return {"type": "http.request", "body": body, "more_body": False}
  417. async def openai_stream_wrapper(self, original_generator, data_items):
  418. for item in data_items:
  419. yield f"data: {json.dumps(item)}\n\n"
  420. async for data in original_generator:
  421. yield data
  422. async def ollama_stream_wrapper(self, original_generator, data_items):
  423. for item in data_items:
  424. yield f"{json.dumps(item)}\n"
  425. async for data in original_generator:
  426. yield data
  427. app.add_middleware(ChatCompletionMiddleware)
  428. ##################################
  429. #
  430. # Pipeline Middleware
  431. #
  432. ##################################
  433. def filter_pipeline(payload, user):
  434. user = {"id": user.id, "email": user.email, "name": user.name, "role": user.role}
  435. model_id = payload["model"]
  436. filters = [
  437. model
  438. for model in app.state.MODELS.values()
  439. if "pipeline" in model
  440. and "type" in model["pipeline"]
  441. and model["pipeline"]["type"] == "filter"
  442. and (
  443. model["pipeline"]["pipelines"] == ["*"]
  444. or any(
  445. model_id == target_model_id
  446. for target_model_id in model["pipeline"]["pipelines"]
  447. )
  448. )
  449. ]
  450. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  451. model = app.state.MODELS[model_id]
  452. if "pipeline" in model:
  453. sorted_filters.append(model)
  454. for filter in sorted_filters:
  455. r = None
  456. try:
  457. urlIdx = filter["urlIdx"]
  458. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  459. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  460. if key != "":
  461. headers = {"Authorization": f"Bearer {key}"}
  462. r = requests.post(
  463. f"{url}/{filter['id']}/filter/inlet",
  464. headers=headers,
  465. json={
  466. "user": user,
  467. "body": payload,
  468. },
  469. )
  470. r.raise_for_status()
  471. payload = r.json()
  472. except Exception as e:
  473. # Handle connection error here
  474. print(f"Connection error: {e}")
  475. if r is not None:
  476. try:
  477. res = r.json()
  478. except:
  479. pass
  480. if "detail" in res:
  481. raise Exception(r.status_code, res["detail"])
  482. else:
  483. pass
  484. if "pipeline" not in app.state.MODELS[model_id]:
  485. if "chat_id" in payload:
  486. del payload["chat_id"]
  487. if "title" in payload:
  488. del payload["title"]
  489. if "task" in payload:
  490. del payload["task"]
  491. return payload
  492. class PipelineMiddleware(BaseHTTPMiddleware):
  493. async def dispatch(self, request: Request, call_next):
  494. if request.method == "POST" and (
  495. "/ollama/api/chat" in request.url.path
  496. or "/chat/completions" in request.url.path
  497. ):
  498. log.debug(f"request.url.path: {request.url.path}")
  499. # Read the original request body
  500. body = await request.body()
  501. # Decode body to string
  502. body_str = body.decode("utf-8")
  503. # Parse string to JSON
  504. data = json.loads(body_str) if body_str else {}
  505. user = get_current_user(
  506. request,
  507. get_http_authorization_cred(request.headers.get("Authorization")),
  508. )
  509. try:
  510. data = filter_pipeline(data, user)
  511. except Exception as e:
  512. return JSONResponse(
  513. status_code=e.args[0],
  514. content={"detail": e.args[1]},
  515. )
  516. modified_body_bytes = json.dumps(data).encode("utf-8")
  517. # Replace the request body with the modified one
  518. request._body = modified_body_bytes
  519. # Set custom header to ensure content-length matches new body length
  520. request.headers.__dict__["_list"] = [
  521. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  522. *[
  523. (k, v)
  524. for k, v in request.headers.raw
  525. if k.lower() != b"content-length"
  526. ],
  527. ]
  528. response = await call_next(request)
  529. return response
  530. async def _receive(self, body: bytes):
  531. return {"type": "http.request", "body": body, "more_body": False}
  532. app.add_middleware(PipelineMiddleware)
  533. app.add_middleware(
  534. CORSMiddleware,
  535. allow_origins=origins,
  536. allow_credentials=True,
  537. allow_methods=["*"],
  538. allow_headers=["*"],
  539. )
  540. @app.middleware("http")
  541. async def check_url(request: Request, call_next):
  542. if len(app.state.MODELS) == 0:
  543. await get_all_models()
  544. else:
  545. pass
  546. start_time = int(time.time())
  547. response = await call_next(request)
  548. process_time = int(time.time()) - start_time
  549. response.headers["X-Process-Time"] = str(process_time)
  550. return response
  551. @app.middleware("http")
  552. async def update_embedding_function(request: Request, call_next):
  553. response = await call_next(request)
  554. if "/embedding/update" in request.url.path:
  555. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  556. return response
  557. app.mount("/ws", socket_app)
  558. app.mount("/ollama", ollama_app)
  559. app.mount("/openai", openai_app)
  560. app.mount("/images/api/v1", images_app)
  561. app.mount("/audio/api/v1", audio_app)
  562. app.mount("/rag/api/v1", rag_app)
  563. app.mount("/api/v1", webui_app)
  564. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  565. async def get_all_models():
  566. openai_models = []
  567. ollama_models = []
  568. if app.state.config.ENABLE_OPENAI_API:
  569. openai_models = await get_openai_models()
  570. openai_models = openai_models["data"]
  571. if app.state.config.ENABLE_OLLAMA_API:
  572. ollama_models = await get_ollama_models()
  573. ollama_models = [
  574. {
  575. "id": model["model"],
  576. "name": model["name"],
  577. "object": "model",
  578. "created": int(time.time()),
  579. "owned_by": "ollama",
  580. "ollama": model,
  581. }
  582. for model in ollama_models["models"]
  583. ]
  584. models = openai_models + ollama_models
  585. custom_models = Models.get_all_models()
  586. for custom_model in custom_models:
  587. if custom_model.base_model_id == None:
  588. for model in models:
  589. if (
  590. custom_model.id == model["id"]
  591. or custom_model.id == model["id"].split(":")[0]
  592. ):
  593. model["name"] = custom_model.name
  594. model["info"] = custom_model.model_dump()
  595. else:
  596. owned_by = "openai"
  597. for model in models:
  598. if (
  599. custom_model.base_model_id == model["id"]
  600. or custom_model.base_model_id == model["id"].split(":")[0]
  601. ):
  602. owned_by = model["owned_by"]
  603. break
  604. models.append(
  605. {
  606. "id": custom_model.id,
  607. "name": custom_model.name,
  608. "object": "model",
  609. "created": custom_model.created_at,
  610. "owned_by": owned_by,
  611. "info": custom_model.model_dump(),
  612. "preset": True,
  613. }
  614. )
  615. app.state.MODELS = {model["id"]: model for model in models}
  616. webui_app.state.MODELS = app.state.MODELS
  617. return models
  618. @app.get("/api/models")
  619. async def get_models(user=Depends(get_verified_user)):
  620. models = await get_all_models()
  621. # Filter out filter pipelines
  622. models = [
  623. model
  624. for model in models
  625. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  626. ]
  627. if app.state.config.ENABLE_MODEL_FILTER:
  628. if user.role == "user":
  629. models = list(
  630. filter(
  631. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  632. models,
  633. )
  634. )
  635. return {"data": models}
  636. return {"data": models}
  637. @app.post("/api/chat/completions")
  638. async def generate_chat_completions(form_data: dict, user=Depends(get_verified_user)):
  639. model_id = form_data["model"]
  640. if model_id not in app.state.MODELS:
  641. raise HTTPException(
  642. status_code=status.HTTP_404_NOT_FOUND,
  643. detail="Model not found",
  644. )
  645. model = app.state.MODELS[model_id]
  646. print(model)
  647. if model["owned_by"] == "ollama":
  648. return await generate_ollama_chat_completion(form_data, user=user)
  649. else:
  650. return await generate_openai_chat_completion(form_data, user=user)
  651. @app.post("/api/chat/completed")
  652. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  653. data = form_data
  654. model_id = data["model"]
  655. if model_id not in app.state.MODELS:
  656. raise HTTPException(
  657. status_code=status.HTTP_404_NOT_FOUND,
  658. detail="Model not found",
  659. )
  660. model = app.state.MODELS[model_id]
  661. filters = [
  662. model
  663. for model in app.state.MODELS.values()
  664. if "pipeline" in model
  665. and "type" in model["pipeline"]
  666. and model["pipeline"]["type"] == "filter"
  667. and (
  668. model["pipeline"]["pipelines"] == ["*"]
  669. or any(
  670. model_id == target_model_id
  671. for target_model_id in model["pipeline"]["pipelines"]
  672. )
  673. )
  674. ]
  675. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  676. if "pipeline" in model:
  677. sorted_filters = [model] + sorted_filters
  678. for filter in sorted_filters:
  679. r = None
  680. try:
  681. urlIdx = filter["urlIdx"]
  682. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  683. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  684. if key != "":
  685. headers = {"Authorization": f"Bearer {key}"}
  686. r = requests.post(
  687. f"{url}/{filter['id']}/filter/outlet",
  688. headers=headers,
  689. json={
  690. "user": {"id": user.id, "name": user.name, "role": user.role},
  691. "body": data,
  692. },
  693. )
  694. r.raise_for_status()
  695. data = r.json()
  696. except Exception as e:
  697. # Handle connection error here
  698. print(f"Connection error: {e}")
  699. if r is not None:
  700. try:
  701. res = r.json()
  702. if "detail" in res:
  703. return JSONResponse(
  704. status_code=r.status_code,
  705. content=res,
  706. )
  707. except:
  708. pass
  709. else:
  710. pass
  711. # Check if the model has any filters
  712. for filter_id in model["info"]["meta"].get("filterIds", []):
  713. filter = Functions.get_function_by_id(filter_id)
  714. if filter:
  715. if filter_id in webui_app.state.FUNCTIONS:
  716. function_module = webui_app.state.FUNCTIONS[filter_id]
  717. else:
  718. function_module, function_type = load_function_module_by_id(filter_id)
  719. webui_app.state.FUNCTIONS[filter_id] = function_module
  720. try:
  721. if hasattr(function_module, "outlet"):
  722. data = function_module.outlet(
  723. data,
  724. {
  725. "id": user.id,
  726. "email": user.email,
  727. "name": user.name,
  728. "role": user.role,
  729. },
  730. )
  731. except Exception as e:
  732. print(f"Error: {e}")
  733. return JSONResponse(
  734. status_code=status.HTTP_400_BAD_REQUEST,
  735. content={"detail": str(e)},
  736. )
  737. return data
  738. ##################################
  739. #
  740. # Task Endpoints
  741. #
  742. ##################################
  743. # TODO: Refactor task API endpoints below into a separate file
  744. @app.get("/api/task/config")
  745. async def get_task_config(user=Depends(get_verified_user)):
  746. return {
  747. "TASK_MODEL": app.state.config.TASK_MODEL,
  748. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  749. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  750. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  751. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  752. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  753. }
  754. class TaskConfigForm(BaseModel):
  755. TASK_MODEL: Optional[str]
  756. TASK_MODEL_EXTERNAL: Optional[str]
  757. TITLE_GENERATION_PROMPT_TEMPLATE: str
  758. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE: str
  759. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD: int
  760. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  761. @app.post("/api/task/config/update")
  762. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  763. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  764. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  765. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  766. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  767. )
  768. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  769. form_data.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  770. )
  771. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  772. form_data.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  773. )
  774. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  775. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  776. )
  777. return {
  778. "TASK_MODEL": app.state.config.TASK_MODEL,
  779. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  780. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  781. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  782. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  783. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  784. }
  785. @app.post("/api/task/title/completions")
  786. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  787. print("generate_title")
  788. model_id = form_data["model"]
  789. if model_id not in app.state.MODELS:
  790. raise HTTPException(
  791. status_code=status.HTTP_404_NOT_FOUND,
  792. detail="Model not found",
  793. )
  794. # Check if the user has a custom task model
  795. # If the user has a custom task model, use that model
  796. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  797. if app.state.config.TASK_MODEL:
  798. task_model_id = app.state.config.TASK_MODEL
  799. if task_model_id in app.state.MODELS:
  800. model_id = task_model_id
  801. else:
  802. if app.state.config.TASK_MODEL_EXTERNAL:
  803. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  804. if task_model_id in app.state.MODELS:
  805. model_id = task_model_id
  806. print(model_id)
  807. model = app.state.MODELS[model_id]
  808. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  809. content = title_generation_template(
  810. template,
  811. form_data["prompt"],
  812. {
  813. "name": user.name,
  814. "location": user.info.get("location") if user.info else None,
  815. },
  816. )
  817. payload = {
  818. "model": model_id,
  819. "messages": [{"role": "user", "content": content}],
  820. "stream": False,
  821. "max_tokens": 50,
  822. "chat_id": form_data.get("chat_id", None),
  823. "title": True,
  824. }
  825. log.debug(payload)
  826. try:
  827. payload = filter_pipeline(payload, user)
  828. except Exception as e:
  829. return JSONResponse(
  830. status_code=e.args[0],
  831. content={"detail": e.args[1]},
  832. )
  833. if model["owned_by"] == "ollama":
  834. return await generate_ollama_chat_completion(payload, user=user)
  835. else:
  836. return await generate_openai_chat_completion(payload, user=user)
  837. @app.post("/api/task/query/completions")
  838. async def generate_search_query(form_data: dict, user=Depends(get_verified_user)):
  839. print("generate_search_query")
  840. if len(form_data["prompt"]) < app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD:
  841. raise HTTPException(
  842. status_code=status.HTTP_400_BAD_REQUEST,
  843. detail=f"Skip search query generation for short prompts (< {app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD} characters)",
  844. )
  845. model_id = form_data["model"]
  846. if model_id not in app.state.MODELS:
  847. raise HTTPException(
  848. status_code=status.HTTP_404_NOT_FOUND,
  849. detail="Model not found",
  850. )
  851. # Check if the user has a custom task model
  852. # If the user has a custom task model, use that model
  853. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  854. if app.state.config.TASK_MODEL:
  855. task_model_id = app.state.config.TASK_MODEL
  856. if task_model_id in app.state.MODELS:
  857. model_id = task_model_id
  858. else:
  859. if app.state.config.TASK_MODEL_EXTERNAL:
  860. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  861. if task_model_id in app.state.MODELS:
  862. model_id = task_model_id
  863. print(model_id)
  864. model = app.state.MODELS[model_id]
  865. template = app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  866. content = search_query_generation_template(
  867. template, form_data["prompt"], {"name": user.name}
  868. )
  869. payload = {
  870. "model": model_id,
  871. "messages": [{"role": "user", "content": content}],
  872. "stream": False,
  873. "max_tokens": 30,
  874. "task": True,
  875. }
  876. print(payload)
  877. try:
  878. payload = filter_pipeline(payload, user)
  879. except Exception as e:
  880. return JSONResponse(
  881. status_code=e.args[0],
  882. content={"detail": e.args[1]},
  883. )
  884. if model["owned_by"] == "ollama":
  885. return await generate_ollama_chat_completion(payload, user=user)
  886. else:
  887. return await generate_openai_chat_completion(payload, user=user)
  888. @app.post("/api/task/emoji/completions")
  889. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  890. print("generate_emoji")
  891. model_id = form_data["model"]
  892. if model_id not in app.state.MODELS:
  893. raise HTTPException(
  894. status_code=status.HTTP_404_NOT_FOUND,
  895. detail="Model not found",
  896. )
  897. # Check if the user has a custom task model
  898. # If the user has a custom task model, use that model
  899. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  900. if app.state.config.TASK_MODEL:
  901. task_model_id = app.state.config.TASK_MODEL
  902. if task_model_id in app.state.MODELS:
  903. model_id = task_model_id
  904. else:
  905. if app.state.config.TASK_MODEL_EXTERNAL:
  906. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  907. if task_model_id in app.state.MODELS:
  908. model_id = task_model_id
  909. print(model_id)
  910. model = app.state.MODELS[model_id]
  911. template = '''
  912. Your task is to reflect the speaker's likely facial expression through a fitting emoji. Interpret emotions from the message and reflect their facial expression using fitting, diverse emojis (e.g., 😊, 😢, 😡, 😱).
  913. Message: """{{prompt}}"""
  914. '''
  915. content = title_generation_template(
  916. template,
  917. form_data["prompt"],
  918. {
  919. "name": user.name,
  920. "location": user.info.get("location") if user.info else None,
  921. },
  922. )
  923. payload = {
  924. "model": model_id,
  925. "messages": [{"role": "user", "content": content}],
  926. "stream": False,
  927. "max_tokens": 4,
  928. "chat_id": form_data.get("chat_id", None),
  929. "task": True,
  930. }
  931. log.debug(payload)
  932. try:
  933. payload = filter_pipeline(payload, user)
  934. except Exception as e:
  935. return JSONResponse(
  936. status_code=e.args[0],
  937. content={"detail": e.args[1]},
  938. )
  939. if model["owned_by"] == "ollama":
  940. return await generate_ollama_chat_completion(payload, user=user)
  941. else:
  942. return await generate_openai_chat_completion(payload, user=user)
  943. @app.post("/api/task/tools/completions")
  944. async def get_tools_function_calling(form_data: dict, user=Depends(get_verified_user)):
  945. print("get_tools_function_calling")
  946. model_id = form_data["model"]
  947. if model_id not in app.state.MODELS:
  948. raise HTTPException(
  949. status_code=status.HTTP_404_NOT_FOUND,
  950. detail="Model not found",
  951. )
  952. # Check if the user has a custom task model
  953. # If the user has a custom task model, use that model
  954. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  955. if app.state.config.TASK_MODEL:
  956. task_model_id = app.state.config.TASK_MODEL
  957. if task_model_id in app.state.MODELS:
  958. model_id = task_model_id
  959. else:
  960. if app.state.config.TASK_MODEL_EXTERNAL:
  961. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  962. if task_model_id in app.state.MODELS:
  963. model_id = task_model_id
  964. print(model_id)
  965. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  966. try:
  967. context, file_handler = await get_function_call_response(
  968. form_data["messages"],
  969. form_data.get("files", []),
  970. form_data["tool_id"],
  971. template,
  972. model_id,
  973. user,
  974. )
  975. return context
  976. except Exception as e:
  977. return JSONResponse(
  978. status_code=e.args[0],
  979. content={"detail": e.args[1]},
  980. )
  981. ##################################
  982. #
  983. # Pipelines Endpoints
  984. #
  985. ##################################
  986. # TODO: Refactor pipelines API endpoints below into a separate file
  987. @app.get("/api/pipelines/list")
  988. async def get_pipelines_list(user=Depends(get_admin_user)):
  989. responses = await get_openai_models(raw=True)
  990. print(responses)
  991. urlIdxs = [
  992. idx
  993. for idx, response in enumerate(responses)
  994. if response != None and "pipelines" in response
  995. ]
  996. return {
  997. "data": [
  998. {
  999. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  1000. "idx": urlIdx,
  1001. }
  1002. for urlIdx in urlIdxs
  1003. ]
  1004. }
  1005. @app.post("/api/pipelines/upload")
  1006. async def upload_pipeline(
  1007. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  1008. ):
  1009. print("upload_pipeline", urlIdx, file.filename)
  1010. # Check if the uploaded file is a python file
  1011. if not file.filename.endswith(".py"):
  1012. raise HTTPException(
  1013. status_code=status.HTTP_400_BAD_REQUEST,
  1014. detail="Only Python (.py) files are allowed.",
  1015. )
  1016. upload_folder = f"{CACHE_DIR}/pipelines"
  1017. os.makedirs(upload_folder, exist_ok=True)
  1018. file_path = os.path.join(upload_folder, file.filename)
  1019. try:
  1020. # Save the uploaded file
  1021. with open(file_path, "wb") as buffer:
  1022. shutil.copyfileobj(file.file, buffer)
  1023. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1024. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1025. headers = {"Authorization": f"Bearer {key}"}
  1026. with open(file_path, "rb") as f:
  1027. files = {"file": f}
  1028. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1029. r.raise_for_status()
  1030. data = r.json()
  1031. return {**data}
  1032. except Exception as e:
  1033. # Handle connection error here
  1034. print(f"Connection error: {e}")
  1035. detail = "Pipeline not found"
  1036. if r is not None:
  1037. try:
  1038. res = r.json()
  1039. if "detail" in res:
  1040. detail = res["detail"]
  1041. except:
  1042. pass
  1043. raise HTTPException(
  1044. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1045. detail=detail,
  1046. )
  1047. finally:
  1048. # Ensure the file is deleted after the upload is completed or on failure
  1049. if os.path.exists(file_path):
  1050. os.remove(file_path)
  1051. class AddPipelineForm(BaseModel):
  1052. url: str
  1053. urlIdx: int
  1054. @app.post("/api/pipelines/add")
  1055. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1056. r = None
  1057. try:
  1058. urlIdx = form_data.urlIdx
  1059. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1060. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1061. headers = {"Authorization": f"Bearer {key}"}
  1062. r = requests.post(
  1063. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1064. )
  1065. r.raise_for_status()
  1066. data = r.json()
  1067. return {**data}
  1068. except Exception as e:
  1069. # Handle connection error here
  1070. print(f"Connection error: {e}")
  1071. detail = "Pipeline not found"
  1072. if r is not None:
  1073. try:
  1074. res = r.json()
  1075. if "detail" in res:
  1076. detail = res["detail"]
  1077. except:
  1078. pass
  1079. raise HTTPException(
  1080. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1081. detail=detail,
  1082. )
  1083. class DeletePipelineForm(BaseModel):
  1084. id: str
  1085. urlIdx: int
  1086. @app.delete("/api/pipelines/delete")
  1087. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1088. r = None
  1089. try:
  1090. urlIdx = form_data.urlIdx
  1091. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1092. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1093. headers = {"Authorization": f"Bearer {key}"}
  1094. r = requests.delete(
  1095. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1096. )
  1097. r.raise_for_status()
  1098. data = r.json()
  1099. return {**data}
  1100. except Exception as e:
  1101. # Handle connection error here
  1102. print(f"Connection error: {e}")
  1103. detail = "Pipeline not found"
  1104. if r is not None:
  1105. try:
  1106. res = r.json()
  1107. if "detail" in res:
  1108. detail = res["detail"]
  1109. except:
  1110. pass
  1111. raise HTTPException(
  1112. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1113. detail=detail,
  1114. )
  1115. @app.get("/api/pipelines")
  1116. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  1117. r = None
  1118. try:
  1119. urlIdx
  1120. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1121. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1122. headers = {"Authorization": f"Bearer {key}"}
  1123. r = requests.get(f"{url}/pipelines", headers=headers)
  1124. r.raise_for_status()
  1125. data = r.json()
  1126. return {**data}
  1127. except Exception as e:
  1128. # Handle connection error here
  1129. print(f"Connection error: {e}")
  1130. detail = "Pipeline not found"
  1131. if r is not None:
  1132. try:
  1133. res = r.json()
  1134. if "detail" in res:
  1135. detail = res["detail"]
  1136. except:
  1137. pass
  1138. raise HTTPException(
  1139. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1140. detail=detail,
  1141. )
  1142. @app.get("/api/pipelines/{pipeline_id}/valves")
  1143. async def get_pipeline_valves(
  1144. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  1145. ):
  1146. models = await get_all_models()
  1147. r = None
  1148. try:
  1149. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1150. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1151. headers = {"Authorization": f"Bearer {key}"}
  1152. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  1153. r.raise_for_status()
  1154. data = r.json()
  1155. return {**data}
  1156. except Exception as e:
  1157. # Handle connection error here
  1158. print(f"Connection error: {e}")
  1159. detail = "Pipeline not found"
  1160. if r is not None:
  1161. try:
  1162. res = r.json()
  1163. if "detail" in res:
  1164. detail = res["detail"]
  1165. except:
  1166. pass
  1167. raise HTTPException(
  1168. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1169. detail=detail,
  1170. )
  1171. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1172. async def get_pipeline_valves_spec(
  1173. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  1174. ):
  1175. models = await get_all_models()
  1176. r = None
  1177. try:
  1178. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1179. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1180. headers = {"Authorization": f"Bearer {key}"}
  1181. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  1182. r.raise_for_status()
  1183. data = r.json()
  1184. return {**data}
  1185. except Exception as e:
  1186. # Handle connection error here
  1187. print(f"Connection error: {e}")
  1188. detail = "Pipeline not found"
  1189. if r is not None:
  1190. try:
  1191. res = r.json()
  1192. if "detail" in res:
  1193. detail = res["detail"]
  1194. except:
  1195. pass
  1196. raise HTTPException(
  1197. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1198. detail=detail,
  1199. )
  1200. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1201. async def update_pipeline_valves(
  1202. urlIdx: Optional[int],
  1203. pipeline_id: str,
  1204. form_data: dict,
  1205. user=Depends(get_admin_user),
  1206. ):
  1207. models = await get_all_models()
  1208. r = None
  1209. try:
  1210. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1211. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1212. headers = {"Authorization": f"Bearer {key}"}
  1213. r = requests.post(
  1214. f"{url}/{pipeline_id}/valves/update",
  1215. headers=headers,
  1216. json={**form_data},
  1217. )
  1218. r.raise_for_status()
  1219. data = r.json()
  1220. return {**data}
  1221. except Exception as e:
  1222. # Handle connection error here
  1223. print(f"Connection error: {e}")
  1224. detail = "Pipeline not found"
  1225. if r is not None:
  1226. try:
  1227. res = r.json()
  1228. if "detail" in res:
  1229. detail = res["detail"]
  1230. except:
  1231. pass
  1232. raise HTTPException(
  1233. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1234. detail=detail,
  1235. )
  1236. ##################################
  1237. #
  1238. # Config Endpoints
  1239. #
  1240. ##################################
  1241. @app.get("/api/config")
  1242. async def get_app_config():
  1243. # Checking and Handling the Absence of 'ui' in CONFIG_DATA
  1244. default_locale = "en-US"
  1245. if "ui" in CONFIG_DATA:
  1246. default_locale = CONFIG_DATA["ui"].get("default_locale", "en-US")
  1247. # The Rest of the Function Now Uses the Variables Defined Above
  1248. return {
  1249. "status": True,
  1250. "name": WEBUI_NAME,
  1251. "version": VERSION,
  1252. "default_locale": default_locale,
  1253. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1254. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1255. "features": {
  1256. "auth": WEBUI_AUTH,
  1257. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1258. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1259. "enable_web_search": rag_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1260. "enable_image_generation": images_app.state.config.ENABLED,
  1261. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1262. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1263. },
  1264. "audio": {
  1265. "tts": {
  1266. "engine": audio_app.state.config.TTS_ENGINE,
  1267. "voice": audio_app.state.config.TTS_VOICE,
  1268. },
  1269. "stt": {
  1270. "engine": audio_app.state.config.STT_ENGINE,
  1271. },
  1272. },
  1273. }
  1274. @app.get("/api/config/model/filter")
  1275. async def get_model_filter_config(user=Depends(get_admin_user)):
  1276. return {
  1277. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1278. "models": app.state.config.MODEL_FILTER_LIST,
  1279. }
  1280. class ModelFilterConfigForm(BaseModel):
  1281. enabled: bool
  1282. models: List[str]
  1283. @app.post("/api/config/model/filter")
  1284. async def update_model_filter_config(
  1285. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  1286. ):
  1287. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  1288. app.state.config.MODEL_FILTER_LIST = form_data.models
  1289. return {
  1290. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1291. "models": app.state.config.MODEL_FILTER_LIST,
  1292. }
  1293. # TODO: webhook endpoint should be under config endpoints
  1294. @app.get("/api/webhook")
  1295. async def get_webhook_url(user=Depends(get_admin_user)):
  1296. return {
  1297. "url": app.state.config.WEBHOOK_URL,
  1298. }
  1299. class UrlForm(BaseModel):
  1300. url: str
  1301. @app.post("/api/webhook")
  1302. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1303. app.state.config.WEBHOOK_URL = form_data.url
  1304. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1305. return {"url": app.state.config.WEBHOOK_URL}
  1306. @app.get("/api/version")
  1307. async def get_app_config():
  1308. return {
  1309. "version": VERSION,
  1310. }
  1311. @app.get("/api/changelog")
  1312. async def get_app_changelog():
  1313. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1314. @app.get("/api/version/updates")
  1315. async def get_app_latest_release_version():
  1316. try:
  1317. async with aiohttp.ClientSession(trust_env=True) as session:
  1318. async with session.get(
  1319. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1320. ) as response:
  1321. response.raise_for_status()
  1322. data = await response.json()
  1323. latest_version = data["tag_name"]
  1324. return {"current": VERSION, "latest": latest_version[1:]}
  1325. except aiohttp.ClientError as e:
  1326. raise HTTPException(
  1327. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  1328. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  1329. )
  1330. @app.get("/manifest.json")
  1331. async def get_manifest_json():
  1332. return {
  1333. "name": WEBUI_NAME,
  1334. "short_name": WEBUI_NAME,
  1335. "start_url": "/",
  1336. "display": "standalone",
  1337. "background_color": "#343541",
  1338. "theme_color": "#343541",
  1339. "orientation": "portrait-primary",
  1340. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  1341. }
  1342. @app.get("/opensearch.xml")
  1343. async def get_opensearch_xml():
  1344. xml_content = rf"""
  1345. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1346. <ShortName>{WEBUI_NAME}</ShortName>
  1347. <Description>Search {WEBUI_NAME}</Description>
  1348. <InputEncoding>UTF-8</InputEncoding>
  1349. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/favicon.png</Image>
  1350. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1351. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1352. </OpenSearchDescription>
  1353. """
  1354. return Response(content=xml_content, media_type="application/xml")
  1355. @app.get("/health")
  1356. async def healthcheck():
  1357. return {"status": True}
  1358. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  1359. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  1360. if os.path.exists(FRONTEND_BUILD_DIR):
  1361. mimetypes.add_type("text/javascript", ".js")
  1362. app.mount(
  1363. "/",
  1364. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1365. name="spa-static-files",
  1366. )
  1367. else:
  1368. log.warning(
  1369. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1370. )