main.py 59 KB

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