BxDolAI.php 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  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 || 'form-input' == $sType || 'alert' == $sType) {
  321. $aParams = ['chat_history_subindex' => (int)($mixedParams['sender_profile_id'] ?? 0)];
  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. /**
  338. * Whether the current (or given) member may interact with the agent
  339. * via chat, messenger, or form-input. Empty acl_levels means Nobody.
  340. * Site admins / Studio operators always may, so they can debug.
  341. */
  342. public function canInteract($aAgent, $iProfileId = false, $bAllowOperators = true)
  343. {
  344. if (!is_array($aAgent) || empty($aAgent['id']))
  345. return false;
  346. if ($bAllowOperators && isAdmin())
  347. return true;
  348. $iLevels = (int)($aAgent['acl_levels'] ?? 0);
  349. if (!$iLevels)
  350. return false;
  351. return (bool)BxDolAcl::getInstance()->isMemberLevelInSet($iLevels, $iProfileId);
  352. }
  353. /**
  354. * Direct HTTP chat (`sys-ai-chat`). Operators may talk to any trigger;
  355. * everyone else only `manual` and `message` agents they can interact with.
  356. */
  357. public function canChatDirectly($aAgent, $iProfileId = false)
  358. {
  359. if (!$this->canInteract($aAgent, $iProfileId))
  360. return false;
  361. if (isAdmin())
  362. return true;
  363. return in_array($aAgent['trigger'] ?? '', ['manual', 'message'], true);
  364. }
  365. public function extractChatPromptFromRequest($aData)
  366. {
  367. if (!is_array($aData))
  368. return '';
  369. if (!empty($aData['prompt']) && is_string($aData['prompt']))
  370. return trim($aData['prompt']);
  371. if (empty($aData['messages']) || !is_array($aData['messages']))
  372. return '';
  373. for ($i = count($aData['messages']) - 1; $i >= 0; $i--) {
  374. $aMessage = $aData['messages'][$i];
  375. if (!is_array($aMessage))
  376. continue;
  377. if (($aMessage['role'] ?? '') !== 'user')
  378. continue;
  379. if (isset($aMessage['content']) && is_string($aMessage['content']))
  380. return trim($aMessage['content']);
  381. if (!empty($aMessage['parts']) && is_array($aMessage['parts'])) {
  382. $aText = [];
  383. foreach ($aMessage['parts'] as $aPart) {
  384. if (is_array($aPart) && ($aPart['type'] ?? '') === 'text' && isset($aPart['content']))
  385. $aText[] = $aPart['content'];
  386. }
  387. $s = trim(implode("\n", $aText));
  388. if ($s !== '')
  389. return $s;
  390. }
  391. }
  392. return '';
  393. }
  394. /**
  395. * Guest threads: `g:{clientKey}` (NEO header) or `s:{memberSession}` (UNA cookie).
  396. * Members: profile id. Guest key is kept in session and adopted on login.
  397. */
  398. public function resolveChatHistoryParams()
  399. {
  400. $iProfileId = (int)bx_get_logged_profile_id();
  401. $oSession = BxDolSession::getInstance();
  402. $sHeaderKey = $this->readAiGuestKeyFromRequest();
  403. $sSessionKey = 'ai_chat_guest_subindex';
  404. if ($iProfileId) {
  405. $sGuest = $sHeaderKey ? ('g:' . $sHeaderKey) : '';
  406. if ($sGuest === '') {
  407. $sStored = $oSession->getValue($sSessionKey);
  408. if ($this->isAiGuestSubindex($sStored))
  409. $sGuest = $sStored;
  410. }
  411. if ($sGuest !== '')
  412. $this->_oDb->adoptGuestChatHistory($sGuest, $iProfileId);
  413. if ($oSession->isValue($sSessionKey))
  414. $oSession->unsetValue($sSessionKey);
  415. return [
  416. 'sender_profile_id' => $iProfileId,
  417. 'chat_history_subindex' => (string)$iProfileId,
  418. ];
  419. }
  420. $oSession->start(true);
  421. $sSessionId = (string)$oSession->getId();
  422. $sSubindex = $sHeaderKey ? ('g:' . $sHeaderKey) : ('s:' . ($sSessionId !== '' ? $sSessionId : '0'));
  423. $oSession->setValue($sSessionKey, $sSubindex);
  424. return [
  425. 'sender_profile_id' => 0,
  426. 'chat_history_subindex' => $sSubindex,
  427. ];
  428. }
  429. /**
  430. * `{trigger}:{agentId}:{contextPid}:{userSubindex}`.
  431. * Context is omitted when 0 so existing site-wide threads still load.
  432. * User suffix stays last so adoptGuestChatHistory keeps matching.
  433. */
  434. public static function chatHistoryThreadId($aAgent, $aParams = [])
  435. {
  436. $s = ($aAgent['trigger'] ?? '') . ':' . ($aAgent['id'] ?? '');
  437. $iContextPid = (int)($aParams['chat_history_context_pid'] ?? 0);
  438. if ($iContextPid > 0)
  439. $s .= ':' . $iContextPid;
  440. if (isset($aParams['chat_history_subindex']) && $aParams['chat_history_subindex'] !== '')
  441. $s .= ':' . (string)$aParams['chat_history_subindex'];
  442. return $s;
  443. }
  444. /**
  445. * Context from chat HTTP (`?context=`). Missing/0 = site-wide. Invalid/unviewable = false (403).
  446. * @return int|false
  447. */
  448. public function resolveChatHistoryContextPid()
  449. {
  450. $mixed = bx_get('context');
  451. if ($mixed === false)
  452. return 0;
  453. $iPid = (int)$mixed;
  454. if ($iPid <= 0)
  455. return 0;
  456. $oProfile = BxDolProfile::getInstance($iPid);
  457. if (!$oProfile || !bx_srv('system', 'is_module_context', [$oProfile->getModule()]))
  458. return false;
  459. if ($oProfile->checkAllowedProfileView() !== CHECK_ACTION_RESULT_ALLOWED)
  460. return false;
  461. return $iPid;
  462. }
  463. /**
  464. * Context of the current page (AI agent block JSON).
  465. * Prefer `bx_get_page_info()`; API page JSON falls back to $_GET after getPageAPI merges params.
  466. */
  467. public function resolveChatHistoryContextPidFromPage()
  468. {
  469. if (function_exists('bx_get_page_info')) {
  470. $aInfo = bx_get_page_info();
  471. if ($aInfo && !empty($aInfo['context_profile_id']))
  472. return $this->filterViewableContextPid((int)$aInfo['context_profile_id']);
  473. }
  474. if (($iPid = (int)bx_process_input(bx_get('profile_id'), BX_DATA_INT)) > 0) {
  475. $oProfile = BxDolProfile::getInstance($iPid);
  476. if ($oProfile && bx_srv('system', 'is_module_context', [$oProfile->getModule()]))
  477. return $this->filterViewableContextPid((int)$oProfile->id());
  478. }
  479. $oPage = BxDolPage::getObjectInstanceByURI();
  480. $sModule = $oPage ? (string)$oPage->getModule() : '';
  481. $iContentId = (int)bx_process_input(bx_get('id'), BX_DATA_INT);
  482. if ($iContentId > 0 && $sModule !== '' && bx_srv('system', 'is_module_context', [$sModule])) {
  483. $oProfile = BxDolProfile::getInstanceByContentAndType($iContentId, $sModule);
  484. if ($oProfile)
  485. return $this->filterViewableContextPid((int)$oProfile->id());
  486. }
  487. return 0;
  488. }
  489. protected function filterViewableContextPid($iPid)
  490. {
  491. $iPid = (int)$iPid;
  492. if ($iPid <= 0)
  493. return 0;
  494. $oProfile = BxDolProfile::getInstance($iPid);
  495. if (!$oProfile || $oProfile->checkAllowedProfileView() !== CHECK_ACTION_RESULT_ALLOWED)
  496. return 0;
  497. return $iPid;
  498. }
  499. /**
  500. * Transcript for TanStack `useChat` hydrate / `initialMessages`.
  501. * Loads the same NeuronAI chat history the agent uses when streaming.
  502. */
  503. public function getChatHistoryUiMessages($iAgentId, $aParams = [])
  504. {
  505. if (!isset($aParams['chat_history_subindex']))
  506. $aParams = array_merge($this->resolveChatHistoryParams(), $aParams);
  507. $aAgent = BxDolAiQuery::getAgentObject((int)$iAgentId);
  508. if (!$aAgent || empty($aAgent['chat_history_context']))
  509. return [];
  510. $sThreadId = self::chatHistoryThreadId($aAgent, $aParams);
  511. $sJson = $this->_oDb->getOne("SELECT `messages` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", [
  512. 't' => $sThreadId,
  513. ]);
  514. $aStored = json_decode((string)$sJson, true);
  515. if (!is_array($aStored) || $aStored === [])
  516. return [];
  517. try {
  518. $o = self::getAgentInstance((int)$iAgentId, $aParams);
  519. } catch (Exception $oException) {
  520. bx_log('sys_agents', "Hydrate exception for agent {$iAgentId}: " . $oException->getMessage(), BX_LOG_ERR);
  521. return [];
  522. }
  523. return $this->neuronMessagesToUiMessages($o->getChatHistory()->getMessages());
  524. }
  525. /**
  526. * @param NeuronAI\Chat\Messages\Message[] $aMessages
  527. * @return array<int, array<string, mixed>>
  528. */
  529. protected function neuronMessagesToUiMessages($aMessages)
  530. {
  531. $aResult = [];
  532. $i = 0;
  533. foreach ($aMessages as $oMessage) {
  534. if (
  535. $oMessage instanceof NeuronAI\Chat\Messages\ToolCallMessage
  536. || $oMessage instanceof NeuronAI\Chat\Messages\ToolResultMessage
  537. ) {
  538. continue;
  539. }
  540. $sRole = $oMessage->getRole();
  541. if ($sRole === 'model')
  542. $sRole = 'assistant';
  543. if ($sRole !== 'user' && $sRole !== 'assistant')
  544. continue;
  545. $aParts = [];
  546. foreach ($oMessage->getContentBlocks() as $oBlock) {
  547. if ($oBlock instanceof NeuronAI\Chat\Messages\ContentBlocks\ReasoningContent) {
  548. if ($oBlock->content !== '')
  549. $aParts[] = ['type' => 'thinking', 'content' => $oBlock->content];
  550. continue;
  551. }
  552. if ($oBlock instanceof NeuronAI\Chat\Messages\ContentBlocks\TextContent && $oBlock->content !== '')
  553. $aParts[] = ['type' => 'text', 'content' => $oBlock->content];
  554. }
  555. if (!$aParts)
  556. continue;
  557. $sId = $oMessage->getMetadata('__id');
  558. $aResult[] = [
  559. 'id' => is_string($sId) && $sId !== '' ? $sId : ('msg_' . $i),
  560. 'role' => $sRole,
  561. 'parts' => $aParts,
  562. ];
  563. $i++;
  564. }
  565. return $aResult;
  566. }
  567. protected function readAiGuestKeyFromRequest()
  568. {
  569. $s = $_SERVER['HTTP_X_UNA_AI_GUEST_KEY'] ?? '';
  570. if ($s === '' && function_exists('apache_request_headers')) {
  571. foreach (apache_request_headers() as $sName => $sValue) {
  572. if (strtolower((string)$sName) === 'x-una-ai-guest-key') {
  573. $s = $sValue;
  574. break;
  575. }
  576. }
  577. }
  578. return $this->sanitizeAiGuestKey($s);
  579. }
  580. protected function sanitizeAiGuestKey($s)
  581. {
  582. $s = is_string($s) ? $s : '';
  583. return preg_match('/^[A-Za-z0-9_-]{16,64}$/', $s) ? $s : '';
  584. }
  585. protected function isAiGuestSubindex($s)
  586. {
  587. $s = is_string($s) ? $s : '';
  588. if ($s === '' || (strncmp($s, 'g:', 2) !== 0 && strncmp($s, 's:', 2) !== 0))
  589. return false;
  590. return $this->sanitizeAiGuestKey(substr($s, 2)) !== '';
  591. }
  592. public function streamAgentChat($iAgentId, $sPrompt, $aParams = [], $sThreadId = null)
  593. {
  594. if (!isset($aParams['chat_history_subindex']))
  595. $aParams = array_merge($this->resolveChatHistoryParams(), $aParams);
  596. $oAdapter = new NeuronAI\Chat\Messages\Stream\Adapters\AGUIAdapter($sThreadId);
  597. foreach ($oAdapter->getHeaders() as $sName => $sValue)
  598. header($sName . ': ' . $sValue);
  599. if (function_exists('apache_setenv'))
  600. @apache_setenv('no-gzip', '1');
  601. @ini_set('zlib.output_compression', '0');
  602. @ini_set('implicit_flush', '1');
  603. while (ob_get_level())
  604. ob_end_flush();
  605. try {
  606. $o = self::getAgentInstance((int)$iAgentId, $aParams);
  607. $oHandler = $o->stream(new NeuronAI\Chat\Messages\UserMessage($sPrompt));
  608. foreach ($oHandler->events($oAdapter) as $sEvent) {
  609. echo $sEvent;
  610. if (ob_get_level())
  611. ob_flush();
  612. flush();
  613. }
  614. } catch (Exception $oException) {
  615. bx_log('sys_agents', "Stream exception for agent {$iAgentId}: " . $oException->getMessage() . " INPUT:" . $sPrompt, BX_LOG_ERR);
  616. echo 'data: ' . json_encode(['type' => 'RUN_ERROR', 'message' => _t('_sys_agents_exception')]) . "\n\n";
  617. flush();
  618. }
  619. exit;
  620. }
  621. public function sendMessengerMessage ($iSender, $iRecipient, $sMsg)
  622. {
  623. $oMessengerModule = BxDolModule::getInstance('bx_messenger');
  624. $aAutoReplyData = [
  625. 'message' => $sMsg,
  626. 'participants' => [$iSender, $iRecipient],
  627. ];
  628. $iSaveProfileId = $oMessengerModule->setProfileId($iSender);
  629. $a = $oMessengerModule->sendMessage($aAutoReplyData, $iRecipient, $iSender);
  630. $oMessengerModule->setProfileId($iSaveProfileId);
  631. return $a;
  632. }
  633. public function getAgentsByAlertUnitAndAction($sUnit, $sAction)
  634. {
  635. $aAgents = [];
  636. $a = $this->_oDb->getAgentsWithAlert();
  637. foreach ($a as $r) {
  638. $aAlert = explode(':', $r['alert']); // TODO: remake to concantenate $sUnit and $sAction and then compare
  639. if (count($aAlert) == 2 && $aAlert[0] == $sUnit && $aAlert[1] == $sAction)
  640. $aAgents[] = $r;
  641. }
  642. return $aAgents;
  643. }
  644. public function getAgentsBy($aParams)
  645. {
  646. return $this->_oDb->getAgentsBy($aParams);
  647. }
  648. public function getAgentsByProfileId($iProfileId)
  649. {
  650. return $this->_oDb->getAgentsByProfileId($iProfileId);
  651. }
  652. public function getAgentsByFormObject($sFormObject)
  653. {
  654. return $this->_oDb->getAgentsByFormObject($sFormObject);
  655. }
  656. public function getAgentsByTriggerType($sTrigger)
  657. {
  658. return $this->_oDb->getAgentsByTriggerType($sTrigger);
  659. }
  660. public function getAgentById($iId)
  661. {
  662. return $this->_oDb->getAgentById($iId);
  663. }
  664. public function getAgentByTriggerWebhookKey($sKey)
  665. {
  666. return $this->_oDb->getAgentByTriggerWebhookKey($sKey);
  667. }
  668. public function callAutomator($sType, $aParams = [])
  669. {
  670. $sMethod = '_callAutomator' . bx_gen_method_name($sType);
  671. if(!method_exists($this, $sMethod))
  672. return false;
  673. return $this->$sMethod($aParams);
  674. }
  675. protected function _callAutomatorEvent($aParams = [])
  676. {
  677. if(!isset($aParams['automator'], $aParams['alert']) || !is_a($aParams['alert'], 'BxDolAlerts'))
  678. return false;
  679. $oAlert = &$aParams['alert'];
  680. $this->evalCode($aParams['automator'], ['alert' => $oAlert]);
  681. }
  682. protected function _callAutomatorScheduler($aParams = [])
  683. {
  684. if(!isset($aParams['automator']))
  685. return false;
  686. $this->evalCode($aParams['automator']);
  687. }
  688. protected function _callAutomatorWebhook($aParams = [])
  689. {
  690. if(!isset($aParams['automator']))
  691. return false;
  692. $this->evalCode($aParams['automator']);
  693. }
  694. public function evalCode($aAutomator, $aParams = [])
  695. {
  696. try {
  697. $this->_evalCode($aAutomator, $aParams);
  698. }
  699. catch (Exception $oException) {
  700. $this->log($oException->getFile() . ':' . $oException->getLine() . ' ' . $oException->getMessage());
  701. }
  702. catch (Error $oError) {
  703. $this->log($oError->getFile() . ':' . $oError->getLine() . ' ' . $oError->getMessage());
  704. }
  705. }
  706. public function emulCode($aAutomator, $aParams = [])
  707. {
  708. ob_start();
  709. try {
  710. $this->_evalCode($aAutomator, $aParams);
  711. }
  712. catch (Exception $oException) {
  713. return $oException->getMessage();
  714. }
  715. catch (Error $oError) {
  716. return $oError->getMessage();
  717. }
  718. finally {
  719. $sOutput = ob_get_clean();
  720. if(!empty($sOutput))
  721. return $sOutput;
  722. }
  723. }
  724. public function log($mixedContents, $sSection = '')
  725. {
  726. if(!$this->_bWriteLog)
  727. return;
  728. if(is_array($mixedContents))
  729. $mixedContents = var_export($mixedContents, true);
  730. else if(is_object($mixedContents))
  731. $mixedContents = json_encode($mixedContents);
  732. if(empty($sSection))
  733. $sSection = "Core";
  734. bx_log('sys_agents', ":\n[" . $sSection . "] " . $mixedContents, BX_LOG_ERR);
  735. }
  736. protected function _evalCode($aAutomator, $aParams = [])
  737. {
  738. $sCode = '';
  739. switch($aAutomator['type']) {
  740. case BX_DOL_AI_AUTOMATOR_EVENT:
  741. $sCode = $aAutomator['code']. '; onAlert($aParams["alert"]->iObject , $aParams["alert"]->iSender , $aParams["alert"]->aExtras);';
  742. break;
  743. case BX_DOL_AI_AUTOMATOR_SCHEDULER:
  744. $sCode = $aAutomator['code'] . '; onCron();';
  745. break;
  746. case BX_DOL_AI_AUTOMATOR_WEBHOOK:
  747. $sCode = $aAutomator['code'] . '; onHook();';
  748. break;
  749. }
  750. eval($sCode);
  751. }
  752. }
  753. class BxDolAIMessage
  754. {
  755. /**
  756. * @var string - message Type with following values: hb, ai
  757. */
  758. protected $_sType;
  759. /**
  760. * @var mixed - an array of message parts (text, image_url) or a string.
  761. */
  762. protected $_mixedContent;
  763. /**
  764. * @var array - an array of of files attached to the message.
  765. */
  766. protected $_aAttachments;
  767. public function __construct($sType)
  768. {
  769. $this->_sType = $sType;
  770. }
  771. public function isAi()
  772. {
  773. return $this->_sType == 'ai';
  774. }
  775. public function getContent()
  776. {
  777. return $this->_mixedContent;
  778. }
  779. public function getAttachments()
  780. {
  781. return $this->_aAttachments;
  782. }
  783. }
  784. class BxDolAIMessageString extends BxDolAIMessage
  785. {
  786. public function __construct($sType, $sContent)
  787. {
  788. parent::__construct($sType);
  789. $this->_mixedContent = is_string($sContent) ? $sContent : '';
  790. }
  791. }
  792. class BxDolAIMessageArray extends BxDolAIMessage
  793. {
  794. public function __construct($sType, $aContent = '')
  795. {
  796. parent::__construct($sType);
  797. $this->_mixedContent = is_array($aContent) ? $aContent : [];
  798. }
  799. public function addText($sText)
  800. {
  801. $this->_mixedContent[] = [
  802. 'type' => 'text',
  803. 'text' => $sText
  804. ];
  805. }
  806. public function addImageUrl($sUrl, $sDetail = 'high')
  807. {
  808. $this->_mixedContent[] = [
  809. 'type' => 'image_url',
  810. 'image_url' => [
  811. 'url' => $sUrl,
  812. 'detail' => $sDetail
  813. ]
  814. ];
  815. }
  816. public function addAttachments($mixedAttachments, $mixedTools = false)
  817. {
  818. if(!is_array($mixedAttachments))
  819. $mixedAttachments = [$mixedAttachments];
  820. if(!$mixedTools)
  821. $mixedTools = [['type' => 'file_search']];
  822. foreach($mixedAttachments as $sAttachment)
  823. $this->_aAttachments[] = [
  824. 'file_id' => $sAttachment,
  825. 'tools' => $mixedTools
  826. ];
  827. }
  828. }
  829. class BxDolAIMessages
  830. {
  831. /**
  832. * @var array - an array of items (messages)
  833. */
  834. protected $_aItems;
  835. public function __construct($aItems = [])
  836. {
  837. $this->_aItems = !empty($aItems) && is_array($aItems) ? $aItems : [];
  838. }
  839. public function add($sType, $mixedMessage)
  840. {
  841. $sClass = 'BxDolAIMessage' . (is_string($mixedMessage) ? 'String' : 'Array');
  842. $this->_aItems[] = new $sClass($sType, $mixedMessage);
  843. }
  844. public function getAll()
  845. {
  846. return $this->_aItems;
  847. }
  848. public function getLast()
  849. {
  850. return end($this->_aItems);
  851. }
  852. }