1
0

BxDolAI.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaCore UNA Core
  7. * @{
  8. */
  9. define('BX_DOL_AI_ASSISTANT', 'assistant');
  10. define('BX_DOL_AI_AUTOMATOR_EVENT', 'event');
  11. define('BX_DOL_AI_AUTOMATOR_SCHEDULER', 'scheduler');
  12. define('BX_DOL_AI_AUTOMATOR_WEBHOOK', 'webhook');
  13. define('BX_DOL_AI_AUTOMATOR_STATUS_AUTO', 'auto');
  14. define('BX_DOL_AI_AUTOMATOR_STATUS_MANUAL', 'manual');
  15. define('BX_DOL_AI_AUTOMATOR_STATUS_READY', 'ready');
  16. class BxDolAI extends BxDolFactory implements iBxDolSingleton
  17. {
  18. protected $_oDb;
  19. protected $_iProfileId;
  20. protected $_aExcludeAlertUnits;
  21. protected $_sCmtsAutomators;
  22. protected $_sCmtsAssistantsChats;
  23. protected $_bWriteLog;
  24. protected function __construct()
  25. {
  26. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  27. trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
  28. parent::__construct();
  29. $this->_oDb = new BxDolAIQuery();
  30. $this->_iProfileId = (int)getParam('sys_profile_bot');
  31. $this->_aExcludeAlertUnits = [
  32. 'system', 'module_template_method_call'
  33. ];
  34. $this->_sCmtsAutomators = 'sys_agents_automators';
  35. $this->_sCmtsAssistantsChats = 'sys_agents_assistants_chats';
  36. $this->_bWriteLog = true;
  37. }
  38. /**
  39. * Prevent cloning the instance
  40. */
  41. public function __clone()
  42. {
  43. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  44. trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
  45. }
  46. /**
  47. * Get singleton instance of the class
  48. */
  49. public static function getInstance()
  50. {
  51. if (!isset($GLOBALS['bxDolClasses'][__CLASS__])) {
  52. $GLOBALS['bxDolClasses'][__CLASS__] = BxDolDb::getInstance()->isTableExists('sys_agents_automators') ? new BxDolAI() : null;
  53. }
  54. return $GLOBALS['bxDolClasses'][__CLASS__];
  55. }
  56. public static function callHelper($mixedHelper, $sMessage)
  57. {
  58. $oAI = BxDolAI::getInstance();
  59. if (is_numeric($mixedHelper))
  60. $aHelper = $oAI->getHelperById($mixedHelper);
  61. else
  62. $aHelper = $oAI->getHelperByName($mixedHelper);
  63. $oAIModel = $oAI->getModelObject($aHelper['model_id']);
  64. return $oAIModel->getResponseText($aHelper['prompt'], $sMessage);
  65. }
  66. public static function pruning()
  67. {
  68. BxDolAIAssistant::pruning();
  69. }
  70. public static function getDefaultApiKey()
  71. {
  72. return getParam('sys_agents_api_key');
  73. }
  74. public static function getDefaultModel()
  75. {
  76. return (int)getParam('sys_agents_model');
  77. }
  78. public static function getAssistantForStudio()
  79. {
  80. return ($iId = (int)getParam('sys_agents_studio_assistant')) != 0 ? $iId : 0;
  81. }
  82. public static function getAssistantForLiveSearch()
  83. {
  84. return ($iId = (int)getParam('sys_agents_live_search_assistant')) != 0 ? $iId : 0;
  85. }
  86. public static function getAssistantForAskBlock()
  87. {
  88. return ($iId = (int)getParam('sys_agents_ask_block_assistant')) != 0 ? $iId : 0;
  89. }
  90. public function getProfileId()
  91. {
  92. return $this->_iProfileId;
  93. }
  94. public function getModels($aParams = [])
  95. {
  96. $aParamsDb = ['sample' => 'all_pairs'];
  97. if(isset($aParams['active']))
  98. $aParamsDb['active'] = $aParams['active'] === true ? 1 : 0;
  99. if(isset($aParams['hidden']))
  100. $aParamsDb['hidden'] = $aParams['hidden'] === true ? 1 : 0;
  101. return $aModel = $this->_oDb->getModelsBy($aParamsDb);
  102. }
  103. public function getModel($iId)
  104. {
  105. $aModel = $this->_oDb->getModelsBy(['sample' => 'id', 'id' => $iId]);
  106. if(!empty($aModel['params']))
  107. $aModel['params'] = json_decode($aModel['params'], true);
  108. return $aModel;
  109. }
  110. public function getModelObject($iId)
  111. {
  112. if(!$iId)
  113. $iId = $this->getDefaultModel();
  114. if(!$iId)
  115. return false;
  116. return BxDolAIModel::getObjectInstance($iId);
  117. }
  118. public function getProviderObject($iId)
  119. {
  120. if(!$iId)
  121. return false;
  122. return BxDolAIProvider::getObjectInstance($iId);
  123. }
  124. public function getAssistants($aParams = [])
  125. {
  126. $aParamsDb = ['sample' => 'all_pairs'];
  127. if(isset($aParams['active']))
  128. $aParamsDb['active'] = $aParams['active'] === true ? 1 : 0;
  129. if(isset($aParams['hidden']))
  130. $aParamsDb['hidden'] = $aParams['hidden'] === true ? 1 : 0;
  131. return $aModel = $this->_oDb->getAssistantsBy($aParamsDb);
  132. }
  133. public function getAssistantById($iId)
  134. {
  135. return $this->_oDb->getAssistantsBy(['sample' => 'id', 'id' => $iId]);
  136. }
  137. public function getAssistantByName($sName)
  138. {
  139. return $this->_oDb->getAssistantsBy(['sample' => 'name', 'name' => $sName]);
  140. }
  141. public function getAssistantChatById($iId)
  142. {
  143. return $this->_oDb->getChatsBy(['sample' => 'id', 'id' => $iId]);
  144. }
  145. public function getAssistantChatsTransient($iLifetime = 0)
  146. {
  147. return $this->_oDb->getChatsBy(['sample' => 'type', 'type' => BX_DOL_AI_ASST_TYPE_TRANSIENT, 'lifetime' => $iLifetime]);
  148. }
  149. public function updateAssistantChatById($iId, $aSet)
  150. {
  151. return $this->_oDb->updateChats($aSet, ['id' => $iId]);
  152. }
  153. public function getAssistantChatCmts()
  154. {
  155. return $this->_sCmtsAssistantsChats;
  156. }
  157. public function getAssistantChatCmtsObject($iId, $oTemplate = false)
  158. {
  159. $oCmts = BxDolCmts::getObjectInstance($this->_sCmtsAssistantsChats, (int)$iId, true, $oTemplate);
  160. if(!$oCmts || !$oCmts->isEnabled())
  161. return false;
  162. return $oCmts;
  163. }
  164. public function getHelperById($iId)
  165. {
  166. return $this->_oDb->getHelpersBy(['sample' => 'id', 'id' => $iId]);
  167. }
  168. public function getHelperByName($sName)
  169. {
  170. return $this->_oDb->getHelpersBy(['sample' => 'name', 'name' => $sName]);
  171. }
  172. public function getAutomator($iId, $bFullInfo = false)
  173. {
  174. $aAutomator = $this->_oDb->getAutomatorsBy(['sample' => 'id' . ($bFullInfo ? '_full' : ''), 'id' => $iId]);
  175. if(!empty($aAutomator['params']))
  176. $aAutomator['params'] = json_decode($aAutomator['params'], true);
  177. if($bFullInfo && !empty($aAutomator['model_params']))
  178. $aAutomator['model_params'] = json_decode($aAutomator['model_params'], true);
  179. return $aAutomator;
  180. }
  181. public function getAutomatorInstruction($sType, $mixedParams = false)
  182. {
  183. $mixedResult = '';
  184. switch($sType) {
  185. case 'profile':
  186. $mixedResult = "\n ProfileId for system actions = " . $mixedParams;
  187. break;
  188. case 'providers':
  189. $aProviders = $this->_oDb->getProvidersBy(['sample' => 'ids', 'ids' => $mixedParams]);
  190. if(!empty($aProviders) && is_array($aProviders)) {
  191. $mixedResult = "\n Proividers list = [";
  192. foreach($aProviders as $aProvider)
  193. $mixedResult .= "\n {'ProviderName' => '" . $aProvider['name'] . "', 'ProviderType' => '" . $aProvider['type_name'] . "'}";
  194. $mixedResult .= "\n ]";
  195. }
  196. break;
  197. case 'helpers':
  198. $aHelpers = $this->_oDb->getHelpersBy(['sample' => 'ids', 'ids' => $mixedParams]);
  199. if(!empty($aHelpers) && is_array($aHelpers)) {
  200. $mixedResult = "\n Helpers list = [";
  201. foreach($aHelpers as $aHelper)
  202. $mixedResult .= "\n {'" . $aHelper['name'] . "', 'HelperDescription' => '" . $aHelper['description'] . "'}";
  203. $mixedResult .= "\n ]";
  204. }
  205. break;
  206. case 'assistants':
  207. $aAssistants = $this->_oDb->getAssistantsBy(['sample' => 'ids', 'ids' => $mixedParams]);
  208. if(!empty($aAssistants) && is_array($aAssistants)) {
  209. $mixedResult = "\n Assistants list = [";
  210. foreach($aAssistants as $aAssistant)
  211. $mixedResult .= "\n {'" . $aAssistant['name'] . "', 'AssistantDescription' => '" . $aAssistant['description'] . "'}";
  212. $mixedResult .= "\n ]";
  213. }
  214. break;
  215. }
  216. return $mixedResult;
  217. }
  218. public function getAutomatorCmts()
  219. {
  220. return $this->_sCmtsAutomators;
  221. }
  222. public function getAutomatorCmtsObject($iId, $oTemplate = false)
  223. {
  224. $oCmts = BxDolCmts::getObjectInstance($this->_sCmtsAutomators, (int)$iId, true, $oTemplate);
  225. if(!$oCmts || !$oCmts->isEnabled())
  226. return false;
  227. return $oCmts;
  228. }
  229. public function hasAutomators($sType, $bActive = null)
  230. {
  231. $aParams = [
  232. 'sample' => 'type',
  233. 'type' => $sType
  234. ];
  235. if($bActive !== null)
  236. $aParams['active'] = $bActive;
  237. return ($aAutomators = $this->_oDb->getAutomatorsBy($aParams)) && is_array($aAutomators);
  238. }
  239. public function getAutomatorsEvent($sUnit, $sAction)
  240. {
  241. if(in_array($sUnit, $this->_aExcludeAlertUnits))
  242. return [];
  243. return $this->_oDb->getAutomatorsBy([
  244. 'sample' => 'events',
  245. 'alert_unit' => $sUnit,
  246. 'alert_action' => $sAction,
  247. 'active' => true
  248. ]);
  249. }
  250. public function getAutomatorsScheduler()
  251. {
  252. $aAutomators = $this->_oDb->getAutomatorsBy(['sample' => 'schedulers', 'active' => true]);
  253. foreach($aAutomators as &$aAutomator)
  254. if(!empty($aAutomator['params']))
  255. $aAutomator['params'] = json_decode($aAutomator['params'], true);
  256. return $aAutomators;
  257. }
  258. public function getAutomatorsWebhook($iProviderId)
  259. {
  260. $aAutomators = $this->_oDb->getAutomatorsBy(['sample' => 'webhooks', 'provider_id' => $iProviderId, 'active' => true]);
  261. foreach($aAutomators as &$aAutomator)
  262. if(!empty($aAutomator['params']))
  263. $aAutomator['params'] = json_decode($aAutomator['params'], true);
  264. return $aAutomators;
  265. }
  266. public function callAutomator($sType, $aParams = [])
  267. {
  268. $sMethod = '_callAutomator' . bx_gen_method_name($sType);
  269. if(!method_exists($this, $sMethod))
  270. return false;
  271. return $this->$sMethod($aParams);
  272. }
  273. protected function _callAutomatorEvent($aParams = [])
  274. {
  275. if(!isset($aParams['automator'], $aParams['alert']) || !is_a($aParams['alert'], 'BxDolAlerts'))
  276. return false;
  277. $oAlert = &$aParams['alert'];
  278. $this->evalCode($aParams['automator'], ['alert' => $oAlert]);
  279. }
  280. protected function _callAutomatorScheduler($aParams = [])
  281. {
  282. if(!isset($aParams['automator']))
  283. return false;
  284. $this->evalCode($aParams['automator']);
  285. }
  286. protected function _callAutomatorWebhook($aParams = [])
  287. {
  288. if(!isset($aParams['automator']))
  289. return false;
  290. $this->evalCode($aParams['automator']);
  291. }
  292. public function evalCode($aAutomator, $aParams = [])
  293. {
  294. try {
  295. $this->_evalCode($aAutomator, $aParams);
  296. }
  297. catch (Exception $oException) {
  298. $this->log($oException->getFile() . ':' . $oException->getLine() . ' ' . $oException->getMessage());
  299. }
  300. catch (Error $oError) {
  301. $this->log($oError->getFile() . ':' . $oError->getLine() . ' ' . $oError->getMessage());
  302. }
  303. }
  304. public function emulCode($aAutomator, $aParams = [])
  305. {
  306. ob_start();
  307. try {
  308. $this->_evalCode($aAutomator, $aParams);
  309. }
  310. catch (Exception $oException) {
  311. return $oException->getMessage();
  312. }
  313. catch (Error $oError) {
  314. return $oError->getMessage();
  315. }
  316. finally {
  317. $sOutput = ob_get_clean();
  318. if(!empty($sOutput))
  319. return $sOutput;
  320. }
  321. }
  322. public function log($mixedContents, $sSection = '')
  323. {
  324. if(!$this->_bWriteLog)
  325. return;
  326. if(is_array($mixedContents))
  327. $mixedContents = var_export($mixedContents, true);
  328. else if(is_object($mixedContents))
  329. $mixedContents = json_encode($mixedContents);
  330. if(empty($sSection))
  331. $sSection = "Core";
  332. bx_log('sys_agents', ":\n[" . $sSection . "] " . $mixedContents, BX_LOG_ERR);
  333. }
  334. protected function _evalCode($aAutomator, $aParams = [])
  335. {
  336. $sCode = '';
  337. switch($aAutomator['type']) {
  338. case BX_DOL_AI_AUTOMATOR_EVENT:
  339. $sCode = $aAutomator['code']. '; onAlert($aParams["alert"]->iObject , $aParams["alert"]->iSender , $aParams["alert"]->aExtras);';
  340. break;
  341. case BX_DOL_AI_AUTOMATOR_SCHEDULER:
  342. $sCode = $aAutomator['code'] . '; onCron();';
  343. break;
  344. case BX_DOL_AI_AUTOMATOR_WEBHOOK:
  345. $sCode = $aAutomator['code'] . '; onHook();';
  346. break;
  347. }
  348. eval($sCode);
  349. }
  350. }
  351. class BxDolAIMessage
  352. {
  353. /**
  354. * @var string - message Type with following values: hb, ai
  355. */
  356. protected $_sType;
  357. /**
  358. * @var mixed - an array of message parts (text, image_url) or a string.
  359. */
  360. protected $_mixedContent;
  361. /**
  362. * @var array - an array of of files attached to the message.
  363. */
  364. protected $_aAttachments;
  365. public function __construct($sType)
  366. {
  367. $this->_sType = $sType;
  368. }
  369. public function isAi()
  370. {
  371. return $this->_sType == 'ai';
  372. }
  373. public function getContent()
  374. {
  375. return $this->_mixedContent;
  376. }
  377. public function getAttachments()
  378. {
  379. return $this->_aAttachments;
  380. }
  381. }
  382. class BxDolAIMessageString extends BxDolAIMessage
  383. {
  384. public function __construct($sType, $sContent)
  385. {
  386. parent::__construct($sType);
  387. $this->_mixedContent = is_string($sContent) ? $sContent : '';
  388. }
  389. }
  390. class BxDolAIMessageArray extends BxDolAIMessage
  391. {
  392. public function __construct($sType, $aContent = '')
  393. {
  394. parent::__construct($sType);
  395. $this->_mixedContent = is_array($aContent) ? $aContent : [];
  396. }
  397. public function addText($sText)
  398. {
  399. $this->_mixedContent[] = [
  400. 'type' => 'text',
  401. 'text' => $sText
  402. ];
  403. }
  404. public function addImageUrl($sUrl, $sDetail = 'high')
  405. {
  406. $this->_mixedContent[] = [
  407. 'type' => 'image_url',
  408. 'image_url' => [
  409. 'url' => $sUrl,
  410. 'detail' => $sDetail
  411. ]
  412. ];
  413. }
  414. public function addAttachments($mixedAttachments, $mixedTools = false)
  415. {
  416. if(!is_array($mixedAttachments))
  417. $mixedAttachments = [$mixedAttachments];
  418. if(!$mixedTools)
  419. $mixedTools = [['type' => 'file_search']];
  420. foreach($mixedAttachments as $sAttachment)
  421. $this->_aAttachments[] = [
  422. 'file_id' => $sAttachment,
  423. 'tools' => $mixedTools
  424. ];
  425. }
  426. }
  427. class BxDolAIMessages
  428. {
  429. /**
  430. * @var array - an array of items (messages)
  431. */
  432. protected $_aItems;
  433. public function __construct($aItems = [])
  434. {
  435. $this->_aItems = !empty($aItems) && is_array($aItems) ? $aItems : [];
  436. }
  437. public function add($sType, $mixedMessage)
  438. {
  439. $sClass = 'BxDolAIMessage' . (is_string($mixedMessage) ? 'String' : 'Array');
  440. $this->_aItems[] = new $sClass($sType, $mixedMessage);
  441. }
  442. public function getAll()
  443. {
  444. return $this->_aItems;
  445. }
  446. public function getLast()
  447. {
  448. return end($this->_aItems);
  449. }
  450. }