models.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. import json
  2. import logging
  3. from typing import Optional
  4. import peewee as pw
  5. from playhouse.shortcuts import model_to_dict
  6. from pydantic import BaseModel
  7. from apps.web.internal.db import DB, JSONField
  8. from config import SRC_LOG_LEVELS
  9. log = logging.getLogger(__name__)
  10. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  11. ####################
  12. # Models DB Schema
  13. ####################
  14. # ModelParams is a model for the data stored in the params field of the Model table
  15. # It isn't currently used in the backend, but it's here as a reference
  16. class ModelParams(BaseModel):
  17. pass
  18. # ModelMeta is a model for the data stored in the meta field of the Model table
  19. # It isn't currently used in the backend, but it's here as a reference
  20. class ModelMeta(BaseModel):
  21. description: str
  22. """
  23. User-facing description of the model.
  24. """
  25. vision_capable: bool
  26. """
  27. A flag indicating if the model is capable of vision and thus image inputs
  28. """
  29. class Model(pw.Model):
  30. id = pw.TextField(unique=True)
  31. """
  32. The model's id as used in the API. If set to an existing model, it will override the model.
  33. """
  34. user_id = pw.TextField()
  35. base_model_id = pw.TextField(null=True)
  36. """
  37. An optional pointer to the actual model that should be used when proxying requests.
  38. Currently unused - but will be used to support Modelfile like behaviour in the future
  39. """
  40. name = pw.TextField()
  41. """
  42. The human-readable display name of the model.
  43. """
  44. params = JSONField()
  45. """
  46. Holds a JSON encoded blob of parameters, see `ModelParams`.
  47. """
  48. meta = JSONField()
  49. """
  50. Holds a JSON encoded blob of metadata, see `ModelMeta`.
  51. """
  52. updated_at: int # timestamp in epoch
  53. created_at: int # timestamp in epoch
  54. class Meta:
  55. database = DB
  56. class ModelModel(BaseModel):
  57. id: str
  58. base_model_id: Optional[str] = None
  59. name: str
  60. params: ModelParams
  61. meta: ModelMeta
  62. ####################
  63. # Forms
  64. ####################
  65. class ModelsTable:
  66. def __init__(
  67. self,
  68. db: pw.SqliteDatabase | pw.PostgresqlDatabase,
  69. ):
  70. self.db = db
  71. self.db.create_tables([Model])
  72. def get_all_models(self) -> list[ModelModel]:
  73. return [ModelModel(**model_to_dict(model)) for model in Model.select()]
  74. def update_all_models(self, models: list[ModelModel]) -> bool:
  75. try:
  76. with self.db.atomic():
  77. # Fetch current models from the database
  78. current_models = self.get_all_models()
  79. current_model_dict = {model.id: model for model in current_models}
  80. # Create a set of model IDs from the current models and the new models
  81. current_model_keys = set(current_model_dict.keys())
  82. new_model_keys = set(model.id for model in models)
  83. # Determine which models need to be created, updated, or deleted
  84. models_to_create = [
  85. model for model in models if model.id not in current_model_keys
  86. ]
  87. models_to_update = [
  88. model for model in models if model.id in current_model_keys
  89. ]
  90. models_to_delete = current_model_keys - new_model_keys
  91. # Perform the necessary database operations
  92. for model in models_to_create:
  93. Model.create(**model.model_dump())
  94. for model in models_to_update:
  95. Model.update(**model.model_dump()).where(
  96. Model.id == model.id
  97. ).execute()
  98. for model_id, model_source in models_to_delete:
  99. Model.delete().where(Model.id == model_id).execute()
  100. return True
  101. except Exception as e:
  102. log.exception(e)
  103. return False
  104. Models = ModelsTable(DB)