main.py 12 KB

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