*/ class Assistant extends \Piko\DbRecord { /** * The table name * * @var string */ protected $tableName = 'chat_assistant'; /** * The role permissions * * @var array */ public $permissions = []; /** * The table schema * * @var array */ protected $schema = [ 'id' => self::TYPE_INT, 'user_id' => self::TYPE_INT, 'title' => self::TYPE_STRING, 'model' => self::TYPE_STRING, 'system_prompt' => self::TYPE_STRING, 'temperature' => self::TYPE_STRING, 'top_p' => self::TYPE_STRING, 'default' => self::TYPE_INT, ]; /** * {@inheritDoc} * @see \Piko\ModelTrait::validate() */ protected function validate(): void { if (empty($this->user_id)) { $this->errors['user_id'] = 'L\'id de l\'utilisateur est obligatoire.'; } if (empty($this->title)) { $this->errors['title'] = 'Le titre doit être renseigné.'; } if (empty($this->model)) { $this->errors['model'] = 'Le modèle doit être renseigné.'; } if (empty($this->system_prompt)) { $this->errors['system_prompt'] = 'Le prompt système doit être renseigné.'; } if (!empty($this->temperature) && $this->temperature < 0 || $this->temperature > 2) { $this->errors['temperature'] = 'Le température doit être comprise entre 0 et 2.'; } } /** * @inheritDoc */ protected function beforeSave(bool $insert): bool { if ($this->default == 1) { $this->db->beginTransaction(); try { // Reset default for all other assistants of the same user $sth = $this->db->prepare('UPDATE chat_assistant SET `default` = 0 WHERE user_id = :user_id'); $sth->execute(['user_id' => $this->user_id]); $this->db->commit(); } catch (\Exception $e) { $this->db->rollBack(); throw $e; } } return parent::beforeSave($insert); } /** * Get assistants * * @param \PDO $db A pdo connexion * @param string $order The order condition * @param number $start The offset start * @param number $limit The offset limit * * @return array An array of role rows */ public static function find(\PDO $db, $userId = 0, $order = '', $start = 0, $limit = 0) { $query = 'SELECT * FROM chat_assistant'; if ($userId) { $query .= ' WHERE user_id = :user_id'; } $query .= ' ORDER BY ' . (empty($order) ? '`id` DESC' : $order); if (!empty($start)) { $query .= ' OFFSET ' . (int) $start; } if (!empty($limit)) { $query .= ' LIMIT ' . (int) $limit; } $sth = $db->prepare($query); $sth->execute(['user_id' => $userId]); return $sth->fetchAll(\PDO::FETCH_ASSOC); } public static function getDefaultUserAssistant(\PDO $db, int $userId): ?self { $query = 'SELECT * FROM chat_assistant WHERE user_id = :user_id AND `default` = 1 LIMIT 1'; $sth = $db->prepare($query); $sth->execute(['user_id' => $userId]); return $sth->fetchObject(self::class) ?: null; } }