main.py 58 KB

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