models.py 4.5 KB

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