models.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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 pydantic import BaseModel, ConfigDict
  7. from sqlalchemy import BigInteger, Column, Text, JSON
  8. log = logging.getLogger(__name__)
  9. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  10. ####################
  11. # Models DB Schema
  12. ####################
  13. # ModelParams is a model for the data stored in the params field of the Model table
  14. class ModelParams(BaseModel):
  15. model_config = ConfigDict(extra="allow")
  16. pass
  17. # ModelMeta is a model for the data stored in the meta field of the Model table
  18. class ModelMeta(BaseModel):
  19. profile_image_url: Optional[str] = "/static/favicon.png"
  20. description: Optional[str] = None
  21. """
  22. User-facing description of the model.
  23. """
  24. capabilities: Optional[dict] = None
  25. model_config = ConfigDict(extra="allow")
  26. pass
  27. class Model(Base):
  28. __tablename__ = "model"
  29. id = Column(Text, primary_key=True)
  30. """
  31. The model's id as used in the API. If set to an existing model, it will override the model.
  32. """
  33. user_id = Column(Text)
  34. base_model_id = Column(Text, nullable=True)
  35. """
  36. An optional pointer to the actual model that should be used when proxying requests.
  37. """
  38. name = Column(Text)
  39. """
  40. The human-readable display name of the model.
  41. """
  42. params = Column(JSONField)
  43. """
  44. Holds a JSON encoded blob of parameters, see `ModelParams`.
  45. """
  46. meta = Column(JSONField)
  47. """
  48. Holds a JSON encoded blob of metadata, see `ModelMeta`.
  49. """
  50. access_control = Column(JSON, nullable=True) # Controls data access levels.
  51. # Defines access control rules for this entry.
  52. # - `None`: Public access, available to all users with the "user" role.
  53. # - `{}`: Private access, restricted exclusively to the owner.
  54. # - Custom permissions: Specific access control for reading and writing;
  55. # Can specify group or user-level restrictions:
  56. # {
  57. # "read": {
  58. # "group_ids": ["group_id1", "group_id2"],
  59. # "user_ids": ["user_id1", "user_id2"]
  60. # },
  61. # "write": {
  62. # "group_ids": ["group_id1", "group_id2"],
  63. # "user_ids": ["user_id1", "user_id2"]
  64. # }
  65. # }
  66. updated_at = Column(BigInteger)
  67. created_at = Column(BigInteger)
  68. class ModelModel(BaseModel):
  69. id: str
  70. user_id: str
  71. base_model_id: Optional[str] = None
  72. name: str
  73. params: ModelParams
  74. meta: ModelMeta
  75. access_control: Optional[dict] = None
  76. updated_at: int # timestamp in epoch
  77. created_at: int # timestamp in epoch
  78. model_config = ConfigDict(from_attributes=True)
  79. ####################
  80. # Forms
  81. ####################
  82. class ModelResponse(BaseModel):
  83. id: str
  84. name: str
  85. meta: ModelMeta
  86. updated_at: int # timestamp in epoch
  87. created_at: int # timestamp in epoch
  88. class ModelForm(BaseModel):
  89. id: str
  90. base_model_id: Optional[str] = None
  91. name: str
  92. meta: ModelMeta
  93. params: ModelParams
  94. class ModelsTable:
  95. def insert_new_model(
  96. self, form_data: ModelForm, user_id: str
  97. ) -> Optional[ModelModel]:
  98. model = ModelModel(
  99. **{
  100. **form_data.model_dump(),
  101. "user_id": user_id,
  102. "created_at": int(time.time()),
  103. "updated_at": int(time.time()),
  104. }
  105. )
  106. try:
  107. with get_db() as db:
  108. result = Model(**model.model_dump())
  109. db.add(result)
  110. db.commit()
  111. db.refresh(result)
  112. if result:
  113. return ModelModel.model_validate(result)
  114. else:
  115. return None
  116. except Exception as e:
  117. print(e)
  118. return None
  119. def get_all_models(self) -> list[ModelModel]:
  120. with get_db() as db:
  121. return [ModelModel.model_validate(model) for model in db.query(Model).all()]
  122. def get_model_by_id(self, id: str) -> Optional[ModelModel]:
  123. try:
  124. with get_db() as db:
  125. model = db.get(Model, id)
  126. return ModelModel.model_validate(model)
  127. except Exception:
  128. return None
  129. def update_model_by_id(self, id: str, model: ModelForm) -> Optional[ModelModel]:
  130. try:
  131. with get_db() as db:
  132. # update only the fields that are present in the model
  133. result = (
  134. db.query(Model)
  135. .filter_by(id=id)
  136. .update(model.model_dump(exclude={"id"}, exclude_none=True))
  137. )
  138. db.commit()
  139. model = db.get(Model, id)
  140. db.refresh(model)
  141. return ModelModel.model_validate(model)
  142. except Exception as e:
  143. print(e)
  144. return None
  145. def delete_model_by_id(self, id: str) -> bool:
  146. try:
  147. with get_db() as db:
  148. db.query(Model).filter_by(id=id).delete()
  149. db.commit()
  150. return True
  151. except Exception:
  152. return False
  153. Models = ModelsTable()