main.py 63 KB

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