main.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  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(
  172. OpenAIChatCompletionForm(**payload), user=user
  173. )
  174. else:
  175. response = await generate_openai_chat_completion(payload, user=user)
  176. content = None
  177. if hasattr(response, "body_iterator"):
  178. async for chunk in response.body_iterator:
  179. data = json.loads(chunk.decode("utf-8"))
  180. content = data["choices"][0]["message"]["content"]
  181. # Cleanup any remaining background tasks if necessary
  182. if response.background is not None:
  183. await response.background()
  184. else:
  185. content = response["choices"][0]["message"]["content"]
  186. # Parse the function response
  187. if content is not None:
  188. print(f"content: {content}")
  189. result = json.loads(content)
  190. print(result)
  191. # Call the function
  192. if "name" in result:
  193. if tool_id in webui_app.state.TOOLS:
  194. toolkit_module = webui_app.state.TOOLS[tool_id]
  195. else:
  196. toolkit_module = load_toolkit_module_by_id(tool_id)
  197. webui_app.state.TOOLS[tool_id] = toolkit_module
  198. function = getattr(toolkit_module, result["name"])
  199. function_result = None
  200. try:
  201. # Get the signature of the function
  202. sig = inspect.signature(function)
  203. # Check if '__user__' is a parameter of the function
  204. if "__user__" in sig.parameters:
  205. # Call the function with the '__user__' parameter included
  206. function_result = function(
  207. **{
  208. **result["parameters"],
  209. "__user__": {
  210. "id": user.id,
  211. "email": user.email,
  212. "name": user.name,
  213. "role": user.role,
  214. },
  215. }
  216. )
  217. else:
  218. # Call the function without modifying the parameters
  219. function_result = function(**result["parameters"])
  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 response:
  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, form_data["prompt"], user.model_dump()
  623. )
  624. payload = {
  625. "model": model_id,
  626. "messages": [{"role": "user", "content": content}],
  627. "stream": False,
  628. "max_tokens": 50,
  629. "chat_id": form_data.get("chat_id", None),
  630. "title": True,
  631. }
  632. log.debug(payload)
  633. try:
  634. payload = filter_pipeline(payload, user)
  635. except Exception as e:
  636. return JSONResponse(
  637. status_code=e.args[0],
  638. content={"detail": e.args[1]},
  639. )
  640. if model["owned_by"] == "ollama":
  641. return await generate_ollama_chat_completion(
  642. OpenAIChatCompletionForm(**payload), user=user
  643. )
  644. else:
  645. return await generate_openai_chat_completion(payload, user=user)
  646. @app.post("/api/task/query/completions")
  647. async def generate_search_query(form_data: dict, user=Depends(get_verified_user)):
  648. print("generate_search_query")
  649. if len(form_data["prompt"]) < app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD:
  650. raise HTTPException(
  651. status_code=status.HTTP_400_BAD_REQUEST,
  652. detail=f"Skip search query generation for short prompts (< {app.state.config.SEARCH_QUERY_PROMPT_LENGTH_THRESHOLD} characters)",
  653. )
  654. model_id = form_data["model"]
  655. if model_id not in app.state.MODELS:
  656. raise HTTPException(
  657. status_code=status.HTTP_404_NOT_FOUND,
  658. detail="Model not found",
  659. )
  660. # Check if the user has a custom task model
  661. # If the user has a custom task model, use that model
  662. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  663. if app.state.config.TASK_MODEL:
  664. task_model_id = app.state.config.TASK_MODEL
  665. if task_model_id in app.state.MODELS:
  666. model_id = task_model_id
  667. else:
  668. if app.state.config.TASK_MODEL_EXTERNAL:
  669. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  670. if task_model_id in app.state.MODELS:
  671. model_id = task_model_id
  672. print(model_id)
  673. model = app.state.MODELS[model_id]
  674. template = app.state.config.SEARCH_QUERY_GENERATION_PROMPT_TEMPLATE
  675. content = search_query_generation_template(
  676. template, form_data["prompt"], user.model_dump()
  677. )
  678. payload = {
  679. "model": model_id,
  680. "messages": [{"role": "user", "content": content}],
  681. "stream": False,
  682. "max_tokens": 30,
  683. "task": True,
  684. }
  685. print(payload)
  686. try:
  687. payload = filter_pipeline(payload, user)
  688. except Exception as e:
  689. return JSONResponse(
  690. status_code=e.args[0],
  691. content={"detail": e.args[1]},
  692. )
  693. if model["owned_by"] == "ollama":
  694. return await generate_ollama_chat_completion(
  695. OpenAIChatCompletionForm(**payload), user=user
  696. )
  697. else:
  698. return await generate_openai_chat_completion(payload, user=user)
  699. @app.post("/api/task/emoji/completions")
  700. async def generate_emoji(form_data: dict, user=Depends(get_verified_user)):
  701. print("generate_emoji")
  702. model_id = form_data["model"]
  703. if model_id not in app.state.MODELS:
  704. raise HTTPException(
  705. status_code=status.HTTP_404_NOT_FOUND,
  706. detail="Model not found",
  707. )
  708. # Check if the user has a custom task model
  709. # If the user has a custom task model, use that model
  710. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  711. if app.state.config.TASK_MODEL:
  712. task_model_id = app.state.config.TASK_MODEL
  713. if task_model_id in app.state.MODELS:
  714. model_id = task_model_id
  715. else:
  716. if app.state.config.TASK_MODEL_EXTERNAL:
  717. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  718. if task_model_id in app.state.MODELS:
  719. model_id = task_model_id
  720. print(model_id)
  721. model = app.state.MODELS[model_id]
  722. template = '''
  723. 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., 😊, 😢, 😡, 😱).
  724. Message: """{{prompt}}"""
  725. '''
  726. content = title_generation_template(
  727. template, form_data["prompt"], user.model_dump()
  728. )
  729. payload = {
  730. "model": model_id,
  731. "messages": [{"role": "user", "content": content}],
  732. "stream": False,
  733. "max_tokens": 4,
  734. "chat_id": form_data.get("chat_id", None),
  735. "task": True,
  736. }
  737. log.debug(payload)
  738. try:
  739. payload = filter_pipeline(payload, user)
  740. except Exception as e:
  741. return JSONResponse(
  742. status_code=e.args[0],
  743. content={"detail": e.args[1]},
  744. )
  745. if model["owned_by"] == "ollama":
  746. return await generate_ollama_chat_completion(
  747. OpenAIChatCompletionForm(**payload), user=user
  748. )
  749. else:
  750. return await generate_openai_chat_completion(payload, user=user)
  751. @app.post("/api/task/tools/completions")
  752. async def get_tools_function_calling(form_data: dict, user=Depends(get_verified_user)):
  753. print("get_tools_function_calling")
  754. model_id = form_data["model"]
  755. if model_id not in app.state.MODELS:
  756. raise HTTPException(
  757. status_code=status.HTTP_404_NOT_FOUND,
  758. detail="Model not found",
  759. )
  760. # Check if the user has a custom task model
  761. # If the user has a custom task model, use that model
  762. if app.state.MODELS[model_id]["owned_by"] == "ollama":
  763. if app.state.config.TASK_MODEL:
  764. task_model_id = app.state.config.TASK_MODEL
  765. if task_model_id in app.state.MODELS:
  766. model_id = task_model_id
  767. else:
  768. if app.state.config.TASK_MODEL_EXTERNAL:
  769. task_model_id = app.state.config.TASK_MODEL_EXTERNAL
  770. if task_model_id in app.state.MODELS:
  771. model_id = task_model_id
  772. print(model_id)
  773. template = app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  774. try:
  775. context = await get_function_call_response(
  776. form_data["messages"], form_data["tool_id"], template, model_id, user
  777. )
  778. return context
  779. except Exception as e:
  780. return JSONResponse(
  781. status_code=e.args[0],
  782. content={"detail": e.args[1]},
  783. )
  784. @app.post("/api/chat/completions")
  785. async def generate_chat_completions(form_data: dict, user=Depends(get_verified_user)):
  786. model_id = form_data["model"]
  787. if model_id not in app.state.MODELS:
  788. raise HTTPException(
  789. status_code=status.HTTP_404_NOT_FOUND,
  790. detail="Model not found",
  791. )
  792. model = app.state.MODELS[model_id]
  793. print(model)
  794. if model["owned_by"] == "ollama":
  795. return await generate_ollama_chat_completion(
  796. OpenAIChatCompletionForm(**form_data), user=user
  797. )
  798. else:
  799. return await generate_openai_chat_completion(form_data, user=user)
  800. @app.post("/api/chat/completed")
  801. async def chat_completed(form_data: dict, user=Depends(get_verified_user)):
  802. data = form_data
  803. model_id = data["model"]
  804. filters = [
  805. model
  806. for model in app.state.MODELS.values()
  807. if "pipeline" in model
  808. and "type" in model["pipeline"]
  809. and model["pipeline"]["type"] == "filter"
  810. and (
  811. model["pipeline"]["pipelines"] == ["*"]
  812. or any(
  813. model_id == target_model_id
  814. for target_model_id in model["pipeline"]["pipelines"]
  815. )
  816. )
  817. ]
  818. sorted_filters = sorted(filters, key=lambda x: x["pipeline"]["priority"])
  819. print(model_id)
  820. if model_id in app.state.MODELS:
  821. model = app.state.MODELS[model_id]
  822. if "pipeline" in model:
  823. sorted_filters = [model] + sorted_filters
  824. for filter in sorted_filters:
  825. r = None
  826. try:
  827. urlIdx = filter["urlIdx"]
  828. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  829. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  830. if key != "":
  831. headers = {"Authorization": f"Bearer {key}"}
  832. r = requests.post(
  833. f"{url}/{filter['id']}/filter/outlet",
  834. headers=headers,
  835. json={
  836. "user": {"id": user.id, "name": user.name, "role": user.role},
  837. "body": data,
  838. },
  839. )
  840. r.raise_for_status()
  841. data = r.json()
  842. except Exception as e:
  843. # Handle connection error here
  844. print(f"Connection error: {e}")
  845. if r is not None:
  846. try:
  847. res = r.json()
  848. if "detail" in res:
  849. return JSONResponse(
  850. status_code=r.status_code,
  851. content=res,
  852. )
  853. except:
  854. pass
  855. else:
  856. pass
  857. return data
  858. @app.get("/api/pipelines/list")
  859. async def get_pipelines_list(user=Depends(get_admin_user)):
  860. responses = await get_openai_models(raw=True)
  861. print(responses)
  862. urlIdxs = [
  863. idx
  864. for idx, response in enumerate(responses)
  865. if response != None and "pipelines" in response
  866. ]
  867. return {
  868. "data": [
  869. {
  870. "url": openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx],
  871. "idx": urlIdx,
  872. }
  873. for urlIdx in urlIdxs
  874. ]
  875. }
  876. @app.post("/api/pipelines/upload")
  877. async def upload_pipeline(
  878. urlIdx: int = Form(...), file: UploadFile = File(...), user=Depends(get_admin_user)
  879. ):
  880. print("upload_pipeline", urlIdx, file.filename)
  881. # Check if the uploaded file is a python file
  882. if not file.filename.endswith(".py"):
  883. raise HTTPException(
  884. status_code=status.HTTP_400_BAD_REQUEST,
  885. detail="Only Python (.py) files are allowed.",
  886. )
  887. upload_folder = f"{CACHE_DIR}/pipelines"
  888. os.makedirs(upload_folder, exist_ok=True)
  889. file_path = os.path.join(upload_folder, file.filename)
  890. try:
  891. # Save the uploaded file
  892. with open(file_path, "wb") as buffer:
  893. shutil.copyfileobj(file.file, buffer)
  894. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  895. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  896. headers = {"Authorization": f"Bearer {key}"}
  897. with open(file_path, "rb") as f:
  898. files = {"file": f}
  899. r = requests.post(f"{url}/pipelines/upload", headers=headers, files=files)
  900. r.raise_for_status()
  901. data = r.json()
  902. return {**data}
  903. except Exception as e:
  904. # Handle connection error here
  905. print(f"Connection error: {e}")
  906. detail = "Pipeline not found"
  907. if r is not None:
  908. try:
  909. res = r.json()
  910. if "detail" in res:
  911. detail = res["detail"]
  912. except:
  913. pass
  914. raise HTTPException(
  915. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  916. detail=detail,
  917. )
  918. finally:
  919. # Ensure the file is deleted after the upload is completed or on failure
  920. if os.path.exists(file_path):
  921. os.remove(file_path)
  922. class AddPipelineForm(BaseModel):
  923. url: str
  924. urlIdx: int
  925. @app.post("/api/pipelines/add")
  926. async def add_pipeline(form_data: AddPipelineForm, user=Depends(get_admin_user)):
  927. r = None
  928. try:
  929. urlIdx = form_data.urlIdx
  930. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  931. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  932. headers = {"Authorization": f"Bearer {key}"}
  933. r = requests.post(
  934. f"{url}/pipelines/add", headers=headers, json={"url": form_data.url}
  935. )
  936. r.raise_for_status()
  937. data = r.json()
  938. return {**data}
  939. except Exception as e:
  940. # Handle connection error here
  941. print(f"Connection error: {e}")
  942. detail = "Pipeline not found"
  943. if r is not None:
  944. try:
  945. res = r.json()
  946. if "detail" in res:
  947. detail = res["detail"]
  948. except:
  949. pass
  950. raise HTTPException(
  951. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  952. detail=detail,
  953. )
  954. class DeletePipelineForm(BaseModel):
  955. id: str
  956. urlIdx: int
  957. @app.delete("/api/pipelines/delete")
  958. async def delete_pipeline(form_data: DeletePipelineForm, user=Depends(get_admin_user)):
  959. r = None
  960. try:
  961. urlIdx = form_data.urlIdx
  962. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  963. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  964. headers = {"Authorization": f"Bearer {key}"}
  965. r = requests.delete(
  966. f"{url}/pipelines/delete", headers=headers, json={"id": form_data.id}
  967. )
  968. r.raise_for_status()
  969. data = r.json()
  970. return {**data}
  971. except Exception as e:
  972. # Handle connection error here
  973. print(f"Connection error: {e}")
  974. detail = "Pipeline not found"
  975. if r is not None:
  976. try:
  977. res = r.json()
  978. if "detail" in res:
  979. detail = res["detail"]
  980. except:
  981. pass
  982. raise HTTPException(
  983. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  984. detail=detail,
  985. )
  986. @app.get("/api/pipelines")
  987. async def get_pipelines(urlIdx: Optional[int] = None, user=Depends(get_admin_user)):
  988. r = None
  989. try:
  990. urlIdx
  991. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  992. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  993. headers = {"Authorization": f"Bearer {key}"}
  994. r = requests.get(f"{url}/pipelines", headers=headers)
  995. r.raise_for_status()
  996. data = r.json()
  997. return {**data}
  998. except Exception as e:
  999. # Handle connection error here
  1000. print(f"Connection error: {e}")
  1001. detail = "Pipeline not found"
  1002. if r is not None:
  1003. try:
  1004. res = r.json()
  1005. if "detail" in res:
  1006. detail = res["detail"]
  1007. except:
  1008. pass
  1009. raise HTTPException(
  1010. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1011. detail=detail,
  1012. )
  1013. @app.get("/api/pipelines/{pipeline_id}/valves")
  1014. async def get_pipeline_valves(
  1015. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  1016. ):
  1017. models = await get_all_models()
  1018. r = None
  1019. try:
  1020. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1021. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1022. headers = {"Authorization": f"Bearer {key}"}
  1023. r = requests.get(f"{url}/{pipeline_id}/valves", headers=headers)
  1024. r.raise_for_status()
  1025. data = r.json()
  1026. return {**data}
  1027. except Exception as e:
  1028. # Handle connection error here
  1029. print(f"Connection error: {e}")
  1030. detail = "Pipeline not found"
  1031. if r is not None:
  1032. try:
  1033. res = r.json()
  1034. if "detail" in res:
  1035. detail = res["detail"]
  1036. except:
  1037. pass
  1038. raise HTTPException(
  1039. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1040. detail=detail,
  1041. )
  1042. @app.get("/api/pipelines/{pipeline_id}/valves/spec")
  1043. async def get_pipeline_valves_spec(
  1044. urlIdx: Optional[int], pipeline_id: str, user=Depends(get_admin_user)
  1045. ):
  1046. models = await get_all_models()
  1047. r = None
  1048. try:
  1049. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1050. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1051. headers = {"Authorization": f"Bearer {key}"}
  1052. r = requests.get(f"{url}/{pipeline_id}/valves/spec", headers=headers)
  1053. r.raise_for_status()
  1054. data = r.json()
  1055. return {**data}
  1056. except Exception as e:
  1057. # Handle connection error here
  1058. print(f"Connection error: {e}")
  1059. detail = "Pipeline not found"
  1060. if r is not None:
  1061. try:
  1062. res = r.json()
  1063. if "detail" in res:
  1064. detail = res["detail"]
  1065. except:
  1066. pass
  1067. raise HTTPException(
  1068. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1069. detail=detail,
  1070. )
  1071. @app.post("/api/pipelines/{pipeline_id}/valves/update")
  1072. async def update_pipeline_valves(
  1073. urlIdx: Optional[int],
  1074. pipeline_id: str,
  1075. form_data: dict,
  1076. user=Depends(get_admin_user),
  1077. ):
  1078. models = await get_all_models()
  1079. r = None
  1080. try:
  1081. url = openai_app.state.config.OPENAI_API_BASE_URLS[urlIdx]
  1082. key = openai_app.state.config.OPENAI_API_KEYS[urlIdx]
  1083. headers = {"Authorization": f"Bearer {key}"}
  1084. r = requests.post(
  1085. f"{url}/{pipeline_id}/valves/update",
  1086. headers=headers,
  1087. json={**form_data},
  1088. )
  1089. r.raise_for_status()
  1090. data = r.json()
  1091. return {**data}
  1092. except Exception as e:
  1093. # Handle connection error here
  1094. print(f"Connection error: {e}")
  1095. detail = "Pipeline not found"
  1096. if r is not None:
  1097. try:
  1098. res = r.json()
  1099. if "detail" in res:
  1100. detail = res["detail"]
  1101. except:
  1102. pass
  1103. raise HTTPException(
  1104. status_code=(r.status_code if r is not None else status.HTTP_404_NOT_FOUND),
  1105. detail=detail,
  1106. )
  1107. @app.get("/api/config")
  1108. async def get_app_config():
  1109. # Checking and Handling the Absence of 'ui' in CONFIG_DATA
  1110. default_locale = "en-US"
  1111. if "ui" in CONFIG_DATA:
  1112. default_locale = CONFIG_DATA["ui"].get("default_locale", "en-US")
  1113. # The Rest of the Function Now Uses the Variables Defined Above
  1114. return {
  1115. "status": True,
  1116. "name": WEBUI_NAME,
  1117. "version": VERSION,
  1118. "default_locale": default_locale,
  1119. "default_models": webui_app.state.config.DEFAULT_MODELS,
  1120. "default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  1121. "features": {
  1122. "auth": WEBUI_AUTH,
  1123. "auth_trusted_header": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
  1124. "enable_signup": webui_app.state.config.ENABLE_SIGNUP,
  1125. "enable_web_search": rag_app.state.config.ENABLE_RAG_WEB_SEARCH,
  1126. "enable_image_generation": images_app.state.config.ENABLED,
  1127. "enable_community_sharing": webui_app.state.config.ENABLE_COMMUNITY_SHARING,
  1128. "enable_admin_export": ENABLE_ADMIN_EXPORT,
  1129. },
  1130. "audio": {
  1131. "tts": {
  1132. "engine": audio_app.state.config.TTS_ENGINE,
  1133. "voice": audio_app.state.config.TTS_VOICE,
  1134. },
  1135. "stt": {
  1136. "engine": audio_app.state.config.STT_ENGINE,
  1137. },
  1138. },
  1139. }
  1140. @app.get("/api/config/model/filter")
  1141. async def get_model_filter_config(user=Depends(get_admin_user)):
  1142. return {
  1143. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1144. "models": app.state.config.MODEL_FILTER_LIST,
  1145. }
  1146. class ModelFilterConfigForm(BaseModel):
  1147. enabled: bool
  1148. models: List[str]
  1149. @app.post("/api/config/model/filter")
  1150. async def update_model_filter_config(
  1151. form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
  1152. ):
  1153. app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
  1154. app.state.config.MODEL_FILTER_LIST = form_data.models
  1155. return {
  1156. "enabled": app.state.config.ENABLE_MODEL_FILTER,
  1157. "models": app.state.config.MODEL_FILTER_LIST,
  1158. }
  1159. @app.get("/api/webhook")
  1160. async def get_webhook_url(user=Depends(get_admin_user)):
  1161. return {
  1162. "url": app.state.config.WEBHOOK_URL,
  1163. }
  1164. class UrlForm(BaseModel):
  1165. url: str
  1166. @app.post("/api/webhook")
  1167. async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
  1168. app.state.config.WEBHOOK_URL = form_data.url
  1169. webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
  1170. return {"url": app.state.config.WEBHOOK_URL}
  1171. @app.get("/api/version")
  1172. async def get_app_config():
  1173. return {
  1174. "version": VERSION,
  1175. }
  1176. @app.get("/api/changelog")
  1177. async def get_app_changelog():
  1178. return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
  1179. @app.get("/api/version/updates")
  1180. async def get_app_latest_release_version():
  1181. try:
  1182. async with aiohttp.ClientSession(trust_env=True) as session:
  1183. async with session.get(
  1184. "https://api.github.com/repos/open-webui/open-webui/releases/latest"
  1185. ) as response:
  1186. response.raise_for_status()
  1187. data = await response.json()
  1188. latest_version = data["tag_name"]
  1189. return {"current": VERSION, "latest": latest_version[1:]}
  1190. except aiohttp.ClientError as e:
  1191. raise HTTPException(
  1192. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  1193. detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
  1194. )
  1195. @app.get("/manifest.json")
  1196. async def get_manifest_json():
  1197. return {
  1198. "name": WEBUI_NAME,
  1199. "short_name": WEBUI_NAME,
  1200. "start_url": "/",
  1201. "display": "standalone",
  1202. "background_color": "#343541",
  1203. "theme_color": "#343541",
  1204. "orientation": "portrait-primary",
  1205. "icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
  1206. }
  1207. @app.get("/opensearch.xml")
  1208. async def get_opensearch_xml():
  1209. xml_content = rf"""
  1210. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
  1211. <ShortName>{WEBUI_NAME}</ShortName>
  1212. <Description>Search {WEBUI_NAME}</Description>
  1213. <InputEncoding>UTF-8</InputEncoding>
  1214. <Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/favicon.png</Image>
  1215. <Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
  1216. <moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
  1217. </OpenSearchDescription>
  1218. """
  1219. return Response(content=xml_content, media_type="application/xml")
  1220. @app.get("/health")
  1221. async def healthcheck():
  1222. return {"status": True}
  1223. app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
  1224. app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
  1225. if os.path.exists(FRONTEND_BUILD_DIR):
  1226. mimetypes.add_type("text/javascript", ".js")
  1227. app.mount(
  1228. "/",
  1229. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  1230. name="spa-static-files",
  1231. )
  1232. else:
  1233. log.warning(
  1234. f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
  1235. )