BxDolAI.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  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): 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);
  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 self::getModelInstance($iId);
  90. }
  91. public static function getAiEmbeddingsProviderInstance(int $iId):NeuronAI\RAG\Embeddings\EmbeddingsProviderInterface
  92. {
  93. return self::getModelInstance($iId);
  94. }
  95. public static function getModelInstance(int $iId): NeuronAI\Providers\AIProviderInterface | NeuronAI\RAG\Embeddings\EmbeddingsProviderInterface
  96. {
  97. if (isset($GLOBALS['bxDolClasses'][__CLASS__ . '_Model_' . $iId]))
  98. return $GLOBALS['bxDolClasses'][__CLASS__ . '_Model_' . $iId];
  99. $aProvidersWithKey = ['anthropic'];
  100. $a = BxDolAIQuery::getModelObject($iId);
  101. if (!$a) {
  102. bx_log('sys_agents', "Agent AI Model with id {$iId} not found", BX_LOG_ERR);
  103. throw new Exception("Agent AI Model with id {$iId} not found");
  104. }
  105. if (in_array($a['type'], $aProvidersWithKey) && empty($a['key'])) {
  106. bx_log('sys_agents', "Model with id {$iId} has empty key, can't be used", BX_LOG_ERR);
  107. throw new Exception("Model with id {$iId} has empty key, can't be used");
  108. }
  109. if (!$a['active']) {
  110. bx_log('sys_agents', "Model with id {$iId} is not active, can't be used", BX_LOG_ERR);
  111. throw new Exception("Model with id {$iId} is not active, can't be used");
  112. }
  113. $aParameters = !empty($a['params']) ? json_decode($a['params'], true) : [];
  114. // replace markers {key} {model} in $aParameters recoursively
  115. $aParameters = bx_replace_markers($aParameters, [
  116. 'key' => $a['key'],
  117. 'model' => $a['model']
  118. ]);
  119. switch($a['type']) {
  120. // regular AI providers ------------------------
  121. case 'anthropic':
  122. $o = new NeuronAI\Providers\Anthropic\Anthropic(
  123. key: $a['key'],
  124. model: $a['model'],
  125. version: $aParameters['version'] ?? '2023-06-01',
  126. max_tokens: $aParameters['max_tokens'] ?? 8192,
  127. parameters: $aParameters['parameters'] ?? [],
  128. );
  129. break;
  130. case 'openai-responses':
  131. $o = new NeuronAI\Providers\OpenAI\Responses\OpenAIResponses(
  132. key: $a['key'],
  133. model: $a['model'],
  134. parameters: $aParameters['parameters'] ?? [],
  135. strict_response: $aParameters['strict_response'] ?? false,
  136. );
  137. break;
  138. case 'azure-openai':
  139. $o = new NeuronAI\Providers\OpenAI\AzureOpenAI(
  140. key: $a['key'],
  141. model: $a['model'],
  142. endpoint: $aParameters['endpoint'],
  143. version: $aParameters['version'],
  144. parameters: $aParameters['parameters'] ?? [],
  145. strict_response: $aParameters['strict_response'] ?? false,
  146. );
  147. break;
  148. case 'openai-like':
  149. $o = new NeuronAI\Providers\OpenAILike(
  150. baseUri: $aParameters['baseUri'],
  151. key: $a['key'],
  152. model: $a['model'],
  153. parameters: $aParameters['parameters'] ?? [],
  154. strict_response: $aParameters['strict_response'] ?? false,
  155. );
  156. break;
  157. case 'ollama':
  158. $o = new NeuronAI\Providers\Ollama\Ollama(
  159. url: $aParameters['url'] ?? 'http://localhost:11434/api',
  160. model: $a['model'],
  161. parameters: $aParameters['parameters'] ?? [],
  162. );
  163. break;
  164. case 'gemini':
  165. $o = new NeuronAI\Providers\Gemini\Gemini(
  166. key: $a['key'],
  167. model: $a['model'],
  168. parameters: $aParameters['parameters'] ?? [],
  169. );
  170. break;
  171. case 'mistral':
  172. $o = new NeuronAI\Providers\Mistral\Mistral(
  173. key: $a['key'],
  174. model: $a['model'],
  175. parameters: $aParameters['parameters'] ?? [],
  176. strict_response: $aParameters['strict_response'] ?? false,
  177. );
  178. break;
  179. case 'huggingface':
  180. $o = new NeuronAI\Providers\HuggingFace\HuggingFace(
  181. key: $a['key'],
  182. model: $a['model'],
  183. inferenceProvider: $aParameters['inferenceProvider'] ?? 'hf-inference/models', // cohere, groq, etc - https://github.com/neuron-core/neuron-ai/blob/3.x/src/Providers/HuggingFace/InferenceProvider.php
  184. parameters: $aParameters['parameters'] ?? [],
  185. strict_response: $aParameters['strict_response'] ?? false,
  186. );
  187. break;
  188. case 'deepseek':
  189. $o = new NeuronAI\Providers\DeepSeek\DeepSeek(
  190. key: $a['key'],
  191. model: $a['model'],
  192. parameters: $aParameters['parameters'] ?? [],
  193. strict_response: $aParameters['strict_response'] ?? false,
  194. );
  195. break;
  196. case 'grok':
  197. $o = new NeuronAI\Providers\XAI\Grok(
  198. key: $a['key'],
  199. model: $a['model'],
  200. parameters: $aParameters['parameters'] ?? [],
  201. strict_response: $aParameters['strict_response'] ?? false,
  202. );
  203. break;
  204. case 'aws-bedrock':
  205. $oClient = new Aws\BedrockRuntime\BedrockRuntimeClient($aParameters['client_params']);
  206. $o = new NeuronAI\Providers\AWS\BedrockRuntime(
  207. client: $oClient,
  208. model: $a['model'],
  209. inferenceConfig: $aParameters['inferenceConfig'] ?? [],
  210. );
  211. break;
  212. case 'cohere':
  213. $o = new NeuronAI\Providers\Cohere\Cohere(
  214. key: $a['key'],
  215. model: $a['model'],
  216. baseUri: $aParameters['baseUri'] ?? 'https://api.cohere.ai/v2',
  217. parameters: $aParameters['parameters'] ?? [],
  218. strict_response: $aParameters['strict_response'] ?? false,
  219. );
  220. break;
  221. // embeddings models ------------------------
  222. case 'ollama-embeddings':
  223. $o = new NeuronAI\RAG\Embeddings\OllamaEmbeddingsProvider(
  224. model: $a['model'],
  225. url: $aParameters['url'] ?? 'http://localhost:11434/api',
  226. parameters: $aParameters['parameters'] ?? [],
  227. );
  228. break;
  229. case 'voyageai-embeddings':
  230. $o = new NeuronAI\RAG\Embeddings\VoyageEmbeddingsProvider(
  231. key: $a['key'],
  232. model: $a['model'],
  233. dimensions: !empty($aParameters['dimensions']) ? (int)$aParameters['dimensions'] : null
  234. );
  235. break;
  236. case 'openai-embeddings':
  237. $o = new NeuronAI\RAG\Embeddings\OpenAIEmbeddingsProvider(
  238. key: $a['key'],
  239. model: $a['model'],
  240. dimensions: !empty($aParameters['dimensions']) ? (int)$aParameters['dimensions'] : 1024
  241. );
  242. break;
  243. case 'openai-like-embeddings':
  244. $o = new NeuronAI\RAG\Embeddings\OpenAILikeEmbeddings(
  245. baseUri: $aParameters['baseUri'],
  246. key: $a['key'],
  247. model: $a['model'],
  248. dimensions: !empty($aParameters['dimensions']) ? (int)$aParameters['dimensions'] : 1024
  249. );
  250. break;
  251. case 'aws-bedrock-embeddings':
  252. $oClient = new Aws\BedrockRuntime\BedrockRuntimeClient($aParameters['client_params']);
  253. $o = new NeuronAI\RAG\Embeddings\AwsBedrockEmbeddingsProvider(
  254. client: $oClient,
  255. model: $a['model']
  256. );
  257. break;
  258. default:
  259. bx_log('sys_agents', "Model type {$a['type']} is not supported", BX_LOG_ERR);
  260. throw new Exception("Model type {$a['type']} is not supported");
  261. }
  262. $GLOBALS['bxDolClasses'][__CLASS__ . '_Model_' . $iId] = $o;
  263. return $o;
  264. }
  265. public static function getVectorStoreInstance(int $iId): NeuronAI\RAG\VectorStore\VectorStoreInterface
  266. {
  267. if (isset($GLOBALS['bxDolClasses'][__CLASS__ . '_VectorStore_' . $iId]))
  268. return $GLOBALS['bxDolClasses'][__CLASS__ . '_VectorStore_' . $iId];
  269. $a = BxDolAIQuery::getVectorStoreObject($iId);
  270. if (!$a) {
  271. bx_log('sys_agents', "Vector store with id {$iId} not found", BX_LOG_ERR);
  272. throw new Exception("Vector store with id {$iId} not found");
  273. }
  274. $aParameters = !empty($a['params']) ? json_decode($a['params'], true) : [];
  275. // replace marker {topk} in $aParameters recoursively
  276. $aParameters = bx_replace_markers($aParameters, [
  277. 'topk' => $a['topk'],
  278. ]);
  279. // TODO: fix params
  280. switch($a['type']) {
  281. case 'file':
  282. $o = new NeuronAI\RAG\VectorStore\FileVectorStore(
  283. directory: BX_DIRECTORY_STORAGE . 'vector_stores/' . $iId,
  284. topK: $a['topk'] ?? 4
  285. );
  286. break;
  287. case 'pinecon':
  288. $o = new NeuronAI\RAG\VectorStore\PineconeVectorStore(
  289. key: $a['key'],
  290. indexUrl: $aParameters['indexUrl'],
  291. topK: $a['topk'] ?? 4,
  292. version: $aParameters['version'] ?? '2025-04',
  293. namespace: $aParameters['namespace'] ?? '__default__'
  294. );
  295. break;
  296. case 'elasticsearch':
  297. $oClient = Elastic\Elasticsearch\ClientBuilder::create()
  298. ->setHosts([$aParameters['client_params']['endpoint']])
  299. ->setApiKey($aParameters['client_params']['key'])
  300. ->build();
  301. $o = new NeuronAI\RAG\VectorStore\ElasticsearchVectorStore(
  302. client: $oClient,
  303. index: $aParameters['index'],
  304. topK: $a['topk'] ?? 4
  305. );
  306. break;
  307. case 'opensearch':
  308. $oClient = (new OpenSearch\GuzzleClientFactory())->create([
  309. 'base_uri' => $aParameters['client_params']['endpoint'] ?? 'http://localhost:9200',
  310. ]);
  311. $o = NeuronAI\RAG\VectorStore\OpenSearchVectorStore(
  312. client: $oClient,
  313. index: $aParameters['index'],
  314. topK: $a['topk'] ?? 4,
  315. );
  316. break;
  317. case 'typesense':
  318. $oClient = new \Typesense\Client($aParameters['client_params']);
  319. $o = new NeuronAI\RAG\VectorStore\TypesenseVectorStore(
  320. client: $oClient,
  321. collection: $aParameters['collection'],
  322. vectorDimension: $aParameters['vectorDimension'] ?? 1024,
  323. topK: $a['topk'] ?? 4,
  324. );
  325. break;
  326. case 'qdrant':
  327. $o = new NeuronAI\RAG\VectorStore\QdrantVectorStore(
  328. collectionUrl: $aParameters['collectionUrl'],
  329. key: $a['key'],
  330. topK: $a['topk'] ?? 4,
  331. dimension: $aParameters['dimension'] ?? 1024
  332. );
  333. break;
  334. case 'chromadb':
  335. $o = new NeuronAI\RAG\VectorStore\ChromaVectorStore(
  336. collection: $aParameters['collection'],
  337. host: $aParameters['host'] ?? 'http://localhost:8000',
  338. tenant: $aParameters['tenant'] ?? 'default_tenant',
  339. database: $aParameters['database'] ?? 'default_database',
  340. key: $a['key'] ?? null,
  341. topK: $a['topk'] ?? 4
  342. );
  343. break;
  344. case 'meilisearch':
  345. $o = new NeuronAI\RAG\VectorStore\MeilisearchVectorStore(
  346. indexUid: $aParameters['indexUid'],
  347. host: $aParameters['host'] ?? 'http://localhost:8000',
  348. key: $a['key'] ?? null,
  349. embedder: $aParameters['embedder'] ?? 'default',
  350. topK: $a['topk'] ?? 4,
  351. dimension: $aParameters['dimension'] ?? 1024
  352. );
  353. break;
  354. default:
  355. bx_log('sys_agents', "Vector store type {$a['type']} is not supported", BX_LOG_ERR);
  356. throw new Exception("Vector store type {$a['type']} is not supported");
  357. }
  358. $GLOBALS['bxDolClasses'][__CLASS__ . '_VectorStore_' . $iId] = $o;
  359. return $o;
  360. }
  361. public static function getToolInstance(int $iId): NeuronAI\Tools\ToolInterface
  362. {
  363. if (isset($GLOBALS['bxDolClasses'][__CLASS__ . '_AiAgentTool_' . $iId]))
  364. return $GLOBALS['bxDolClasses'][__CLASS__ . '_AiAgentTool_' . $iId];
  365. $a = BxDolAIQuery::getToolObject($iId);
  366. if (!$a) {
  367. bx_log('sys_agents', "Tool with id {$iId} not found", BX_LOG_ERR);
  368. throw new Exception("Tool with id {$iId} not found");
  369. }
  370. $aParameters = !empty($a['params']) ? json_decode($a['params'], true) : [];
  371. switch($a['type']) {
  372. case 'mysql_schema':
  373. $o = NeuronAI\Tools\Toolkits\MySQL\MySQLSchemaTool::make(
  374. pdo: BxDolDb::getInstance()->getLink(),
  375. tables: $aParameters['tables'] ?? null
  376. );
  377. break;
  378. case 'mysql_select':
  379. $o = NeuronAI\Tools\Toolkits\MySQL\MySQLSelectTool::make(
  380. pdo: BxDolDb::getInstance()->getLink(),
  381. );
  382. break;
  383. case 'mysql_write':
  384. $o = NeuronAI\Tools\Toolkits\MySQL\MySQLWriteTool::make(
  385. pdo: BxDolDb::getInstance()->getLink(),
  386. );
  387. break;
  388. default:
  389. bx_log('sys_agents', "Tool type {$a['type']} is not supported", BX_LOG_ERR);
  390. throw new Exception("Tool type {$a['type']} is not supported");
  391. }
  392. $GLOBALS['bxDolClasses'][__CLASS__ . '_AiAgentTool_' . $iId] = $o;
  393. return $o;
  394. }
  395. public static function callHelper($mixedHelper, $sMessage)
  396. {
  397. $oAI = BxDolAI::getInstance();
  398. if (is_numeric($mixedHelper))
  399. $aHelper = $oAI->getHelperById($mixedHelper);
  400. else
  401. $aHelper = $oAI->getHelperByName($mixedHelper);
  402. $oAIModel = $oAI->getModelObject($aHelper['model_id']);
  403. return $oAIModel->getResponseText($aHelper['prompt'], $sMessage);
  404. }
  405. public static function pruning()
  406. {
  407. BxDolAIAssistant::pruning();
  408. }
  409. public static function getDefaultApiKey()
  410. {
  411. return getParam('sys_agents_api_key');
  412. }
  413. public static function getDefaultModel()
  414. {
  415. return (int)getParam('sys_agents_model');
  416. }
  417. public static function getAssistantForStudio()
  418. {
  419. return ($iId = (int)getParam('sys_agents_studio_assistant')) != 0 ? $iId : 0;
  420. }
  421. public static function getAssistantForLiveSearch()
  422. {
  423. return ($iId = (int)getParam('sys_agents_live_search_assistant')) != 0 ? $iId : 0;
  424. }
  425. public static function getAssistantForAskBlock()
  426. {
  427. return ($iId = (int)getParam('sys_agents_ask_block_assistant')) != 0 ? $iId : 0;
  428. }
  429. public function getProfileId()
  430. {
  431. return $this->_iProfileId;
  432. }
  433. public function getModels($aParams = [])
  434. {
  435. $aParamsDb = ['sample' => 'all_pairs'];
  436. if(isset($aParams['active']))
  437. $aParamsDb['active'] = $aParams['active'] === true ? 1 : 0;
  438. if(isset($aParams['capabilities']))
  439. $aParamsDb['capabilities'] = $aParams['capabilities'];
  440. return $aModel = $this->_oDb->getModelsBy($aParamsDb);
  441. }
  442. public function getModel($iId)
  443. {
  444. $aModel = $this->_oDb->getModelsBy(['sample' => 'id', 'id' => $iId]);
  445. if(!empty($aModel['params']))
  446. $aModel['params'] = json_decode($aModel['params'], true);
  447. return $aModel;
  448. }
  449. public function getModelObject($iId)
  450. {
  451. if(!$iId)
  452. $iId = $this->getDefaultModel();
  453. if(!$iId)
  454. return false;
  455. return BxDolAIModel::getObjectInstance($iId);
  456. }
  457. public function getProviderObject($iId)
  458. {
  459. if(!$iId)
  460. return false;
  461. return BxDolAIProvider::getObjectInstance($iId);
  462. }
  463. public function getAssistants($aParams = [])
  464. {
  465. $aParamsDb = ['sample' => 'all_pairs'];
  466. if(isset($aParams['active']))
  467. $aParamsDb['active'] = $aParams['active'] === true ? 1 : 0;
  468. if(isset($aParams['hidden']))
  469. $aParamsDb['hidden'] = $aParams['hidden'] === true ? 1 : 0;
  470. return $aModel = $this->_oDb->getAssistantsBy($aParamsDb);
  471. }
  472. public function getAssistantById($iId)
  473. {
  474. return $this->_oDb->getAssistantsBy(['sample' => 'id', 'id' => $iId]);
  475. }
  476. public function getAssistantByName($sName)
  477. {
  478. return $this->_oDb->getAssistantsBy(['sample' => 'name', 'name' => $sName]);
  479. }
  480. public function getAssistantChatById($iId)
  481. {
  482. return $this->_oDb->getChatsBy(['sample' => 'id', 'id' => $iId]);
  483. }
  484. public function getAssistantChatsTransient($iLifetime = 0)
  485. {
  486. return $this->_oDb->getChatsBy(['sample' => 'type', 'type' => BX_DOL_AI_ASST_TYPE_TRANSIENT, 'lifetime' => $iLifetime]);
  487. }
  488. public function updateAssistantChatById($iId, $aSet)
  489. {
  490. return $this->_oDb->updateChats($aSet, ['id' => $iId]);
  491. }
  492. public function getAssistantChatCmts()
  493. {
  494. return $this->_sCmtsAssistantsChats;
  495. }
  496. public function getAssistantChatCmtsObject($iId, $oTemplate = false)
  497. {
  498. $oCmts = BxDolCmts::getObjectInstance($this->_sCmtsAssistantsChats, (int)$iId, true, $oTemplate);
  499. if(!$oCmts || !$oCmts->isEnabled())
  500. return false;
  501. return $oCmts;
  502. }
  503. public function getHelperById($iId)
  504. {
  505. return $this->_oDb->getHelpersBy(['sample' => 'id', 'id' => $iId]);
  506. }
  507. public function getHelperByName($sName)
  508. {
  509. return $this->_oDb->getHelpersBy(['sample' => 'name', 'name' => $sName]);
  510. }
  511. public function getAutomator($iId, $bFullInfo = false)
  512. {
  513. $aAutomator = $this->_oDb->getAutomatorsBy(['sample' => 'id' . ($bFullInfo ? '_full' : ''), 'id' => $iId]);
  514. if(!empty($aAutomator['params']))
  515. $aAutomator['params'] = json_decode($aAutomator['params'], true);
  516. if($bFullInfo && !empty($aAutomator['model_params']))
  517. $aAutomator['model_params'] = json_decode($aAutomator['model_params'], true);
  518. return $aAutomator;
  519. }
  520. public function getAutomatorInstruction($sType, $mixedParams = false)
  521. {
  522. $mixedResult = '';
  523. switch($sType) {
  524. case 'profile':
  525. $mixedResult = "\n ProfileId for system actions = " . $mixedParams;
  526. break;
  527. case 'providers':
  528. $aProviders = $this->_oDb->getProvidersBy(['sample' => 'ids', 'ids' => $mixedParams]);
  529. if(!empty($aProviders) && is_array($aProviders)) {
  530. $mixedResult = "\n Proividers list = [";
  531. foreach($aProviders as $aProvider)
  532. $mixedResult .= "\n {'ProviderName' => '" . $aProvider['name'] . "', 'ProviderType' => '" . $aProvider['type_name'] . "'}";
  533. $mixedResult .= "\n ]";
  534. }
  535. break;
  536. case 'helpers':
  537. $aHelpers = $this->_oDb->getHelpersBy(['sample' => 'ids', 'ids' => $mixedParams]);
  538. if(!empty($aHelpers) && is_array($aHelpers)) {
  539. $mixedResult = "\n Helpers list = [";
  540. foreach($aHelpers as $aHelper)
  541. $mixedResult .= "\n {'" . $aHelper['name'] . "', 'HelperDescription' => '" . $aHelper['description'] . "'}";
  542. $mixedResult .= "\n ]";
  543. }
  544. break;
  545. case 'assistants':
  546. $aAssistants = $this->_oDb->getAssistantsBy(['sample' => 'ids', 'ids' => $mixedParams]);
  547. if(!empty($aAssistants) && is_array($aAssistants)) {
  548. $mixedResult = "\n Assistants list = [";
  549. foreach($aAssistants as $aAssistant)
  550. $mixedResult .= "\n {'" . $aAssistant['name'] . "', 'AssistantDescription' => '" . $aAssistant['description'] . "'}";
  551. $mixedResult .= "\n ]";
  552. }
  553. break;
  554. }
  555. return $mixedResult;
  556. }
  557. public function getAutomatorCmts()
  558. {
  559. return $this->_sCmtsAutomators;
  560. }
  561. public function getAutomatorCmtsObject($iId, $oTemplate = false)
  562. {
  563. $oCmts = BxDolCmts::getObjectInstance($this->_sCmtsAutomators, (int)$iId, true, $oTemplate);
  564. if(!$oCmts || !$oCmts->isEnabled())
  565. return false;
  566. return $oCmts;
  567. }
  568. public function hasAutomators($sType, $bActive = null)
  569. {
  570. $aParams = [
  571. 'sample' => 'type',
  572. 'type' => $sType
  573. ];
  574. if($bActive !== null)
  575. $aParams['active'] = $bActive;
  576. return ($aAutomators = $this->_oDb->getAutomatorsBy($aParams)) && is_array($aAutomators);
  577. }
  578. public function getAutomatorsEvent($sUnit, $sAction)
  579. {
  580. if(in_array($sUnit, $this->_aExcludeAlertUnits))
  581. return [];
  582. return $this->_oDb->getAutomatorsBy([
  583. 'sample' => 'events',
  584. 'alert_unit' => $sUnit,
  585. 'alert_action' => $sAction,
  586. 'active' => true
  587. ]);
  588. }
  589. public function getAutomatorsScheduler()
  590. {
  591. $aAutomators = $this->_oDb->getAutomatorsBy(['sample' => 'schedulers', 'active' => true]);
  592. foreach($aAutomators as &$aAutomator)
  593. if(!empty($aAutomator['params']))
  594. $aAutomator['params'] = json_decode($aAutomator['params'], true);
  595. return $aAutomators;
  596. }
  597. public function getAutomatorsWebhook($iProviderId)
  598. {
  599. $aAutomators = $this->_oDb->getAutomatorsBy(['sample' => 'webhooks', 'provider_id' => $iProviderId, 'active' => true]);
  600. foreach($aAutomators as &$aAutomator)
  601. if(!empty($aAutomator['params']))
  602. $aAutomator['params'] = json_decode($aAutomator['params'], true);
  603. return $aAutomators;
  604. }
  605. public function callAgent($sType, $aAgent, $aParams = [])
  606. {
  607. // update sample data
  608. $a = ['alert' => 'alert_sample', 'webhook' => 'webhook_sample'];
  609. if (isset($a[$sType]) && empty($aAgent[$a[$sType]])) {
  610. $this->updateAgentField($aAgent['id'], $a[$sType], json_encode($aParams));
  611. }
  612. $o = self::getAgentInstance($aAgent['id']);
  613. if (!$o)
  614. return false;
  615. $o->chat(new UserMessage($aParams));
  616. $o->run();
  617. return $o->getMessage();
  618. }
  619. public function getAgentsByAlertUnitAndAction($sUnit, $sAction)
  620. {
  621. return $this->_oDb->getAgentsByAlertUnitAndAction($sUnit, $sAction);
  622. }
  623. public function callAutomator($sType, $aParams = [])
  624. {
  625. $sMethod = '_callAutomator' . bx_gen_method_name($sType);
  626. if(!method_exists($this, $sMethod))
  627. return false;
  628. return $this->$sMethod($aParams);
  629. }
  630. protected function _callAutomatorEvent($aParams = [])
  631. {
  632. if(!isset($aParams['automator'], $aParams['alert']) || !is_a($aParams['alert'], 'BxDolAlerts'))
  633. return false;
  634. $oAlert = &$aParams['alert'];
  635. $this->evalCode($aParams['automator'], ['alert' => $oAlert]);
  636. }
  637. protected function _callAutomatorScheduler($aParams = [])
  638. {
  639. if(!isset($aParams['automator']))
  640. return false;
  641. $this->evalCode($aParams['automator']);
  642. }
  643. protected function _callAutomatorWebhook($aParams = [])
  644. {
  645. if(!isset($aParams['automator']))
  646. return false;
  647. $this->evalCode($aParams['automator']);
  648. }
  649. public function evalCode($aAutomator, $aParams = [])
  650. {
  651. try {
  652. $this->_evalCode($aAutomator, $aParams);
  653. }
  654. catch (Exception $oException) {
  655. $this->log($oException->getFile() . ':' . $oException->getLine() . ' ' . $oException->getMessage());
  656. }
  657. catch (Error $oError) {
  658. $this->log($oError->getFile() . ':' . $oError->getLine() . ' ' . $oError->getMessage());
  659. }
  660. }
  661. public function emulCode($aAutomator, $aParams = [])
  662. {
  663. ob_start();
  664. try {
  665. $this->_evalCode($aAutomator, $aParams);
  666. }
  667. catch (Exception $oException) {
  668. return $oException->getMessage();
  669. }
  670. catch (Error $oError) {
  671. return $oError->getMessage();
  672. }
  673. finally {
  674. $sOutput = ob_get_clean();
  675. if(!empty($sOutput))
  676. return $sOutput;
  677. }
  678. }
  679. public function log($mixedContents, $sSection = '')
  680. {
  681. if(!$this->_bWriteLog)
  682. return;
  683. if(is_array($mixedContents))
  684. $mixedContents = var_export($mixedContents, true);
  685. else if(is_object($mixedContents))
  686. $mixedContents = json_encode($mixedContents);
  687. if(empty($sSection))
  688. $sSection = "Core";
  689. bx_log('sys_agents', ":\n[" . $sSection . "] " . $mixedContents, BX_LOG_ERR);
  690. }
  691. protected function _evalCode($aAutomator, $aParams = [])
  692. {
  693. $sCode = '';
  694. switch($aAutomator['type']) {
  695. case BX_DOL_AI_AUTOMATOR_EVENT:
  696. $sCode = $aAutomator['code']. '; onAlert($aParams["alert"]->iObject , $aParams["alert"]->iSender , $aParams["alert"]->aExtras);';
  697. break;
  698. case BX_DOL_AI_AUTOMATOR_SCHEDULER:
  699. $sCode = $aAutomator['code'] . '; onCron();';
  700. break;
  701. case BX_DOL_AI_AUTOMATOR_WEBHOOK:
  702. $sCode = $aAutomator['code'] . '; onHook();';
  703. break;
  704. }
  705. eval($sCode);
  706. }
  707. }
  708. class BxDolAIMessage
  709. {
  710. /**
  711. * @var string - message Type with following values: hb, ai
  712. */
  713. protected $_sType;
  714. /**
  715. * @var mixed - an array of message parts (text, image_url) or a string.
  716. */
  717. protected $_mixedContent;
  718. /**
  719. * @var array - an array of of files attached to the message.
  720. */
  721. protected $_aAttachments;
  722. public function __construct($sType)
  723. {
  724. $this->_sType = $sType;
  725. }
  726. public function isAi()
  727. {
  728. return $this->_sType == 'ai';
  729. }
  730. public function getContent()
  731. {
  732. return $this->_mixedContent;
  733. }
  734. public function getAttachments()
  735. {
  736. return $this->_aAttachments;
  737. }
  738. }
  739. class BxDolAIMessageString extends BxDolAIMessage
  740. {
  741. public function __construct($sType, $sContent)
  742. {
  743. parent::__construct($sType);
  744. $this->_mixedContent = is_string($sContent) ? $sContent : '';
  745. }
  746. }
  747. class BxDolAIMessageArray extends BxDolAIMessage
  748. {
  749. public function __construct($sType, $aContent = '')
  750. {
  751. parent::__construct($sType);
  752. $this->_mixedContent = is_array($aContent) ? $aContent : [];
  753. }
  754. public function addText($sText)
  755. {
  756. $this->_mixedContent[] = [
  757. 'type' => 'text',
  758. 'text' => $sText
  759. ];
  760. }
  761. public function addImageUrl($sUrl, $sDetail = 'high')
  762. {
  763. $this->_mixedContent[] = [
  764. 'type' => 'image_url',
  765. 'image_url' => [
  766. 'url' => $sUrl,
  767. 'detail' => $sDetail
  768. ]
  769. ];
  770. }
  771. public function addAttachments($mixedAttachments, $mixedTools = false)
  772. {
  773. if(!is_array($mixedAttachments))
  774. $mixedAttachments = [$mixedAttachments];
  775. if(!$mixedTools)
  776. $mixedTools = [['type' => 'file_search']];
  777. foreach($mixedAttachments as $sAttachment)
  778. $this->_aAttachments[] = [
  779. 'file_id' => $sAttachment,
  780. 'tools' => $mixedTools
  781. ];
  782. }
  783. }
  784. class BxDolAIMessages
  785. {
  786. /**
  787. * @var array - an array of items (messages)
  788. */
  789. protected $_aItems;
  790. public function __construct($aItems = [])
  791. {
  792. $this->_aItems = !empty($aItems) && is_array($aItems) ? $aItems : [];
  793. }
  794. public function add($sType, $mixedMessage)
  795. {
  796. $sClass = 'BxDolAIMessage' . (is_string($mixedMessage) ? 'String' : 'Array');
  797. $this->_aItems[] = new $sClass($sType, $mixedMessage);
  798. }
  799. public function getAll()
  800. {
  801. return $this->_aItems;
  802. }
  803. public function getLast()
  804. {
  805. return end($this->_aItems);
  806. }
  807. }