models.py 7.5 KB

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