models.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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
  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. updated_at = Column(BigInteger)
  71. created_at = Column(BigInteger)
  72. class ModelModel(BaseModel):
  73. id: str
  74. user_id: str
  75. base_model_id: Optional[str] = None
  76. name: str
  77. params: ModelParams
  78. meta: ModelMeta
  79. access_control: Optional[dict] = None
  80. updated_at: int # timestamp in epoch
  81. created_at: int # timestamp in epoch
  82. model_config = ConfigDict(from_attributes=True)
  83. ####################
  84. # Forms
  85. ####################
  86. class ModelResponse(BaseModel):
  87. id: str
  88. user_id: str
  89. base_model_id: Optional[str] = None
  90. name: str
  91. params: ModelParams
  92. meta: ModelMeta
  93. access_control: Optional[dict] = None
  94. updated_at: int # timestamp in epoch
  95. created_at: int # timestamp in epoch
  96. class ModelForm(BaseModel):
  97. id: str
  98. base_model_id: Optional[str] = None
  99. name: str
  100. meta: ModelMeta
  101. params: ModelParams
  102. class ModelsTable:
  103. def insert_new_model(
  104. self, form_data: ModelForm, user_id: str
  105. ) -> Optional[ModelModel]:
  106. model = ModelModel(
  107. **{
  108. **form_data.model_dump(),
  109. "user_id": user_id,
  110. "created_at": int(time.time()),
  111. "updated_at": int(time.time()),
  112. }
  113. )
  114. try:
  115. with get_db() as db:
  116. result = Model(**model.model_dump())
  117. db.add(result)
  118. db.commit()
  119. db.refresh(result)
  120. if result:
  121. return ModelModel.model_validate(result)
  122. else:
  123. return None
  124. except Exception as e:
  125. print(e)
  126. return None
  127. def get_all_models(self) -> list[ModelModel]:
  128. with get_db() as db:
  129. return [ModelModel.model_validate(model) for model in db.query(Model).all()]
  130. def get_models(self) -> list[ModelModel]:
  131. with get_db() as db:
  132. return [
  133. ModelModel.model_validate(model)
  134. for model in db.query(Model).filter(Model.base_model_id != None).all()
  135. ]
  136. def get_models_by_user_id(
  137. self, user_id: str, permission: str = "write"
  138. ) -> list[ModelModel]:
  139. models = self.get_all_models()
  140. return [
  141. model
  142. for model in models
  143. if model.user_id == user_id
  144. or has_access(user_id, permission, model.access_control)
  145. ]
  146. def get_model_by_id(self, id: str) -> Optional[ModelModel]:
  147. try:
  148. with get_db() as db:
  149. model = db.get(Model, id)
  150. return ModelModel.model_validate(model)
  151. except Exception:
  152. return None
  153. def update_model_by_id(self, id: str, model: ModelForm) -> Optional[ModelModel]:
  154. try:
  155. with get_db() as db:
  156. # update only the fields that are present in the model
  157. result = (
  158. db.query(Model)
  159. .filter_by(id=id)
  160. .update(model.model_dump(exclude={"id"}, exclude_none=True))
  161. )
  162. db.commit()
  163. model = db.get(Model, id)
  164. db.refresh(model)
  165. return ModelModel.model_validate(model)
  166. except Exception as e:
  167. print(e)
  168. return None
  169. def delete_model_by_id(self, id: str) -> bool:
  170. try:
  171. with get_db() as db:
  172. db.query(Model).filter_by(id=id).delete()
  173. db.commit()
  174. return True
  175. except Exception:
  176. return False
  177. Models = ModelsTable()