main.py 60 KB

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