main.py 48 KB

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