main.py 50 KB

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