BxDolAI.php 33 KB

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