models.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. # NULL for public access (open to all users with "user" role).
  52. # {} for individual access (private to the owner).
  53. # {"group_ids": ["group_id1", "group_id2"]} for access restricted to specific groups.
  54. # {"user_ids": ["user_id1", "user_id2"]} for access restricted to specific users.
  55. updated_at = Column(BigInteger)
  56. created_at = Column(BigInteger)
  57. class ModelModel(BaseModel):
  58. id: str
  59. user_id: str
  60. base_model_id: Optional[str] = None
  61. name: str
  62. params: ModelParams
  63. meta: ModelMeta
  64. access_control = Optional[dict] = None
  65. updated_at: int # timestamp in epoch
  66. created_at: int # timestamp in epoch
  67. model_config = ConfigDict(from_attributes=True)
  68. ####################
  69. # Forms
  70. ####################
  71. class ModelResponse(BaseModel):
  72. id: str
  73. name: str
  74. meta: ModelMeta
  75. updated_at: int # timestamp in epoch
  76. created_at: int # timestamp in epoch
  77. class ModelForm(BaseModel):
  78. id: str
  79. base_model_id: Optional[str] = None
  80. name: str
  81. meta: ModelMeta
  82. params: ModelParams
  83. class ModelsTable:
  84. def insert_new_model(
  85. self, form_data: ModelForm, user_id: str
  86. ) -> Optional[ModelModel]:
  87. model = ModelModel(
  88. **{
  89. **form_data.model_dump(),
  90. "user_id": user_id,
  91. "created_at": int(time.time()),
  92. "updated_at": int(time.time()),
  93. }
  94. )
  95. try:
  96. with get_db() as db:
  97. result = Model(**model.model_dump())
  98. db.add(result)
  99. db.commit()
  100. db.refresh(result)
  101. if result:
  102. return ModelModel.model_validate(result)
  103. else:
  104. return None
  105. except Exception as e:
  106. print(e)
  107. return None
  108. def get_all_models(self) -> list[ModelModel]:
  109. with get_db() as db:
  110. return [ModelModel.model_validate(model) for model in db.query(Model).all()]
  111. def get_model_by_id(self, id: str) -> Optional[ModelModel]:
  112. try:
  113. with get_db() as db:
  114. model = db.get(Model, id)
  115. return ModelModel.model_validate(model)
  116. except Exception:
  117. return None
  118. def update_model_by_id(self, id: str, model: ModelForm) -> Optional[ModelModel]:
  119. try:
  120. with get_db() as db:
  121. # update only the fields that are present in the model
  122. result = (
  123. db.query(Model)
  124. .filter_by(id=id)
  125. .update(model.model_dump(exclude={"id"}, exclude_none=True))
  126. )
  127. db.commit()
  128. model = db.get(Model, id)
  129. db.refresh(model)
  130. return ModelModel.model_validate(model)
  131. except Exception as e:
  132. print(e)
  133. return None
  134. def delete_model_by_id(self, id: str) -> bool:
  135. try:
  136. with get_db() as db:
  137. db.query(Model).filter_by(id=id).delete()
  138. db.commit()
  139. return True
  140. except Exception:
  141. return False
  142. Models = ModelsTable()