main.py 48 KB

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