main.py 15 KB

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