main.py 12 KB

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