BxDolAI.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  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_agents') ? new BxDolAI() : null;
  53. }
  54. return $GLOBALS['bxDolClasses'][__CLASS__];
  55. }
  56. public static function getAgentInstance(int $iId, array $aParams = []): NeuronAI\Agent\Agent
  57. {
  58. if (isset($GLOBALS['bxDolClasses'][__CLASS__ . '_Agent_' . $iId]))
  59. return $GLOBALS['bxDolClasses'][__CLASS__ . '_Agent_' . $iId];
  60. $a = BxDolAIQuery::getAgentObject($iId);
  61. if (!$a) {
  62. $s = "Agent with id {$iId} not found";
  63. bx_log('sys_agents', $s, BX_LOG_ERR);
  64. throw new Exception($s);
  65. }
  66. if (!$a['active']) {
  67. $s = "Agent with id {$iId} isn't active";
  68. bx_log('sys_agents', $s, BX_LOG_ERR);
  69. throw new Exception($s);
  70. }
  71. if (!$a['prompt_system'] || !$a['model_id']) {
  72. $s = "Agent with id {$iId} can't be used because it haven't prompt or AI model";
  73. bx_log('sys_agents', $s, BX_LOG_ERR);
  74. throw new Exception($s);
  75. }
  76. $o = BxDolAiAgent::make($a, $aParams);
  77. if ((int)$a['tools_max_run'] > 0)
  78. $o->toolMaxRuns($a['tools_max_run']);
  79. if ($a['vector_store_id']) {
  80. $aVectorStore = BxDolAIQuery::getVectorStoreObject($a['vector_store_id']);
  81. if ($aVectorStore && $aVectorStore['embedding_provider_id']) {
  82. $oEmbedder = self::getAiEmbeddingsProviderInstance($aVectorStore['embedding_provider_id']);
  83. $o->setEmbeddingsProvider($oEmbedder);
  84. }
  85. }
  86. $GLOBALS['bxDolClasses'][__CLASS__ . '_Agent_' . $iId] = $o;
  87. return $o;
  88. }
  89. public static function getAiProviderInstance(int $iId):NeuronAI\Providers\AIProviderInterface
  90. {
  91. return BxDolAIModelFactory::getModelInstance($iId);
  92. }
  93. public static function getAiEmbeddingsProviderInstance(int $iId):NeuronAI\RAG\Embeddings\EmbeddingsProviderInterface
  94. {
  95. return BxDolAIModelFactory::getModelInstance($iId);
  96. }
  97. public static function callHelper($mixedHelper, $sMessage)
  98. {
  99. $oAI = BxDolAI::getInstance();
  100. if (is_numeric($mixedHelper))
  101. $aHelper = $oAI->getHelperById($mixedHelper);
  102. else
  103. $aHelper = $oAI->getHelperByName($mixedHelper);
  104. $oAIModel = $oAI->getModelObject($aHelper['model_id']);
  105. return $oAIModel->getResponseText($aHelper['prompt'], $sMessage);
  106. }
  107. public static function pruning()
  108. {
  109. BxDolAIAssistant::pruning();
  110. }
  111. public static function getDefaultApiKey()
  112. {
  113. return getParam('sys_agents_api_key');
  114. }
  115. public static function getDefaultModel()
  116. {
  117. return (int)getParam('sys_agents_model');
  118. }
  119. public static function getAssistantForStudio()
  120. {
  121. return ($iId = (int)getParam('sys_agents_studio_assistant')) != 0 ? $iId : 0;
  122. }
  123. public static function getAssistantForLiveSearch()
  124. {
  125. return ($iId = (int)getParam('sys_agents_live_search_assistant')) != 0 ? $iId : 0;
  126. }
  127. public static function getAssistantForAskBlock()
  128. {
  129. return ($iId = (int)getParam('sys_agents_ask_block_assistant')) != 0 ? $iId : 0;
  130. }
  131. public function getProfileId()
  132. {
  133. return $this->_iProfileId;
  134. }
  135. public function getModels($aParams = [])
  136. {
  137. $aParamsDb = ['sample' => 'all_pairs'];
  138. if(isset($aParams['active']))
  139. $aParamsDb['active'] = $aParams['active'] === true ? 1 : 0;
  140. if(isset($aParams['capabilities']))
  141. $aParamsDb['capabilities'] = $aParams['capabilities'];
  142. return $aModel = $this->_oDb->getModelsBy($aParamsDb);
  143. }
  144. public function getModel($iId)
  145. {
  146. $aModel = $this->_oDb->getModelsBy(['sample' => 'id', 'id' => $iId]);
  147. if(!empty($aModel['params']))
  148. $aModel['params'] = json_decode($aModel['params'], true);
  149. return $aModel;
  150. }
  151. public function getModelObject($iId)
  152. {
  153. if(!$iId)
  154. $iId = $this->getDefaultModel();
  155. if(!$iId)
  156. return false;
  157. return BxDolAIModel::getObjectInstance($iId);
  158. }
  159. public function getProviderObject($iId)
  160. {
  161. if(!$iId)
  162. return false;
  163. return BxDolAIProvider::getObjectInstance($iId);
  164. }
  165. public function getAssistants($aParams = [])
  166. {
  167. $aParamsDb = ['sample' => 'all_pairs'];
  168. if(isset($aParams['active']))
  169. $aParamsDb['active'] = $aParams['active'] === true ? 1 : 0;
  170. if(isset($aParams['hidden']))
  171. $aParamsDb['hidden'] = $aParams['hidden'] === true ? 1 : 0;
  172. return $aModel = $this->_oDb->getAssistantsBy($aParamsDb);
  173. }
  174. public function getAssistantById($iId)
  175. {
  176. return $this->_oDb->getAssistantsBy(['sample' => 'id', 'id' => $iId]);
  177. }
  178. public function getAssistantByName($sName)
  179. {
  180. return $this->_oDb->getAssistantsBy(['sample' => 'name', 'name' => $sName]);
  181. }
  182. public function getAssistantChatById($iId)
  183. {
  184. return $this->_oDb->getChatsBy(['sample' => 'id', 'id' => $iId]);
  185. }
  186. public function getAssistantChatsTransient($iLifetime = 0)
  187. {
  188. return $this->_oDb->getChatsBy(['sample' => 'type', 'type' => BX_DOL_AI_ASST_TYPE_TRANSIENT, 'lifetime' => $iLifetime]);
  189. }
  190. public function updateAssistantChatById($iId, $aSet)
  191. {
  192. return $this->_oDb->updateChats($aSet, ['id' => $iId]);
  193. }
  194. public function getAssistantChatCmts()
  195. {
  196. return $this->_sCmtsAssistantsChats;
  197. }
  198. public function getAssistantChatCmtsObject($iId, $oTemplate = false)
  199. {
  200. $oCmts = BxDolCmts::getObjectInstance($this->_sCmtsAssistantsChats, (int)$iId, true, $oTemplate);
  201. if(!$oCmts || !$oCmts->isEnabled())
  202. return false;
  203. return $oCmts;
  204. }
  205. public function getHelperById($iId)
  206. {
  207. return $this->_oDb->getHelpersBy(['sample' => 'id', 'id' => $iId]);
  208. }
  209. public function getHelperByName($sName)
  210. {
  211. return $this->_oDb->getHelpersBy(['sample' => 'name', 'name' => $sName]);
  212. }
  213. public function getAutomator($iId, $bFullInfo = false)
  214. {
  215. $aAutomator = $this->_oDb->getAutomatorsBy(['sample' => 'id' . ($bFullInfo ? '_full' : ''), 'id' => $iId]);
  216. if(!empty($aAutomator['params']))
  217. $aAutomator['params'] = json_decode($aAutomator['params'], true);
  218. if($bFullInfo && !empty($aAutomator['model_params']))
  219. $aAutomator['model_params'] = json_decode($aAutomator['model_params'], true);
  220. return $aAutomator;
  221. }
  222. public function getAutomatorInstruction($sType, $mixedParams = false)
  223. {
  224. $mixedResult = '';
  225. switch($sType) {
  226. case 'profile':
  227. $mixedResult = "\n ProfileId for system actions = " . $mixedParams;
  228. break;
  229. case 'providers':
  230. $aProviders = $this->_oDb->getProvidersBy(['sample' => 'ids', 'ids' => $mixedParams]);
  231. if(!empty($aProviders) && is_array($aProviders)) {
  232. $mixedResult = "\n Proividers list = [";
  233. foreach($aProviders as $aProvider)
  234. $mixedResult .= "\n {'ProviderName' => '" . $aProvider['name'] . "', 'ProviderType' => '" . $aProvider['type_name'] . "'}";
  235. $mixedResult .= "\n ]";
  236. }
  237. break;
  238. case 'helpers':
  239. $aHelpers = $this->_oDb->getHelpersBy(['sample' => 'ids', 'ids' => $mixedParams]);
  240. if(!empty($aHelpers) && is_array($aHelpers)) {
  241. $mixedResult = "\n Helpers list = [";
  242. foreach($aHelpers as $aHelper)
  243. $mixedResult .= "\n {'" . $aHelper['name'] . "', 'HelperDescription' => '" . $aHelper['description'] . "'}";
  244. $mixedResult .= "\n ]";
  245. }
  246. break;
  247. case 'assistants':
  248. $aAssistants = $this->_oDb->getAssistantsBy(['sample' => 'ids', 'ids' => $mixedParams]);
  249. if(!empty($aAssistants) && is_array($aAssistants)) {
  250. $mixedResult = "\n Assistants list = [";
  251. foreach($aAssistants as $aAssistant)
  252. $mixedResult .= "\n {'" . $aAssistant['name'] . "', 'AssistantDescription' => '" . $aAssistant['description'] . "'}";
  253. $mixedResult .= "\n ]";
  254. }
  255. break;
  256. }
  257. return $mixedResult;
  258. }
  259. public function getAutomatorCmts()
  260. {
  261. return $this->_sCmtsAutomators;
  262. }
  263. public function getAutomatorCmtsObject($iId, $oTemplate = false)
  264. {
  265. $oCmts = BxDolCmts::getObjectInstance($this->_sCmtsAutomators, (int)$iId, true, $oTemplate);
  266. if(!$oCmts || !$oCmts->isEnabled())
  267. return false;
  268. return $oCmts;
  269. }
  270. public function hasAutomators($sType, $bActive = null)
  271. {
  272. $aParams = [
  273. 'sample' => 'type',
  274. 'type' => $sType
  275. ];
  276. if($bActive !== null)
  277. $aParams['active'] = $bActive;
  278. return ($aAutomators = $this->_oDb->getAutomatorsBy($aParams)) && is_array($aAutomators);
  279. }
  280. public function getAutomatorsEvent($sUnit, $sAction)
  281. {
  282. if(in_array($sUnit, $this->_aExcludeAlertUnits))
  283. return [];
  284. return $this->_oDb->getAutomatorsBy([
  285. 'sample' => 'events',
  286. 'alert_unit' => $sUnit,
  287. 'alert_action' => $sAction,
  288. 'active' => true
  289. ]);
  290. }
  291. public function getAutomatorsScheduler()
  292. {
  293. $aAutomators = $this->_oDb->getAutomatorsBy(['sample' => 'schedulers', 'active' => true]);
  294. foreach($aAutomators as &$aAutomator)
  295. if(!empty($aAutomator['params']))
  296. $aAutomator['params'] = json_decode($aAutomator['params'], true);
  297. return $aAutomators;
  298. }
  299. public function getAutomatorsWebhook($iProviderId)
  300. {
  301. $aAutomators = $this->_oDb->getAutomatorsBy(['sample' => 'webhooks', 'provider_id' => $iProviderId, 'active' => true]);
  302. foreach($aAutomators as &$aAutomator)
  303. if(!empty($aAutomator['params']))
  304. $aAutomator['params'] = json_decode($aAutomator['params'], true);
  305. return $aAutomators;
  306. }
  307. public function callAgent($sType, $aAgent, $mixedParams = [])
  308. {
  309. if ($mixedParams)
  310. $sParams = is_string($mixedParams) ? $mixedParams : json_encode($mixedParams);
  311. else
  312. $sParams = 'START';
  313. // update sample data
  314. $a = ['webhook' => 'webhook_sample'];
  315. if (isset($a[$sType]) && empty($aAgent[$a[$sType]])) {
  316. $this->_oDb->updateAgentField($aAgent['id'], $a[$sType], $sParams);
  317. }
  318. // set additional params
  319. $aParams = [];
  320. if ('message' == $sType) {
  321. $aParams = ['chat_history_subindex' => $mixedParams['sender_profile_id']];
  322. }
  323. // call agent
  324. $mixed = '';
  325. try {
  326. $o = self::getAgentInstance($aAgent['id'], $aParams);
  327. if (!$o)
  328. return false;
  329. $oMessage = $o->chat(new NeuronAI\Chat\Messages\UserMessage($sParams))->getMessage();
  330. $mixed = $oMessage->getContent();
  331. } catch (Exception $exception) {
  332. bx_log('sys_agents', "Exception in '{$aAgent['name']}' agent: " . $exception->getMessage() . " INPUT:" . $sParams, BX_LOG_ERR);
  333. $mixed = _t('_sys_agents_exception');
  334. }
  335. return $mixed;
  336. }
  337. public function sendMessengerMessage ($iSender, $iRecipient, $sMsg)
  338. {
  339. $oMessengerModule = BxDolModule::getInstance('bx_messenger');
  340. $aAutoReplyData = [
  341. 'message' => $sMsg,
  342. 'participants' => [$iSender, $iRecipient],
  343. ];
  344. $iSaveProfileId = $oMessengerModule->setProfileId($iSender);
  345. $a = $oMessengerModule->sendMessage($aAutoReplyData, $iRecipient, $iSender);
  346. $oMessengerModule->setProfileId($iSaveProfileId);
  347. return $a;
  348. }
  349. public function getAgentsByAlertUnitAndAction($sUnit, $sAction)
  350. {
  351. return $this->_oDb->getAgentsByAlertUnitAndAction($sUnit, $sAction);
  352. }
  353. public function getAgentsByProfileId($iProfileId)
  354. {
  355. return $this->_oDb->getAgentsByProfileId($iProfileId);
  356. }
  357. public function getAgentsByTriggerType($sTrigger)
  358. {
  359. return $this->_oDb->getAgentsByTriggerType($sTrigger);
  360. }
  361. public function getAgentByTriggerWebhookKey($sKey)
  362. {
  363. return $this->_oDb->getAgentByTriggerWebhookKey($sKey);
  364. }
  365. public function callAutomator($sType, $aParams = [])
  366. {
  367. $sMethod = '_callAutomator' . bx_gen_method_name($sType);
  368. if(!method_exists($this, $sMethod))
  369. return false;
  370. return $this->$sMethod($aParams);
  371. }
  372. protected function _callAutomatorEvent($aParams = [])
  373. {
  374. if(!isset($aParams['automator'], $aParams['alert']) || !is_a($aParams['alert'], 'BxDolAlerts'))
  375. return false;
  376. $oAlert = &$aParams['alert'];
  377. $this->evalCode($aParams['automator'], ['alert' => $oAlert]);
  378. }
  379. protected function _callAutomatorScheduler($aParams = [])
  380. {
  381. if(!isset($aParams['automator']))
  382. return false;
  383. $this->evalCode($aParams['automator']);
  384. }
  385. protected function _callAutomatorWebhook($aParams = [])
  386. {
  387. if(!isset($aParams['automator']))
  388. return false;
  389. $this->evalCode($aParams['automator']);
  390. }
  391. public function evalCode($aAutomator, $aParams = [])
  392. {
  393. try {
  394. $this->_evalCode($aAutomator, $aParams);
  395. }
  396. catch (Exception $oException) {
  397. $this->log($oException->getFile() . ':' . $oException->getLine() . ' ' . $oException->getMessage());
  398. }
  399. catch (Error $oError) {
  400. $this->log($oError->getFile() . ':' . $oError->getLine() . ' ' . $oError->getMessage());
  401. }
  402. }
  403. public function emulCode($aAutomator, $aParams = [])
  404. {
  405. ob_start();
  406. try {
  407. $this->_evalCode($aAutomator, $aParams);
  408. }
  409. catch (Exception $oException) {
  410. return $oException->getMessage();
  411. }
  412. catch (Error $oError) {
  413. return $oError->getMessage();
  414. }
  415. finally {
  416. $sOutput = ob_get_clean();
  417. if(!empty($sOutput))
  418. return $sOutput;
  419. }
  420. }
  421. public function log($mixedContents, $sSection = '')
  422. {
  423. if(!$this->_bWriteLog)
  424. return;
  425. if(is_array($mixedContents))
  426. $mixedContents = var_export($mixedContents, true);
  427. else if(is_object($mixedContents))
  428. $mixedContents = json_encode($mixedContents);
  429. if(empty($sSection))
  430. $sSection = "Core";
  431. bx_log('sys_agents', ":\n[" . $sSection . "] " . $mixedContents, BX_LOG_ERR);
  432. }
  433. protected function _evalCode($aAutomator, $aParams = [])
  434. {
  435. $sCode = '';
  436. switch($aAutomator['type']) {
  437. case BX_DOL_AI_AUTOMATOR_EVENT:
  438. $sCode = $aAutomator['code']. '; onAlert($aParams["alert"]->iObject , $aParams["alert"]->iSender , $aParams["alert"]->aExtras);';
  439. break;
  440. case BX_DOL_AI_AUTOMATOR_SCHEDULER:
  441. $sCode = $aAutomator['code'] . '; onCron();';
  442. break;
  443. case BX_DOL_AI_AUTOMATOR_WEBHOOK:
  444. $sCode = $aAutomator['code'] . '; onHook();';
  445. break;
  446. }
  447. eval($sCode);
  448. }
  449. }
  450. class BxDolAIMessage
  451. {
  452. /**
  453. * @var string - message Type with following values: hb, ai
  454. */
  455. protected $_sType;
  456. /**
  457. * @var mixed - an array of message parts (text, image_url) or a string.
  458. */
  459. protected $_mixedContent;
  460. /**
  461. * @var array - an array of of files attached to the message.
  462. */
  463. protected $_aAttachments;
  464. public function __construct($sType)
  465. {
  466. $this->_sType = $sType;
  467. }
  468. public function isAi()
  469. {
  470. return $this->_sType == 'ai';
  471. }
  472. public function getContent()
  473. {
  474. return $this->_mixedContent;
  475. }
  476. public function getAttachments()
  477. {
  478. return $this->_aAttachments;
  479. }
  480. }
  481. class BxDolAIMessageString extends BxDolAIMessage
  482. {
  483. public function __construct($sType, $sContent)
  484. {
  485. parent::__construct($sType);
  486. $this->_mixedContent = is_string($sContent) ? $sContent : '';
  487. }
  488. }
  489. class BxDolAIMessageArray extends BxDolAIMessage
  490. {
  491. public function __construct($sType, $aContent = '')
  492. {
  493. parent::__construct($sType);
  494. $this->_mixedContent = is_array($aContent) ? $aContent : [];
  495. }
  496. public function addText($sText)
  497. {
  498. $this->_mixedContent[] = [
  499. 'type' => 'text',
  500. 'text' => $sText
  501. ];
  502. }
  503. public function addImageUrl($sUrl, $sDetail = 'high')
  504. {
  505. $this->_mixedContent[] = [
  506. 'type' => 'image_url',
  507. 'image_url' => [
  508. 'url' => $sUrl,
  509. 'detail' => $sDetail
  510. ]
  511. ];
  512. }
  513. public function addAttachments($mixedAttachments, $mixedTools = false)
  514. {
  515. if(!is_array($mixedAttachments))
  516. $mixedAttachments = [$mixedAttachments];
  517. if(!$mixedTools)
  518. $mixedTools = [['type' => 'file_search']];
  519. foreach($mixedAttachments as $sAttachment)
  520. $this->_aAttachments[] = [
  521. 'file_id' => $sAttachment,
  522. 'tools' => $mixedTools
  523. ];
  524. }
  525. }
  526. class BxDolAIMessages
  527. {
  528. /**
  529. * @var array - an array of items (messages)
  530. */
  531. protected $_aItems;
  532. public function __construct($aItems = [])
  533. {
  534. $this->_aItems = !empty($aItems) && is_array($aItems) ? $aItems : [];
  535. }
  536. public function add($sType, $mixedMessage)
  537. {
  538. $sClass = 'BxDolAIMessage' . (is_string($mixedMessage) ? 'String' : 'Array');
  539. $this->_aItems[] = new $sClass($sType, $mixedMessage);
  540. }
  541. public function getAll()
  542. {
  543. return $this->_aItems;
  544. }
  545. public function getLast()
  546. {
  547. return end($this->_aItems);
  548. }
  549. }