models.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. models = []
  132. for model in db.query(Model).filter(Model.base_model_id != None).all():
  133. user = Users.get_user_by_id(model.user_id)
  134. models.append(
  135. ModelUserResponse.model_validate(
  136. {
  137. **ModelModel.model_validate(model).model_dump(),
  138. "user": user.model_dump() if user else None,
  139. }
  140. )
  141. )
  142. return models
  143. def get_base_models(self) -> list[ModelModel]:
  144. with get_db() as db:
  145. return [
  146. ModelModel.model_validate(model)
  147. for model in db.query(Model).filter(Model.base_model_id == None).all()
  148. ]
  149. def get_models_by_user_id(
  150. self, user_id: str, permission: str = "write"
  151. ) -> list[ModelUserResponse]:
  152. models = self.get_models()
  153. user_group_ids = {group.id for group in Groups.get_groups_by_member_id(user_id)}
  154. return [
  155. model
  156. for model in models
  157. if model.user_id == user_id
  158. or has_access(user_id, permission, model.access_control, user_group_ids)
  159. ]
  160. def get_model_by_id(self, id: str) -> Optional[ModelModel]:
  161. try:
  162. with get_db() as db:
  163. model = db.get(Model, id)
  164. return ModelModel.model_validate(model)
  165. except Exception:
  166. return None
  167. def toggle_model_by_id(self, id: str) -> Optional[ModelModel]:
  168. with get_db() as db:
  169. try:
  170. is_active = db.query(Model).filter_by(id=id).first().is_active
  171. db.query(Model).filter_by(id=id).update(
  172. {
  173. "is_active": not is_active,
  174. "updated_at": int(time.time()),
  175. }
  176. )
  177. db.commit()
  178. return self.get_model_by_id(id)
  179. except Exception:
  180. return None
  181. def update_model_by_id(self, id: str, model: ModelForm) -> Optional[ModelModel]:
  182. try:
  183. with get_db() as db:
  184. # update only the fields that are present in the model
  185. result = (
  186. db.query(Model)
  187. .filter_by(id=id)
  188. .update(model.model_dump(exclude={"id"}))
  189. )
  190. db.commit()
  191. model = db.get(Model, id)
  192. db.refresh(model)
  193. return ModelModel.model_validate(model)
  194. except Exception as e:
  195. log.exception(f"Failed to update the model by id {id}: {e}")
  196. return None
  197. def delete_model_by_id(self, id: str) -> bool:
  198. try:
  199. with get_db() as db:
  200. db.query(Model).filter_by(id=id).delete()
  201. db.commit()
  202. return True
  203. except Exception:
  204. return False
  205. def delete_all_models(self) -> bool:
  206. try:
  207. with get_db() as db:
  208. db.query(Model).delete()
  209. db.commit()
  210. return True
  211. except Exception:
  212. return False
  213. def sync_models(self, user_id: str, models: list[ModelModel]) -> list[ModelModel]:
  214. try:
  215. with get_db() as db:
  216. # Get existing models
  217. existing_models = db.query(Model).all()
  218. existing_ids = {model.id for model in existing_models}
  219. # Prepare a set of new model IDs
  220. new_model_ids = {model.id for model in models}
  221. # Update or insert models
  222. for model in models:
  223. if model.id in existing_ids:
  224. db.query(Model).filter_by(id=model.id).update(
  225. {
  226. **model.model_dump(),
  227. "user_id": user_id,
  228. "updated_at": int(time.time()),
  229. }
  230. )
  231. else:
  232. new_model = Model(
  233. **{
  234. **model.model_dump(),
  235. "user_id": user_id,
  236. "updated_at": int(time.time()),
  237. }
  238. )
  239. db.add(new_model)
  240. # Remove models that are no longer present
  241. for model in existing_models:
  242. if model.id not in new_model_ids:
  243. db.delete(model)
  244. db.commit()
  245. return [
  246. ModelModel.model_validate(model) for model in db.query(Model).all()
  247. ]
  248. except Exception as e:
  249. log.exception(f"Error syncing models for user {user_id}: {e}")
  250. return []
  251. Models = ModelsTable()