BxDolAI.php 20 KB

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