models.py 8.2 KB

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