models.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. "tags": model.get("tags", []),
  38. }
  39. for model in ollama_models["models"]
  40. ]
  41. function_models = await get_function_models(request)
  42. models = function_models + openai_models + ollama_models
  43. return models
  44. async def get_all_models(request, user: UserModel = None):
  45. models = await get_all_base_models(request, user=user)
  46. # If there are no models, return an empty list
  47. if len(models) == 0:
  48. return []
  49. # Add arena models
  50. if request.app.state.config.ENABLE_EVALUATION_ARENA_MODELS:
  51. arena_models = []
  52. if len(request.app.state.config.EVALUATION_ARENA_MODELS) > 0:
  53. arena_models = [
  54. {
  55. "id": model["id"],
  56. "name": model["name"],
  57. "info": {
  58. "meta": model["meta"],
  59. },
  60. "object": "model",
  61. "created": int(time.time()),
  62. "owned_by": "arena",
  63. "arena": True,
  64. }
  65. for model in request.app.state.config.EVALUATION_ARENA_MODELS
  66. ]
  67. else:
  68. # Add default arena model
  69. arena_models = [
  70. {
  71. "id": DEFAULT_ARENA_MODEL["id"],
  72. "name": DEFAULT_ARENA_MODEL["name"],
  73. "info": {
  74. "meta": DEFAULT_ARENA_MODEL["meta"],
  75. },
  76. "object": "model",
  77. "created": int(time.time()),
  78. "owned_by": "arena",
  79. "arena": True,
  80. }
  81. ]
  82. models = models + arena_models
  83. global_action_ids = [
  84. function.id for function in Functions.get_global_action_functions()
  85. ]
  86. enabled_action_ids = [
  87. function.id
  88. for function in Functions.get_functions_by_type("action", active_only=True)
  89. ]
  90. custom_models = Models.get_all_models()
  91. for custom_model in custom_models:
  92. if custom_model.base_model_id is None:
  93. for model in models:
  94. if (
  95. custom_model.id == model["id"]
  96. or custom_model.id == model["id"].split(":")[0]
  97. ):
  98. if custom_model.is_active:
  99. model["name"] = custom_model.name
  100. model["info"] = custom_model.model_dump()
  101. action_ids = []
  102. if "info" in model and "meta" in model["info"]:
  103. action_ids.extend(
  104. model["info"]["meta"].get("actionIds", [])
  105. )
  106. model["action_ids"] = action_ids
  107. else:
  108. models.remove(model)
  109. elif custom_model.is_active and (
  110. custom_model.id not in [model["id"] for model in models]
  111. ):
  112. owned_by = "openai"
  113. pipe = None
  114. action_ids = []
  115. for model in models:
  116. if (
  117. custom_model.base_model_id == model["id"]
  118. or custom_model.base_model_id == model["id"].split(":")[0]
  119. ):
  120. owned_by = model.get("owned_by", "unknown owner")
  121. if "pipe" in model:
  122. pipe = model["pipe"]
  123. break
  124. if custom_model.meta:
  125. meta = custom_model.meta.model_dump()
  126. if "actionIds" in meta:
  127. action_ids.extend(meta["actionIds"])
  128. models.append(
  129. {
  130. "id": f"{custom_model.id}",
  131. "name": custom_model.name,
  132. "object": "model",
  133. "created": custom_model.created_at,
  134. "owned_by": owned_by,
  135. "info": custom_model.model_dump(),
  136. "preset": True,
  137. **({"pipe": pipe} if pipe is not None else {}),
  138. "action_ids": action_ids,
  139. }
  140. )
  141. # Process action_ids to get the actions
  142. def get_action_items_from_module(function, module):
  143. actions = []
  144. if hasattr(module, "actions"):
  145. actions = module.actions
  146. return [
  147. {
  148. "id": f"{function.id}.{action['id']}",
  149. "name": action.get("name", f"{function.name} ({action['id']})"),
  150. "description": function.meta.description,
  151. "icon_url": action.get(
  152. "icon_url", function.meta.manifest.get("icon_url", None)
  153. ),
  154. }
  155. for action in actions
  156. ]
  157. else:
  158. return [
  159. {
  160. "id": function.id,
  161. "name": function.name,
  162. "description": function.meta.description,
  163. "icon_url": function.meta.manifest.get("icon_url", None),
  164. }
  165. ]
  166. def get_function_module_by_id(function_id):
  167. if function_id in request.app.state.FUNCTIONS:
  168. function_module = request.app.state.FUNCTIONS[function_id]
  169. else:
  170. function_module, _, _ = load_function_module_by_id(function_id)
  171. request.app.state.FUNCTIONS[function_id] = function_module
  172. for model in models:
  173. action_ids = [
  174. action_id
  175. for action_id in list(set(model.pop("action_ids", []) + global_action_ids))
  176. if action_id in enabled_action_ids
  177. ]
  178. model["actions"] = []
  179. for action_id in action_ids:
  180. action_function = Functions.get_function_by_id(action_id)
  181. if action_function is None:
  182. raise Exception(f"Action not found: {action_id}")
  183. function_module = get_function_module_by_id(action_id)
  184. model["actions"].extend(
  185. get_action_items_from_module(action_function, function_module)
  186. )
  187. log.debug(f"get_all_models() returned {len(models)} models")
  188. request.app.state.MODELS = {model["id"]: model for model in models}
  189. return models
  190. def check_model_access(user, model):
  191. if model.get("arena"):
  192. if not has_access(
  193. user.id,
  194. type="read",
  195. access_control=model.get("info", {})
  196. .get("meta", {})
  197. .get("access_control", {}),
  198. ):
  199. raise Exception("Model not found")
  200. else:
  201. model_info = Models.get_model_by_id(model.get("id"))
  202. if not model_info:
  203. raise Exception("Model not found")
  204. elif not (
  205. user.id == model_info.user_id
  206. or has_access(
  207. user.id, type="read", access_control=model_info.access_control
  208. )
  209. ):
  210. raise Exception("Model not found")