models.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. import logging
  2. import time
  3. from typing import Optional
  4. from open_webui.internal.db import Base, JSONField, get_db
  5. from open_webui.env import SRC_LOG_LEVELS
  6. from open_webui.models.groups import Groups
  7. from open_webui.models.users import Users, UserResponse
  8. from pydantic import BaseModel, ConfigDict
  9. from sqlalchemy import or_, and_, func
  10. from sqlalchemy.dialects import postgresql, sqlite
  11. from sqlalchemy import BigInteger, Column, Text, JSON, Boolean
  12. from open_webui.utils.access_control import has_access
  13. log = logging.getLogger(__name__)
  14. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  15. ####################
  16. # Models DB Schema
  17. ####################
  18. # ModelParams is a model for the data stored in the params field of the Model table
  19. class ModelParams(BaseModel):
  20. model_config = ConfigDict(extra="allow")
  21. pass
  22. # ModelMeta is a model for the data stored in the meta field of the Model table
  23. class ModelMeta(BaseModel):
  24. profile_image_url: Optional[str] = "/static/favicon.png"
  25. description: Optional[str] = None
  26. """
  27. User-facing description of the model.
  28. """
  29. capabilities: Optional[dict] = None
  30. model_config = ConfigDict(extra="allow")
  31. pass
  32. class Model(Base):
  33. __tablename__ = "model"
  34. id = Column(Text, primary_key=True)
  35. """
  36. The model's id as used in the API. If set to an existing model, it will override the model.
  37. """
  38. user_id = Column(Text)
  39. base_model_id = Column(Text, nullable=True)
  40. """
  41. An optional pointer to the actual model that should be used when proxying requests.
  42. """
  43. name = Column(Text)
  44. """
  45. The human-readable display name of the model.
  46. """
  47. params = Column(JSONField)
  48. """
  49. Holds a JSON encoded blob of parameters, see `ModelParams`.
  50. """
  51. meta = Column(JSONField)
  52. """
  53. Holds a JSON encoded blob of metadata, see `ModelMeta`.
  54. """
  55. access_control = Column(JSON, nullable=True) # Controls data access levels.
  56. # Defines access control rules for this entry.
  57. # - `None`: Public access, available to all users with the "user" role.
  58. # - `{}`: Private access, restricted exclusively to the owner.
  59. # - Custom permissions: Specific access control for reading and writing;
  60. # Can specify group or user-level restrictions:
  61. # {
  62. # "read": {
  63. # "group_ids": ["group_id1", "group_id2"],
  64. # "user_ids": ["user_id1", "user_id2"]
  65. # },
  66. # "write": {
  67. # "group_ids": ["group_id1", "group_id2"],
  68. # "user_ids": ["user_id1", "user_id2"]
  69. # }
  70. # }
  71. is_active = Column(Boolean, default=True)
  72. updated_at = Column(BigInteger)
  73. created_at = Column(BigInteger)
  74. class ModelModel(BaseModel):
  75. id: str
  76. user_id: str
  77. base_model_id: Optional[str] = None
  78. name: str
  79. params: ModelParams
  80. meta: ModelMeta
  81. access_control: Optional[dict] = None
  82. is_active: bool
  83. updated_at: int # timestamp in epoch
  84. created_at: int # timestamp in epoch
  85. model_config = ConfigDict(from_attributes=True)
  86. ####################
  87. # Forms
  88. ####################
  89. class ModelUserResponse(ModelModel):
  90. user: Optional[UserResponse] = None
  91. class ModelResponse(ModelModel):
  92. pass
  93. class ModelForm(BaseModel):
  94. id: str
  95. base_model_id: Optional[str] = None
  96. name: str
  97. meta: ModelMeta
  98. params: ModelParams
  99. access_control: Optional[dict] = None
  100. is_active: bool = True
  101. class ModelsTable:
  102. def insert_new_model(
  103. self, form_data: ModelForm, user_id: str
  104. ) -> Optional[ModelModel]:
  105. model = ModelModel(
  106. **{
  107. **form_data.model_dump(),
  108. "user_id": user_id,
  109. "created_at": int(time.time()),
  110. "updated_at": int(time.time()),
  111. }
  112. )
  113. try:
  114. with get_db() as db:
  115. result = Model(**model.model_dump())
  116. db.add(result)
  117. db.commit()
  118. db.refresh(result)
  119. if result:
  120. return ModelModel.model_validate(result)
  121. else:
  122. return None
  123. except Exception as e:
  124. log.exception(f"Failed to insert a new model: {e}")
  125. return None
  126. def get_all_models(self) -> list[ModelModel]:
  127. with get_db() as db:
  128. return [ModelModel.model_validate(model) for model in db.query(Model).all()]
  129. def get_models(self) -> list[ModelUserResponse]:
  130. with get_db() as db:
  131. all_models = db.query(Model).filter(Model.base_model_id != None).all()
  132. user_ids = list(set(model.user_id for model in all_models))
  133. users = Users.get_users_by_user_ids(user_ids) if user_ids else []
  134. users_dict = {user.id: user for user in users}
  135. models = []
  136. for model in all_models:
  137. user = users_dict.get(model.user_id)
  138. models.append(
  139. ModelUserResponse.model_validate(
  140. {
  141. **ModelModel.model_validate(model).model_dump(),
  142. "user": user.model_dump() if user else None,
  143. }
  144. )
  145. )
  146. return models
  147. def get_base_models(self) -> list[ModelModel]:
  148. with get_db() as db:
  149. return [
  150. ModelModel.model_validate(model)
  151. for model in db.query(Model).filter(Model.base_model_id == None).all()
  152. ]
  153. def get_models_by_user_id(
  154. self, user_id: str, permission: str = "write"
  155. ) -> list[ModelUserResponse]:
  156. models = self.get_models()
  157. user_group_ids = {group.id for group in Groups.get_groups_by_member_id(user_id)}
  158. return [
  159. model
  160. for model in models
  161. if model.user_id == user_id
  162. or has_access(user_id, permission, model.access_control, user_group_ids)
  163. ]
  164. def get_model_by_id(self, id: str) -> Optional[ModelModel]:
  165. try:
  166. with get_db() as db:
  167. model = db.get(Model, id)
  168. return ModelModel.model_validate(model)
  169. except Exception:
  170. return None
  171. def toggle_model_by_id(self, id: str) -> Optional[ModelModel]:
  172. with get_db() as db:
  173. try:
  174. is_active = db.query(Model).filter_by(id=id).first().is_active
  175. db.query(Model).filter_by(id=id).update(
  176. {
  177. "is_active": not is_active,
  178. "updated_at": int(time.time()),
  179. }
  180. )
  181. db.commit()
  182. return self.get_model_by_id(id)
  183. except Exception:
  184. return None
  185. def update_model_by_id(self, id: str, model: ModelForm) -> Optional[ModelModel]:
  186. try:
  187. with get_db() as db:
  188. # update only the fields that are present in the model
  189. result = (
  190. db.query(Model)
  191. .filter_by(id=id)
  192. .update(model.model_dump(exclude={"id"}))
  193. )
  194. db.commit()
  195. model = db.get(Model, id)
  196. db.refresh(model)
  197. return ModelModel.model_validate(model)
  198. except Exception as e:
  199. log.exception(f"Failed to update the model by id {id}: {e}")
  200. return None
  201. def delete_model_by_id(self, id: str) -> bool:
  202. try:
  203. with get_db() as db:
  204. db.query(Model).filter_by(id=id).delete()
  205. db.commit()
  206. return True
  207. except Exception:
  208. return False
  209. def delete_all_models(self) -> bool:
  210. try:
  211. with get_db() as db:
  212. db.query(Model).delete()
  213. db.commit()
  214. return True
  215. except Exception:
  216. return False
  217. def sync_models(self, user_id: str, models: list[ModelModel]) -> list[ModelModel]:
  218. try:
  219. with get_db() as db:
  220. # Get existing models
  221. existing_models = db.query(Model).all()
  222. existing_ids = {model.id for model in existing_models}
  223. # Prepare a set of new model IDs
  224. new_model_ids = {model.id for model in models}
  225. # Update or insert models
  226. for model in models:
  227. if model.id in existing_ids:
  228. db.query(Model).filter_by(id=model.id).update(
  229. {
  230. **model.model_dump(),
  231. "user_id": user_id,
  232. "updated_at": int(time.time()),
  233. }
  234. )
  235. else:
  236. new_model = Model(
  237. **{
  238. **model.model_dump(),
  239. "user_id": user_id,
  240. "updated_at": int(time.time()),
  241. }
  242. )
  243. db.add(new_model)
  244. # Remove models that are no longer present
  245. for model in existing_models:
  246. if model.id not in new_model_ids:
  247. db.delete(model)
  248. db.commit()
  249. return [
  250. ModelModel.model_validate(model) for model in db.query(Model).all()
  251. ]
  252. except Exception as e:
  253. log.exception(f"Error syncing models for user {user_id}: {e}")
  254. return []
  255. Models = ModelsTable()