main.py 78 KB

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