BxDolAi.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. class BxDolAi extends BxDolFactory implements iBxDolSingleton
  10. {
  11. protected $_oDb;
  12. protected $_iProfileId;
  13. protected $_aAgentProfiles = [];
  14. protected function __construct()
  15. {
  16. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  17. trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
  18. parent::__construct();
  19. $this->_oDb = new BxDolAiQuery();
  20. $this->_iProfileId = (int)getParam('sys_profile_bot');
  21. }
  22. /**
  23. * Prevent cloning the instance
  24. */
  25. public function __clone()
  26. {
  27. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  28. trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
  29. }
  30. /**
  31. * Get singleton instance of the class
  32. */
  33. public static function getInstance()
  34. {
  35. if (!isset($GLOBALS['bxDolClasses'][__CLASS__])) {
  36. $GLOBALS['bxDolClasses'][__CLASS__] = BxDolDb::getInstance()->isTableExists('sys_agents_agents') ? new BxDolAi() : null;
  37. }
  38. return $GLOBALS['bxDolClasses'][__CLASS__];
  39. }
  40. public static function getAgentInstance(int $iId, array $aParams = []): NeuronAI\Agent\Agent
  41. {
  42. if (isset($GLOBALS['bxDolClasses'][__CLASS__ . '_Agent_' . $iId]))
  43. return $GLOBALS['bxDolClasses'][__CLASS__ . '_Agent_' . $iId];
  44. $a = BxDolAiQuery::getAgentObject($iId);
  45. if (!$a) {
  46. $s = "Agent with id {$iId} not found";
  47. bx_log('sys_agents', $s, BX_LOG_ERR);
  48. throw new Exception($s);
  49. }
  50. if (!$a['active']) {
  51. $s = "Agent with id {$iId} isn't active";
  52. bx_log('sys_agents', $s, BX_LOG_ERR);
  53. throw new Exception($s);
  54. }
  55. if (!$a['prompt_system'] || !$a['model_id']) {
  56. $s = "Agent with id {$iId} can't be used because it haven't prompt or AI model";
  57. bx_log('sys_agents', $s, BX_LOG_ERR);
  58. throw new Exception($s);
  59. }
  60. $o = BxDolAiAgent::make($a, $aParams);
  61. if ((int)$a['tools_max_run'] > 0)
  62. $o->toolMaxRuns($a['tools_max_run']);
  63. if ($a['vector_store_id']) {
  64. $aVectorStore = BxDolAiQuery::getVectorStoreObject($a['vector_store_id']);
  65. if ($aVectorStore && $aVectorStore['embedding_provider_id']) {
  66. $oEmbedder = self::getAiEmbeddingsProviderInstance($aVectorStore['embedding_provider_id']);
  67. $o->setEmbeddingsProvider($oEmbedder);
  68. }
  69. }
  70. $GLOBALS['bxDolClasses'][__CLASS__ . '_Agent_' . $iId] = $o;
  71. return $o;
  72. }
  73. public static function getAiProviderInstance(int $iId):NeuronAI\Providers\AIProviderInterface
  74. {
  75. return BxDolAIModelFactory::getModelInstance($iId);
  76. }
  77. public static function getAiEmbeddingsProviderInstance(int $iId):NeuronAI\RAG\Embeddings\EmbeddingsProviderInterface
  78. {
  79. return BxDolAIModelFactory::getModelInstance($iId);
  80. }
  81. public function getProfileId()
  82. {
  83. return $this->_iProfileId;
  84. }
  85. public function getModels($aParams = [])
  86. {
  87. $aParamsDb = ['sample' => 'all_pairs'];
  88. if(isset($aParams['active']))
  89. $aParamsDb['active'] = $aParams['active'] === true ? 1 : 0;
  90. if(isset($aParams['capabilities']))
  91. $aParamsDb['capabilities'] = $aParams['capabilities'];
  92. return $this->_oDb->getModelsBy($aParamsDb);
  93. }
  94. public function callAgent($sType, $aAgent, $mixedParams = [])
  95. {
  96. return BxDolAiTrigger::getInstance($sType)->call($aAgent, $mixedParams);
  97. }
  98. /**
  99. * Whether the current (or given) member may interact with the agent
  100. * via chat, messenger, or form-input. Empty acl_levels means Nobody.
  101. * Site admins / Studio operators always may, so they can debug.
  102. */
  103. public function canInteract($aAgent, $iProfileId = false, $bAllowOperators = true)
  104. {
  105. if (!is_array($aAgent) || empty($aAgent['id']))
  106. return false;
  107. if ($bAllowOperators && isAdmin())
  108. return true;
  109. $iLevels = (int)($aAgent['acl_levels'] ?? 0);
  110. if (!$iLevels)
  111. return false;
  112. return (bool)BxDolAcl::getInstance()->isMemberLevelInSet($iLevels, $iProfileId);
  113. }
  114. /**
  115. * Direct HTTP chat (`sys-ai-chat`). Operators may talk to any trigger;
  116. * everyone else only `manual` and `message` agents they can interact with.
  117. */
  118. public function canChatDirectly($aAgent, $iProfileId = false)
  119. {
  120. if (!$this->canInteract($aAgent, $iProfileId))
  121. return false;
  122. if (isAdmin())
  123. return true;
  124. return in_array($aAgent['trigger'] ?? '', ['manual', 'message'], true);
  125. }
  126. public function extractChatPromptFromRequest($aData)
  127. {
  128. return BxDolAiTrigger::getInstance('chat')->extractPromptFromRequest($aData);
  129. }
  130. public function streamAgentChat($iAgentId, $sPrompt, $aParams = [], $sThreadId = null)
  131. {
  132. return BxDolAiTrigger::getInstance('chat')->stream($iAgentId, $sPrompt, $aParams, $sThreadId);
  133. }
  134. public function sendMessengerMessage($iSender, $iRecipient, $sMsg)
  135. {
  136. return BxDolAiTrigger::getInstance('message')->sendMessengerMessage($iSender, $iRecipient, $sMsg);
  137. }
  138. public function getAgentsByAlertUnitAndAction($sUnit, $sAction)
  139. {
  140. return BxDolAiTrigger::getInstance('alert')->getAgentsByUnitAndAction($sUnit, $sAction);
  141. }
  142. public function getAgentsBy($aParams)
  143. {
  144. return $this->_oDb->getAgentsBy($aParams);
  145. }
  146. public function getAgentsByProfileId($iProfileId)
  147. {
  148. return BxDolAiTrigger::getInstance('message')->getAgentsByProfileId($iProfileId);
  149. }
  150. public function getAgentsByFormObject($sFormObject)
  151. {
  152. return $this->_oDb->getAgentsByFormObject($sFormObject);
  153. }
  154. public function getAgentsByTriggerType($sTrigger)
  155. {
  156. return $this->_oDb->getAgentsByTriggerType($sTrigger);
  157. }
  158. public function getAgentByTriggerWebhookKey($sKey)
  159. {
  160. return BxDolAiTrigger::getInstance('webhook')->getAgentByKey($sKey);
  161. }
  162. /**
  163. * Profile is used by an active agent (any trigger). Cached per request.
  164. */
  165. public function isAgentProfile($iProfileId)
  166. {
  167. $iProfileId = (int)$iProfileId;
  168. if ($iProfileId <= 0)
  169. return false;
  170. if (!array_key_exists($iProfileId, $this->_aAgentProfiles))
  171. $this->_aAgentProfiles[$iProfileId] = $this->_oDb->isAgentProfile($iProfileId);
  172. return $this->_aAgentProfiles[$iProfileId];
  173. }
  174. }
  175. /** @} */