main.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666
  1. from contextlib import asynccontextmanager
  2. from bs4 import BeautifulSoup
  3. import json
  4. import markdown
  5. import time
  6. import os
  7. import sys
  8. import logging
  9. import aiohttp
  10. import requests
  11. import mimetypes
  12. import shutil
  13. import os
  14. import uuid
  15. import inspect
  16. import asyncio
  17. from fastapi import FastAPI, Request, Depends, status, UploadFile, File, Form
  18. from fastapi.staticfiles import StaticFiles
  19. from fastapi.responses import JSONResponse
  20. from fastapi import HTTPException
  21. from fastapi.middleware.wsgi import WSGIMiddleware
  22. from fastapi.middleware.cors import CORSMiddleware
  23. from starlette.exceptions import HTTPException as StarletteHTTPException
  24. from starlette.middleware.base import BaseHTTPMiddleware
  25. from starlette.responses import StreamingResponse, Response
  26. from apps.socket.main import app as socket_app
  27. from apps.ollama.main import (
  28. app as ollama_app,
  29. OpenAIChatCompletionForm,
  30. get_all_models as get_ollama_models,
  31. generate_openai_chat_completion as generate_ollama_chat_completion,
  32. )
  33. from apps.openai.main import (
  34. app as openai_app,
  35. get_all_models as get_openai_models,
  36. generate_chat_completion as generate_openai_chat_completion,
  37. )
  38. from apps.audio.main import app as audio_app
  39. from apps.images.main import app as images_app
  40. from apps.rag.main import app as rag_app
  41. from apps.webui.main import app as webui_app
  42. from pydantic import BaseModel
  43. from typing import List, Optional
  44. from apps.webui.models.models import Models, ModelModel
  45. from apps.webui.models.tools import Tools
  46. from apps.webui.models.functions import Functions
  47. from apps.webui.utils import load_toolkit_module_by_id, load_function_module_by_id
  48. from utils.utils import (
  49. get_admin_user,
  50. get_verified_user,
  51. get_current_user,
  52. get_http_authorization_cred,
  53. )
  54. from utils.task import (
  55. title_generation_template,
  56. search_query_generation_template,
  57. tools_function_calling_generation_template,
  58. )
  59. from utils.misc import get_last_user_message, add_or_update_system_message
  60. from apps.rag.utils import get_rag_context, rag_template
  61. from config import (
  62. CONFIG_DATA,
  63. WEBUI_NAME,
  64. WEBUI_URL,
  65. WEBUI_AUTH,
  66. ENV,
  67. VERSION,
  68. CHANGELOG,
  69. FRONTEND_BUILD_DIR,
  70. UPLOAD_DIR,
  71. CACHE_DIR,
  72. STATIC_DIR,
  73. ENABLE_OPENAI_API,
  74. ENABLE_OLLAMA_API,
  75. ENABLE_MODEL_FILTER,
  76. MODEL_FILTER_LIST,
  77. GLOBAL_LOG_LEVEL,
  78. SRC_LOG_LEVELS,
  79. WEBHOOK_URL,
  80. ENABLE_ADMIN_EXPORT,
  81. WEBUI_BUILD_HASH,
  82. TASK_MODEL,
  83. TASK_MODEL_EXTERNAL,
  84. TITLE_GENERATION_PROMPT_TEMPLATE,
  85. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  86. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  87. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  88. AppConfig,
  89. )
  90. from constants import ERROR_MESSAGES
  91. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  92. log = logging.getLogger(__name__)
  93. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  94. class SPAStaticFiles(StaticFiles):
  95. async def get_response(self, path: str, scope):
  96. try:
  97. return await super().get_response(path, scope)
  98. except (HTTPException, StarletteHTTPException) as ex:
  99. if ex.status_code == 404:
  100. return await super().get_response("index.html", scope)
  101. else:
  102. raise ex
  103. print(
  104. rf"""
  105. ___ __ __ _ _ _ ___
  106. / _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
  107. | | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
  108. | |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
  109. \___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
  110. |_|
  111. v{VERSION} - building the best open-source AI user interface.
  112. {f"Commit: {WEBUI_BUILD_HASH}" if WEBUI_BUILD_HASH != "dev-build" else ""}
  113. https://github.com/open-webui/open-webui
  114. """
  115. )
  116. @asynccontextmanager
  117. async def lifespan(app: FastAPI):
  118. yield
  119. app = FastAPI(
  120. docs_url="/docs" if ENV == "dev" else None, redoc_url=None, lifespan=lifespan
  121. )
  122. app.state.config = AppConfig()
  123. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  124. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  125. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  126. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  127. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  128. app.state.config.TASK_MODEL = TASK_MODEL
  129. app.state.config.TASK_MODEL_EXTERNAL = TASK_MODEL_EXTERNAL
  130. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = TITLE_GENERATION_PROMPT_TEMPLATE
  131. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  132. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  133. )
  134. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  135. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  136. )
  137. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  138. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  139. )
  140. app.state.MODELS = {}
  141. origins = ["*"]
  142. ##################################
  143. #
  144. # ChatCompletion Middleware
  145. #
  146. ##################################
  147. async def get_function_call_response(
  148. messages, files, tool_id, template, task_model_id, user
  149. ):
  150. tool = Tools.get_tool_by_id(tool_id)
  151. tools_specs = json.dumps(tool.specs, indent=2)
  152. content = tools_function_calling_generation_template(template, tools_specs)
  153. user_message = get_last_user_message(messages)
  154. prompt = (
  155. "History:\n"
  156. + "\n".join(
  157. [
  158. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  159. for message in messages[::-1][:4]
  160. ]
  161. )
  162. + f"\nQuery: {user_message}"
  163. )
  164. print(prompt)
  165. payload = {
  166. "model": task_model_id,
  167. "messages": [
  168. {"role": "system", "content": content},
  169. {"role": "user", "content": f"Query: {prompt}"},
  170. ],
  171. "stream": False,
  172. }
  173. try:
  174. payload = filter_pipeline(payload, user)
  175. except Exception as e:
  176. raise e
  177. model = app.state.MODELS[task_model_id]
  178. response = None
  179. try:
  180. if model["owned_by"] == "ollama":
  181. response = await generate_ollama_chat_completion(payload, user=user)
  182. else:
  183. response = await generate_openai_chat_completion(payload, user=user)
  184. content = None
  185. if hasattr(response, "body_iterator"):
  186. async for chunk in response.body_iterator:
  187. data = json.loads(chunk.decode("utf-8"))
  188. content = data["choices"][0]["message"]["content"]
  189. # Cleanup any remaining background tasks if necessary
  190. if response.background is not None:
  191. await response.background()
  192. else:
  193. content = response["choices"][0]["message"]["content"]
  194. # Parse the function response
  195. if content is not None:
  196. print(f"content: {content}")
  197. result = json.loads(content)
  198. print(result)
  199. # Call the function
  200. if "name" in result:
  201. if tool_id in webui_app.state.TOOLS:
  202. toolkit_module = webui_app.state.TOOLS[tool_id]
  203. else:
  204. toolkit_module = load_toolkit_module_by_id(tool_id)
  205. webui_app.state.TOOLS[tool_id] = toolkit_module
  206. file_handler = False
  207. # check if toolkit_module has file_handler self variable
  208. if hasattr(toolkit_module, "file_handler"):
  209. file_handler = True
  210. print("file_handler: ", file_handler)
  211. function = getattr(toolkit_module, result["name"])
  212. function_result = None
  213. try:
  214. # Get the signature of the function
  215. sig = inspect.signature(function)
  216. params = result["parameters"]
  217. if "__user__" in sig.parameters:
  218. # Call the function with the '__user__' parameter included
  219. params = {
  220. **params,
  221. "__user__": {
  222. "id": user.id,
  223. "email": user.email,
  224. "name": user.name,
  225. "role": user.role,
  226. },
  227. }
  228. if "__messages__" in sig.parameters:
  229. # Call the function with the '__messages__' parameter included
  230. params = {
  231. **params,
  232. "__messages__": messages,
  233. }
  234. if "__files__" in sig.parameters:
  235. # Call the function with the '__files__' parameter included
  236. params = {
  237. **params,
  238. "__files__": files,
  239. }
  240. if "__model__" in sig.parameters:
  241. # Call the function with the '__model__' parameter included
  242. params = {
  243. **params,
  244. "__model__": model,
  245. }
  246. if "__id__" in sig.parameters:
  247. # Call the function with the '__id__' parameter included
  248. params = {
  249. **params,
  250. "__id__": tool_id,
  251. }
  252. function_result = function(**params)
  253. except Exception as e:
  254. print(e)
  255. # Add the function result to the system prompt
  256. if function_result is not None:
  257. return function_result, file_handler
  258. except Exception as e:
  259. print(f"Error: {e}")
  260. return None, False
  261. class ChatCompletionMiddleware(BaseHTTPMiddleware):
  262. async def dispatch(self, request: Request, call_next):
  263. data_items = []
  264. if request.method == "POST" and any(
  265. endpoint in request.url.path
  266. for endpoint in ["/ollama/api/chat", "/chat/completions"]
  267. ):
  268. log.debug(f"request.url.path: {request.url.path}")
  269. # Read the original request body
  270. body = await request.body()
  271. body_str = body.decode("utf-8")
  272. data = json.loads(body_str) if body_str else {}
  273. user = get_current_user(
  274. request,
  275. get_http_authorization_cred(request.headers.get("Authorization")),
  276. )
  277. # Flag to skip RAG completions if file_handler is present in tools/functions
  278. skip_files = False
  279. model_id = data["model"]
  280. if model_id not in app.state.MODELS:
  281. raise HTTPException(
  282. status_code=status.HTTP_404_NOT_FOUND,
  283. detail="Model not found",
  284. )
  285. model = app.state.MODELS[model_id]
  286. print(":", data)
  287. # Check if the model has any filters
  288. for filter_id in model["info"]["meta"].get("filterIds", []):
  289. filter = Functions.get_function_by_id(filter_id)
  290. if filter:
  291. if filter_id in webui_app.state.FUNCTIONS:
  292. function_module = webui_app.state.FUNCTIONS[filter_id]
  293. else:
  294. function_module, function_type = load_function_module_by_id(
  295. filter_id
  296. )
  297. webui_app.state.FUNCTIONS[filter_id] = function_module
  298. # Check if the function has a file_handler variable
  299. if getattr(function_module, "file_handler"):
  300. skip_files = True
  301. try:
  302. if hasattr(function_module, "inlet"):
  303. data = function_module.inlet(
  304. data,
  305. {
  306. "id": user.id,
  307. "email": user.email,
  308. "name": user.name,
  309. "role": user.role,
  310. },
  311. )
  312. except Exception as e:
  313. print(f"Error: {e}")
  314. raise HTTPException(
  315. status_code=status.HTTP_400_BAD_REQUEST,
  316. detail=e,
  317. )
  318. print("Filtered:", data)
  319. # Set the task model
  320. task_model_id = data["model"]
  321. # Check if the user has a custom task model and use that model
  322. if app.state.MODELS[task_model_id]["owned_by"] == "ollama":
  323. if (
  324. app.state.config.TASK_MODEL
  325. and app.state.config.TASK_MODEL in app.state.MODELS
  326. ):
  327. task_model_id = app.state.config.TASK_MODEL
  328. else:
  329. if (
  330. app.state.config.TASK_MODEL_EXTERNAL
  331. and app.state.config.TASK_MODEL_EXTERNAL in app.state.MODELS
  332. ):
  333. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  334. prompt = get_last_user_message(data["messages"])
  335. context = ""
  336. # If tool_ids field is present, call the functions
  337. if "tool_ids" in data:
  338. print(data["tool_ids"])
  339. for tool_id in data["tool_ids"]:
  340. print(tool_id)
  341. try:
  342. response, file_handler = await get_function_call_response(
  343. messages=data["messages"],
  344. files=data.get("files", []),
  345. tool_id=tool_id,
  346. template=app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  347. task_model_id=task_model_id,
  348. user=user,
  349. )
  350. print(file_handler)
  351. if isinstance(response, str):
  352. context += ("\n" if context != "" else "") + response
  353. if file_handler:
  354. skip_files = True
  355. except Exception as e:
  356. print(f"Error: {e}")
  357. del data["tool_ids"]
  358. print(f"tool_context: {context}")
  359. # If files field is present, generate RAG completions
  360. # If skip_files is True, skip the RAG completions
  361. if "files" in data:
  362. if not skip_files:
  363. data = {**data}
  364. rag_context, citations = get_rag_context(
  365. files=data["files"],
  366. messages=data["messages"],
  367. embedding_function=rag_app.state.EMBEDDING_FUNCTION,
  368. k=rag_app.state.config.TOP_K,
  369. reranking_function=rag_app.state.sentence_transformer_rf,
  370. r=rag_app.state.config.RELEVANCE_THRESHOLD,
  371. hybrid_search=rag_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  372. )
  373. if rag_context:
  374. context += ("\n" if context != "" else "") + rag_context
  375. log.debug(f"rag_context: {rag_context}, citations: {citations}")
  376. if citations and data.get("citations"):
  377. data_items.append({"citations": citations})
  378. del data["citations"]
  379. del data["files"]
  380. if context != "":
  381. system_prompt = rag_template(
  382. rag_app.state.config.RAG_TEMPLATE, context, prompt
  383. )
  384. print(system_prompt)
  385. data["messages"] = add_or_update_system_message(
  386. system_prompt, data["messages"]
  387. )
  388. modified_body_bytes = json.dumps(data).encode("utf-8")
  389. # Replace the request body with the modified one
  390. request._body = modified_body_bytes
  391. # Set custom header to ensure content-length matches new body length
  392. request.headers.__dict__["_list"] = [
  393. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  394. *[
  395. (k, v)
  396. for k, v in request.headers.raw
  397. if k.lower() != b"content-length"
  398. ],
  399. ]
  400. response = await call_next(request)
  401. # If there are data_items to inject into the response
  402. if len(data_items) > 0:
  403. if isinstance(response, StreamingResponse):
  404. # If it's a streaming response, inject it as SSE event or NDJSON line
  405. content_type = response.headers.get("Content-Type")
  406. if "text/event-stream" in content_type:
  407. return StreamingResponse(
  408. self.openai_stream_wrapper(response.body_iterator, data_items),
  409. )
  410. if "application/x-ndjson" in content_type:
  411. return StreamingResponse(
  412. self.ollama_stream_wrapper(response.body_iterator, data_items),
  413. )
  414. return response
  415. async def _receive(self, body: bytes):
  416. return {"type": "http.request", "body": body, "more_body": False}
  417. async def openai_stream_wrapper(self, original_generator, data_items):
  418. for item in data_items:
  419. yield f"data: {json.dumps(item)}\n\n"
  420. async for data in original_generator:
  421. yield data
  422. async def ollama_stream_wrapper(self, original_generator, data_items):
  423. for item in data_items:
  424. yield f"{json.dumps(item)}\n"
  425. async for data in original_generator:
  426. yield data
  427. app.add_middleware(ChatCompletionMiddleware)
  428. ##################################
  429. #
  430. # Pipeline Middleware
  431. #
  432. ##################################
  433. def filter_pipeline(payload, user):
  434. user = {"id": user.id, "email": user.email, "name": user.name, "role": user.role}
  435. model_id = payload["model"]
  436. filters = [
  437. model
  438. for model in app.state.MODELS.values()
  439. if "pipeline" in model
  440. and "type" in model["pipeline"]
  441. and model["pipeline"]["type"] == "filter"
  442. and (
  443. model["pipeline"]["pipelines"] == ["*"]
  444. or any(
  445. model_id == target_model_id
  446. for target_model_id in model["pipeline"]["pipelines"]
  447. )
  448. )
  449. ]
  450. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  451. model = app.state.MODELS[model_id]
  452. if "pipeline" in model:
  453. sorted_filters.append(model)
  454. for filter in sorted_filters:
  455. r = None
  456. try:
  457. urlIdx = filter["urlIdx"]
  458. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  459. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  460. if key != "":
  461. headers = {"Authorization": f"Bearer {key}"}
  462. r = requests.post(
  463. f"{url}/{filter['id']}/filter/inlet",
  464. headers=headers,
  465. json={
  466. "user": user,
  467. "body": payload,
  468. },
  469. )
  470. r.raise_for_status()
  471. payload = r.json()
  472. except Exception as e:
  473. # Handle connection error here
  474. print(f"Connection error: {e}")
  475. if r is not None:
  476. try:
  477. res = r.json()
  478. except:
  479. pass
  480. if "detail" in res:
  481. raise Exception(r.status_code, res["detail"])
  482. else:
  483. pass
  484. if "pipeline" not in app.state.MODELS[model_id]:
  485. if "chat_id" in payload:
  486. del payload["chat_id"]
  487. if "title" in payload:
  488. del payload["title"]
  489. if "task" in payload:
  490. del payload["task"]
  491. return payload
  492. class PipelineMiddleware(BaseHTTPMiddleware):
  493. async def dispatch(self, request: Request, call_next):
  494. if request.method == "POST" and (
  495. "/ollama/api/chat" in request.url.path
  496. or "/chat/completions" in request.url.path
  497. ):
  498. log.debug(f"request.url.path: {request.url.path}")
  499. # Read the original request body
  500. body = await request.body()
  501. # Decode body to string
  502. body_str = body.decode("utf-8")
  503. # Parse string to JSON
  504. data = json.loads(body_str) if body_str else {}
  505. user = get_current_user(
  506. request,
  507. get_http_authorization_cred(request.headers.get("Authorization")),
  508. )
  509. try:
  510. data = filter_pipeline(data, user)
  511. except Exception as e:
  512. return JSONResponse(
  513. status_code=e.args[0],
  514. content={"detail": e.args[1]},
  515. )
  516. modified_body_bytes = json.dumps(data).encode("utf-8")
  517. # Replace the request body with the modified one
  518. request._body = modified_body_bytes
  519. # Set custom header to ensure content-length matches new body length
  520. request.headers.__dict__["_list"] = [
  521. (b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
  522. *[
  523. (k, v)
  524. for k, v in request.headers.raw
  525. if k.lower() != b"content-length"
  526. ],
  527. ]
  528. response = await call_next(request)
  529. return response
  530. async def _receive(self, body: bytes):
  531. return {"type": "http.request", "body": body, "more_body": False}
  532. app.add_middleware(PipelineMiddleware)
  533. app.add_middleware(
  534. CORSMiddleware,
  535. allow_origins=origins,
  536. allow_credentials=True,
  537. allow_methods=["*"],
  538. allow_headers=["*"],
  539. )
  540. @app.middleware("http")
  541. async def check_url(request: Request, call_next):
  542. if len(app.state.MODELS) == 0:
  543. await get_all_models()
  544. else:
  545. pass
  546. start_time = int(time.time())
  547. response = await call_next(request)
  548. process_time = int(time.time()) - start_time
  549. response.headers["X-Process-Time"] = str(process_time)
  550. return response
  551. @app.middleware("http")
  552. async def update_embedding_function(request: Request, call_next):
  553. response = await call_next(request)
  554. if "/embedding/update" in request.url.path:
  555. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  556. return response
  557. app.mount("/ws", socket_app)
  558. app.mount("/ollama", ollama_app)
  559. app.mount("/openai", openai_app)
  560. app.mount("/images/api/v1", images_app)
  561. app.mount("/audio/api/v1", audio_app)
  562. app.mount("/rag/api/v1", rag_app)
  563. app.mount("/api/v1", webui_app)
  564. webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
  565. async def get_all_models():
  566. openai_models = []
  567. ollama_models = []
  568. if app.state.config.ENABLE_OPENAI_API:
  569. openai_models = await get_openai_models()
  570. openai_models = openai_models["data"]
  571. if app.state.config.ENABLE_OLLAMA_API:
  572. ollama_models = await get_ollama_models()
  573. ollama_models = [
  574. {
  575. "id": model["model"],
  576. "name": model["name"],
  577. "object": "model",
  578. "created": int(time.time()),
  579. "owned_by": "ollama",
  580. "ollama": model,
  581. }
  582. for model in ollama_models["models"]
  583. ]
  584. models = openai_models + ollama_models
  585. custom_models = Models.get_all_models()
  586. for custom_model in custom_models:
  587. if custom_model.base_model_id == None:
  588. for model in models:
  589. if (
  590. custom_model.id == model["id"]
  591. or custom_model.id == model["id"].split(":")[0]
  592. ):
  593. model["name"] = custom_model.name
  594. model["info"] = custom_model.model_dump()
  595. else:
  596. owned_by = "openai"
  597. for model in models:
  598. if (
  599. custom_model.base_model_id == model["id"]
  600. or custom_model.base_model_id == model["id"].split(":")[0]
  601. ):
  602. owned_by = model["owned_by"]
  603. break
  604. models.append(
  605. {
  606. "id": custom_model.id,
  607. "name": custom_model.name,
  608. "object": "model",
  609. "created": custom_model.created_at,
  610. "owned_by": owned_by,
  611. "info": custom_model.model_dump(),
  612. "preset": True,
  613. }
  614. )
  615. app.state.MODELS = {model["id"]: model for model in models}
  616. webui_app.state.MODELS = app.state.MODELS
  617. return models
  618. @app.get("/api/models")
  619. async def get_models(user=Depends(get_verified_user)):
  620. models = await get_all_models()
  621. # Filter out filter pipelines
  622. models = [
  623. model
  624. for model in models
  625. if "pipeline" not in model or model["pipeline"].get("type", None) != "filter"
  626. ]
  627. if app.state.config.ENABLE_MODEL_FILTER:
  628. if user.role == "user":
  629. models = list(
  630. filter(
  631. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  632. models,
  633. )
  634. )
  635. return {"data": models}
  636. return {"data": models}
  637. @app.post("/api/chat/completions")
  638. async def generate_chat_completions(form_data: dict, user=Depends(get_verified_user)):
  639. model_id = form_data["model"]
  640. if model_id not in app.state.MODELS:
  641. raise HTTPException(
  642. status_code=status.HTTP_404_NOT_FOUND,
  643. detail="Model not found",
  644. )
  645. model = app.state.MODELS[model_id]
  646. print(model)
  647. if model["owned_by"] == "ollama":
  648. return await generate_ollama_chat_completion(form_data, user=user)
  649. else:
  650. return await generate_openai_chat_completion(form_data, user=user)
  651. @app.post("/api/chat/completed")
  652. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  653. data = form_data
  654. model_id = data["model"]
  655. filters = [
  656. model
  657. for model in app.state.MODELS.values()
  658. if "pipeline" in model
  659. and "type" in model["pipeline"]
  660. and model["pipeline"]["type"] == "filter"
  661. and (
  662. model["pipeline"]["pipelines"] == ["*"]
  663. or any(
  664. model_id == target_model_id
  665. for target_model_id in model["pipeline"]["pipelines"]
  666. )
  667. )
  668. ]
  669. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  670. print(model_id)
  671. if model_id in app.state.MODELS:
  672. model = app.state.MODELS[model_id]
  673. if "pipeline" in model:
  674. sorted_filters = [model] + sorted_filters
  675. for filter in sorted_filters:
  676. r = None
  677. try:
  678. urlIdx = filter["urlIdx"]
  679. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  680. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  681. if key != "":
  682. headers = {"Authorization": f"Bearer {key}"}
  683. r = requests.post(
  684. f"{url}/{filter['id']}/filter/outlet",
  685. headers=headers,
  686. json={
  687. "user": {"id": user.id, "name": user.name, "role": user.role},
  688. "body": data,
  689. },
  690. )
  691. r.raise_for_status()
  692. data = r.json()
  693. except Exception as e:
  694. # Handle connection error here
  695. print(f"Connection error: {e}")
  696. if r is not None:
  697. try:
  698. res = r.json()
  699. if "detail" in res:
  700. return JSONResponse(
  701. status_code=r.status_code,
  702. content=res,
  703. )
  704. except:
  705. pass
  706. else:
  707. pass
  708. return data
  709. ##################################
  710. #
  711. # Task Endpoints
  712. #
  713. ##################################
  714. # TODO: Refactor task API endpoints below into a separate file
  715. @app.get("/api/task/config")
  716. async def get_task_config(user=Depends(get_verified_user)):
  717. return {
  718. "TASK_MODEL": app.state.config.TASK_MODEL,
  719. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  720. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  721. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  722. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  723. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  724. }
  725. class TaskConfigForm(BaseModel):
  726. TASK_MODEL: Optional[str]
  727. TASK_MODEL_EXTERNAL: Optional[str]
  728. TITLE_GENERATION_PROMPT_TEMPLATE: str
  729. SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE: str
  730. SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD: int
  731. TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE: str
  732. @app.post("/api/task/config/update")
  733. async def update_task_config(form_data: TaskConfigForm, user=Depends(get_admin_user)):
  734. app.state.config.TASK_MODEL = form_data.TASK_MODEL
  735. app.state.config.TASK_MODEL_EXTERNAL = form_data.TASK_MODEL_EXTERNAL
  736. app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE = (
  737. form_data.TITLE_GENERATION_PROMPT_TEMPLATE
  738. )
  739. app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE = (
  740. form_data.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  741. )
  742. app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD = (
  743. form_data.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD
  744. )
  745. app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = (
  746. form_data.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  747. )
  748. return {
  749. "TASK_MODEL": app.state.config.TASK_MODEL,
  750. "TASK_MODEL_EXTERNAL": app.state.config.TASK_MODEL_EXTERNAL,
  751. "TITLE_GENERATION_PROMPT_TEMPLATE": app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE,
  752. "SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE": app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE,
  753. "SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD": app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD,
  754. "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE": app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  755. }
  756. @app.post("/api/task/title/completions")
  757. async def generate_title(form_data: dict, user=Depends(get_verified_user)):
  758. print("generate_title")
  759. model_id = form_data["model"]
  760. if model_id not in app.state.MODELS:
  761. raise HTTPException(
  762. status_code=status.HTTP_404_NOT_FOUND,
  763. detail="Model not found",
  764. )
  765. # Check if the user has a custom task model
  766. # If the user has a custom task model, use that model
  767. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  768. if app.state.config.TASK_MODEL:
  769. task_model_id = app.state.config.TASK_MODEL
  770. if task_model_id in app.state.MODELS:
  771. model_id = task_model_id
  772. else:
  773. if app.state.config.TASK_MODEL_EXTERNAL:
  774. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  775. if task_model_id in app.state.MODELS:
  776. model_id = task_model_id
  777. print(model_id)
  778. model = app.state.MODELS[model_id]
  779. template = app.state.config.TITLE_GENERATION_PROMPT_TEMPLATE
  780. content = title_generation_template(
  781. template,
  782. form_data["prompt"],
  783. {
  784. "name": user.name,
  785. "location": user.info.get("location") if user.info else None,
  786. },
  787. )
  788. payload = {
  789. "model": model_id,
  790. "messages": [{"role": "user", "content": content}],
  791. "stream": False,
  792. "max_tokens": 50,
  793. "chat_id": form_data.get("chat_id", None),
  794. "title": True,
  795. }
  796. log.debug(payload)
  797. try:
  798. payload = filter_pipeline(payload, user)
  799. except Exception as e:
  800. return JSONResponse(
  801. status_code=e.args[0],
  802. content={"detail": e.args[1]},
  803. )
  804. if model["owned_by"] == "ollama":
  805. return await generate_ollama_chat_completion(payload, user=user)
  806. else:
  807. return await generate_openai_chat_completion(payload, user=user)
  808. @app.post("/api/task/query/completions")
  809. async def generate_search_query(form_data: dict, user=Depends(get_verified_user)):
  810. print("generate_search_query")
  811. if len(form_data["prompt"]) < app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD:
  812. raise HTTPException(
  813. status_code=status.HTTP_400_BAD_REQUEST,
  814. detail=f"Skip search query generation for short prompts (< {app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD} characters)",
  815. )
  816. model_id = form_data["model"]
  817. if model_id not in app.state.MODELS:
  818. raise HTTPException(
  819. status_code=status.HTTP_404_NOT_FOUND,
  820. detail="Model not found",
  821. )
  822. # Check if the user has a custom task model
  823. # If the user has a custom task model, use that model
  824. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  825. if app.state.config.TASK_MODEL:
  826. task_model_id = app.state.config.TASK_MODEL
  827. if task_model_id in app.state.MODELS:
  828. model_id = task_model_id
  829. else:
  830. if app.state.config.TASK_MODEL_EXTERNAL:
  831. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  832. if task_model_id in app.state.MODELS:
  833. model_id = task_model_id
  834. print(model_id)
  835. model = app.state.MODELS[model_id]
  836. template = app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  837. content = search_query_generation_template(
  838. template, form_data["prompt"], {"name": user.name}
  839. )
  840. payload = {
  841. "model": model_id,
  842. "messages": [{"role": "user", "content": content}],
  843. "stream": False,
  844. "max_tokens": 30,
  845. "task": True,
  846. }
  847. print(payload)
  848. try:
  849. payload = filter_pipeline(payload, user)
  850. except Exception as e:
  851. return JSONResponse(
  852. status_code=e.args[0],
  853. content={"detail": e.args[1]},
  854. )
  855. if model["owned_by"] == "ollama":
  856. return await generate_ollama_chat_completion(payload, user=user)
  857. else:
  858. return await generate_openai_chat_completion(payload, user=user)
  859. @app.post("/api/task/emoji/completions")
  860. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  861. print("generate_emoji")
  862. model_id = form_data["model"]
  863. if model_id not in app.state.MODELS:
  864. raise HTTPException(
  865. status_code=status.HTTP_404_NOT_FOUND,
  866. detail="Model not found",
  867. )
  868. # Check if the user has a custom task model
  869. # If the user has a custom task model, use that model
  870. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  871. if app.state.config.TASK_MODEL:
  872. task_model_id = app.state.config.TASK_MODEL
  873. if task_model_id in app.state.MODELS:
  874. model_id = task_model_id
  875. else:
  876. if app.state.config.TASK_MODEL_EXTERNAL:
  877. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  878. if task_model_id in app.state.MODELS:
  879. model_id = task_model_id
  880. print(model_id)
  881. model = app.state.MODELS[model_id]
  882. template = '''
  883. 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., 😊, 😢, 😡, 😱).
  884. Message: """{{prompt}}"""
  885. '''
  886. content = title_generation_template(
  887. template,
  888. form_data["prompt"],
  889. {
  890. "name": user.name,
  891. "location": user.info.get("location") if user.info else None,
  892. },
  893. )
  894. payload = {
  895. "model": model_id,
  896. "messages": [{"role": "user", "content": content}],
  897. "stream": False,
  898. "max_tokens": 4,
  899. "chat_id": form_data.get("chat_id", None),
  900. "task": True,
  901. }
  902. log.debug(payload)
  903. try:
  904. payload = filter_pipeline(payload, user)
  905. except Exception as e:
  906. return JSONResponse(
  907. status_code=e.args[0],
  908. content={"detail": e.args[1]},
  909. )
  910. if model["owned_by"] == "ollama":
  911. return await generate_ollama_chat_completion(payload, user=user)
  912. else:
  913. return await generate_openai_chat_completion(payload, user=user)
  914. @app.post("/api/task/tools/completions")
  915. async def get_tools_function_calling(form_data: dict, user=Depends(get_verified_user)):
  916. print("get_tools_function_calling")
  917. model_id = form_data["model"]
  918. if model_id not in app.state.MODELS:
  919. raise HTTPException(
  920. status_code=status.HTTP_404_NOT_FOUND,
  921. detail="Model not found",
  922. )
  923. # Check if the user has a custom task model
  924. # If the user has a custom task model, use that model
  925. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  926. if app.state.config.TASK_MODEL:
  927. task_model_id = app.state.config.TASK_MODEL
  928. if task_model_id in app.state.MODELS:
  929. model_id = task_model_id
  930. else:
  931. if app.state.config.TASK_MODEL_EXTERNAL:
  932. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  933. if task_model_id in app.state.MODELS:
  934. model_id = task_model_id
  935. print(model_id)
  936. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  937. try:
  938. context, file_handler = await get_function_call_response(
  939. form_data["messages"],
  940. form_data.get("files", []),
  941. form_data["tool_id"],
  942. template,
  943. model_id,
  944. user,
  945. )
  946. return context
  947. except Exception as e:
  948. return JSONResponse(
  949. status_code=e.args[0],
  950. content={"detail": e.args[1]},
  951. )
  952. ##################################
  953. #
  954. # Pipelines Endpoints
  955. #
  956. ##################################
  957. # TODO: Refactor pipelines API endpoints below into a separate file
  958. @app.get("/api/pipelines/list")
  959. async def get_pipelines_list(user=Depends(get_admin_user)):
  960. responses = await get_openai_models(raw=True)
  961. print(responses)
  962. urlIdxs = [
  963. idx
  964. for idx, response in enumerate(responses)
  965. if response != None and "pipelines" in response
  966. ]
  967. return {
  968. "data": [
  969. {
  970. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  971. "idx": urlIdx,
  972. }
  973. for urlIdx in urlIdxs
  974. ]
  975. }
  976. @app.post("/api/pipelines/upload")
  977. async def upload_pipeline(
  978. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  979. ):
  980. print("upload_pipeline", urlIdx, file.filename)
  981. # Check if the uploaded file is a python file
  982. if not file.filename.endswith(".py"):
  983. raise HTTPException(
  984. status_code=status.HTTP_400_BAD_REQUEST,
  985. detail="Only Python (.py) files are allowed.",
  986. )
  987. upload_folder = f"{CACHE_DIR}/pipelines"
  988. os.makedirs(upload_folder, exist_ok=True)
  989. file_path = os.path.join(upload_folder, file.filename)
  990. try:
  991. # Save the uploaded file
  992. with open(file_path, "wb") as buffer:
  993. shutil.copyfileobj(file.file, buffer)
  994. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  995. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  996. headers = {"Authorization": f"Bearer {key}"}
  997. with open(file_path, "rb") as f:
  998. files = {"file": f}
  999. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  1000. r.raise_for_status()
  1001. data = r.json()
  1002. return {**data}
  1003. except Exception as e:
  1004. # Handle connection error here
  1005. print(f"Connection error: {e}")
  1006. detail = "Pipeline not found"
  1007. if r is not None:
  1008. try:
  1009. res = r.json()
  1010. if "detail" in res:
  1011. detail = res["detail"]
  1012. except:
  1013. pass
  1014. raise HTTPException(
  1015. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1016. detail=detail,
  1017. )
  1018. finally:
  1019. # Ensure the file is deleted after the upload is completed or on failure
  1020. if os.path.exists(file_path):
  1021. os.remove(file_path)
  1022. class AddPipelineForm(BaseModel):
  1023. url: str
  1024. urlIdx: int
  1025. @app.post("/api/pipelines/add")
  1026. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  1027. r = None
  1028. try:
  1029. urlIdx = form_data.urlIdx
  1030. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1031. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1032. headers = {"Authorization": f"Bearer {key}"}
  1033. r = requests.post(
  1034. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  1035. )
  1036. r.raise_for_status()
  1037. data = r.json()
  1038. return {**data}
  1039. except Exception as e:
  1040. # Handle connection error here
  1041. print(f"Connection error: {e}")
  1042. detail = "Pipeline not found"
  1043. if r is not None:
  1044. try:
  1045. res = r.json()
  1046. if "detail" in res:
  1047. detail = res["detail"]
  1048. except:
  1049. pass
  1050. raise HTTPException(
  1051. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1052. detail=detail,
  1053. )
  1054. class DeletePipelineForm(BaseModel):
  1055. id: str
  1056. urlIdx: int
  1057. @app.delete("/api/pipelines/delete")
  1058. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  1059. r = None
  1060. try:
  1061. urlIdx = form_data.urlIdx
  1062. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1063. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1064. headers = {"Authorization": f"Bearer {key}"}
  1065. r = requests.delete(
  1066. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  1067. )
  1068. r.raise_for_status()
  1069. data = r.json()
  1070. return {**data}
  1071. except Exception as e:
  1072. # Handle connection error here
  1073. print(f"Connection error: {e}")
  1074. detail = "Pipeline not found"
  1075. if r is not None:
  1076. try:
  1077. res = r.json()
  1078. if "detail" in res:
  1079. detail = res["detail"]
  1080. except:
  1081. pass
  1082. raise HTTPException(
  1083. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1084. detail=detail,
  1085. )
  1086. @app.get("/api/pipelines")
  1087. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  1088. r = None
  1089. try:
  1090. urlIdx
  1091. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1092. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1093. headers = {"Authorization": f"Bearer {key}"}
  1094. r = requests.get(f"{url}/pipelines", headers=headers)
  1095. r.raise_for_status()
  1096. data = r.json()
  1097. return {**data}
  1098. except Exception as e:
  1099. # Handle connection error here
  1100. print(f"Connection error: {e}")
  1101. detail = "Pipeline not found"
  1102. if r is not None:
  1103. try:
  1104. res = r.json()
  1105. if "detail" in res:
  1106. detail = res["detail"]
  1107. except:
  1108. pass
  1109. raise HTTPException(
  1110. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1111. detail=detail,
  1112. )
  1113. @app.get("/api/pipelines/{pipeline_id}/valves")
  1114. async def get_pipeline_valves(
  1115. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  1116. ):
  1117. models = await get_all_models()
  1118. r = None
  1119. try:
  1120. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1121. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1122. headers = {"Authorization": f"Bearer {key}"}
  1123. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  1124. r.raise_for_status()
  1125. data = r.json()
  1126. return {**data}
  1127. except Exception as e:
  1128. # Handle connection error here
  1129. print(f"Connection error: {e}")
  1130. detail = "Pipeline not found"
  1131. if r is not None:
  1132. try:
  1133. res = r.json()
  1134. if "detail" in res:
  1135. detail = res["detail"]
  1136. except:
  1137. pass
  1138. raise HTTPException(
  1139. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1140. detail=detail,
  1141. )
  1142. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1143. async def get_pipeline_valves_spec(
  1144. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  1145. ):
  1146. models = await get_all_models()
  1147. r = None
  1148. try:
  1149. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1150. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1151. headers = {"Authorization": f"Bearer {key}"}
  1152. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  1153. r.raise_for_status()
  1154. data = r.json()
  1155. return {**data}
  1156. except Exception as e:
  1157. # Handle connection error here
  1158. print(f"Connection error: {e}")
  1159. detail = "Pipeline not found"
  1160. if r is not None:
  1161. try:
  1162. res = r.json()
  1163. if "detail" in res:
  1164. detail = res["detail"]
  1165. except:
  1166. pass
  1167. raise HTTPException(
  1168. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1169. detail=detail,
  1170. )
  1171. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1172. async def update_pipeline_valves(
  1173. urlIdx: Optional[int],
  1174. pipeline_id: str,
  1175. form_data: dict,
  1176. user=Depends(get_admin_user),
  1177. ):
  1178. models = await get_all_models()
  1179. r = None
  1180. try:
  1181. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1182. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1183. headers = {"Authorization": f"Bearer {key}"}
  1184. r = requests.post(
  1185. f"{url}/{pipeline_id}/valves/update",
  1186. headers=headers,
  1187. json={**form_data},
  1188. )
  1189. r.raise_for_status()
  1190. data = r.json()
  1191. return {**data}
  1192. except Exception as e:
  1193. # Handle connection error here
  1194. print(f"Connection error: {e}")
  1195. detail = "Pipeline not found"
  1196. if r is not None:
  1197. try:
  1198. res = r.json()
  1199. if "detail" in res:
  1200. detail = res["detail"]
  1201. except:
  1202. pass
  1203. raise HTTPException(
  1204. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1205. detail=detail,
  1206. )
  1207. ##################################
  1208. #
  1209. # Config Endpoints
  1210. #
  1211. ##################################
  1212. @app.get("/api/config")
  1213. async def get_app_config():
  1214. # Checking and Handling the Absence of 'ui' in CONFIG_DATA
  1215. default_locale = "en-US"
  1216. if "ui" in CONFIG_DATA:
  1217. default_locale = CONFIG_DATA["ui"].get("default_locale", "en-US")
  1218. # The Rest of the Function Now Uses the Variables Defined Above
  1219. return {
  1220. "status": True,
  1221. "name": WEBUI_NAME,
  1222. "version": VERSION,
  1223. "default_locale": default_locale,
  1224. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1225. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1226. "features": {
  1227. "auth": WEBUI_AUTH,
  1228. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1229. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1230. "enable_web_search": rag_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1231. "enable_image_generation": images_app.state.config.ENABLED,
  1232. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1233. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1234. },
  1235. "audio": {
  1236. "tts": {
  1237. "engine": audio_app.state.config.TTS_ENGINE,
  1238. "voice": audio_app.state.config.TTS_VOICE,
  1239. },
  1240. "stt": {
  1241. "engine": audio_app.state.config.STT_ENGINE,
  1242. },
  1243. },
  1244. }
  1245. @app.get("/api/config/model/filter")
  1246. async def get_model_filter_config(user=Depends(get_admin_user)):
  1247. return {
  1248. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1249. "models": app.state.config.MODEL_FILTER_LIST,
  1250. }
  1251. class ModelFilterConfigForm(BaseModel):
  1252. enabled: bool
  1253. models: List[str]
  1254. @app.post("/api/config/model/filter")
  1255. async def update_model_filter_config(
  1256. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  1257. ):
  1258. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  1259. app.state.config.MODEL_FILTER_LIST = form_data.models
  1260. return {
  1261. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1262. "models": app.state.config.MODEL_FILTER_LIST,
  1263. }
  1264. # TODO: webhook endpoint should be under config endpoints
  1265. @app.get("/api/webhook")
  1266. async def get_webhook_url(user=Depends(get_admin_user)):
  1267. return {
  1268. "url": app.state.config.WEBHOOK_URL,
  1269. }
  1270. class UrlForm(BaseModel):
  1271. url: str
  1272. @app.post("/api/webhook")
  1273. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1274. app.state.config.WEBHOOK_URL = form_data.url
  1275. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1276. return {"url": app.state.config.WEBHOOK_URL}
  1277. @app.get("/api/version")
  1278. async def get_app_config():
  1279. return {
  1280. "version": VERSION,
  1281. }
  1282. @app.get("/api/changelog")
  1283. async def get_app_changelog():
  1284. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1285. @app.get("/api/version/updates")
  1286. async def get_app_latest_release_version():
  1287. try:
  1288. async with aiohttp.ClientSession(trust_env=True) as session:
  1289. async with session.get(
  1290. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1291. ) as response:
  1292. response.raise_for_status()
  1293. data = await response.json()
  1294. latest_version = data["tag_name"]
  1295. return {"current": VERSION, "latest": latest_version[1:]}
  1296. except aiohttp.ClientError as e:
  1297. raise HTTPException(
  1298. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  1299. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  1300. )
  1301. @app.get("/manifest.json")
  1302. async def get_manifest_json():
  1303. return {
  1304. "name": WEBUI_NAME,
  1305. "short_name": WEBUI_NAME,
  1306. "start_url": "/",
  1307. "display": "standalone",
  1308. "background_color": "#343541",
  1309. "theme_color": "#343541",
  1310. "orientation": "portrait-primary",
  1311. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  1312. }
  1313. @app.get("/opensearch.xml")
  1314. async def get_opensearch_xml():
  1315. xml_content = rf"""
  1316. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1317. <ShortName>{WEBUI_NAME}</ShortName>
  1318. <Description>Search {WEBUI_NAME}</Description>
  1319. <InputEncoding>UTF-8</InputEncoding>
  1320. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/favicon.png</Image>
  1321. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1322. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1323. </OpenSearchDescription>
  1324. """
  1325. return Response(content=xml_content, media_type="application/xml")
  1326. @app.get("/health")
  1327. async def healthcheck():
  1328. return {"status": True}
  1329. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  1330. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  1331. if os.path.exists(FRONTEND_BUILD_DIR):
  1332. mimetypes.add_type("text/javascript", ".js")
  1333. app.mount(
  1334. "/",
  1335. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1336. name="spa-static-files",
  1337. )
  1338. else:
  1339. log.warning(
  1340. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1341. )