models.py 4.4 KB

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