models.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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. meta = JSONField()
  35. """
  36. Holds a JSON encoded blob of metadata, see `ModelMeta`.
  37. """
  38. base_model_id = pw.TextField(null=True)
  39. """
  40. An optional pointer to the actual model that should be used when proxying requests.
  41. Currently unused - but will be used to support Modelfile like behaviour in the future
  42. """
  43. name = pw.TextField()
  44. """
  45. The human-readable display name of the model.
  46. """
  47. params = JSONField()
  48. """
  49. Holds a JSON encoded blob of parameters, see `ModelParams`.
  50. """
  51. class Meta:
  52. database = DB
  53. class ModelModel(BaseModel):
  54. id: str
  55. meta: ModelMeta
  56. base_model_id: Optional[str] = None
  57. name: str
  58. params: ModelParams
  59. ####################
  60. # Forms
  61. ####################
  62. class ModelsTable:
  63. def __init__(
  64. self,
  65. db: pw.SqliteDatabase | pw.PostgresqlDatabase,
  66. ):
  67. self.db = db
  68. self.db.create_tables([Model])
  69. def get_all_models(self) -> list[ModelModel]:
  70. return [ModelModel(**model_to_dict(model)) for model in Model.select()]
  71. def update_all_models(self, models: list[ModelModel]) -> bool:
  72. try:
  73. with self.db.atomic():
  74. # Fetch current models from the database
  75. current_models = self.get_all_models()
  76. current_model_dict = {model.id: model for model in current_models}
  77. # Create a set of model IDs from the current models and the new models
  78. current_model_keys = set(current_model_dict.keys())
  79. new_model_keys = set(model.id for model in models)
  80. # Determine which models need to be created, updated, or deleted
  81. models_to_create = [
  82. model for model in models if model.id not in current_model_keys
  83. ]
  84. models_to_update = [
  85. model for model in models if model.id in current_model_keys
  86. ]
  87. models_to_delete = current_model_keys - new_model_keys
  88. # Perform the necessary database operations
  89. for model in models_to_create:
  90. Model.create(**model.model_dump())
  91. for model in models_to_update:
  92. Model.update(**model.model_dump()).where(
  93. Model.id == model.id
  94. ).execute()
  95. for model_id, model_source in models_to_delete:
  96. Model.delete().where(Model.id == model_id).execute()
  97. return True
  98. except Exception as e:
  99. log.exception(e)
  100. return False
  101. Models = ModelsTable(DB)