main.py 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272
  1. import asyncio
  2. import inspect
  3. import json
  4. import logging
  5. import mimetypes
  6. import os
  7. import shutil
  8. import sys
  9. import time
  10. from contextlib import asynccontextmanager
  11. from typing import Optional
  12. import aiohttp
  13. import requests
  14. from fastapi import (
  15. Depends,
  16. FastAPI,
  17. File,
  18. Form,
  19. HTTPException,
  20. Request,
  21. UploadFile,
  22. status,
  23. )
  24. from fastapi.middleware.cors import CORSMiddleware
  25. from fastapi.responses import JSONResponse
  26. from fastapi.staticfiles import StaticFiles
  27. from pydantic import BaseModel
  28. from sqlalchemy import text
  29. from starlette.exceptions import HTTPException as StarletteHTTPException
  30. from starlette.middleware.base import BaseHTTPMiddleware
  31. from starlette.middleware.sessions import SessionMiddleware
  32. from starlette.responses import Response, StreamingResponse
  33. from open_webui.apps.audio.main import app as audio_app
  34. from open_webui.apps.images.main import app as images_app
  35. from open_webui.apps.ollama.main import (
  36. app as ollama_app,
  37. get_all_models as get_ollama_models,
  38. generate_chat_completion as generate_ollama_chat_completion,
  39. GenerateChatCompletionForm,
  40. )
  41. from open_webui.apps.openai.main import (
  42. app as openai_app,
  43. generate_chat_completion as generate_openai_chat_completion,
  44. get_all_models as get_openai_models,
  45. )
  46. from open_webui.apps.retrieval.main import app as retrieval_app
  47. from open_webui.apps.retrieval.utils import get_rag_context, rag_template
  48. from open_webui.apps.socket.main import (
  49. app as socket_app,
  50. periodic_usage_pool_cleanup,
  51. get_event_call,
  52. get_event_emitter,
  53. )
  54. from open_webui.apps.webui.internal.db import Session
  55. from open_webui.apps.webui.main import (
  56. app as webui_app,
  57. generate_function_chat_completion,
  58. get_pipe_models,
  59. )
  60. from open_webui.apps.webui.models.functions import Functions
  61. from open_webui.apps.webui.models.models import Models
  62. from open_webui.apps.webui.models.users import UserModel, Users
  63. from open_webui.apps.webui.utils import load_function_module_by_id
  64. from open_webui.config import (
  65. CACHE_DIR,
  66. CORS_ALLOW_ORIGIN,
  67. DEFAULT_LOCALE,
  68. ENABLE_ADMIN_CHAT_ACCESS,
  69. ENABLE_ADMIN_EXPORT,
  70. ENABLE_MODEL_FILTER,
  71. ENABLE_OLLAMA_API,
  72. ENABLE_OPENAI_API,
  73. ENV,
  74. FRONTEND_BUILD_DIR,
  75. MODEL_FILTER_LIST,
  76. OAUTH_PROVIDERS,
  77. ENABLE_SEARCH_QUERY,
  78. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  79. STATIC_DIR,
  80. TASK_MODEL,
  81. TASK_MODEL_EXTERNAL,
  82. TITLE_GENERATION_PROMPT_TEMPLATE,
  83. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  84. WEBHOOK_URL,
  85. WEBUI_AUTH,
  86. WEBUI_NAME,
  87. AppConfig,
  88. reset_config,
  89. )
  90. from open_webui.constants import TASKS
  91. from open_webui.env import (
  92. CHANGELOG,
  93. GLOBAL_LOG_LEVEL,
  94. SAFE_MODE,
  95. SRC_LOG_LEVELS,
  96. VERSION,
  97. WEBUI_BUILD_HASH,
  98. WEBUI_SECRET_KEY,
  99. WEBUI_SESSION_COOKIE_SAME_SITE,
  100. WEBUI_SESSION_COOKIE_SECURE,
  101. WEBUI_URL,
  102. RESET_CONFIG_ON_START,
  103. )
  104. from open_webui.utils.misc import (
  105. add_or_update_system_message,
  106. get_last_user_message,
  107. prepend_to_first_user_message_content,
  108. )
  109. from open_webui.utils.oauth import oauth_manager
  110. from open_webui.utils.payload import convert_payload_openai_to_ollama
  111. from open_webui.utils.response import (
  112. convert_response_ollama_to_openai,
  113. convert_streaming_response_ollama_to_openai,
  114. )
  115. from open_webui.utils.security_headers import SecurityHeadersMiddleware
  116. from open_webui.utils.task import (
  117. moa_response_generation_template,
  118. search_query_generation_template,
  119. title_generation_template,
  120. tools_function_calling_generation_template,
  121. )
  122. from open_webui.utils.tools import get_tools
  123. from open_webui.utils.utils import (
  124. decode_token,
  125. get_admin_user,
  126. get_current_user,
  127. get_http_authorization_cred,
  128. get_verified_user,
  129. )
  130. if SAFE_MODE:
  131. print("SAFE MODE ENABLED")
  132. Functions.deactivate_all_functions()
  133. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  134. log = logging.getLogger(__name__)
  135. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  136. class SPAStaticFiles(StaticFiles):
  137. async def get_response(self, path: str, scope):
  138. try:
  139. return await super().get_response(path, scope)
  140. except (HTTPException, StarletteHTTPException) as ex:
  141. if ex.status_code == 404:
  142. return await super().get_response("index.html", scope)
  143. else:
  144. raise ex
  145. print(
  146. rf"""
  147. ___ __ __ _ _ _ ___
  148. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  149. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  150. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  151. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  152. |_|
  153. v{VERSION} - building the best open-source AI user interface.
  154. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  155. https://github.com/open-webui/open-webui
  156. """
  157. )
  158. @asynccontextmanager
  159. async def lifespan(app: FastAPI):
  160. if RESET_CONFIG_ON_START:
  161. reset_config()
  162. asyncio.create_task(periodic_usage_pool_cleanup())
  163. yield
  164. app = FastAPI(
  165. docs_url="/docs" if ENV == "dev" else None, redoc_url=None, lifespan=lifespan
  166. )
  167. app.state.config = AppConfig()
  168. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  169. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  170. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  171. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  172. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  173. app.state.config.TASK_MODEL = TASK_MODEL
  174. app.state.config.TASK_MODEL_EXTERNAL = TASK_MODEL_EXTERNAL
  175. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = TITLE_GENERATION_PROMPT_TEMPLATE
  176. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  177. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  178. )
  179. app.state.config.ENABLE_SEARCH_QUERY = ENABLE_SEARCH_QUERY
  180. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  181. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  182. )
  183. app.state.MODELS = {}
  184. ##################################
  185. #
  186. # ChatCompletion Middleware
  187. #
  188. ##################################
  189. def get_task_model_id(default_model_id):
  190. # Set the task model
  191. task_model_id = default_model_id
  192. # Check if the user has a custom task model and use that model
  193. if app.state.MODELS[task_model_id]["owned_by"] == "ollama":
  194. if (
  195. app.state.config.TASK_MODEL
  196. and app.state.config.TASK_MODEL in app.state.MODELS
  197. ):
  198. task_model_id = app.state.config.TASK_MODEL
  199. else:
  200. if (
  201. app.state.config.TASK_MODEL_EXTERNAL
  202. and app.state.config.TASK_MODEL_EXTERNAL in app.state.MODELS
  203. ):
  204. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  205. return task_model_id
  206. def get_filter_function_ids(model):
  207. def get_priority(function_id):
  208. function = Functions.get_function_by_id(function_id)
  209. if function is not None and hasattr(function, "valves"):
  210. # TODO: Fix FunctionModel
  211. return (function.valves if function.valves else {}).get("priority", 0)
  212. return 0
  213. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  214. if "info" in model and "meta" in model["info"]:
  215. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  216. filter_ids = list(set(filter_ids))
  217. enabled_filter_ids = [
  218. function.id
  219. for function in Functions.get_functions_by_type("filter", active_only=True)
  220. ]
  221. filter_ids = [
  222. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  223. ]
  224. filter_ids.sort(key=get_priority)
  225. return filter_ids
  226. async def chat_completion_filter_functions_handler(body, model, extra_params):
  227. skip_files = None
  228. filter_ids = get_filter_function_ids(model)
  229. for filter_id in filter_ids:
  230. filter = Functions.get_function_by_id(filter_id)
  231. if not filter:
  232. continue
  233. if filter_id in webui_app.state.FUNCTIONS:
  234. function_module = webui_app.state.FUNCTIONS[filter_id]
  235. else:
  236. function_module, _, _ = load_function_module_by_id(filter_id)
  237. webui_app.state.FUNCTIONS[filter_id] = function_module
  238. # Check if the function has a file_handler variable
  239. if hasattr(function_module, "file_handler"):
  240. skip_files = function_module.file_handler
  241. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  242. valves = Functions.get_function_valves_by_id(filter_id)
  243. function_module.valves = function_module.Valves(
  244. **(valves if valves else {})
  245. )
  246. if not hasattr(function_module, "inlet"):
  247. continue
  248. try:
  249. inlet = function_module.inlet
  250. # Get the signature of the function
  251. sig = inspect.signature(inlet)
  252. params = {"body": body} | {
  253. k: v
  254. for k, v in {
  255. **extra_params,
  256. "__model__": model,
  257. "__id__": filter_id,
  258. }.items()
  259. if k in sig.parameters
  260. }
  261. if "__user__" in params and hasattr(function_module, "UserValves"):
  262. try:
  263. params["__user__"]["valves"] = function_module.UserValves(
  264. **Functions.get_user_valves_by_id_and_user_id(
  265. filter_id, params["__user__"]["id"]
  266. )
  267. )
  268. except Exception as e:
  269. print(e)
  270. if inspect.iscoroutinefunction(inlet):
  271. body = await inlet(**params)
  272. else:
  273. body = inlet(**params)
  274. except Exception as e:
  275. print(f"Error: {e}")
  276. raise e
  277. if skip_files and "files" in body.get("metadata", {}):
  278. del body["metadata"]["files"]
  279. return body, {}
  280. def get_tools_function_calling_payload(messages, task_model_id, content):
  281. user_message = get_last_user_message(messages)
  282. history = "\n".join(
  283. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  284. for message in messages[::-1][:4]
  285. )
  286. prompt = f"History:\n{history}\nQuery: {user_message}"
  287. return {
  288. "model": task_model_id,
  289. "messages": [
  290. {"role": "system", "content": content},
  291. {"role": "user", "content": f"Query: {prompt}"},
  292. ],
  293. "stream": False,
  294. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  295. }
  296. async def get_content_from_response(response) -> Optional[str]:
  297. content = None
  298. if hasattr(response, "body_iterator"):
  299. async for chunk in response.body_iterator:
  300. data = json.loads(chunk.decode("utf-8"))
  301. content = data["choices"][0]["message"]["content"]
  302. # Cleanup any remaining background tasks if necessary
  303. if response.background is not None:
  304. await response.background()
  305. else:
  306. content = response["choices"][0]["message"]["content"]
  307. return content
  308. async def chat_completion_tools_handler(
  309. body: dict, user: UserModel, extra_params: dict
  310. ) -> tuple[dict, dict]:
  311. # If tool_ids field is present, call the functions
  312. metadata = body.get("metadata", {})
  313. tool_ids = metadata.get("tool_ids", None)
  314. log.debug(f"{tool_ids=}")
  315. if not tool_ids:
  316. return body, {}
  317. skip_files = False
  318. contexts = []
  319. citations = []
  320. task_model_id = get_task_model_id(body["model"])
  321. tools = get_tools(
  322. webui_app,
  323. tool_ids,
  324. user,
  325. {
  326. **extra_params,
  327. "__model__": app.state.MODELS[task_model_id],
  328. "__messages__": body["messages"],
  329. "__files__": metadata.get("files", []),
  330. },
  331. )
  332. log.info(f"{tools=}")
  333. specs = [tool["spec"] for tool in tools.values()]
  334. tools_specs = json.dumps(specs)
  335. if app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE != "":
  336. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  337. else:
  338. template = """Available Tools: {{TOOLS}}\nReturn an empty string if no tools match the query. If a function tool matches, construct and return a JSON object in the format {\"name\": \"functionName\", \"parameters\": {\"requiredFunctionParamKey\": \"requiredFunctionParamValue\"}} using the appropriate tool and its parameters. Only return the object and limit the response to the JSON object without additional text."""
  339. tools_function_calling_prompt = tools_function_calling_generation_template(
  340. template, tools_specs
  341. )
  342. log.info(f"{tools_function_calling_prompt=}")
  343. payload = get_tools_function_calling_payload(
  344. body["messages"], task_model_id, tools_function_calling_prompt
  345. )
  346. try:
  347. payload = filter_pipeline(payload, user)
  348. except Exception as e:
  349. raise e
  350. try:
  351. response = await generate_chat_completions(form_data=payload, user=user)
  352. log.debug(f"{response=}")
  353. content = await get_content_from_response(response)
  354. log.debug(f"{content=}")
  355. if not content:
  356. return body, {}
  357. try:
  358. content = content[content.find("{") : content.rfind("}") + 1]
  359. if not content:
  360. raise Exception("No JSON object found in the response")
  361. result = json.loads(content)
  362. tool_function_name = result.get("name", None)
  363. if tool_function_name not in tools:
  364. return body, {}
  365. tool_function_params = result.get("parameters", {})
  366. try:
  367. tool_output = await tools[tool_function_name]["callable"](
  368. **tool_function_params
  369. )
  370. except Exception as e:
  371. tool_output = str(e)
  372. if tools[tool_function_name]["citation"]:
  373. citations.append(
  374. {
  375. "source": {
  376. "name": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  377. },
  378. "document": [tool_output],
  379. "metadata": [{"source": tool_function_name}],
  380. }
  381. )
  382. if tools[tool_function_name]["file_handler"]:
  383. skip_files = True
  384. if isinstance(tool_output, str):
  385. contexts.append(tool_output)
  386. except Exception as e:
  387. log.exception(f"Error: {e}")
  388. content = None
  389. except Exception as e:
  390. log.exception(f"Error: {e}")
  391. content = None
  392. log.debug(f"tool_contexts: {contexts}")
  393. if skip_files and "files" in body.get("metadata", {}):
  394. del body["metadata"]["files"]
  395. return body, {"contexts": contexts, "citations": citations}
  396. async def chat_completion_files_handler(body) -> tuple[dict, dict[str, list]]:
  397. contexts = []
  398. citations = []
  399. if files := body.get("metadata", {}).get("files", None):
  400. contexts, citations = get_rag_context(
  401. files=files,
  402. messages=body["messages"],
  403. embedding_function=retrieval_app.state.EMBEDDING_FUNCTION,
  404. k=retrieval_app.state.config.TOP_K,
  405. reranking_function=retrieval_app.state.sentence_transformer_rf,
  406. r=retrieval_app.state.config.RELEVANCE_THRESHOLD,
  407. hybrid_search=retrieval_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  408. )
  409. log.debug(f"rag_contexts: {contexts}, citations: {citations}")
  410. return body, {"contexts": contexts, "citations": citations}
  411. def is_chat_completion_request(request):
  412. return request.method == "POST" and any(
  413. endpoint in request.url.path
  414. for endpoint in ["/ollama/api/chat", "/chat/completions"]
  415. )
  416. async def get_body_and_model_and_user(request):
  417. # Read the original request body
  418. body = await request.body()
  419. body_str = body.decode("utf-8")
  420. body = json.loads(body_str) if body_str else {}
  421. model_id = body["model"]
  422. if model_id not in app.state.MODELS:
  423. raise Exception("Model not found")
  424. model = app.state.MODELS[model_id]
  425. user = get_current_user(
  426. request,
  427. get_http_authorization_cred(request.headers.get("Authorization")),
  428. )
  429. return body, model, user
  430. class ChatCompletionMiddleware(BaseHTTPMiddleware):
  431. async def dispatch(self, request: Request, call_next):
  432. if not is_chat_completion_request(request):
  433. return await call_next(request)
  434. log.debug(f"request.url.path: {request.url.path}")
  435. try:
  436. body, model, user = await get_body_and_model_and_user(request)
  437. except Exception as e:
  438. return JSONResponse(
  439. status_code=status.HTTP_400_BAD_REQUEST,
  440. content={"detail": str(e)},
  441. )
  442. metadata = {
  443. "chat_id": body.pop("chat_id", None),
  444. "message_id": body.pop("id", None),
  445. "session_id": body.pop("session_id", None),
  446. "tool_ids": body.get("tool_ids", None),
  447. "files": body.get("files", None),
  448. }
  449. body["metadata"] = metadata
  450. extra_params = {
  451. "__event_emitter__": get_event_emitter(metadata),
  452. "__event_call__": get_event_call(metadata),
  453. "__user__": {
  454. "id": user.id,
  455. "email": user.email,
  456. "name": user.name,
  457. "role": user.role,
  458. },
  459. }
  460. # Initialize data_items to store additional data to be sent to the client
  461. # Initalize contexts and citation
  462. data_items = []
  463. contexts = []
  464. citations = []
  465. try:
  466. body, flags = await chat_completion_filter_functions_handler(
  467. body, model, extra_params
  468. )
  469. except Exception as e:
  470. return JSONResponse(
  471. status_code=status.HTTP_400_BAD_REQUEST,
  472. content={"detail": str(e)},
  473. )
  474. metadata = {
  475. **metadata,
  476. "tool_ids": body.pop("tool_ids", None),
  477. "files": body.pop("files", None),
  478. }
  479. body["metadata"] = metadata
  480. try:
  481. body, flags = await chat_completion_tools_handler(body, user, extra_params)
  482. contexts.extend(flags.get("contexts", []))
  483. citations.extend(flags.get("citations", []))
  484. except Exception as e:
  485. log.exception(e)
  486. try:
  487. body, flags = await chat_completion_files_handler(body)
  488. contexts.extend(flags.get("contexts", []))
  489. citations.extend(flags.get("citations", []))
  490. except Exception as e:
  491. log.exception(e)
  492. # If context is not empty, insert it into the messages
  493. if len(contexts) > 0:
  494. context_string = "/n".join(contexts).strip()
  495. prompt = get_last_user_message(body["messages"])
  496. if prompt is None:
  497. raise Exception("No user message found")
  498. if (
  499. retrieval_app.state.config.RELEVANCE_THRESHOLD == 0
  500. and context_string.strip() == ""
  501. ):
  502. log.debug(
  503. f"With a 0 relevancy threshold for RAG, the context cannot be empty"
  504. )
  505. # Workaround for Ollama 2.0+ system prompt issue
  506. # TODO: replace with add_or_update_system_message
  507. if model["owned_by"] == "ollama":
  508. body["messages"] = prepend_to_first_user_message_content(
  509. rag_template(
  510. retrieval_app.state.config.RAG_TEMPLATE, context_string, prompt
  511. ),
  512. body["messages"],
  513. )
  514. else:
  515. body["messages"] = add_or_update_system_message(
  516. rag_template(
  517. retrieval_app.state.config.RAG_TEMPLATE, context_string, prompt
  518. ),
  519. body["messages"],
  520. )
  521. # If there are citations, add them to the data_items
  522. if len(citations) > 0:
  523. data_items.append({"citations": citations})
  524. modified_body_bytes = json.dumps(body).encode("utf-8")
  525. # Replace the request body with the modified one
  526. request._body = modified_body_bytes
  527. # Set custom header to ensure content-length matches new body length
  528. request.headers.__dict__["_list"] = [
  529. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  530. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  531. ]
  532. response = await call_next(request)
  533. if not isinstance(response, StreamingResponse):
  534. return response
  535. content_type = response.headers["Content-Type"]
  536. is_openai = "text/event-stream" in content_type
  537. is_ollama = "application/x-ndjson" in content_type
  538. if not is_openai and not is_ollama:
  539. return response
  540. def wrap_item(item):
  541. return f"data: {item}\n\n" if is_openai else f"{item}\n"
  542. async def stream_wrapper(original_generator, data_items):
  543. for item in data_items:
  544. yield wrap_item(json.dumps(item))
  545. async for data in original_generator:
  546. yield data
  547. return StreamingResponse(
  548. stream_wrapper(response.body_iterator, data_items),
  549. headers=dict(response.headers),
  550. )
  551. async def _receive(self, body: bytes):
  552. return {"type": "http.request", "body": body, "more_body": False}
  553. app.add_middleware(ChatCompletionMiddleware)
  554. ##################################
  555. #
  556. # Pipeline Middleware
  557. #
  558. ##################################
  559. def get_sorted_filters(model_id):
  560. filters = [
  561. model
  562. for model in app.state.MODELS.values()
  563. if "pipeline" in model
  564. and "type" in model["pipeline"]
  565. and model["pipeline"]["type"] == "filter"
  566. and (
  567. model["pipeline"]["pipelines"] == ["*"]
  568. or any(
  569. model_id == target_model_id
  570. for target_model_id in model["pipeline"]["pipelines"]
  571. )
  572. )
  573. ]
  574. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  575. return sorted_filters
  576. def filter_pipeline(payload, user):
  577. user = {"id": user.id, "email": user.email, "name": user.name, "role": user.role}
  578. model_id = payload["model"]
  579. sorted_filters = get_sorted_filters(model_id)
  580. model = app.state.MODELS[model_id]
  581. if "pipeline" in model:
  582. sorted_filters.append(model)
  583. for filter in sorted_filters:
  584. r = None
  585. try:
  586. urlIdx = filter["urlIdx"]
  587. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  588. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  589. if key == "":
  590. continue
  591. headers = {"Authorization": f"Bearer {key}"}
  592. r = requests.post(
  593. f"{url}/{filter['id']}/filter/inlet",
  594. headers=headers,
  595. json={
  596. "user": user,
  597. "body": payload,
  598. },
  599. )
  600. r.raise_for_status()
  601. payload = r.json()
  602. except Exception as e:
  603. # Handle connection error here
  604. print(f"Connection error: {e}")
  605. if r is not None:
  606. res = r.json()
  607. if "detail" in res:
  608. raise Exception(r.status_code, res["detail"])
  609. return payload
  610. class PipelineMiddleware(BaseHTTPMiddleware):
  611. async def dispatch(self, request: Request, call_next):
  612. if not is_chat_completion_request(request):
  613. return await call_next(request)
  614. log.debug(f"request.url.path: {request.url.path}")
  615. # Read the original request body
  616. body = await request.body()
  617. # Decode body to string
  618. body_str = body.decode("utf-8")
  619. # Parse string to JSON
  620. data = json.loads(body_str) if body_str else {}
  621. try:
  622. user = get_current_user(
  623. request,
  624. get_http_authorization_cred(request.headers["Authorization"]),
  625. )
  626. except KeyError as e:
  627. if len(e.args) > 1:
  628. return JSONResponse(
  629. status_code=e.args[0],
  630. content={"detail": e.args[1]},
  631. )
  632. else:
  633. return JSONResponse(
  634. status_code=status.HTTP_401_UNAUTHORIZED,
  635. content={"detail": "Not authenticated"},
  636. )
  637. try:
  638. data = filter_pipeline(data, user)
  639. except Exception as e:
  640. if len(e.args) > 1:
  641. return JSONResponse(
  642. status_code=e.args[0],
  643. content={"detail": e.args[1]},
  644. )
  645. else:
  646. return JSONResponse(
  647. status_code=status.HTTP_400_BAD_REQUEST,
  648. content={"detail": str(e)},
  649. )
  650. modified_body_bytes = json.dumps(data).encode("utf-8")
  651. # Replace the request body with the modified one
  652. request._body = modified_body_bytes
  653. # Set custom header to ensure content-length matches new body length
  654. request.headers.__dict__["_list"] = [
  655. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  656. *[(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"],
  657. ]
  658. response = await call_next(request)
  659. return response
  660. async def _receive(self, body: bytes):
  661. return {"type": "http.request", "body": body, "more_body": False}
  662. app.add_middleware(PipelineMiddleware)
  663. app.add_middleware(
  664. CORSMiddleware,
  665. allow_origins=CORS_ALLOW_ORIGIN,
  666. allow_credentials=True,
  667. allow_methods=["*"],
  668. allow_headers=["*"],
  669. )
  670. app.add_middleware(SecurityHeadersMiddleware)
  671. @app.middleware("http")
  672. async def commit_session_after_request(request: Request, call_next):
  673. response = await call_next(request)
  674. log.debug("Commit session after request")
  675. Session.commit()
  676. return response
  677. @app.middleware("http")
  678. async def check_url(request: Request, call_next):
  679. if len(app.state.MODELS) == 0:
  680. await get_all_models()
  681. else:
  682. pass
  683. start_time = int(time.time())
  684. response = await call_next(request)
  685. process_time = int(time.time()) - start_time
  686. response.headers["X-Process-Time"] = str(process_time)
  687. return response
  688. @app.middleware("http")
  689. async def update_embedding_function(request: Request, call_next):
  690. response = await call_next(request)
  691. if "/embedding/update" in request.url.path:
  692. webui_app.state.EMBEDDING_FUNCTION = retrieval_app.state.EMBEDDING_FUNCTION
  693. return response
  694. @app.middleware("http")
  695. async def inspect_websocket(request: Request, call_next):
  696. if (
  697. "/ws/socket.io" in request.url.path
  698. and request.query_params.get("transport") == "websocket"
  699. ):
  700. upgrade = (request.headers.get("Upgrade") or "").lower()
  701. connection = (request.headers.get("Connection") or "").lower().split(",")
  702. # Check that there's the correct headers for an upgrade, else reject the connection
  703. # This is to work around this upstream issue: https://github.com/miguelgrinberg/python-engineio/issues/367
  704. if upgrade != "websocket" or "upgrade" not in connection:
  705. return JSONResponse(
  706. status_code=status.HTTP_400_BAD_REQUEST,
  707. content={"detail": "Invalid WebSocket upgrade request"},
  708. )
  709. return await call_next(request)
  710. app.mount("/ws", socket_app)
  711. app.mount("/ollama", ollama_app)
  712. app.mount("/openai", openai_app)
  713. app.mount("/images/api/v1", images_app)
  714. app.mount("/audio/api/v1", audio_app)
  715. app.mount("/retrieval/api/v1", retrieval_app)
  716. app.mount("/api/v1", webui_app)
  717. webui_app.state.EMBEDDING_FUNCTION = retrieval_app.state.EMBEDDING_FUNCTION
  718. async def get_all_models():
  719. # TODO: Optimize this function
  720. pipe_models = []
  721. openai_models = []
  722. ollama_models = []
  723. pipe_models = await get_pipe_models()
  724. if app.state.config.ENABLE_OPENAI_API:
  725. openai_models = await get_openai_models()
  726. openai_models = openai_models["data"]
  727. if app.state.config.ENABLE_OLLAMA_API:
  728. ollama_models = await get_ollama_models()
  729. ollama_models = [
  730. {
  731. "id": model["model"],
  732. "name": model["name"],
  733. "object": "model",
  734. "created": int(time.time()),
  735. "owned_by": "ollama",
  736. "ollama": model,
  737. }
  738. for model in ollama_models["models"]
  739. ]
  740. models = pipe_models + openai_models + ollama_models
  741. global_action_ids = [
  742. function.id for function in Functions.get_global_action_functions()
  743. ]
  744. enabled_action_ids = [
  745. function.id
  746. for function in Functions.get_functions_by_type("action", active_only=True)
  747. ]
  748. custom_models = Models.get_all_models()
  749. for custom_model in custom_models:
  750. if custom_model.base_model_id is None:
  751. for model in models:
  752. if (
  753. custom_model.id == model["id"]
  754. or custom_model.id == model["id"].split(":")[0]
  755. ):
  756. model["name"] = custom_model.name
  757. model["info"] = custom_model.model_dump()
  758. action_ids = []
  759. if "info" in model and "meta" in model["info"]:
  760. action_ids.extend(model["info"]["meta"].get("actionIds", []))
  761. model["action_ids"] = action_ids
  762. else:
  763. owned_by = "openai"
  764. pipe = None
  765. action_ids = []
  766. for model in models:
  767. if (
  768. custom_model.base_model_id == model["id"]
  769. or custom_model.base_model_id == model["id"].split(":")[0]
  770. ):
  771. owned_by = model["owned_by"]
  772. if "pipe" in model:
  773. pipe = model["pipe"]
  774. if "info" in model and "meta" in model["info"]:
  775. action_ids.extend(model["info"]["meta"].get("actionIds", []))
  776. break
  777. models.append(
  778. {
  779. "id": custom_model.id,
  780. "name": custom_model.name,
  781. "object": "model",
  782. "created": custom_model.created_at,
  783. "owned_by": owned_by,
  784. "info": custom_model.model_dump(),
  785. "preset": True,
  786. **({"pipe": pipe} if pipe is not None else {}),
  787. "action_ids": action_ids,
  788. }
  789. )
  790. for model in models:
  791. action_ids = []
  792. if "action_ids" in model:
  793. action_ids = model["action_ids"]
  794. del model["action_ids"]
  795. action_ids = action_ids + global_action_ids
  796. action_ids = list(set(action_ids))
  797. action_ids = [
  798. action_id for action_id in action_ids if action_id in enabled_action_ids
  799. ]
  800. model["actions"] = []
  801. for action_id in action_ids:
  802. action = Functions.get_function_by_id(action_id)
  803. if action is None:
  804. raise Exception(f"Action not found: {action_id}")
  805. if action_id in webui_app.state.FUNCTIONS:
  806. function_module = webui_app.state.FUNCTIONS[action_id]
  807. else:
  808. function_module, _, _ = load_function_module_by_id(action_id)
  809. webui_app.state.FUNCTIONS[action_id] = function_module
  810. __webui__ = False
  811. if hasattr(function_module, "__webui__"):
  812. __webui__ = function_module.__webui__
  813. if hasattr(function_module, "actions"):
  814. actions = function_module.actions
  815. model["actions"].extend(
  816. [
  817. {
  818. "id": f"{action_id}.{_action['id']}",
  819. "name": _action.get(
  820. "name", f"{action.name} ({_action['id']})"
  821. ),
  822. "description": action.meta.description,
  823. "icon_url": _action.get(
  824. "icon_url", action.meta.manifest.get("icon_url", None)
  825. ),
  826. **({"__webui__": __webui__} if __webui__ else {}),
  827. }
  828. for _action in actions
  829. ]
  830. )
  831. else:
  832. model["actions"].append(
  833. {
  834. "id": action_id,
  835. "name": action.name,
  836. "description": action.meta.description,
  837. "icon_url": action.meta.manifest.get("icon_url", None),
  838. **({"__webui__": __webui__} if __webui__ else {}),
  839. }
  840. )
  841. app.state.MODELS = {model["id"]: model for model in models}
  842. webui_app.state.MODELS = app.state.MODELS
  843. return models
  844. @app.get("/api/models")
  845. async def get_models(user=Depends(get_verified_user)):
  846. models = await get_all_models()
  847. # Filter out filter pipelines
  848. models = [
  849. model
  850. for model in models
  851. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  852. ]
  853. if app.state.config.ENABLE_MODEL_FILTER:
  854. if user.role == "user":
  855. models = list(
  856. filter(
  857. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  858. models,
  859. )
  860. )
  861. return {"data": models}
  862. return {"data": models}
  863. @app.post("/api/chat/completions")
  864. async def generate_chat_completions(form_data: dict, user=Depends(get_verified_user)):
  865. model_id = form_data["model"]
  866. if model_id not in app.state.MODELS:
  867. raise HTTPException(
  868. status_code=status.HTTP_404_NOT_FOUND,
  869. detail="Model not found",
  870. )
  871. if app.state.config.ENABLE_MODEL_FILTER:
  872. if user.role == "user" and model_id not in app.state.config.MODEL_FILTER_LIST:
  873. raise HTTPException(
  874. status_code=status.HTTP_403_FORBIDDEN,
  875. detail="Model not found",
  876. )
  877. model = app.state.MODELS[model_id]
  878. if model.get("pipe"):
  879. return await generate_function_chat_completion(form_data, user=user)
  880. if model["owned_by"] == "ollama":
  881. # Using /ollama/api/chat endpoint
  882. form_data = convert_payload_openai_to_ollama(form_data)
  883. form_data = GenerateChatCompletionForm(**form_data)
  884. response = await generate_ollama_chat_completion(form_data=form_data, user=user)
  885. if form_data.stream:
  886. response.headers["content-type"] = "text/event-stream"
  887. return StreamingResponse(
  888. convert_streaming_response_ollama_to_openai(response),
  889. headers=dict(response.headers),
  890. )
  891. else:
  892. return convert_response_ollama_to_openai(response)
  893. else:
  894. return await generate_openai_chat_completion(form_data, user=user)
  895. @app.post("/api/chat/completed")
  896. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  897. data = form_data
  898. model_id = data["model"]
  899. if model_id not in app.state.MODELS:
  900. raise HTTPException(
  901. status_code=status.HTTP_404_NOT_FOUND,
  902. detail="Model not found",
  903. )
  904. model = app.state.MODELS[model_id]
  905. sorted_filters = get_sorted_filters(model_id)
  906. if "pipeline" in model:
  907. sorted_filters = [model] + sorted_filters
  908. for filter in sorted_filters:
  909. r = None
  910. try:
  911. urlIdx = filter["urlIdx"]
  912. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  913. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  914. if key != "":
  915. headers = {"Authorization": f"Bearer {key}"}
  916. r = requests.post(
  917. f"{url}/{filter['id']}/filter/outlet",
  918. headers=headers,
  919. json={
  920. "user": {
  921. "id": user.id,
  922. "name": user.name,
  923. "email": user.email,
  924. "role": user.role,
  925. },
  926. "body": data,
  927. },
  928. )
  929. r.raise_for_status()
  930. data = r.json()
  931. except Exception as e:
  932. # Handle connection error here
  933. print(f"Connection error: {e}")
  934. if r is not None:
  935. try:
  936. res = r.json()
  937. if "detail" in res:
  938. return JSONResponse(
  939. status_code=r.status_code,
  940. content=res,
  941. )
  942. except Exception:
  943. pass
  944. else:
  945. pass
  946. __event_emitter__ = get_event_emitter(
  947. {
  948. "chat_id": data["chat_id"],
  949. "message_id": data["id"],
  950. "session_id": data["session_id"],
  951. }
  952. )
  953. __event_call__ = get_event_call(
  954. {
  955. "chat_id": data["chat_id"],
  956. "message_id": data["id"],
  957. "session_id": data["session_id"],
  958. }
  959. )
  960. def get_priority(function_id):
  961. function = Functions.get_function_by_id(function_id)
  962. if function is not None and hasattr(function, "valves"):
  963. # TODO: Fix FunctionModel to include vavles
  964. return (function.valves if function.valves else {}).get("priority", 0)
  965. return 0
  966. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  967. if "info" in model and "meta" in model["info"]:
  968. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  969. filter_ids = list(set(filter_ids))
  970. enabled_filter_ids = [
  971. function.id
  972. for function in Functions.get_functions_by_type("filter", active_only=True)
  973. ]
  974. filter_ids = [
  975. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  976. ]
  977. # Sort filter_ids by priority, using the get_priority function
  978. filter_ids.sort(key=get_priority)
  979. for filter_id in filter_ids:
  980. filter = Functions.get_function_by_id(filter_id)
  981. if not filter:
  982. continue
  983. if filter_id in webui_app.state.FUNCTIONS:
  984. function_module = webui_app.state.FUNCTIONS[filter_id]
  985. else:
  986. function_module, _, _ = load_function_module_by_id(filter_id)
  987. webui_app.state.FUNCTIONS[filter_id] = function_module
  988. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  989. valves = Functions.get_function_valves_by_id(filter_id)
  990. function_module.valves = function_module.Valves(
  991. **(valves if valves else {})
  992. )
  993. if not hasattr(function_module, "outlet"):
  994. continue
  995. try:
  996. outlet = function_module.outlet
  997. # Get the signature of the function
  998. sig = inspect.signature(outlet)
  999. params = {"body": data}
  1000. # Extra parameters to be passed to the function
  1001. extra_params = {
  1002. "__model__": model,
  1003. "__id__": filter_id,
  1004. "__event_emitter__": __event_emitter__,
  1005. "__event_call__": __event_call__,
  1006. }
  1007. # Add extra params in contained in function signature
  1008. for key, value in extra_params.items():
  1009. if key in sig.parameters:
  1010. params[key] = value
  1011. if "__user__" in sig.parameters:
  1012. __user__ = {
  1013. "id": user.id,
  1014. "email": user.email,
  1015. "name": user.name,
  1016. "role": user.role,
  1017. }
  1018. try:
  1019. if hasattr(function_module, "UserValves"):
  1020. __user__["valves"] = function_module.UserValves(
  1021. **Functions.get_user_valves_by_id_and_user_id(
  1022. filter_id, user.id
  1023. )
  1024. )
  1025. except Exception as e:
  1026. print(e)
  1027. params = {**params, "__user__": __user__}
  1028. if inspect.iscoroutinefunction(outlet):
  1029. data = await outlet(**params)
  1030. else:
  1031. data = outlet(**params)
  1032. except Exception as e:
  1033. print(f"Error: {e}")
  1034. return JSONResponse(
  1035. status_code=status.HTTP_400_BAD_REQUEST,
  1036. content={"detail": str(e)},
  1037. )
  1038. return data
  1039. @app.post("/api/chat/actions/{action_id}")
  1040. async def chat_action(action_id: str, form_data: dict, user=Depends(get_verified_user)):
  1041. if "." in action_id:
  1042. action_id, sub_action_id = action_id.split(".")
  1043. else:
  1044. sub_action_id = None
  1045. action = Functions.get_function_by_id(action_id)
  1046. if not action:
  1047. raise HTTPException(
  1048. status_code=status.HTTP_404_NOT_FOUND,
  1049. detail="Action not found",
  1050. )
  1051. data = form_data
  1052. model_id = data["model"]
  1053. if model_id not in app.state.MODELS:
  1054. raise HTTPException(
  1055. status_code=status.HTTP_404_NOT_FOUND,
  1056. detail="Model not found",
  1057. )
  1058. model = app.state.MODELS[model_id]
  1059. __event_emitter__ = get_event_emitter(
  1060. {
  1061. "chat_id": data["chat_id"],
  1062. "message_id": data["id"],
  1063. "session_id": data["session_id"],
  1064. }
  1065. )
  1066. __event_call__ = get_event_call(
  1067. {
  1068. "chat_id": data["chat_id"],
  1069. "message_id": data["id"],
  1070. "session_id": data["session_id"],
  1071. }
  1072. )
  1073. if action_id in webui_app.state.FUNCTIONS:
  1074. function_module = webui_app.state.FUNCTIONS[action_id]
  1075. else:
  1076. function_module, _, _ = load_function_module_by_id(action_id)
  1077. webui_app.state.FUNCTIONS[action_id] = function_module
  1078. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  1079. valves = Functions.get_function_valves_by_id(action_id)
  1080. function_module.valves = function_module.Valves(**(valves if valves else {}))
  1081. if hasattr(function_module, "action"):
  1082. try:
  1083. action = function_module.action
  1084. # Get the signature of the function
  1085. sig = inspect.signature(action)
  1086. params = {"body": data}
  1087. # Extra parameters to be passed to the function
  1088. extra_params = {
  1089. "__model__": model,
  1090. "__id__": sub_action_id if sub_action_id is not None else action_id,
  1091. "__event_emitter__": __event_emitter__,
  1092. "__event_call__": __event_call__,
  1093. }
  1094. # Add extra params in contained in function signature
  1095. for key, value in extra_params.items():
  1096. if key in sig.parameters:
  1097. params[key] = value
  1098. if "__user__" in sig.parameters:
  1099. __user__ = {
  1100. "id": user.id,
  1101. "email": user.email,
  1102. "name": user.name,
  1103. "role": user.role,
  1104. }
  1105. try:
  1106. if hasattr(function_module, "UserValves"):
  1107. __user__["valves"] = function_module.UserValves(
  1108. **Functions.get_user_valves_by_id_and_user_id(
  1109. action_id, user.id
  1110. )
  1111. )
  1112. except Exception as e:
  1113. print(e)
  1114. params = {**params, "__user__": __user__}
  1115. if inspect.iscoroutinefunction(action):
  1116. data = await action(**params)
  1117. else:
  1118. data = action(**params)
  1119. except Exception as e:
  1120. print(f"Error: {e}")
  1121. return JSONResponse(
  1122. status_code=status.HTTP_400_BAD_REQUEST,
  1123. content={"detail": str(e)},
  1124. )
  1125. return data
  1126. ##################################
  1127. #
  1128. # Task Endpoints
  1129. #
  1130. ##################################
  1131. # TODO: Refactor task API endpoints below into a separate file
  1132. @app.get("/api/task/config")
  1133. async def get_task_config(user=Depends(get_verified_user)):
  1134. return {
  1135. "TASK_MODEL": app.state.config.TASK_MODEL,
  1136. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1137. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1138. "ENABLE_SEARCH_QUERY": app.state.config.ENABLE_SEARCH_QUERY,
  1139. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1140. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1141. }
  1142. class TaskConfigForm(BaseModel):
  1143. TASK_MODEL: Optional[str]
  1144. TASK_MODEL_EXTERNAL: Optional[str]
  1145. TITLE_GENERATION_PROMPT_TEMPLATE: str
  1146. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE: str
  1147. ENABLE_SEARCH_QUERY: bool
  1148. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  1149. @app.post("/api/task/config/update")
  1150. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  1151. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  1152. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  1153. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  1154. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  1155. )
  1156. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  1157. form_data.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1158. )
  1159. app.state.config.ENABLE_SEARCH_QUERY = form_data.ENABLE_SEARCH_QUERY
  1160. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  1161. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  1162. )
  1163. return {
  1164. "TASK_MODEL": app.state.config.TASK_MODEL,
  1165. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  1166. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  1167. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  1168. "ENABLE_SEARCH_QUERY": app.state.config.ENABLE_SEARCH_QUERY,
  1169. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  1170. }
  1171. @app.post("/api/task/title/completions")
  1172. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  1173. print("generate_title")
  1174. model_id = form_data["model"]
  1175. if model_id not in app.state.MODELS:
  1176. raise HTTPException(
  1177. status_code=status.HTTP_404_NOT_FOUND,
  1178. detail="Model not found",
  1179. )
  1180. # Check if the user has a custom task model
  1181. # If the user has a custom task model, use that model
  1182. task_model_id = get_task_model_id(model_id)
  1183. print(task_model_id)
  1184. model = app.state.MODELS[task_model_id]
  1185. if app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE != "":
  1186. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  1187. else:
  1188. template = """Create a concise, 3-5 word title with an emoji as a title for the prompt in the given language. Suitable Emojis for the summary can be used to enhance understanding but avoid quotation marks or special formatting. RESPOND ONLY WITH THE TITLE TEXT.
  1189. Examples of titles:
  1190. 📉 Stock Market Trends
  1191. 🍪 Perfect Chocolate Chip Recipe
  1192. Evolution of Music Streaming
  1193. Remote Work Productivity Tips
  1194. Artificial Intelligence in Healthcare
  1195. 🎮 Video Game Development Insights
  1196. Prompt: {{prompt:middletruncate:8000}}"""
  1197. content = title_generation_template(
  1198. template,
  1199. form_data["prompt"],
  1200. {
  1201. "name": user.name,
  1202. "location": user.info.get("location") if user.info else None,
  1203. },
  1204. )
  1205. payload = {
  1206. "model": task_model_id,
  1207. "messages": [{"role": "user", "content": content}],
  1208. "stream": False,
  1209. **(
  1210. {"max_tokens": 50}
  1211. if app.state.MODELS[task_model_id]["owned_by"] == "ollama"
  1212. else {
  1213. "max_completion_tokens": 50,
  1214. }
  1215. ),
  1216. "chat_id": form_data.get("chat_id", None),
  1217. "metadata": {"task": str(TASKS.TITLE_GENERATION), "task_body": form_data},
  1218. }
  1219. log.debug(payload)
  1220. # Handle pipeline filters
  1221. try:
  1222. payload = filter_pipeline(payload, user)
  1223. except Exception as e:
  1224. if len(e.args) > 1:
  1225. return JSONResponse(
  1226. status_code=e.args[0],
  1227. content={"detail": e.args[1]},
  1228. )
  1229. else:
  1230. return JSONResponse(
  1231. status_code=status.HTTP_400_BAD_REQUEST,
  1232. content={"detail": str(e)},
  1233. )
  1234. if "chat_id" in payload:
  1235. del payload["chat_id"]
  1236. return await generate_chat_completions(form_data=payload, user=user)
  1237. @app.post("/api/task/query/completions")
  1238. async def generate_search_query(form_data: dict, user=Depends(get_verified_user)):
  1239. print("generate_search_query")
  1240. if not app.state.config.ENABLE_SEARCH_QUERY:
  1241. raise HTTPException(
  1242. status_code=status.HTTP_400_BAD_REQUEST,
  1243. detail=f"Search query generation is disabled",
  1244. )
  1245. model_id = form_data["model"]
  1246. if model_id not in app.state.MODELS:
  1247. raise HTTPException(
  1248. status_code=status.HTTP_404_NOT_FOUND,
  1249. detail="Model not found",
  1250. )
  1251. # Check if the user has a custom task model
  1252. # If the user has a custom task model, use that model
  1253. task_model_id = get_task_model_id(model_id)
  1254. print(task_model_id)
  1255. model = app.state.MODELS[task_model_id]
  1256. if app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE != "":
  1257. template = app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  1258. else:
  1259. template = """Given the user's message and interaction history, decide if a web search is necessary. You must be concise and exclusively provide a search query if one is necessary. Refrain from verbose responses or any additional commentary. Prefer suggesting a search if uncertain to provide comprehensive or updated information. If a search isn't needed at all, respond with an empty string. Default to a search query when in doubt. Today's date is {{CURRENT_DATE}}.
  1260. User Message:
  1261. {{prompt:end:4000}}
  1262. Interaction History:
  1263. {{MESSAGES:END:6}}
  1264. Search Query:"""
  1265. content = search_query_generation_template(
  1266. template, form_data["messages"], {"name": user.name}
  1267. )
  1268. print("content", content)
  1269. payload = {
  1270. "model": task_model_id,
  1271. "messages": [{"role": "user", "content": content}],
  1272. "stream": False,
  1273. **(
  1274. {"max_tokens": 30}
  1275. if app.state.MODELS[task_model_id]["owned_by"] == "ollama"
  1276. else {
  1277. "max_completion_tokens": 30,
  1278. }
  1279. ),
  1280. "metadata": {"task": str(TASKS.QUERY_GENERATION), "task_body": form_data},
  1281. }
  1282. log.debug(payload)
  1283. # Handle pipeline filters
  1284. try:
  1285. payload = filter_pipeline(payload, user)
  1286. except Exception as e:
  1287. if len(e.args) > 1:
  1288. return JSONResponse(
  1289. status_code=e.args[0],
  1290. content={"detail": e.args[1]},
  1291. )
  1292. else:
  1293. return JSONResponse(
  1294. status_code=status.HTTP_400_BAD_REQUEST,
  1295. content={"detail": str(e)},
  1296. )
  1297. if "chat_id" in payload:
  1298. del payload["chat_id"]
  1299. return await generate_chat_completions(form_data=payload, user=user)
  1300. @app.post("/api/task/emoji/completions")
  1301. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  1302. print("generate_emoji")
  1303. model_id = form_data["model"]
  1304. if model_id not in app.state.MODELS:
  1305. raise HTTPException(
  1306. status_code=status.HTTP_404_NOT_FOUND,
  1307. detail="Model not found",
  1308. )
  1309. # Check if the user has a custom task model
  1310. # If the user has a custom task model, use that model
  1311. task_model_id = get_task_model_id(model_id)
  1312. print(task_model_id)
  1313. model = app.state.MODELS[task_model_id]
  1314. template = '''
  1315. 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., 😊, 😢, 😡, 😱).
  1316. Message: """{{prompt}}"""
  1317. '''
  1318. content = title_generation_template(
  1319. template,
  1320. form_data["prompt"],
  1321. {
  1322. "name": user.name,
  1323. "location": user.info.get("location") if user.info else None,
  1324. },
  1325. )
  1326. payload = {
  1327. "model": task_model_id,
  1328. "messages": [{"role": "user", "content": content}],
  1329. "stream": False,
  1330. **(
  1331. {"max_tokens": 4}
  1332. if app.state.MODELS[task_model_id]["owned_by"] == "ollama"
  1333. else {
  1334. "max_completion_tokens": 4,
  1335. }
  1336. ),
  1337. "chat_id": form_data.get("chat_id", None),
  1338. "metadata": {"task": str(TASKS.EMOJI_GENERATION), "task_body": form_data},
  1339. }
  1340. log.debug(payload)
  1341. # Handle pipeline filters
  1342. try:
  1343. payload = filter_pipeline(payload, user)
  1344. except Exception as e:
  1345. if len(e.args) > 1:
  1346. return JSONResponse(
  1347. status_code=e.args[0],
  1348. content={"detail": e.args[1]},
  1349. )
  1350. else:
  1351. return JSONResponse(
  1352. status_code=status.HTTP_400_BAD_REQUEST,
  1353. content={"detail": str(e)},
  1354. )
  1355. if "chat_id" in payload:
  1356. del payload["chat_id"]
  1357. return await generate_chat_completions(form_data=payload, user=user)
  1358. @app.post("/api/task/moa/completions")
  1359. async def generate_moa_response(form_data: dict, user=Depends(get_verified_user)):
  1360. print("generate_moa_response")
  1361. model_id = form_data["model"]
  1362. if model_id not in app.state.MODELS:
  1363. raise HTTPException(
  1364. status_code=status.HTTP_404_NOT_FOUND,
  1365. detail="Model not found",
  1366. )
  1367. # Check if the user has a custom task model
  1368. # If the user has a custom task model, use that model
  1369. task_model_id = get_task_model_id(model_id)
  1370. print(task_model_id)
  1371. model = app.state.MODELS[task_model_id]
  1372. template = """You have been provided with a set of responses from various models to the latest user query: "{{prompt}}"
  1373. Your task is to synthesize these responses into a single, high-quality response. It is crucial to critically evaluate the information provided in these responses, recognizing that some of it may be biased or incorrect. Your response should not simply replicate the given answers but should offer a refined, accurate, and comprehensive reply to the instruction. Ensure your response is well-structured, coherent, and adheres to the highest standards of accuracy and reliability.
  1374. Responses from models: {{responses}}"""
  1375. content = moa_response_generation_template(
  1376. template,
  1377. form_data["prompt"],
  1378. form_data["responses"],
  1379. )
  1380. payload = {
  1381. "model": task_model_id,
  1382. "messages": [{"role": "user", "content": content}],
  1383. "stream": form_data.get("stream", False),
  1384. "chat_id": form_data.get("chat_id", None),
  1385. "metadata": {
  1386. "task": str(TASKS.MOA_RESPONSE_GENERATION),
  1387. "task_body": form_data,
  1388. },
  1389. }
  1390. log.debug(payload)
  1391. try:
  1392. payload = filter_pipeline(payload, user)
  1393. except Exception as e:
  1394. if len(e.args) > 1:
  1395. return JSONResponse(
  1396. status_code=e.args[0],
  1397. content={"detail": e.args[1]},
  1398. )
  1399. else:
  1400. return JSONResponse(
  1401. status_code=status.HTTP_400_BAD_REQUEST,
  1402. content={"detail": str(e)},
  1403. )
  1404. if "chat_id" in payload:
  1405. del payload["chat_id"]
  1406. return await generate_chat_completions(form_data=payload, user=user)
  1407. ##################################
  1408. #
  1409. # Pipelines Endpoints
  1410. #
  1411. ##################################
  1412. # TODO: Refactor pipelines API endpoints below into a separate file
  1413. @app.get("/api/pipelines/list")
  1414. async def get_pipelines_list(user=Depends(get_admin_user)):
  1415. responses = await get_openai_models(raw=True)
  1416. print(responses)
  1417. urlIdxs = [
  1418. idx
  1419. for idx, response in enumerate(responses)
  1420. if response is not None and "pipelines" in response
  1421. ]
  1422. return {
  1423. "data": [
  1424. {
  1425. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  1426. "idx": urlIdx,
  1427. }
  1428. for urlIdx in urlIdxs
  1429. ]
  1430. }
  1431. @app.post("/api/pipelines/upload")
  1432. async def upload_pipeline(
  1433. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  1434. ):
  1435. print("upload_pipeline", urlIdx, file.filename)
  1436. # Check if the uploaded file is a python file
  1437. if not (file.filename and file.filename.endswith(".py")):
  1438. raise HTTPException(
  1439. status_code=status.HTTP_400_BAD_REQUEST,
  1440. detail="Only Python (.py) files are allowed.",
  1441. )
  1442. upload_folder = f"{CACHE_DIR}/pipelines"
  1443. os.makedirs(upload_folder, exist_ok=True)
  1444. file_path = os.path.join(upload_folder, file.filename)
  1445. r = None
  1446. try:
  1447. # Save the uploaded file
  1448. with open(file_path, "wb") as buffer:
  1449. shutil.copyfileobj(file.file, buffer)
  1450. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1451. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1452. headers = {"Authorization": f"Bearer {key}"}
  1453. with open(file_path, "rb") as f:
  1454. files = {"file": f}
  1455. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1456. r.raise_for_status()
  1457. data = r.json()
  1458. return {**data}
  1459. except Exception as e:
  1460. # Handle connection error here
  1461. print(f"Connection error: {e}")
  1462. detail = "Pipeline not found"
  1463. status_code = status.HTTP_404_NOT_FOUND
  1464. if r is not None:
  1465. status_code = r.status_code
  1466. try:
  1467. res = r.json()
  1468. if "detail" in res:
  1469. detail = res["detail"]
  1470. except Exception:
  1471. pass
  1472. raise HTTPException(
  1473. status_code=status_code,
  1474. detail=detail,
  1475. )
  1476. finally:
  1477. # Ensure the file is deleted after the upload is completed or on failure
  1478. if os.path.exists(file_path):
  1479. os.remove(file_path)
  1480. class AddPipelineForm(BaseModel):
  1481. url: str
  1482. urlIdx: int
  1483. @app.post("/api/pipelines/add")
  1484. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1485. r = None
  1486. try:
  1487. urlIdx = form_data.urlIdx
  1488. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1489. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1490. headers = {"Authorization": f"Bearer {key}"}
  1491. r = requests.post(
  1492. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1493. )
  1494. r.raise_for_status()
  1495. data = r.json()
  1496. return {**data}
  1497. except Exception as e:
  1498. # Handle connection error here
  1499. print(f"Connection error: {e}")
  1500. detail = "Pipeline not found"
  1501. if r is not None:
  1502. try:
  1503. res = r.json()
  1504. if "detail" in res:
  1505. detail = res["detail"]
  1506. except Exception:
  1507. pass
  1508. raise HTTPException(
  1509. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1510. detail=detail,
  1511. )
  1512. class DeletePipelineForm(BaseModel):
  1513. id: str
  1514. urlIdx: int
  1515. @app.delete("/api/pipelines/delete")
  1516. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1517. r = None
  1518. try:
  1519. urlIdx = form_data.urlIdx
  1520. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1521. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1522. headers = {"Authorization": f"Bearer {key}"}
  1523. r = requests.delete(
  1524. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1525. )
  1526. r.raise_for_status()
  1527. data = r.json()
  1528. return {**data}
  1529. except Exception as e:
  1530. # Handle connection error here
  1531. print(f"Connection error: {e}")
  1532. detail = "Pipeline not found"
  1533. if r is not None:
  1534. try:
  1535. res = r.json()
  1536. if "detail" in res:
  1537. detail = res["detail"]
  1538. except Exception:
  1539. pass
  1540. raise HTTPException(
  1541. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1542. detail=detail,
  1543. )
  1544. @app.get("/api/pipelines")
  1545. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  1546. r = None
  1547. try:
  1548. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1549. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1550. headers = {"Authorization": f"Bearer {key}"}
  1551. r = requests.get(f"{url}/pipelines", headers=headers)
  1552. r.raise_for_status()
  1553. data = r.json()
  1554. return {**data}
  1555. except Exception as e:
  1556. # Handle connection error here
  1557. print(f"Connection error: {e}")
  1558. detail = "Pipeline not found"
  1559. if r is not None:
  1560. try:
  1561. res = r.json()
  1562. if "detail" in res:
  1563. detail = res["detail"]
  1564. except Exception:
  1565. pass
  1566. raise HTTPException(
  1567. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1568. detail=detail,
  1569. )
  1570. @app.get("/api/pipelines/{pipeline_id}/valves")
  1571. async def get_pipeline_valves(
  1572. urlIdx: Optional[int],
  1573. pipeline_id: str,
  1574. user=Depends(get_admin_user),
  1575. ):
  1576. r = None
  1577. try:
  1578. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1579. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1580. headers = {"Authorization": f"Bearer {key}"}
  1581. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  1582. r.raise_for_status()
  1583. data = r.json()
  1584. return {**data}
  1585. except Exception as e:
  1586. # Handle connection error here
  1587. print(f"Connection error: {e}")
  1588. detail = "Pipeline not found"
  1589. if r is not None:
  1590. try:
  1591. res = r.json()
  1592. if "detail" in res:
  1593. detail = res["detail"]
  1594. except Exception:
  1595. pass
  1596. raise HTTPException(
  1597. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1598. detail=detail,
  1599. )
  1600. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1601. async def get_pipeline_valves_spec(
  1602. urlIdx: Optional[int],
  1603. pipeline_id: str,
  1604. user=Depends(get_admin_user),
  1605. ):
  1606. r = None
  1607. try:
  1608. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1609. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1610. headers = {"Authorization": f"Bearer {key}"}
  1611. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  1612. r.raise_for_status()
  1613. data = r.json()
  1614. return {**data}
  1615. except Exception as e:
  1616. # Handle connection error here
  1617. print(f"Connection error: {e}")
  1618. detail = "Pipeline not found"
  1619. if r is not None:
  1620. try:
  1621. res = r.json()
  1622. if "detail" in res:
  1623. detail = res["detail"]
  1624. except Exception:
  1625. pass
  1626. raise HTTPException(
  1627. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1628. detail=detail,
  1629. )
  1630. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1631. async def update_pipeline_valves(
  1632. urlIdx: Optional[int],
  1633. pipeline_id: str,
  1634. form_data: dict,
  1635. user=Depends(get_admin_user),
  1636. ):
  1637. r = None
  1638. try:
  1639. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1640. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1641. headers = {"Authorization": f"Bearer {key}"}
  1642. r = requests.post(
  1643. f"{url}/{pipeline_id}/valves/update",
  1644. headers=headers,
  1645. json={**form_data},
  1646. )
  1647. r.raise_for_status()
  1648. data = r.json()
  1649. return {**data}
  1650. except Exception as e:
  1651. # Handle connection error here
  1652. print(f"Connection error: {e}")
  1653. detail = "Pipeline not found"
  1654. if r is not None:
  1655. try:
  1656. res = r.json()
  1657. if "detail" in res:
  1658. detail = res["detail"]
  1659. except Exception:
  1660. pass
  1661. raise HTTPException(
  1662. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1663. detail=detail,
  1664. )
  1665. ##################################
  1666. #
  1667. # Config Endpoints
  1668. #
  1669. ##################################
  1670. @app.get("/api/config")
  1671. async def get_app_config(request: Request):
  1672. user = None
  1673. if "token" in request.cookies:
  1674. token = request.cookies.get("token")
  1675. data = decode_token(token)
  1676. if data is not None and "id" in data:
  1677. user = Users.get_user_by_id(data["id"])
  1678. return {
  1679. "status": True,
  1680. "name": WEBUI_NAME,
  1681. "version": VERSION,
  1682. "default_locale": str(DEFAULT_LOCALE),
  1683. "oauth": {
  1684. "providers": {
  1685. name: config.get("name", name)
  1686. for name, config in OAUTH_PROVIDERS.items()
  1687. }
  1688. },
  1689. "features": {
  1690. "auth": WEBUI_AUTH,
  1691. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1692. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1693. "enable_login_form": webui_app.state.config.ENABLE_LOGIN_FORM,
  1694. **(
  1695. {
  1696. "enable_web_search": retrieval_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1697. "enable_image_generation": images_app.state.config.ENABLED,
  1698. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1699. "enable_message_rating": webui_app.state.config.ENABLE_MESSAGE_RATING,
  1700. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1701. "enable_admin_chat_access": ENABLE_ADMIN_CHAT_ACCESS,
  1702. }
  1703. if user is not None
  1704. else {}
  1705. ),
  1706. },
  1707. **(
  1708. {
  1709. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1710. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1711. "audio": {
  1712. "tts": {
  1713. "engine": audio_app.state.config.TTS_ENGINE,
  1714. "voice": audio_app.state.config.TTS_VOICE,
  1715. "split_on": audio_app.state.config.TTS_SPLIT_ON,
  1716. },
  1717. "stt": {
  1718. "engine": audio_app.state.config.STT_ENGINE,
  1719. },
  1720. },
  1721. "file": {
  1722. "max_size": retrieval_app.state.config.FILE_MAX_SIZE,
  1723. "max_count": retrieval_app.state.config.FILE_MAX_COUNT,
  1724. },
  1725. "permissions": {**webui_app.state.config.USER_PERMISSIONS},
  1726. }
  1727. if user is not None
  1728. else {}
  1729. ),
  1730. }
  1731. @app.get("/api/config/model/filter")
  1732. async def get_model_filter_config(user=Depends(get_admin_user)):
  1733. return {
  1734. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1735. "models": app.state.config.MODEL_FILTER_LIST,
  1736. }
  1737. class ModelFilterConfigForm(BaseModel):
  1738. enabled: bool
  1739. models: list[str]
  1740. @app.post("/api/config/model/filter")
  1741. async def update_model_filter_config(
  1742. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  1743. ):
  1744. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  1745. app.state.config.MODEL_FILTER_LIST = form_data.models
  1746. return {
  1747. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1748. "models": app.state.config.MODEL_FILTER_LIST,
  1749. }
  1750. # TODO: webhook endpoint should be under config endpoints
  1751. @app.get("/api/webhook")
  1752. async def get_webhook_url(user=Depends(get_admin_user)):
  1753. return {
  1754. "url": app.state.config.WEBHOOK_URL,
  1755. }
  1756. class UrlForm(BaseModel):
  1757. url: str
  1758. @app.post("/api/webhook")
  1759. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1760. app.state.config.WEBHOOK_URL = form_data.url
  1761. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1762. return {"url": app.state.config.WEBHOOK_URL}
  1763. @app.get("/api/version")
  1764. async def get_app_version():
  1765. return {
  1766. "version": VERSION,
  1767. }
  1768. @app.get("/api/changelog")
  1769. async def get_app_changelog():
  1770. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1771. @app.get("/api/version/updates")
  1772. async def get_app_latest_release_version():
  1773. try:
  1774. timeout = aiohttp.ClientTimeout(total=1)
  1775. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  1776. async with session.get(
  1777. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1778. ) as response:
  1779. response.raise_for_status()
  1780. data = await response.json()
  1781. latest_version = data["tag_name"]
  1782. return {"current": VERSION, "latest": latest_version[1:]}
  1783. except Exception as e:
  1784. log.debug(e)
  1785. return {"current": VERSION, "latest": VERSION}
  1786. ############################
  1787. # OAuth Login & Callback
  1788. ############################
  1789. # SessionMiddleware is used by authlib for oauth
  1790. if len(OAUTH_PROVIDERS) > 0:
  1791. app.add_middleware(
  1792. SessionMiddleware,
  1793. secret_key=WEBUI_SECRET_KEY,
  1794. session_cookie="oui-session",
  1795. same_site=WEBUI_SESSION_COOKIE_SAME_SITE,
  1796. https_only=WEBUI_SESSION_COOKIE_SECURE,
  1797. )
  1798. @app.get("/oauth/{provider}/login")
  1799. async def oauth_login(provider: str, request: Request):
  1800. return await oauth_manager.handle_login(provider, request)
  1801. # OAuth login logic is as follows:
  1802. # 1. Attempt to find a user with matching subject ID, tied to the provider
  1803. # 2. If OAUTH_MERGE_ACCOUNTS_BY_EMAIL is true, find a user with the email address provided via OAuth
  1804. # - This is considered insecure in general, as OAuth providers do not always verify email addresses
  1805. # 3. If there is no user, and ENABLE_OAUTH_SIGNUP is true, create a user
  1806. # - Email addresses are considered unique, so we fail registration if the email address is alreayd taken
  1807. @app.get("/oauth/{provider}/callback")
  1808. async def oauth_callback(provider: str, request: Request, response: Response):
  1809. return await oauth_manager.handle_callback(provider, request, response)
  1810. @app.get("/manifest.json")
  1811. async def get_manifest_json():
  1812. return {
  1813. "name": WEBUI_NAME,
  1814. "short_name": WEBUI_NAME,
  1815. "description": "Open WebUI is an open, extensible, user-friendly interface for AI that adapts to your workflow.",
  1816. "start_url": "/",
  1817. "display": "standalone",
  1818. "background_color": "#343541",
  1819. "orientation": "any",
  1820. "icons": [
  1821. {
  1822. "src": "/static/logo.png",
  1823. "type": "image/png",
  1824. "sizes": "500x500",
  1825. "purpose": "any",
  1826. },
  1827. {
  1828. "src": "/static/logo.png",
  1829. "type": "image/png",
  1830. "sizes": "500x500",
  1831. "purpose": "maskable",
  1832. },
  1833. ],
  1834. }
  1835. @app.get("/opensearch.xml")
  1836. async def get_opensearch_xml():
  1837. xml_content = rf"""
  1838. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1839. <ShortName>{WEBUI_NAME}</ShortName>
  1840. <Description>Search {WEBUI_NAME}</Description>
  1841. <InputEncoding>UTF-8</InputEncoding>
  1842. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/static/favicon.png</Image>
  1843. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1844. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1845. </OpenSearchDescription>
  1846. """
  1847. return Response(content=xml_content, media_type="application/xml")
  1848. @app.get("/health")
  1849. async def healthcheck():
  1850. return {"status": True}
  1851. @app.get("/health/db")
  1852. async def healthcheck_with_db():
  1853. Session.execute(text("SELECT 1;")).all()
  1854. return {"status": True}
  1855. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  1856. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  1857. if os.path.exists(FRONTEND_BUILD_DIR):
  1858. mimetypes.add_type("text/javascript", ".js")
  1859. app.mount(
  1860. "/",
  1861. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1862. name="spa-static-files",
  1863. )
  1864. else:
  1865. log.warning(
  1866. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1867. )