models.py 11 KB

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