main.py 47 KB

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