main.py 51 KB

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