models.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. import time
  2. import logging
  3. import asyncio
  4. import sys
  5. from aiocache import cached
  6. from fastapi import Request
  7. from open_webui.routers import openai, ollama
  8. from open_webui.functions import get_function_models
  9. from open_webui.models.functions import Functions
  10. from open_webui.models.models import Models
  11. from open_webui.utils.plugin import (
  12. load_function_module_by_id,
  13. get_function_module_from_cache,
  14. )
  15. from open_webui.utils.access_control import has_access
  16. from open_webui.config import (
  17. DEFAULT_ARENA_MODEL,
  18. )
  19. from open_webui.env import SRC_LOG_LEVELS, GLOBAL_LOG_LEVEL
  20. from open_webui.models.users import UserModel
  21. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  22. log = logging.getLogger(__name__)
  23. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  24. async def fetch_ollama_models(request: Request, user: UserModel = None):
  25. raw_ollama_models = await ollama.get_all_models(request, user=user)
  26. return [
  27. {
  28. "id": model["model"],
  29. "name": model["name"],
  30. "object": "model",
  31. "created": int(time.time()),
  32. "owned_by": "ollama",
  33. "ollama": model,
  34. "connection_type": model.get("connection_type", "local"),
  35. "tags": model.get("tags", []),
  36. }
  37. for model in raw_ollama_models["models"]
  38. ]
  39. async def fetch_openai_models(request: Request, user: UserModel = None):
  40. openai_response = await openai.get_all_models(request, user=user)
  41. return openai_response["data"]
  42. async def get_all_base_models(request: Request, user: UserModel = None):
  43. openai_task = (
  44. fetch_openai_models(request, user)
  45. if request.app.state.config.ENABLE_OPENAI_API
  46. else asyncio.sleep(0, result=[])
  47. )
  48. ollama_task = (
  49. fetch_ollama_models(request, user)
  50. if request.app.state.config.ENABLE_OLLAMA_API
  51. else asyncio.sleep(0, result=[])
  52. )
  53. function_task = get_function_models(request)
  54. openai_models, ollama_models, function_models = await asyncio.gather(
  55. openai_task, ollama_task, function_task
  56. )
  57. return function_models + openai_models + ollama_models
  58. async def get_all_models(request, refresh: bool = False, user: UserModel = None):
  59. if (
  60. request.app.state.MODELS
  61. and request.app.state.BASE_MODELS
  62. and (request.app.state.config.ENABLE_BASE_MODELS_CACHE and not refresh)
  63. ):
  64. base_models = request.app.state.BASE_MODELS
  65. else:
  66. base_models = await get_all_base_models(request, user=user)
  67. request.app.state.BASE_MODELS = base_models
  68. # deep copy the base models to avoid modifying the original list
  69. models = [model.copy() for model in base_models]
  70. # If there are no models, return an empty list
  71. if len(models) == 0:
  72. return []
  73. # Add arena models
  74. if request.app.state.config.ENABLE_EVALUATION_ARENA_MODELS:
  75. arena_models = []
  76. if len(request.app.state.config.EVALUATION_ARENA_MODELS) > 0:
  77. arena_models = [
  78. {
  79. "id": model["id"],
  80. "name": model["name"],
  81. "info": {
  82. "meta": model["meta"],
  83. },
  84. "object": "model",
  85. "created": int(time.time()),
  86. "owned_by": "arena",
  87. "arena": True,
  88. }
  89. for model in request.app.state.config.EVALUATION_ARENA_MODELS
  90. ]
  91. else:
  92. # Add default arena model
  93. arena_models = [
  94. {
  95. "id": DEFAULT_ARENA_MODEL["id"],
  96. "name": DEFAULT_ARENA_MODEL["name"],
  97. "info": {
  98. "meta": DEFAULT_ARENA_MODEL["meta"],
  99. },
  100. "object": "model",
  101. "created": int(time.time()),
  102. "owned_by": "arena",
  103. "arena": True,
  104. }
  105. ]
  106. models = models + arena_models
  107. global_action_ids = [
  108. function.id for function in Functions.get_global_action_functions()
  109. ]
  110. enabled_action_ids = [
  111. function.id
  112. for function in Functions.get_functions_by_type("action", active_only=True)
  113. ]
  114. global_filter_ids = [
  115. function.id for function in Functions.get_global_filter_functions()
  116. ]
  117. enabled_filter_ids = [
  118. function.id
  119. for function in Functions.get_functions_by_type("filter", active_only=True)
  120. ]
  121. custom_models = Models.get_all_models()
  122. for custom_model in custom_models:
  123. if custom_model.base_model_id is None:
  124. # Applied directly to a base model
  125. for model in models:
  126. if custom_model.id == model["id"] or (
  127. model.get("owned_by") == "ollama"
  128. and custom_model.id
  129. == model["id"].split(":")[
  130. 0
  131. ] # Ollama may return model ids in different formats (e.g., 'llama3' vs. 'llama3:7b')
  132. ):
  133. if custom_model.is_active:
  134. model["name"] = custom_model.name
  135. model["info"] = custom_model.model_dump()
  136. # Set action_ids and filter_ids
  137. action_ids = []
  138. filter_ids = []
  139. if "info" in model and "meta" in model["info"]:
  140. action_ids.extend(
  141. model["info"]["meta"].get("actionIds", [])
  142. )
  143. filter_ids.extend(
  144. model["info"]["meta"].get("filterIds", [])
  145. )
  146. model["action_ids"] = action_ids
  147. model["filter_ids"] = filter_ids
  148. else:
  149. models.remove(model)
  150. elif custom_model.is_active and (
  151. custom_model.id not in [model["id"] for model in models]
  152. ):
  153. owned_by = "openai"
  154. pipe = None
  155. action_ids = []
  156. filter_ids = []
  157. for model in models:
  158. if (
  159. custom_model.base_model_id == model["id"]
  160. or custom_model.base_model_id == model["id"].split(":")[0]
  161. ):
  162. owned_by = model.get("owned_by", "unknown owner")
  163. if "pipe" in model:
  164. pipe = model["pipe"]
  165. break
  166. if custom_model.meta:
  167. meta = custom_model.meta.model_dump()
  168. if "actionIds" in meta:
  169. action_ids.extend(meta["actionIds"])
  170. if "filterIds" in meta:
  171. filter_ids.extend(meta["filterIds"])
  172. models.append(
  173. {
  174. "id": f"{custom_model.id}",
  175. "name": custom_model.name,
  176. "object": "model",
  177. "created": custom_model.created_at,
  178. "owned_by": owned_by,
  179. "info": custom_model.model_dump(),
  180. "preset": True,
  181. **({"pipe": pipe} if pipe is not None else {}),
  182. "action_ids": action_ids,
  183. "filter_ids": filter_ids,
  184. }
  185. )
  186. # Process action_ids to get the actions
  187. def get_action_items_from_module(function, module):
  188. actions = []
  189. if hasattr(module, "actions"):
  190. actions = module.actions
  191. return [
  192. {
  193. "id": f"{function.id}.{action['id']}",
  194. "name": action.get("name", f"{function.name} ({action['id']})"),
  195. "description": function.meta.description,
  196. "icon": action.get(
  197. "icon_url",
  198. function.meta.manifest.get("icon_url", None)
  199. or getattr(module, "icon_url", None)
  200. or getattr(module, "icon", None),
  201. ),
  202. }
  203. for action in actions
  204. ]
  205. else:
  206. return [
  207. {
  208. "id": function.id,
  209. "name": function.name,
  210. "description": function.meta.description,
  211. "icon": function.meta.manifest.get("icon_url", None)
  212. or getattr(module, "icon_url", None)
  213. or getattr(module, "icon", None),
  214. }
  215. ]
  216. # Process filter_ids to get the filters
  217. def get_filter_items_from_module(function, module):
  218. return [
  219. {
  220. "id": function.id,
  221. "name": function.name,
  222. "description": function.meta.description,
  223. "icon": function.meta.manifest.get("icon_url", None)
  224. or getattr(module, "icon_url", None)
  225. or getattr(module, "icon", None),
  226. }
  227. ]
  228. def get_function_module_by_id(function_id):
  229. function_module, _, _ = get_function_module_from_cache(request, function_id)
  230. return function_module
  231. for model in models:
  232. action_ids = [
  233. action_id
  234. for action_id in list(set(model.pop("action_ids", []) + global_action_ids))
  235. if action_id in enabled_action_ids
  236. ]
  237. filter_ids = [
  238. filter_id
  239. for filter_id in list(set(model.pop("filter_ids", []) + global_filter_ids))
  240. if filter_id in enabled_filter_ids
  241. ]
  242. model["actions"] = []
  243. for action_id in action_ids:
  244. action_function = Functions.get_function_by_id(action_id)
  245. if action_function is None:
  246. raise Exception(f"Action not found: {action_id}")
  247. function_module = get_function_module_by_id(action_id)
  248. model["actions"].extend(
  249. get_action_items_from_module(action_function, function_module)
  250. )
  251. model["filters"] = []
  252. for filter_id in filter_ids:
  253. filter_function = Functions.get_function_by_id(filter_id)
  254. if filter_function is None:
  255. raise Exception(f"Filter not found: {filter_id}")
  256. function_module = get_function_module_by_id(filter_id)
  257. if getattr(function_module, "toggle", None):
  258. model["filters"].extend(
  259. get_filter_items_from_module(filter_function, function_module)
  260. )
  261. log.debug(f"get_all_models() returned {len(models)} models")
  262. request.app.state.MODELS = {model["id"]: model for model in models}
  263. return models
  264. def check_model_access(user, model):
  265. if model.get("arena"):
  266. if not has_access(
  267. user.id,
  268. type="read",
  269. access_control=model.get("info", {})
  270. .get("meta", {})
  271. .get("access_control", {}),
  272. ):
  273. raise Exception("Model not found")
  274. else:
  275. model_info = Models.get_model_by_id(model.get("id"))
  276. if not model_info:
  277. raise Exception("Model not found")
  278. elif not (
  279. user.id == model_info.user_id
  280. or has_access(
  281. user.id, type="read", access_control=model_info.access_control
  282. )
  283. ):
  284. raise Exception("Model not found")