models.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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 custom_model.id == model["id"] or (
  95. model.get("owned_by") == "ollama"
  96. and custom_model.id
  97. == model["id"].split(":")[
  98. 0
  99. ] # Ollama may return model ids in different formats (e.g., 'llama3' vs. 'llama3:7b')
  100. ):
  101. if custom_model.is_active:
  102. model["name"] = custom_model.name
  103. model["info"] = custom_model.model_dump()
  104. action_ids = []
  105. if "info" in model and "meta" in model["info"]:
  106. action_ids.extend(
  107. model["info"]["meta"].get("actionIds", [])
  108. )
  109. model["action_ids"] = action_ids
  110. else:
  111. models.remove(model)
  112. elif custom_model.is_active and (
  113. custom_model.id not in [model["id"] for model in models]
  114. ):
  115. owned_by = "openai"
  116. pipe = None
  117. action_ids = []
  118. for model in models:
  119. if (
  120. custom_model.base_model_id == model["id"]
  121. or custom_model.base_model_id == model["id"].split(":")[0]
  122. ):
  123. owned_by = model.get("owned_by", "unknown owner")
  124. if "pipe" in model:
  125. pipe = model["pipe"]
  126. break
  127. if custom_model.meta:
  128. meta = custom_model.meta.model_dump()
  129. if "actionIds" in meta:
  130. action_ids.extend(meta["actionIds"])
  131. models.append(
  132. {
  133. "id": f"{custom_model.id}",
  134. "name": custom_model.name,
  135. "object": "model",
  136. "created": custom_model.created_at,
  137. "owned_by": owned_by,
  138. "info": custom_model.model_dump(),
  139. "preset": True,
  140. **({"pipe": pipe} if pipe is not None else {}),
  141. "action_ids": action_ids,
  142. }
  143. )
  144. # Process action_ids to get the actions
  145. def get_action_items_from_module(function, module):
  146. actions = []
  147. if hasattr(module, "actions"):
  148. actions = module.actions
  149. return [
  150. {
  151. "id": f"{function.id}.{action['id']}",
  152. "name": action.get("name", f"{function.name} ({action['id']})"),
  153. "description": function.meta.description,
  154. "icon_url": action.get(
  155. "icon_url", function.meta.manifest.get("icon_url", None)
  156. ),
  157. }
  158. for action in actions
  159. ]
  160. else:
  161. return [
  162. {
  163. "id": function.id,
  164. "name": function.name,
  165. "description": function.meta.description,
  166. "icon_url": function.meta.manifest.get("icon_url", None),
  167. }
  168. ]
  169. def get_function_module_by_id(function_id):
  170. if function_id in request.app.state.FUNCTIONS:
  171. function_module = request.app.state.FUNCTIONS[function_id]
  172. else:
  173. function_module, _, _ = load_function_module_by_id(function_id)
  174. request.app.state.FUNCTIONS[function_id] = function_module
  175. for model in models:
  176. action_ids = [
  177. action_id
  178. for action_id in list(set(model.pop("action_ids", []) + global_action_ids))
  179. if action_id in enabled_action_ids
  180. ]
  181. model["actions"] = []
  182. for action_id in action_ids:
  183. action_function = Functions.get_function_by_id(action_id)
  184. if action_function is None:
  185. raise Exception(f"Action not found: {action_id}")
  186. function_module = get_function_module_by_id(action_id)
  187. model["actions"].extend(
  188. get_action_items_from_module(action_function, function_module)
  189. )
  190. log.debug(f"get_all_models() returned {len(models)} models")
  191. request.app.state.MODELS = {model["id"]: model for model in models}
  192. return models
  193. def check_model_access(user, model):
  194. if model.get("arena"):
  195. if not has_access(
  196. user.id,
  197. type="read",
  198. access_control=model.get("info", {})
  199. .get("meta", {})
  200. .get("access_control", {}),
  201. ):
  202. raise Exception("Model not found")
  203. else:
  204. model_info = Models.get_model_by_id(model.get("id"))
  205. if not model_info:
  206. raise Exception("Model not found")
  207. elif not (
  208. user.id == model_info.user_id
  209. or has_access(
  210. user.id, type="read", access_control=model_info.access_control
  211. )
  212. ):
  213. raise Exception("Model not found")