AntonLV 2 лет назад
Родитель
Сommit
ac038451cf

+ 39 - 2
inc/classes/BxDolAI.php

@@ -7,9 +7,15 @@
  * @{
  */
 
+define('BX_DOL_AI_AUTOMATOR_EVENT', 'event');
+define('BX_DOL_AI_AUTOMATOR_SCHEDULER', 'scheduler');
+define('BX_DOL_AI_AUTOMATOR_WEBHOOK', 'webhook');
+
 class BxDolAI extends BxDolFactory implements iBxDolSingleton
 {
+    protected $_oDb;
     protected $_sPathInst;
+    protected $_iProfileId;
 
     protected function __construct()
     {
@@ -18,7 +24,9 @@ class BxDolAI extends BxDolFactory implements iBxDolSingleton
 
         parent::__construct();
 
+        $this->_oDb = new BxDolAIQuery();
         $this->_sPathInst = BX_DIRECTORY_PATH_ROOT . 'ai/instructions/';
+        $this->_iProfileId = (int)getParam('sys_profile_bot'); 
     }
 
     /**
@@ -41,6 +49,11 @@ class BxDolAI extends BxDolFactory implements iBxDolSingleton
         return $GLOBALS['bxDolClasses'][__CLASS__];
     }
 
+    public function getProfileId()
+    {
+        return $this->_iProfileId;
+    }
+
     public function getAutomatorInstructions($sType, $bIncludeCommon = false)
     {
         $sResult = file_get_contents($this->_sPathInst . $sType . '.html');
@@ -49,6 +62,26 @@ class BxDolAI extends BxDolFactory implements iBxDolSingleton
 
         return $sResult;
     }
+    
+    public function getModel($iId)
+    {
+        $aModel = $this->_oDb->getModelsBy(['sample' => 'id', 'id' => $iId]);
+        if(!empty($aModel['params']))
+            $aModel['params'] = json_decode($aModel['params'], true);
+
+        return $aModel;
+    }
+
+    public function getAutomator($iId, $bFullInfo = false)
+    {
+        $aAutomator = $this->_oDb->getAutomatorsBy(['sample' => 'id' . ($bFullInfo ? '_full' : ''), 'id' => $iId]);
+        if(!empty($aAutomator['params']))
+            $aAutomator['params'] = json_decode($aAutomator['params'], true);
+        if($bFullInfo && !empty($aAutomator['model_params']))
+            $aAutomator['model_params'] = json_decode($aAutomator['model_params'], true);
+
+        return $aAutomator;
+    }
 
     public function chat($sEndpoint, $sModel, $sApiKey, $aParams, $aMessages)
     {
@@ -61,9 +94,13 @@ class BxDolAI extends BxDolFactory implements iBxDolSingleton
             $aData = array_merge($aData, $aParams);
 
         $sRv = bx_file_get_contents($sEndpoint, $aData, "post-json", ["Authorization: Bearer ".$sApiKey, 'Content-Type: application/json', 'OpenAI-Beta: assistants=v1']);
-
         $aRv = json_decode($sRv, true);
 
-        return $aRv['choices'][0]['message']['content'];
+        if(isset($aRv['error'])) {
+            //TODO: log error in AI related log file.
+            return 'false';
+        }
+
+        return trim(str_replace(['```json', '```php', '```'], '', $aRv['choices'][0]['message']['content']));
     }
 }

+ 100 - 0
inc/classes/BxDolAIQuery.php

@@ -0,0 +1,100 @@
+<?php defined('BX_DOL') or die('hack attempt');
+/**
+ * Copyright (c) UNA, Inc - https://una.io
+ * MIT License - https://opensource.org/licenses/MIT
+ *
+ * @defgroup    UnaCore UNA Core
+ * @{
+ */
+
+class BxDolAIQuery extends BxDolDb
+{
+    public function __construct()
+    {
+        parent::__construct();
+    }
+
+    public function getModelsBy($aParams = [])
+    {
+        $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
+    	$sWhereClause = "";
+
+        switch($aParams['sample']) {
+            case 'id':
+            	$aMethod['name'] = 'getRow';
+            	$aMethod['params'][1] = [
+                    'id' => $aParams['id']
+                ];
+
+                $sWhereClause .= " AND `id`=:id";
+                break;
+
+            case 'name':
+            	$aMethod['name'] = 'getRow';
+            	$aMethod['params'][1] = [
+                    'name' => $aParams['name']
+                ];
+
+                $sWhereClause .= " AND `name`=:name";
+                break;
+
+            case 'all_pairs':
+                $aMethod['name'] = 'getPairs';
+                $aMethod['params'][1] = 'id';
+                $aMethod['params'][2] = 'name';
+                break;
+        }
+
+        $aMethod['params'][0] = "SELECT * 
+            FROM `sys_agents_models`
+            WHERE 1" . $sWhereClause;
+
+        return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
+    }
+
+    public function getAutomatorsBy($aParams = [])
+    {
+        $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
+        $sSelectClause = "`taa`.*";
+    	$sJoinClause = $sWhereClause = "";
+
+        switch($aParams['sample']) {
+            case 'id':
+            	$aMethod['name'] = 'getRow';
+            	$aMethod['params'][1] = [
+                    'id' => $aParams['id']
+                ];
+
+                $sWhereClause .= " AND `taa`.`id`=:id";
+                break;
+
+            case 'id_full':
+            	$aMethod['name'] = 'getRow';
+            	$aMethod['params'][1] = [
+                    'id' => $aParams['id']
+                ];
+
+                $sSelectClause .= ", `tam`.`name` AS `model_name`, `tam`.`url` AS `model_url`, `tam`.`key` AS `model_key`, `tam`.`model` AS `model_model`, `tam`.`params` AS `model_params`";
+                $sJoinClause .= " LEFT JOIN `sys_agents_models` AS `tam` ON `taa`.`model_id`=`tam`.`id`";
+                $sWhereClause .= " AND `taa`.`id`=:id";
+                break;
+        }
+
+        $aMethod['params'][0] = "SELECT " . $sSelectClause . "
+            FROM `sys_agents_automators` AS `taa` " . $sJoinClause . "
+            WHERE 1" . $sWhereClause;
+
+        return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
+    }
+
+    public function updateAutomators($aSetClause, $aWhereClause)
+    {
+        if(empty($aSetClause) || empty($aWhereClause))
+            return false;
+
+        return (int)$this->query("UPDATE `sys_agents_automators` SET " . $this->arrayToSQL($aSetClause) . " WHERE " . $this->arrayToSQL($aWhereClause)) > 0;
+    }
+    
+}
+
+/** @} */

+ 10 - 6
install/sql/system.sql

@@ -5416,17 +5416,19 @@ INSERT INTO `sys_grid_actions` (`object`, `type`, `name`, `title`, `icon`, `icon
 
 -- GRID: Agents Automators
 INSERT INTO `sys_objects_grid` (`object`, `source_type`, `source`, `table`, `field_id`, `field_order`, `field_active`, `paginate_url`, `paginate_per_page`, `paginate_simple`, `paginate_get_start`, `paginate_get_per_page`, `filter_fields`, `filter_fields_translatable`, `filter_mode`, `sorting_fields`, `sorting_fields_translatable`, `override_class_name`, `override_class_file`) VALUES
-('sys_studio_agents_automators', 'Sql', 'SELECT * FROM `sys_agents_automators` WHERE 1 ', 'sys_agents_automators', 'id', '', 'active', '', 20, NULL, 'start', '', '', '', 'like', '', '', 'BxTemplStudioAgentsAutomators', '');
+('sys_studio_agents_automators', 'Sql', 'SELECT * FROM `sys_agents_automators` WHERE 1 ', 'sys_agents_automators', 'id', 'added', 'active', '', 20, NULL, 'start', '', '', '', 'like', '', '', 'BxTemplStudioAgentsAutomators', '');
 
 INSERT INTO `sys_grid_fields` (`object`, `name`, `title`, `width`, `translatable`, `chars_limit`, `params`, `hidden_on`, `order`) VALUES
 ('sys_studio_agents_automators', 'checkbox', '', '2%', 0, 0, '', '', 1),
 ('sys_studio_agents_automators', 'switcher', '_sys_agents_automators_txt_active', '8%', 0, 0, '', '', 2),
 ('sys_studio_agents_automators', 'type', '_sys_agents_automators_txt_type', '10%', 0, 0, '', '', 3),
-('sys_studio_agents_automators', 'model_id', '_sys_agents_automators_txt_model_id', '20%', 0, 0, '', '', 4),
-('sys_studio_agents_automators', 'profile_id', '_sys_agents_automators_txt_profile_id', '20%', 0, 0, '', '', 5),
-('sys_studio_agents_automators', 'messages', '_sys_agents_automators_txt_messages', '10%', 0, 0, '', '', 6),
-('sys_studio_agents_automators', 'status', '_sys_agents_automators_txt_status', '10%', 0, 0, '', '', 7),
-('sys_studio_agents_automators', 'actions', '', '20%', 0, 0, '', '', 8);
+('sys_studio_agents_automators', 'model_id', '_sys_agents_automators_txt_model_id', '10%', 0, 0, '', '', 4),
+('sys_studio_agents_automators', 'profile_id', '_sys_agents_automators_txt_profile_id', '10%', 0, 0, '', '', 5),
+('sys_studio_agents_automators', 'message_id', '_sys_agents_automators_txt_message_id', '20%', 0, 32, '', '', 6),
+('sys_studio_agents_automators', 'messages', '_sys_agents_automators_txt_messages', '10%', 0, 0, '', '', 7),
+('sys_studio_agents_automators', 'added', '_sys_agents_automators_txt_added', '5%', 0, 0, '', '', 8),
+('sys_studio_agents_automators', 'status', '_sys_agents_automators_txt_status', '5%', 0, 0, '', '', 9),
+('sys_studio_agents_automators', 'actions', '', '20%', 0, 0, '', '', 10);
 
 INSERT INTO `sys_grid_actions` (`object`, `type`, `name`, `title`, `icon`, `icon_only`, `confirm`, `order`) VALUES
 ('sys_studio_agents_automators', 'bulk', 'delete', '_Delete', '', 0, 1, 1),
@@ -6288,7 +6290,9 @@ CREATE TABLE `sys_agents_automators` (
   `params` text NOT NULL,
   `alert_unit` varchar(128) NOT NULL default '',
   `alert_action` varchar(128) NOT NULL default '',
+  `message_id` int(11) NOT NULL default '0',
   `code` text NOT NULL,
+  `added` int(11) unsigned NOT NULL DEFAULT '0',
   `messages` int(11) NOT NULL default '0',
   `status` enum('auto','manual','ready') NOT NULL DEFAULT 'auto',
   `active` tinyint(4) NOT NULL DEFAULT '0',

+ 2 - 0
modules/boonex/english/data/langs/system/en.xml

@@ -2130,7 +2130,9 @@
         <string name="_sys_agents_automators_txt_type"><![CDATA[Type]]></string>
         <string name="_sys_agents_automators_txt_model_id"><![CDATA[Model]]></string>
         <string name="_sys_agents_automators_txt_profile_id"><![CDATA[Profile]]></string>
+        <string name="_sys_agents_automators_txt_message_id"><![CDATA[Prompt]]></string>
         <string name="_sys_agents_automators_txt_messages"><![CDATA[Messages]]></string>
+        <string name="_sys_agents_automators_txt_added"><![CDATA[Added]]></string>
         <string name="_sys_agents_automators_txt_status"><![CDATA[Status]]></string>
         <string name="_sys_agents_automators_btn_add"><![CDATA[Add]]></string>
         <string name="_sys_agents_automators_btn_tune"><![CDATA[Tune]]></string>

+ 2 - 0
modules/boonex/russian/data/langs/system/ru.xml

@@ -2105,7 +2105,9 @@
         <string name="_sys_agents_automators_txt_type"><![CDATA[Тип]]></string>
         <string name="_sys_agents_automators_txt_model_id"><![CDATA[Модель]]></string>
         <string name="_sys_agents_automators_txt_profile_id"><![CDATA[Профиль]]></string>
+        <string name="_sys_agents_automators_txt_message_id"><![CDATA[Инструкции]]></string>
         <string name="_sys_agents_automators_txt_messages"><![CDATA[Сообщения]]></string>
+        <string name="_sys_agents_automators_txt_added"><![CDATA[Добавлено]]></string>
         <string name="_sys_agents_automators_txt_status"><![CDATA[Статус]]></string>
         <string name="_sys_agents_automators_btn_add"><![CDATA[Добавить]]></string>
         <string name="_sys_agents_automators_btn_tune"><![CDATA[Настройка]]></string>

+ 4 - 2
studio/classes/BxDolStudioAgentsAutomators.php

@@ -13,17 +13,19 @@ class BxDolStudioAgentsAutomators extends BxTemplStudioGrid
 
     protected $_sCmts;
 
-    protected $_iProfileAi;
+    protected $_iProfileIdAi;
 
     public function __construct ($aOptions, $oTemplate = false)
     {
         parent::__construct ($aOptions, $oTemplate);
 
+        $this->_sDefaultSortingOrder = 'DESC';
+
         $this->_oDb = new BxDolStudioAgentsQuery();
 
         $this->_sCmts = 'sys_agents_automators';
 
-        $this->_iProfileAi = (int)getParam('sys_profile_bot');
+        $this->_iProfileIdAi = BxDolAI::getInstance()->getProfileId();
     }
 
     protected function _delete ($mixedId)

+ 20 - 10
studio/classes/BxDolStudioAgentsAutomatorsCmts.php

@@ -10,7 +10,7 @@
 class BxDolStudioAgentsAutomatorsCmts extends BxTemplCmts
 {
     protected $_oQueryAgents;
-    protected $_iProfileAi;
+    protected $_iProfileIdAi;
     protected $_bAuto;
 
     public function __construct($sSystem, $iId, $iInit = true, $oTemplate = false)
@@ -19,7 +19,7 @@ class BxDolStudioAgentsAutomatorsCmts extends BxTemplCmts
 
         $this->_oQueryAgents = new BxDolStudioAgentsQuery();
 
-        $this->_iProfileAi = (int)getParam('sys_profile_bot'); 
+        $this->_iProfileIdAi = BxDolAI::getInstance()->getProfileId(); 
         $this->_bAuto = false;
     }
 
@@ -77,7 +77,7 @@ class BxDolStudioAgentsAutomatorsCmts extends BxTemplCmts
         $aComments = $this->_oQuery->getCommentsBy(['type' => 'latest', 'start' => 0, 'per_page' => 1]);
         if(!empty($aComments) && is_array($aComments)) {
             $aLast = current($aComments);
-            if($aLast['cmt_author_id'] != $this->_iProfileAi)
+            if($aLast['cmt_author_id'] != $this->_iProfileIdAi)
                 return '';
         }
 
@@ -104,21 +104,31 @@ class BxDolStudioAgentsAutomatorsCmts extends BxTemplCmts
         if(!$this->_bAuto && $mixedResult !== false) {
             $iObjId = (int)$this->getId();
 
-            $aAutomator = $this->_oQueryAgents->getAutomatorsBy(['sample' => 'id_full', 'id' => $iObjId]);
+            $oAI = BxDolAI::getInstance();
 
             $aMessages = [
-                ['role' => 'system', 'content' => file_get_contents(BX_DIRECTORY_PATH_ROOT. '/ai_' . $aAutomator['type'] . '_instructions.html' ) . file_get_contents(BX_DIRECTORY_PATH_ROOT. '/ai_common_instructions.html' )],
+                ['role' => 'system', 'content' => $oAI->getAutomatorInstructions($aAutomator['type'], true)],
             ];
-            
+
+            $aAutomator = $oAI->getAutomator($iObjId, true);
+
             $aComments = $this->_oQuery->getCommentsBy(['type' => 'object_id', 'object_id' => $iObjId]);
-            foreach($aComments as $aComment) {
+            if($aAutomator['type'] == BX_DOL_AI_AUTOMATOR_EVENT && !empty($aAutomator['params']['trigger']))
+                $aComments[0]['cmt_text'] .= $aAutomator['params']['trigger'];
+
+            foreach($aComments as $aComment)
                 $aMessages[] = [
-                    'role' => (int)$aComment['cmt_author_id'] == $this->_iProfileAi ? 'assistant' : 'user',
+                    'role' => (int)$aComment['cmt_author_id'] == $this->_iProfileIdAi ? 'assistant' : 'user',
                     'content' => $aComment['cmt_text']
                 ];
-            }
 
-            //TODO: Send to AI $aMessages
+            $sResponse = $oAI->chat($aAutomator['url'], $aAutomator['model'], $aAutomator['key'], $aAutomator['params'], $aMessages);
+            if($sResponse != 'false') 
+                $this->addAuto([
+                    'cmt_author_id' => $this->_iProfileIdAi,
+                    'cmt_parent_id' => 0,
+                    'cmt_text' => $sResponse
+                ]);
         }
 
         return $mixedResult;

+ 1 - 75
studio/classes/BxDolStudioAgentsQuery.php

@@ -7,86 +7,12 @@
  * @{
  */
 
-class BxDolStudioAgentsQuery extends BxDolDb
+class BxDolStudioAgentsQuery extends BxDolAIQuery
 {
     public function __construct()
     {
         parent::__construct();
     }
-
-    public function getModelsBy($aParams = [])
-    {
-        $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
-    	$sWhereClause = "";
-
-        switch($aParams['sample']) {
-            case 'id':
-            	$aMethod['name'] = 'getRow';
-            	$aMethod['params'][1] = [
-                    'id' => $aParams['id']
-                ];
-
-                $sWhereClause .= " AND `id`=:id";
-                break;
-
-            case 'name':
-            	$aMethod['name'] = 'getRow';
-            	$aMethod['params'][1] = [
-                    'name' => $aParams['name']
-                ];
-
-                $sWhereClause .= " AND `name`=:name";
-                break;
-
-            case 'all_pairs':
-                $aMethod['name'] = 'getPairs';
-                $aMethod['params'][1] = 'id';
-                $aMethod['params'][2] = 'name';
-                break;
-        }
-
-        $aMethod['params'][0] = "SELECT * 
-            FROM `sys_agents_models`
-            WHERE 1" . $sWhereClause;
-
-        return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
-    }
-
-    public function getAutomatorsBy($aParams = [])
-    {
-        $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
-        $sSelectClause = "`taa`.*";
-    	$sJoinClause = $sWhereClause = "";
-
-        switch($aParams['sample']) {
-            case 'id':
-            	$aMethod['name'] = 'getRow';
-            	$aMethod['params'][1] = [
-                    'id' => $aParams['id']
-                ];
-
-                $sWhereClause .= " AND `taa`.`id`=:id";
-                break;
-
-            case 'id_full':
-            	$aMethod['name'] = 'getRow';
-            	$aMethod['params'][1] = [
-                    'id' => $aParams['id']
-                ];
-
-                $sSelectClause .= ", `tam`.`name` AS `model_name`, `tam`.`url` AS `model_url`, `tam`.`key` AS `model_key`, `tam`.`model` AS `model_model`, `tam`.`params` AS `model_params`";
-                $sJoinClause .= " LEFT JOIN `sys_agents_models` AS `tam` ON `taa`.`model_id`=`tam`.`id`";
-                $sWhereClause .= " AND `taa`.`id`=:id";
-                break;
-        }
-
-        $aMethod['params'][0] = "SELECT " . $sSelectClause . "
-            FROM `sys_agents_automators` AS `taa` " . $sJoinClause . "
-            WHERE 1" . $sWhereClause;
-
-        return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
-    }
-    
 }
 
 /** @} */

+ 41 - 29
studio/template/scripts/BxBaseStudioAgentsAutomators.php

@@ -33,8 +33,8 @@ class BxBaseStudioAgentsAutomators extends BxDolStudioAgentsAutomators
         $oForm->initChecker();
 
         if($oForm->isSubmittedAndValid()) {
-            $aValsToAdd = [];
-            
+            $aValsToAdd = ['added' => time()];
+
             $iProfileId = $oForm->getCleanValue('profile_id');
             if(empty($iProfileId)) {
                 $iProfileId = (int)getParam('sys_agents_profile');
@@ -48,53 +48,48 @@ class BxBaseStudioAgentsAutomators extends BxDolStudioAgentsAutomators
             if(!empty($sSchedulerTime))
                 $aValsToAdd['params'] = json_encode(['scheduler_time' => $sSchedulerTime]);
 
+            $iModel = $oForm->getCleanValue('model_id');
             $sType = $oForm->getCleanValue('type');
             $sMessage = $oForm->getCleanValue('message');
             $bMessage = !empty($sMessage);
             $sMessageAdd = '';
             $sMessageResponse = '';
 
-            if($bMessage)
-                $aValsToAdd['messages'] = 1;
-
             $oAI = BxDolAI::getInstance();
-            
+
             $aMessages = [
                 ['role' => 'system', 'content' => $oAI->getAutomatorInstructions($sType . '_init')],
                 ['role' => 'user', 'content' => $sMessage]
             ];
 
-            $iModel = $oForm->getCleanValue('model_id');
-            $aModel = $this->_oDb->getModelsBy(['sample' => 'id', 'id' => $iModel]);
-            if(!empty($aModel['params']))
-                $aModel['params'] = json_decode($aModel['params'], true);
+            $aModel = $oAI->getModel($iModel);
 
-            $bIsValid = true;
+            $bIsValid = true;/*
             switch($sType) {
-                case 'event':
+                case BX_DOL_AI_AUTOMATOR_EVENT:
                     $sResponse = $oAI->chat($aModel['url'], $aModel['model'], $aModel['key'], $aModel['params'], $aMessages);
-                    if(trim($sResponse) != 'false') {
-                        $sResponse = str_replace(['```json', '```'], '', $sResponse);
+                    if($sResponse != 'false') {
                         $aResponse = json_decode($sResponse, true);
                         $aValsToAdd = array_merge($aValsToAdd, [
                             'alert_unit' => $aResponse['alert_unit'],
-                            'alert_action' => $aResponse['alert_action']
+                            'alert_action' => $aResponse['alert_action'],
+                            'params' => json_encode(['trigger' => $aResponse['trigger']])
                         ]);
                         $sMessageAdd = $aResponse['trigger'];
                     }
                     else {
-                        $oForm->aInputs['message']['err'] = _t('_sys_agents_automators_err_event_not_found');
+                        $oForm->aInputs['message']['error'] = _t('_sys_agents_automators_err_event_not_found');
                         $bIsValid = false;
                     }
                     break;
 
-                case 'scheduler':
+                case BX_DOL_AI_AUTOMATOR_SCHEDULER:
                     $sResponse = $oAI->chat($aModel['url'], $aModel['model'], $aModel['key'], $aModel['params'], $aMessages);
-                    if(trim($sResponse) != 'false') {
-                        $aValsToAdd['params'] = json_encode(['scheduler_time' => $aResponse]);
+                    if($sResponse != 'false') {
+                        $aValsToAdd['params'] = json_encode(['scheduler_time' => $sResponse]);
                     }
                     else {
-                        $oForm->aInputs['message']['err'] = _t('_sys_agents_automators_err_event_not_found');
+                        $oForm->aInputs['message']['error'] = _t('_sys_agents_automators_err_event_not_found');
                         $bIsValid = false;
                     }
                     break;
@@ -107,36 +102,37 @@ class BxBaseStudioAgentsAutomators extends BxDolStudioAgentsAutomators
                 ];
 
                 $sResponse = $oAI->chat($aModel['url'], $aModel['model'], $aModel['key'], $aModel['params'], $aMessages);
-                if(trim($sResponse) != 'false') {
-                    $sResponse = str_replace(['```php', '```'], '', $sResponse);
+                if($sResponse != 'false') {
                     $sMessageResponse = $sResponse;
                 }
                 else {
-                    $oForm->aInputs['message']['err'] = _t('_sys_agents_automators_err_cannot_get_code');
+                    $oForm->aInputs['message']['error'] = _t('_sys_agents_automators_err_cannot_get_code');
                     $bIsValid = false;
                 }
             }
-
+*/
             if($bIsValid) {
                 if(($iId = $oForm->insert($aValsToAdd)) !== false) {
                     if(($oCmts = BxDolCmts::getObjectInstance($this->_sCmts, $iId)) !== null) {
-                        if($bMessage)
-                            $oCmts->addAuto([
+                        if($bMessage) {
+                            $aResult = $oCmts->addAuto([
                                 'cmt_author_id' => bx_get_logged_profile_id(),
                                 'cmt_parent_id' => 0,
                                 'cmt_text' => $sMessage
                             ]);
 
+                            if(!empty($aResult['id']))
+                                $this->_oDb->updateAutomators(['message_id' => $aResult['id']], ['id' => $iId]);
+                        }
+
                         if($sMessageResponse) {
                             sleep(1);
 
                             $oCmts->addAuto([
-                                'cmt_author_id' => $this->_iProfileAi,
+                                'cmt_author_id' => $this->_iProfileIdAi,
                                 'cmt_parent_id' => 0,
                                 'cmt_text' => $sMessageResponse
                             ]);
-
-                            $aValsToAdd['messages']++;
                         }
                     }
 
@@ -236,6 +232,22 @@ class BxBaseStudioAgentsAutomators extends BxDolStudioAgentsAutomators
         return parent::_getCellDefault(_t('_sys_agents_automators_field_type_' . $mixedValue), $sKey, $aField, $aRow);
     }
 
+    protected function _getCellData($sKey, $aField, $aRow)
+    {
+        if($sKey == 'message_id' && ($iCmtId = (int)$aRow[$sKey]) != 0 && ($oCmts = BxDolCmts::getObjectInstance($this->_sCmts, $aRow['id'])) !== null) {
+            $aCmt = $oCmts->getCommentSimple($iCmtId);
+            if(!empty($aCmt) && is_array($aCmt))
+                $aRow[$sKey] = $aCmt['cmt_text'];
+        }
+
+        return parent::_getCellData($sKey, $aField, $aRow);
+    }
+
+    protected function _getCellAdded($mixedValue, $sKey, $aField, $aRow)
+    {
+        return parent::_getCellDefault(bx_time_js($mixedValue), $sKey, $aField, $aRow);
+    }
+
     protected function _getCellStatus($mixedValue, $sKey, $aField, $aRow)
     {
         return parent::_getCellDefault(_t('_sys_agents_automators_field_status_' . $mixedValue), $sKey, $aField, $aRow);