main.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. import inspect
  2. import json
  3. import logging
  4. import time
  5. from typing import AsyncGenerator, Generator, Iterator
  6. from open_webui.apps.socket.main import get_event_call, get_event_emitter
  7. from open_webui.apps.webui.models.functions import Functions
  8. from open_webui.apps.webui.models.models import Models
  9. from open_webui.apps.webui.routers import (
  10. auths,
  11. chats,
  12. folders,
  13. configs,
  14. groups,
  15. files,
  16. functions,
  17. memories,
  18. models,
  19. knowledge,
  20. prompts,
  21. evaluations,
  22. tools,
  23. users,
  24. utils,
  25. )
  26. from open_webui.apps.webui.utils import load_function_module_by_id
  27. from open_webui.config import (
  28. ADMIN_EMAIL,
  29. CORS_ALLOW_ORIGIN,
  30. DEFAULT_MODELS,
  31. DEFAULT_PROMPT_SUGGESTIONS,
  32. DEFAULT_USER_ROLE,
  33. MODEL_ORDER_LIST,
  34. ENABLE_COMMUNITY_SHARING,
  35. ENABLE_LOGIN_FORM,
  36. ENABLE_MESSAGE_RATING,
  37. ENABLE_SIGNUP,
  38. ENABLE_API_KEY,
  39. ENABLE_EVALUATION_ARENA_MODELS,
  40. EVALUATION_ARENA_MODELS,
  41. DEFAULT_ARENA_MODEL,
  42. JWT_EXPIRES_IN,
  43. ENABLE_OAUTH_ROLE_MANAGEMENT,
  44. OAUTH_ROLES_CLAIM,
  45. OAUTH_EMAIL_CLAIM,
  46. OAUTH_PICTURE_CLAIM,
  47. OAUTH_USERNAME_CLAIM,
  48. OAUTH_ALLOWED_ROLES,
  49. OAUTH_ADMIN_ROLES,
  50. SHOW_ADMIN_DETAILS,
  51. USER_PERMISSIONS,
  52. WEBHOOK_URL,
  53. WEBUI_AUTH,
  54. WEBUI_BANNERS,
  55. ENABLE_LDAP,
  56. LDAP_SERVER_LABEL,
  57. LDAP_SERVER_HOST,
  58. LDAP_SERVER_PORT,
  59. LDAP_ATTRIBUTE_FOR_USERNAME,
  60. LDAP_SEARCH_FILTERS,
  61. LDAP_SEARCH_BASE,
  62. LDAP_APP_DN,
  63. LDAP_APP_PASSWORD,
  64. LDAP_USE_TLS,
  65. LDAP_CA_CERT_FILE,
  66. LDAP_CIPHERS,
  67. AppConfig,
  68. )
  69. from open_webui.env import (
  70. ENV,
  71. SRC_LOG_LEVELS,
  72. WEBUI_AUTH_TRUSTED_EMAIL_HEADER,
  73. WEBUI_AUTH_TRUSTED_NAME_HEADER,
  74. )
  75. from fastapi import FastAPI
  76. from fastapi.middleware.cors import CORSMiddleware
  77. from fastapi.responses import StreamingResponse
  78. from pydantic import BaseModel
  79. from open_webui.utils.misc import (
  80. openai_chat_chunk_message_template,
  81. openai_chat_completion_message_template,
  82. )
  83. from open_webui.utils.payload import (
  84. apply_model_params_to_body_openai,
  85. apply_model_system_prompt_to_body,
  86. )
  87. from open_webui.utils.tools import get_tools
  88. app = FastAPI(
  89. docs_url="/docs" if ENV == "dev" else None,
  90. openapi_url="/openapi.json" if ENV == "dev" else None,
  91. redoc_url=None,
  92. )
  93. log = logging.getLogger(__name__)
  94. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  95. app.state.config = AppConfig()
  96. app.state.config.ENABLE_SIGNUP = ENABLE_SIGNUP
  97. app.state.config.ENABLE_LOGIN_FORM = ENABLE_LOGIN_FORM
  98. app.state.config.ENABLE_API_KEY = ENABLE_API_KEY
  99. app.state.config.JWT_EXPIRES_IN = JWT_EXPIRES_IN
  100. app.state.AUTH_TRUSTED_EMAIL_HEADER = WEBUI_AUTH_TRUSTED_EMAIL_HEADER
  101. app.state.AUTH_TRUSTED_NAME_HEADER = WEBUI_AUTH_TRUSTED_NAME_HEADER
  102. app.state.config.SHOW_ADMIN_DETAILS = SHOW_ADMIN_DETAILS
  103. app.state.config.ADMIN_EMAIL = ADMIN_EMAIL
  104. app.state.config.DEFAULT_MODELS = DEFAULT_MODELS
  105. app.state.config.DEFAULT_PROMPT_SUGGESTIONS = DEFAULT_PROMPT_SUGGESTIONS
  106. app.state.config.DEFAULT_USER_ROLE = DEFAULT_USER_ROLE
  107. app.state.config.USER_PERMISSIONS = USER_PERMISSIONS
  108. app.state.config.WEBHOOK_URL = WEBHOOK_URL
  109. app.state.config.BANNERS = WEBUI_BANNERS
  110. app.state.config.MODEL_ORDER_LIST = MODEL_ORDER_LIST
  111. app.state.config.ENABLE_COMMUNITY_SHARING = ENABLE_COMMUNITY_SHARING
  112. app.state.config.ENABLE_MESSAGE_RATING = ENABLE_MESSAGE_RATING
  113. app.state.config.ENABLE_EVALUATION_ARENA_MODELS = ENABLE_EVALUATION_ARENA_MODELS
  114. app.state.config.EVALUATION_ARENA_MODELS = EVALUATION_ARENA_MODELS
  115. app.state.config.OAUTH_USERNAME_CLAIM = OAUTH_USERNAME_CLAIM
  116. app.state.config.OAUTH_PICTURE_CLAIM = OAUTH_PICTURE_CLAIM
  117. app.state.config.OAUTH_EMAIL_CLAIM = OAUTH_EMAIL_CLAIM
  118. app.state.config.ENABLE_OAUTH_ROLE_MANAGEMENT = ENABLE_OAUTH_ROLE_MANAGEMENT
  119. app.state.config.OAUTH_ROLES_CLAIM = OAUTH_ROLES_CLAIM
  120. app.state.config.OAUTH_ALLOWED_ROLES = OAUTH_ALLOWED_ROLES
  121. app.state.config.OAUTH_ADMIN_ROLES = OAUTH_ADMIN_ROLES
  122. app.state.config.ENABLE_LDAP = ENABLE_LDAP
  123. app.state.config.LDAP_SERVER_LABEL = LDAP_SERVER_LABEL
  124. app.state.config.LDAP_SERVER_HOST = LDAP_SERVER_HOST
  125. app.state.config.LDAP_SERVER_PORT = LDAP_SERVER_PORT
  126. app.state.config.LDAP_ATTRIBUTE_FOR_USERNAME = LDAP_ATTRIBUTE_FOR_USERNAME
  127. app.state.config.LDAP_APP_DN = LDAP_APP_DN
  128. app.state.config.LDAP_APP_PASSWORD = LDAP_APP_PASSWORD
  129. app.state.config.LDAP_SEARCH_BASE = LDAP_SEARCH_BASE
  130. app.state.config.LDAP_SEARCH_FILTERS = LDAP_SEARCH_FILTERS
  131. app.state.config.LDAP_USE_TLS = LDAP_USE_TLS
  132. app.state.config.LDAP_CA_CERT_FILE = LDAP_CA_CERT_FILE
  133. app.state.config.LDAP_CIPHERS = LDAP_CIPHERS
  134. app.state.TOOLS = {}
  135. app.state.FUNCTIONS = {}
  136. app.add_middleware(
  137. CORSMiddleware,
  138. allow_origins=CORS_ALLOW_ORIGIN,
  139. allow_credentials=True,
  140. allow_methods=["*"],
  141. allow_headers=["*"],
  142. )
  143. app.include_router(configs.router, prefix="/configs", tags=["configs"])
  144. app.include_router(auths.router, prefix="/auths", tags=["auths"])
  145. app.include_router(users.router, prefix="/users", tags=["users"])
  146. app.include_router(chats.router, prefix="/chats", tags=["chats"])
  147. app.include_router(models.router, prefix="/models", tags=["models"])
  148. app.include_router(knowledge.router, prefix="/knowledge", tags=["knowledge"])
  149. app.include_router(prompts.router, prefix="/prompts", tags=["prompts"])
  150. app.include_router(tools.router, prefix="/tools", tags=["tools"])
  151. app.include_router(memories.router, prefix="/memories", tags=["memories"])
  152. app.include_router(folders.router, prefix="/folders", tags=["folders"])
  153. app.include_router(groups.router, prefix="/groups", tags=["groups"])
  154. app.include_router(files.router, prefix="/files", tags=["files"])
  155. app.include_router(functions.router, prefix="/functions", tags=["functions"])
  156. app.include_router(evaluations.router, prefix="/evaluations", tags=["evaluations"])
  157. app.include_router(utils.router, prefix="/utils", tags=["utils"])
  158. @app.get("/")
  159. async def get_status():
  160. return {
  161. "status": True,
  162. "auth": WEBUI_AUTH,
  163. "default_models": app.state.config.DEFAULT_MODELS,
  164. "default_prompt_suggestions": app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
  165. }
  166. async def get_all_models():
  167. models = []
  168. pipe_models = await get_pipe_models()
  169. models = models + pipe_models
  170. if app.state.config.ENABLE_EVALUATION_ARENA_MODELS:
  171. arena_models = []
  172. if len(app.state.config.EVALUATION_ARENA_MODELS) > 0:
  173. arena_models = [
  174. {
  175. "id": model["id"],
  176. "name": model["name"],
  177. "info": {
  178. "meta": model["meta"],
  179. },
  180. "object": "model",
  181. "created": int(time.time()),
  182. "owned_by": "arena",
  183. "arena": True,
  184. }
  185. for model in app.state.config.EVALUATION_ARENA_MODELS
  186. ]
  187. else:
  188. # Add default arena model
  189. arena_models = [
  190. {
  191. "id": DEFAULT_ARENA_MODEL["id"],
  192. "name": DEFAULT_ARENA_MODEL["name"],
  193. "info": {
  194. "meta": DEFAULT_ARENA_MODEL["meta"],
  195. },
  196. "object": "model",
  197. "created": int(time.time()),
  198. "owned_by": "arena",
  199. "arena": True,
  200. }
  201. ]
  202. models = models + arena_models
  203. return models
  204. def get_function_module(pipe_id: str):
  205. # Check if function is already loaded
  206. if pipe_id not in app.state.FUNCTIONS:
  207. function_module, _, _ = load_function_module_by_id(pipe_id)
  208. app.state.FUNCTIONS[pipe_id] = function_module
  209. else:
  210. function_module = app.state.FUNCTIONS[pipe_id]
  211. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  212. valves = Functions.get_function_valves_by_id(pipe_id)
  213. function_module.valves = function_module.Valves(**(valves if valves else {}))
  214. return function_module
  215. async def get_pipe_models():
  216. pipes = Functions.get_functions_by_type("pipe", active_only=True)
  217. pipe_models = []
  218. for pipe in pipes:
  219. function_module = get_function_module(pipe.id)
  220. # Check if function is a manifold
  221. if hasattr(function_module, "pipes"):
  222. sub_pipes = []
  223. # Check if pipes is a function or a list
  224. try:
  225. if callable(function_module.pipes):
  226. sub_pipes = function_module.pipes()
  227. else:
  228. sub_pipes = function_module.pipes
  229. except Exception as e:
  230. log.exception(e)
  231. sub_pipes = []
  232. log.debug(
  233. f"get_pipe_models: function '{pipe.id}' is a manifold of {sub_pipes}"
  234. )
  235. for p in sub_pipes:
  236. sub_pipe_id = f'{pipe.id}.{p["id"]}'
  237. sub_pipe_name = p["name"]
  238. if hasattr(function_module, "name"):
  239. sub_pipe_name = f"{function_module.name}{sub_pipe_name}"
  240. pipe_flag = {"type": pipe.type}
  241. pipe_models.append(
  242. {
  243. "id": sub_pipe_id,
  244. "name": sub_pipe_name,
  245. "object": "model",
  246. "created": pipe.created_at,
  247. "owned_by": "openai",
  248. "pipe": pipe_flag,
  249. }
  250. )
  251. else:
  252. pipe_flag = {"type": "pipe"}
  253. log.debug(
  254. f"get_pipe_models: function '{pipe.id}' is a single pipe {{ 'id': {pipe.id}, 'name': {pipe.name} }}"
  255. )
  256. pipe_models.append(
  257. {
  258. "id": pipe.id,
  259. "name": pipe.name,
  260. "object": "model",
  261. "created": pipe.created_at,
  262. "owned_by": "openai",
  263. "pipe": pipe_flag,
  264. }
  265. )
  266. return pipe_models
  267. async def execute_pipe(pipe, params):
  268. if inspect.iscoroutinefunction(pipe):
  269. return await pipe(**params)
  270. else:
  271. return pipe(**params)
  272. async def get_message_content(res: str | Generator | AsyncGenerator) -> str:
  273. if isinstance(res, str):
  274. return res
  275. if isinstance(res, Generator):
  276. return "".join(map(str, res))
  277. if isinstance(res, AsyncGenerator):
  278. return "".join([str(stream) async for stream in res])
  279. def process_line(form_data: dict, line):
  280. if isinstance(line, BaseModel):
  281. line = line.model_dump_json()
  282. line = f"data: {line}"
  283. if isinstance(line, dict):
  284. line = f"data: {json.dumps(line)}"
  285. try:
  286. line = line.decode("utf-8")
  287. except Exception:
  288. pass
  289. if line.startswith("data:"):
  290. return f"{line}\n\n"
  291. else:
  292. line = openai_chat_chunk_message_template(form_data["model"], line)
  293. return f"data: {json.dumps(line)}\n\n"
  294. def get_pipe_id(form_data: dict) -> str:
  295. pipe_id = form_data["model"]
  296. if "." in pipe_id:
  297. pipe_id, _ = pipe_id.split(".", 1)
  298. return pipe_id
  299. def get_function_params(function_module, form_data, user, extra_params=None):
  300. if extra_params is None:
  301. extra_params = {}
  302. pipe_id = get_pipe_id(form_data)
  303. # Get the signature of the function
  304. sig = inspect.signature(function_module.pipe)
  305. params = {"body": form_data} | {
  306. k: v for k, v in extra_params.items() if k in sig.parameters
  307. }
  308. if "__user__" in params and hasattr(function_module, "UserValves"):
  309. user_valves = Functions.get_user_valves_by_id_and_user_id(pipe_id, user.id)
  310. try:
  311. params["__user__"]["valves"] = function_module.UserValves(**user_valves)
  312. except Exception as e:
  313. log.exception(e)
  314. params["__user__"]["valves"] = function_module.UserValves()
  315. return params
  316. async def generate_function_chat_completion(form_data, user, models: dict = {}):
  317. model_id = form_data.get("model")
  318. model_info = Models.get_model_by_id(model_id)
  319. metadata = form_data.pop("metadata", {})
  320. files = metadata.get("files", [])
  321. tool_ids = metadata.get("tool_ids", [])
  322. # Check if tool_ids is None
  323. if tool_ids is None:
  324. tool_ids = []
  325. __event_emitter__ = None
  326. __event_call__ = None
  327. __task__ = None
  328. __task_body__ = None
  329. if metadata:
  330. if all(k in metadata for k in ("session_id", "chat_id", "message_id")):
  331. __event_emitter__ = get_event_emitter(metadata)
  332. __event_call__ = get_event_call(metadata)
  333. __task__ = metadata.get("task", None)
  334. __task_body__ = metadata.get("task_body", None)
  335. extra_params = {
  336. "__event_emitter__": __event_emitter__,
  337. "__event_call__": __event_call__,
  338. "__task__": __task__,
  339. "__task_body__": __task_body__,
  340. "__files__": files,
  341. "__user__": {
  342. "id": user.id,
  343. "email": user.email,
  344. "name": user.name,
  345. "role": user.role,
  346. },
  347. "__metadata__": metadata,
  348. }
  349. extra_params["__tools__"] = get_tools(
  350. app,
  351. tool_ids,
  352. user,
  353. {
  354. **extra_params,
  355. "__model__": models.get(form_data["model"], None),
  356. "__messages__": form_data["messages"],
  357. "__files__": files,
  358. },
  359. )
  360. if model_info:
  361. if model_info.base_model_id:
  362. form_data["model"] = model_info.base_model_id
  363. params = model_info.params.model_dump()
  364. form_data = apply_model_params_to_body_openai(params, form_data)
  365. form_data = apply_model_system_prompt_to_body(params, form_data, user)
  366. pipe_id = get_pipe_id(form_data)
  367. function_module = get_function_module(pipe_id)
  368. pipe = function_module.pipe
  369. params = get_function_params(function_module, form_data, user, extra_params)
  370. if form_data.get("stream", False):
  371. async def stream_content():
  372. try:
  373. res = await execute_pipe(pipe, params)
  374. # Directly return if the response is a StreamingResponse
  375. if isinstance(res, StreamingResponse):
  376. async for data in res.body_iterator:
  377. yield data
  378. return
  379. if isinstance(res, dict):
  380. yield f"data: {json.dumps(res)}\n\n"
  381. return
  382. except Exception as e:
  383. log.error(f"Error: {e}")
  384. yield f"data: {json.dumps({'error': {'detail':str(e)}})}\n\n"
  385. return
  386. if isinstance(res, str):
  387. message = openai_chat_chunk_message_template(form_data["model"], res)
  388. yield f"data: {json.dumps(message)}\n\n"
  389. if isinstance(res, Iterator):
  390. for line in res:
  391. yield process_line(form_data, line)
  392. if isinstance(res, AsyncGenerator):
  393. async for line in res:
  394. yield process_line(form_data, line)
  395. if isinstance(res, str) or isinstance(res, Generator):
  396. finish_message = openai_chat_chunk_message_template(
  397. form_data["model"], ""
  398. )
  399. finish_message["choices"][0]["finish_reason"] = "stop"
  400. yield f"data: {json.dumps(finish_message)}\n\n"
  401. yield "data: [DONE]"
  402. return StreamingResponse(stream_content(), media_type="text/event-stream")
  403. else:
  404. try:
  405. res = await execute_pipe(pipe, params)
  406. except Exception as e:
  407. log.error(f"Error: {e}")
  408. return {"error": {"detail": str(e)}}
  409. if isinstance(res, StreamingResponse) or isinstance(res, dict):
  410. return res
  411. if isinstance(res, BaseModel):
  412. return res.model_dump()
  413. message = await get_message_content(res)
  414. return openai_chat_completion_message_template(form_data["model"], message)