main.py 57 KB

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