models.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import json
  2. import logging
  3. from typing import Optional
  4. import peewee as pw
  5. from peewee import *
  6. from playhouse.shortcuts import model_to_dict
  7. from pydantic import BaseModel, ConfigDict
  8. from apps.web.internal.db import DB, JSONField
  9. from typing import List, Union, Optional
  10. from config import SRC_LOG_LEVELS
  11. import time
  12. log = logging.getLogger(__name__)
  13. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  14. ####################
  15. # Models DB Schema
  16. ####################
  17. # ModelParams is a model for the data stored in the params field of the Model table
  18. class ModelParams(BaseModel):
  19. model_config = ConfigDict(extra="allow")
  20. pass
  21. # ModelMeta is a model for the data stored in the meta field of the Model table
  22. # It isn't currently used in the backend, but it's here as a reference
  23. class ModelMeta(BaseModel):
  24. description: Optional[str] = None
  25. """
  26. User-facing description of the model.
  27. """
  28. vision_capable: Optional[bool] = None
  29. """
  30. A flag indicating if the model is capable of vision and thus image inputs
  31. """
  32. model_config = ConfigDict(extra="allow")
  33. pass
  34. class Model(pw.Model):
  35. id = pw.TextField(unique=True)
  36. """
  37. The model's id as used in the API. If set to an existing model, it will override the model.
  38. """
  39. user_id = pw.TextField()
  40. base_model_id = pw.TextField(null=True)
  41. """
  42. An optional pointer to the actual model that should be used when proxying requests.
  43. """
  44. name = pw.TextField()
  45. """
  46. The human-readable display name of the model.
  47. """
  48. params = JSONField()
  49. """
  50. Holds a JSON encoded blob of parameters, see `ModelParams`.
  51. """
  52. meta = JSONField()
  53. """
  54. Holds a JSON encoded blob of metadata, see `ModelMeta`.
  55. """
  56. updated_at = BigIntegerField()
  57. created_at = BigIntegerField()
  58. class Meta:
  59. database = DB
  60. class ModelModel(BaseModel):
  61. id: str
  62. base_model_id: Optional[str] = None
  63. name: str
  64. params: ModelParams
  65. meta: ModelMeta
  66. updated_at: int # timestamp in epoch
  67. created_at: int # timestamp in epoch
  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 __init__(
  85. self,
  86. db: pw.SqliteDatabase | pw.PostgresqlDatabase,
  87. ):
  88. self.db = db
  89. self.db.create_tables([Model])
  90. def insert_new_model(self, model: ModelForm, user_id: str) -> Optional[ModelModel]:
  91. try:
  92. model = Model.create(
  93. **{
  94. **model.model_dump(),
  95. "user_id": user_id,
  96. "created_at": int(time.time()),
  97. "updated_at": int(time.time()),
  98. }
  99. )
  100. return ModelModel(**model_to_dict(model))
  101. except:
  102. return None
  103. def get_all_models(self) -> List[ModelModel]:
  104. return [ModelModel(**model_to_dict(model)) for model in Model.select()]
  105. def get_model_by_id(self, id: str) -> Optional[ModelModel]:
  106. try:
  107. model = Model.get(Model.id == id)
  108. return ModelModel(**model_to_dict(model))
  109. except:
  110. return None
  111. def update_model_by_id(self, id: str, model: ModelForm) -> Optional[ModelModel]:
  112. try:
  113. # update only the fields that are present in the model
  114. query = Model.update(**model.model_dump()).where(Model.id == id)
  115. query.execute()
  116. model = Model.get(Model.id == id)
  117. return ModelModel(**model_to_dict(model))
  118. except:
  119. return None
  120. def delete_model_by_id(self, id: str) -> bool:
  121. try:
  122. query = Model.delete().where(Model.id == id)
  123. query.execute()
  124. return True
  125. except:
  126. return False
  127. Models = ModelsTable(DB)