main.py 48 KB

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