main.py 72 KB

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