main.py 78 KB

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