main.py 47 KB

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