main.py 64 KB

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