models.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import logging
  2. import time
  3. from typing import Optional
  4. from open_webui.apps.webui.internal.db import Base, JSONField, get_db
  5. from open_webui.env import SRC_LOG_LEVELS
  6. from open_webui.apps.webui.models.groups import Groups
  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.utils 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 ModelResponse(BaseModel):
  89. id: str
  90. user_id: str
  91. base_model_id: Optional[str] = None
  92. name: str
  93. params: ModelParams
  94. meta: ModelMeta
  95. access_control: Optional[dict] = None
  96. is_active: bool
  97. updated_at: int # timestamp in epoch
  98. created_at: int # timestamp in epoch
  99. class ModelForm(BaseModel):
  100. id: str
  101. base_model_id: Optional[str] = None
  102. name: str
  103. meta: ModelMeta
  104. params: ModelParams
  105. access_control: Optional[dict] = None
  106. is_active: bool = True
  107. class ModelsTable:
  108. def insert_new_model(
  109. self, form_data: ModelForm, user_id: str
  110. ) -> Optional[ModelModel]:
  111. model = ModelModel(
  112. **{
  113. **form_data.model_dump(),
  114. "user_id": user_id,
  115. "created_at": int(time.time()),
  116. "updated_at": int(time.time()),
  117. }
  118. )
  119. try:
  120. with get_db() as db:
  121. result = Model(**model.model_dump())
  122. db.add(result)
  123. db.commit()
  124. db.refresh(result)
  125. if result:
  126. return ModelModel.model_validate(result)
  127. else:
  128. return None
  129. except Exception as e:
  130. print(e)
  131. return None
  132. def get_all_models(self) -> list[ModelModel]:
  133. with get_db() as db:
  134. return [ModelModel.model_validate(model) for model in db.query(Model).all()]
  135. def get_models(self) -> list[ModelModel]:
  136. with get_db() as db:
  137. return [
  138. ModelModel.model_validate(model)
  139. for model in db.query(Model).filter(Model.base_model_id != None).all()
  140. ]
  141. def get_models_by_user_id(
  142. self, user_id: str, permission: str = "write"
  143. ) -> list[ModelModel]:
  144. models = self.get_all_models()
  145. return [
  146. model
  147. for model in models
  148. if model.user_id == user_id
  149. or has_access(user_id, permission, model.access_control)
  150. ]
  151. def get_model_by_id(self, id: str) -> Optional[ModelModel]:
  152. try:
  153. with get_db() as db:
  154. model = db.get(Model, id)
  155. return ModelModel.model_validate(model)
  156. except Exception:
  157. return None
  158. def toggle_model_by_id(self, id: str) -> Optional[ModelModel]:
  159. with get_db() as db:
  160. try:
  161. is_active = db.query(Model).filter_by(id=id).first().is_active
  162. db.query(Model).filter_by(id=id).update(
  163. {
  164. "is_active": not is_active,
  165. "updated_at": int(time.time()),
  166. }
  167. )
  168. db.commit()
  169. return self.get_model_by_id(id)
  170. except Exception:
  171. return None
  172. def update_model_by_id(self, id: str, model: ModelForm) -> Optional[ModelModel]:
  173. try:
  174. with get_db() as db:
  175. # update only the fields that are present in the model
  176. result = (
  177. db.query(Model)
  178. .filter_by(id=id)
  179. .update(model.model_dump(exclude={"id"}, exclude_none=True))
  180. )
  181. db.commit()
  182. model = db.get(Model, id)
  183. db.refresh(model)
  184. return ModelModel.model_validate(model)
  185. except Exception as e:
  186. print(e)
  187. return None
  188. def delete_model_by_id(self, id: str) -> bool:
  189. try:
  190. with get_db() as db:
  191. db.query(Model).filter_by(id=id).delete()
  192. db.commit()
  193. return True
  194. except Exception:
  195. return False
  196. Models = ModelsTable()