main.py 12 KB

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