main.py 60 KB

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