main.py 61 KB

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