main.py 15 KB

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