Просмотр исходного кода

Ticket #5395 - Agents: Improve functionality. Point 3.

AntonLV 8 месяцев назад
Родитель
Сommit
d4e38c4806
3 измененных файлов с 34 добавлено и 231 удалено
  1. 0 220
      ai/BxDolAI.php
  2. 1 1
      install/sql/system.sql
  3. 33 10
      studio/classes/BxDolStudioAgentsAsstChatsCmts.php

+ 0 - 220
ai/BxDolAI.php

@@ -1,220 +0,0 @@
-<?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
- * @{
- */
-
-define('BX_DOL_AI_AUTOMATOR_EVENT', 'event');
-define('BX_DOL_AI_AUTOMATOR_SCHEDULER', 'scheduler');
-define('BX_DOL_AI_AUTOMATOR_WEBHOOK', 'webhook');
-
-define('BX_DOL_AI_AUTOMATOR_STATUS_AUTO', 'auto');
-define('BX_DOL_AI_AUTOMATOR_STATUS_MANUAL', 'manual');
-define('BX_DOL_AI_AUTOMATOR_STATUS_READY', 'ready');
-
-class BxDolAI extends BxDolFactory implements iBxDolSingleton
-{
-    protected $_oDb;
-    protected $_sPathInst;
-    protected $_iProfileId;
-    
-    protected $_aExcludeAlertUnits;
-
-    protected function __construct()
-    {
-        if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
-            trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
-
-        parent::__construct();
-
-        $this->_oDb = new BxDolAIQuery();
-        $this->_sPathInst = BX_DIRECTORY_PATH_ROOT . 'ai/instructions/';
-        $this->_iProfileId = (int)getParam('sys_profile_bot'); 
-
-        $this->_aExcludeAlertUnits = [
-            'system', 'module_template_method_call'
-        ];
-    }
-
-    /**
-     * Prevent cloning the instance
-     */
-    public function __clone()
-    {
-        if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
-            trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
-    }
-
-    /**
-     * Get singleton instance of the class
-     */
-    public static function getInstance()
-    {
-        if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
-            $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolAI();
-
-        return $GLOBALS['bxDolClasses'][__CLASS__];
-    }
-
-    public function getProfileId()
-    {
-        return $this->_iProfileId;
-    }
-
-    public function getAutomatorInstructions($sType, $bIncludeCommon = false)
-    {
-        $sResult = file_get_contents($this->_sPathInst . $sType . '.html');
-        if($bIncludeCommon)
-            $sResult .= file_get_contents($this->_sPathInst. 'common.html');
-
-        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 getAutomatorsEvent($sUnit, $sAction)
-    {
-        if(in_array($sUnit, $this->_aExcludeAlertUnits))
-            return [];
-
-        return $this->_oDb->getAutomatorsBy([
-            'sample' => 'events', 
-            'alert_unit' => $sUnit,
-            'alert_action' => $sAction,
-            'active' => true
-        ]);
-    }
-    public function getAutomatorsScheduler()
-    {
-        $aAutomators = $this->_oDb->getAutomatorsBy(['sample' => 'schedulers', 'active' => true]);
-        foreach($aAutomators as &$aAutomator)
-            if(!empty($aAutomator['params']))
-                $aAutomator['params'] = json_decode($aAutomator['params'], true);
-
-        return $aAutomators;
-    }
-
-    public function chat($sEndpoint, $sModel, $sApiKey, $aParams, $aMessages)
-    {
-        $aData = [
-            'model' => $sModel,
-            'messages' => $aMessages
-        ];
-
-        if(!empty($aParams) && is_array($aParams))
-            $aData = array_merge($aData, $aParams);
-
-        $sRv = bx_file_get_contents($sEndpoint, $aData, "post-json", ["Authorization: Bearer ".$sApiKey, 'Content-Type: application/json', 'OpenAI-Beta: assistants=v2']);
-        $aRv = json_decode($sRv, true);
-
-        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']));
-    }
-
-    public function callAutomator($sType, $aParams = [])
-    {
-        $sMethod = '_callAutomator' . bx_gen_method_name($sType);
-        if(!method_exists($this, $sMethod))
-            return false;
-
-        return $this->$sMethod($aParams);
-    }
-
-    protected function _callAutomatorEvent($aParams = [])
-    {
-        if(!isset($aParams['automator'], $aParams['alert']) || !is_a($aParams['alert'], 'BxDolAlerts'))
-            return false;
-        
-        $oAlert = &$aParams['alert'];
-
-        $this->evalCode($aParams['automator'], true, ['alert' => $oAlert]);
-    }
-
-    protected function _callAutomatorScheduler($aParams = [])
-    {
-        if(!isset($aParams['automator']))
-            return false;
-        
-        $this->evalCode($aParams['automator'], true);
-    }
-
-    public function evalCode($aAutomator, $isWriteLog = true, $aParams = null)
-    {
-        /*
-         * TODO: Improve code evaluation.
-         * 
-        ob_start();
-        set_error_handler("evalErrorHandler");
-         */
-        try {
-             $sCode = '';
-             if ($aAutomator['type'] == 'scheduler'){
-                 $sCode = $aAutomator['code'] . '; onCron();';
-             }
-             
-             if ($aAutomator['type'] == 'event'){
-                 $sCode = $aAutomator['code']. '; onAlert($aParams["alert"]->iObject , $aParams["alert"]->iSender , $aParams["alert"]->aExtras);';  
-             }
-             
-             
-             eval($sCode);
-            
-        }
-        catch (Exception $oException) {
-            if ($isWriteLog){
-                $this->writeLog($oException->getFile() . ':' . $oException->getLine() . ' ' . $oException->getMessage());
-            }
-            return $oException->getMessage();
-        } 
-        finally {
-            /*
-             * TODO: Improve code evaluation.
-             * 
-            $sOutput = ob_get_clean();
-            if ($sOutput != '')
-                return "Eval error: " . $sOutput;
-            restore_error_handler();
-             */
-        }
-    }
-
-    private function writeLog($sString)
-    {
-        bx_log('sys_agents', $sString, BX_LOG_ERR);
-    }
-}
-
-class EvalException extends Exception {}
-
-function evalErrorHandler($errno, $errstr, $errfile, $errline) {
-    if (!(error_reporting() & $errno)) {
-        // This error code is not included in error_reporting
-        return false;
-    }
-    throw new EvalException($errstr, $errno);
-}

+ 1 - 1
install/sql/system.sql

@@ -5709,7 +5709,7 @@ INSERT INTO `sys_grid_fields` (`object`, `name`, `title`, `width`, `translatable
 ('sys_studio_agents_assistants_chats', 'checkbox', '', '2%', 0, 0, '', '', 1),
 ('sys_studio_agents_assistants_chats', 'name', '_sys_agents_assistants_chats_txt_name', '18%', 0, 0, '', '', 2),
 ('sys_studio_agents_assistants_chats', 'type', '_sys_agents_assistants_chats_txt_type', '5%', 0, 0, '', '', 3),
-('sys_studio_agents_assistants_chats', 'description', '_sys_agents_assistants_chats_txt_description', '25%', 0, 16, '', '', 4),
+('sys_studio_agents_assistants_chats', 'description', '_sys_agents_assistants_chats_txt_description', '25%', 1, 16, '', '', 4),
 ('sys_studio_agents_assistants_chats', 'messages', '_sys_agents_assistants_chats_txt_messages', '10%', 0, 0, '', '', 5),
 ('sys_studio_agents_assistants_chats', 'added', '_sys_agents_assistants_chats_txt_added', '15%', 0, 0, '', '', 6),
 ('sys_studio_agents_assistants_chats', 'stored', '_sys_agents_assistants_chats_txt_stored', '15%', 0, 0, '', '', 7),

+ 33 - 10
studio/classes/BxDolStudioAgentsAsstChatsCmts.php

@@ -12,7 +12,10 @@ class BxDolStudioAgentsAsstChatsCmts extends BxDolStudioAgentsCmts
     protected static $_sPrefixLoad = '#-#';
     protected static $_sPrefixRetrieve = '|-|';
     protected static $_sParamAllowDelete = 'allow_delete';
-       
+
+    protected $_aChat;
+
+    protected $_aAssistant;
     protected $_iAssistantId;
     protected $_sAssistantUrl;
 
@@ -22,17 +25,39 @@ class BxDolStudioAgentsAsstChatsCmts extends BxDolStudioAgentsCmts
 
         parent::__construct($sSystem, $iId, $iInit, $oTemplate);
 
+        $this->_aChat = $this->_oQueryAgents->getChatsBy([
+            'sample' => 'id', 
+            'id' => (int)$iId
+        ]);
+
         $this->_iAssistantId = 0;
-        if(($iAssistantId = bx_get('aid')) !== false) {
-            $this->_iAssistantId = bx_process_input($iAssistantId, BX_DATA_INT);
-            $this->_aMarkers['assistant_id'] = $this->_iAssistantId;
-        }
-        $this->_sAssistantUrl = BX_DOL_URL_STUDIO . bx_append_url_params('agents.php', ['page' => 'assistants', 'spage' => 'chats', 'aid' => $this->_iAssistantId]);
+        $this->_sAssistantUrl = BX_DOL_URL_STUDIO . bx_append_url_params('agents.php', ['page' => 'assistants', 'spage' => 'chats']);
+
+        if(($iAssistantId = bx_get('aid')) !== false)
+            $this->setAssistantId(bx_process_input($iAssistantId, BX_DATA_INT));
+        else if(($iAssistantId = $this->_aChat['assistant_id'] ?? false))
+            $this->setAssistantId($iAssistantId);
 
         if(!$this->isParam(self::$_sParamAllowDelete))
             $this->setAllowDelete(true);
     }
 
+    public function setAssistantId($iAssistantId)
+    {
+        $this->_iAssistantId = (int)$iAssistantId;
+        $this->_sAssistantUrl = BX_DOL_URL_STUDIO . bx_append_url_params('agents.php', ['page' => 'assistants', 'spage' => 'chats', 'aid' => $this->_iAssistantId]);
+
+        $this->_aAssistant = $this->_oQueryAgents->getAssistantsBy([
+            'sample' => 'id', 
+            'id' => $this->_iAssistantId
+        ]);
+
+        if(!empty($this->_aAssistant) && is_array($this->_aAssistant) && ($iAssistantPid = $this->_aAssistant['profile_id'] ?: false))
+            $this->_iProfileIdAi = (int)$iAssistantPid;
+
+        $this->_aMarkers['assistant_id'] = $this->_iAssistantId;
+    }
+
     public function getPageJsObject()
     {
         return 'oBxDolStudioPageAgents';
@@ -44,12 +69,10 @@ class BxDolStudioAgentsAsstChatsCmts extends BxDolStudioAgentsCmts
         if(empty($aComments['content']))
             return MsgBox(_t('_error occured'));
 
-        $aChat = $this->_oQueryAgents->getChatsBy(['sample' => 'id', 'id' => (int)$this->getId()]);
-        if(empty($aChat) || !is_array($aChat))
+        if(empty($this->_aChat) || !is_array($this->_aChat))
             return MsgBox(_t('_error occured'));
         
-        $aAssistant = $this->_oQueryAgents->getAssistantsBy(['sample' => 'id', 'id' => (int)$aChat['assistant_id']]);
-        if(empty($aAssistant) || !is_array($aAssistant))
+        if(empty($this->_aAssistant) || !is_array($this->_aAssistant))
             return MsgBox(_t('_error occured'));
 
         return $aComments['content'];