main.py 59 KB

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