main.py 66 KB

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